Skip to main content

agentmux_srv_core/backend/storage/
dreams.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The record of Dreams: one row per pass of the memory organizer, and one row per file operation it proposes
5//! (docs/specs/SPEC_DREAMS_BACKGROUND_MEMORY_ORGANIZING_2026_11_27.md §9, build step 1).
6//!
7//! A dream changes nothing by being recorded: it is a proposal until a person applies it. So the record keeps each
8//! operation's base text and new text beside its base hash, which is what lets the Memory tab show a diff and revert an
9//! applied dream long after the memory's own version history has been pruned (50 versions a file, 90 days). Nothing here
10//! prunes a dream.
11//!
12//! It lives in the always-global identity store, beside the job-run ledger, so every channel and version on this computer
13//! sees one record, and it is created on every open with no schema version bump (see `work_claims::SCHEMA`): an older build
14//! ignores the tables.
15//!
16//! This module stores and moves a dream between states; it runs no model, reads no memory file and applies nothing.
17
18use rusqlite::{params, OptionalExtension, Row};
19use serde::{Deserialize, Serialize};
20
21use super::store::Store;
22use super::StoreError;
23
24pub(crate) const SCHEMA: &str = "
25    CREATE TABLE IF NOT EXISTS db_dreams (
26        id             TEXT PRIMARY KEY,
27        memory_kind    TEXT NOT NULL,
28        agent_id       TEXT NOT NULL DEFAULT '',
29        trigger_kind   TEXT NOT NULL,
30        state          TEXT NOT NULL,
31        hold_reason    TEXT NOT NULL DEFAULT '',
32        error          TEXT NOT NULL DEFAULT '',
33        model          TEXT NOT NULL DEFAULT '',
34        account_id     TEXT NOT NULL DEFAULT '',
35        requested_by   TEXT NOT NULL DEFAULT '',
36        read_set       TEXT NOT NULL DEFAULT '[]',
37        caps_hit       TEXT NOT NULL DEFAULT '[]',
38        input_tokens   INTEGER NOT NULL DEFAULT 0,
39        output_tokens  INTEGER NOT NULL DEFAULT 0,
40        cost_usd       REAL NOT NULL DEFAULT 0,
41        cost_known     INTEGER NOT NULL DEFAULT 0,
42        created_at_ms  INTEGER NOT NULL,
43        started_at_ms  INTEGER,
44        ended_at_ms    INTEGER,
45        decided_at_ms  INTEGER,
46        decided_by     TEXT NOT NULL DEFAULT ''
47    );
48    CREATE INDEX IF NOT EXISTS idx_ids_dreams_created ON db_dreams(created_at_ms);
49    CREATE INDEX IF NOT EXISTS idx_ids_dreams_memory ON db_dreams(memory_kind, agent_id, created_at_ms);
50    CREATE INDEX IF NOT EXISTS idx_ids_dreams_state ON db_dreams(state);
51    CREATE TABLE IF NOT EXISTS db_dream_ops (
52        id                 TEXT PRIMARY KEY,
53        dream_id           TEXT NOT NULL,
54        seq                INTEGER NOT NULL,
55        op                 TEXT NOT NULL,
56        filename           TEXT NOT NULL,
57        merged_from        TEXT NOT NULL DEFAULT '[]',
58        base_hash          TEXT NOT NULL DEFAULT '',
59        base_text          TEXT NOT NULL DEFAULT '',
60        new_text           TEXT NOT NULL DEFAULT '',
61        reason             TEXT NOT NULL DEFAULT '',
62        evidence           TEXT NOT NULL DEFAULT '[]',
63        flags              TEXT NOT NULL DEFAULT '[]',
64        applied_version_id TEXT NOT NULL DEFAULT '',
65        merged_bases       TEXT NOT NULL DEFAULT '[]'
66    );
67    CREATE UNIQUE INDEX IF NOT EXISTS idx_ids_dream_ops_seq ON db_dream_ops(dream_id, seq);";
68
69/// Columns added after the tables' first shape, run on every open as the other stores' are: a table an earlier build
70/// created gains them, and "duplicate column" is the column already being there.
71const COLUMNS: [&str; 1] = ["ALTER TABLE db_dream_ops ADD COLUMN merged_bases TEXT NOT NULL DEFAULT '[]'"];
72
73/// Create the tables, then add any column an earlier build's table lacks.
74pub(crate) fn apply_schema(conn: &rusqlite::Connection) -> Result<(), StoreError> {
75    conn.execute_batch(SCHEMA)?;
76    super::migrations::apply_additive_columns(conn, COLUMNS)
77}
78
79/// Which memory a dream tidies.
80pub mod memory_kind {
81    /// One agent's personal memory (`agent_id` says whose).
82    pub const PERSONAL: &str = "personal";
83    /// Global Memory (`agent_id` is empty).
84    pub const GLOBAL: &str = "global";
85}
86
87/// What queued a dream (§3). `person` is "Dream now".
88pub mod trigger {
89    pub const COMPACTION: &str = "compaction";
90    pub const IDLE: &str = "idle";
91    pub const BUILT_UP: &str = "built_up";
92    pub const NIGHTLY: &str = "nightly";
93    pub const PERSON: &str = "person";
94}
95
96/// A dream's states (§9). `held` carries a `hold_reason`, `failed` an `error`.
97pub mod state {
98    pub const QUEUED: &str = "queued";
99    pub const RUNNING: &str = "running";
100    pub const READY: &str = "ready";
101    pub const APPLIED: &str = "applied";
102    pub const REJECTED: &str = "rejected";
103    pub const REVERTED: &str = "reverted";
104    pub const HELD: &str = "held";
105    pub const FAILED: &str = "failed";
106
107    /// Where a dream may go from `from`. A decided dream (rejected, reverted, failed) never moves again; an applied one
108    /// can only be reverted; a held one goes back to the queue when what held it passes.
109    pub fn can_move(from: &str, to: &str) -> bool {
110        match from {
111            QUEUED => matches!(to, RUNNING | HELD),
112            RUNNING => matches!(to, READY | HELD | FAILED),
113            HELD => matches!(to, QUEUED),
114            READY => matches!(to, APPLIED | REJECTED),
115            APPLIED => matches!(to, REVERTED),
116            _ => false,
117        }
118    }
119}
120
121/// A file operation a dream proposes (§2.5).
122pub mod op {
123    pub const ADD: &str = "add";
124    pub const MERGE: &str = "merge";
125    pub const REWRITE: &str = "rewrite";
126    pub const REMOVE: &str = "remove";
127}
128
129/// One pass of the organizer. The JSON fields (`read_set`, `caps_hit`) are written and read by the runner and the UI;
130/// the store keeps them as text and does not look inside.
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132pub struct Dream {
133    pub id: String,
134    pub memory_kind: String,
135    pub agent_id: String,
136    pub trigger_kind: String,
137    pub state: String,
138    pub hold_reason: String,
139    pub error: String,
140    pub model: String,
141    pub account_id: String,
142    pub requested_by: String,
143    pub read_set: String,
144    pub caps_hit: String,
145    pub input_tokens: i64,
146    pub output_tokens: i64,
147    pub cost_usd: f64,
148    pub cost_known: bool,
149    pub created_at_ms: i64,
150    pub started_at_ms: Option<i64>,
151    pub ended_at_ms: Option<i64>,
152    pub decided_at_ms: Option<i64>,
153    pub decided_by: String,
154}
155
156impl Dream {
157    /// A queued dream with nothing read yet.
158    pub fn queued(
159        id: &str,
160        memory_kind: &str,
161        agent_id: &str,
162        trigger_kind: &str,
163        created_at_ms: i64,
164    ) -> Self {
165        Self {
166            id: id.into(),
167            memory_kind: memory_kind.into(),
168            agent_id: agent_id.into(),
169            trigger_kind: trigger_kind.into(),
170            state: state::QUEUED.into(),
171            hold_reason: String::new(),
172            error: String::new(),
173            model: String::new(),
174            account_id: String::new(),
175            requested_by: String::new(),
176            read_set: "[]".into(),
177            caps_hit: "[]".into(),
178            input_tokens: 0,
179            output_tokens: 0,
180            cost_usd: 0.0,
181            cost_known: false,
182            created_at_ms,
183            started_at_ms: None,
184            ended_at_ms: None,
185            decided_at_ms: None,
186            decided_by: String::new(),
187        }
188    }
189}
190
191/// One operation of a dream's proposal, on one file. `base_hash` is the head version's content hash the pass read, which
192/// apply compares with the head at apply time (§2.6); `base_text` and `new_text` are kept with the record so the diff
193/// and a revert do not depend on the memory's own version history. `evidence` and `flags` are JSON (§6).
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
195pub struct DreamOp {
196    pub id: String,
197    pub dream_id: String,
198    pub seq: i64,
199    pub op: String,
200    pub filename: String,
201    pub merged_from: String,
202    pub base_hash: String,
203    pub base_text: String,
204    pub new_text: String,
205    pub reason: String,
206    pub evidence: String,
207    pub flags: String,
208    /// The memory version that applying this operation wrote; empty until it is applied.
209    pub applied_version_id: String,
210    /// What a `merge` read of the files it merges away, as JSON `[{"file","hash","text"}]` in the order of `merged_from`
211    /// (`[]` for any other operation): apply checks each is still at that hash, and a revert puts that text back.
212    pub merged_bases: String,
213}
214
215/// What a pass reports when its model call ends. `cost` is `None` when the price is not known (a login's quota is not dollars).
216#[derive(Debug, Clone, Default, PartialEq)]
217pub struct DreamResult {
218    pub model: String,
219    pub account_id: String,
220    pub read_set: String,
221    pub caps_hit: String,
222    pub input_tokens: i64,
223    pub output_tokens: i64,
224    pub cost: Option<f64>,
225}
226
227const DREAM_COLS: &str = "id, memory_kind, agent_id, trigger_kind, state, hold_reason, error, model, account_id, \
228     requested_by, read_set, caps_hit, input_tokens, output_tokens, cost_usd, cost_known, created_at_ms, started_at_ms, \
229     ended_at_ms, decided_at_ms, decided_by";
230const OP_COLS: &str = "id, dream_id, seq, op, filename, merged_from, base_hash, base_text, new_text, reason, evidence, \
231     flags, applied_version_id, merged_bases";
232
233fn dream_from(r: &Row<'_>) -> rusqlite::Result<Dream> {
234    Ok(Dream {
235        id: r.get(0)?,
236        memory_kind: r.get(1)?,
237        agent_id: r.get(2)?,
238        trigger_kind: r.get(3)?,
239        state: r.get(4)?,
240        hold_reason: r.get(5)?,
241        error: r.get(6)?,
242        model: r.get(7)?,
243        account_id: r.get(8)?,
244        requested_by: r.get(9)?,
245        read_set: r.get(10)?,
246        caps_hit: r.get(11)?,
247        input_tokens: r.get(12)?,
248        output_tokens: r.get(13)?,
249        cost_usd: r.get(14)?,
250        cost_known: r.get::<_, i64>(15)? != 0,
251        created_at_ms: r.get(16)?,
252        started_at_ms: r.get(17)?,
253        ended_at_ms: r.get(18)?,
254        decided_at_ms: r.get(19)?,
255        decided_by: r.get(20)?,
256    })
257}
258
259fn op_from(r: &Row<'_>) -> rusqlite::Result<DreamOp> {
260    Ok(DreamOp {
261        id: r.get(0)?,
262        dream_id: r.get(1)?,
263        seq: r.get(2)?,
264        op: r.get(3)?,
265        filename: r.get(4)?,
266        merged_from: r.get(5)?,
267        base_hash: r.get(6)?,
268        base_text: r.get(7)?,
269        new_text: r.get(8)?,
270        reason: r.get(9)?,
271        evidence: r.get(10)?,
272        flags: r.get(11)?,
273        applied_version_id: r.get(12)?,
274        merged_bases: r.get(13)?,
275    })
276}
277
278impl Store {
279    /// Record a dream. The id is the caller's; a second insert of the same id is an error, so a dream is never recorded twice.
280    pub fn dream_insert(&self, d: &Dream) -> Result<(), StoreError> {
281        let conn = self.conn.lock().unwrap();
282        conn.execute(
283            &format!("INSERT INTO db_dreams ({DREAM_COLS}) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21)"),
284            params![
285                d.id, d.memory_kind, d.agent_id, d.trigger_kind, d.state, d.hold_reason, d.error, d.model, d.account_id,
286                d.requested_by, d.read_set, d.caps_hit, d.input_tokens, d.output_tokens, d.cost_usd, d.cost_known as i64,
287                d.created_at_ms, d.started_at_ms, d.ended_at_ms, d.decided_at_ms, d.decided_by,
288            ],
289        )?;
290        Ok(())
291    }
292
293    pub fn dream_get(&self, id: &str) -> Result<Option<Dream>, StoreError> {
294        let conn = self.conn.lock().unwrap();
295        Ok(conn
296            .query_row(
297                &format!("SELECT {DREAM_COLS} FROM db_dreams WHERE id = ?1"),
298                params![id],
299                dream_from,
300            )
301            .optional()?)
302    }
303
304    /// Newest first, by creation time and then id. `memory_kind` and `agent_id` narrow the list (an agent's personal dreams,
305    /// or Global's); `before` continues a page from the last dream shown, as its `(created_at_ms, id)`, so dreams made in
306    /// the same millisecond are neither repeated nor skipped across a page boundary.
307    pub fn dream_list(
308        &self,
309        memory_kind: Option<&str>,
310        agent_id: Option<&str>,
311        before: Option<(i64, &str)>,
312        limit: usize,
313    ) -> Result<Vec<Dream>, StoreError> {
314        let conn = self.conn.lock().unwrap();
315        let mut stmt = conn.prepare(&format!(
316            "SELECT {DREAM_COLS} FROM db_dreams
317             WHERE (?1 IS NULL OR memory_kind = ?1) AND (?2 IS NULL OR agent_id = ?2)
318               AND (?3 IS NULL OR created_at_ms < ?3 OR (created_at_ms = ?3 AND id < ?4))
319             ORDER BY created_at_ms DESC, id DESC LIMIT ?5"
320        ))?;
321        let rows = stmt.query_map(
322            params![memory_kind, agent_id, before.map(|(ms, _)| ms), before.map(|(_, id)| id), limit.clamp(1, 500) as i64],
323            dream_from,
324        )?;
325        Ok(rows.collect::<Result<Vec<_>, _>>()?)
326    }
327
328    /// Move a dream from `from` to `to` in one conditional update, so two callers that both saw it queued cannot both start
329    /// it. `Ok(false)` when it was no longer in `from`, or the move is not one `state::can_move` allows. `detail` is the
330    /// hold reason for `held`, the error for `failed`, and ignored otherwise. A move out of `running` stamps `ended_at_ms`,
331    /// a move into it `started_at_ms`, and a decision (applied, rejected, reverted) `decided_at_ms` and `decided_by`.
332    pub fn dream_move(
333        &self,
334        id: &str,
335        from: &str,
336        to: &str,
337        detail: &str,
338        by: &str,
339        now_ms: i64,
340    ) -> Result<bool, StoreError> {
341        if !state::can_move(from, to) {
342            return Ok(false);
343        }
344        let hold = if to == state::HELD { detail } else { "" };
345        let error = if to == state::FAILED { detail } else { "" };
346        let decided = matches!(to, state::APPLIED | state::REJECTED | state::REVERTED);
347        let conn = self.conn.lock().unwrap();
348        let n = conn.execute(
349            "UPDATE db_dreams SET state = ?3, hold_reason = ?4, error = ?5,
350                 started_at_ms = CASE WHEN ?3 = 'running' THEN ?8 ELSE started_at_ms END,
351                 ended_at_ms = CASE WHEN ?2 = 'running' THEN ?8 ELSE ended_at_ms END,
352                 decided_at_ms = CASE WHEN ?6 THEN ?8 ELSE decided_at_ms END,
353                 decided_by = CASE WHEN ?6 THEN ?7 ELSE decided_by END
354             WHERE id = ?1 AND state = ?2",
355            params![id, from, to, hold, error, decided, by, now_ms],
356        )?;
357        Ok(n == 1)
358    }
359
360    /// What a pass read, what it cost and which model and account it used, written when the model call ends.
361    pub fn dream_set_result(&self, id: &str, r: &DreamResult) -> Result<bool, StoreError> {
362        let conn = self.conn.lock().unwrap();
363        let n = conn.execute(
364            "UPDATE db_dreams SET model = ?2, account_id = ?3, read_set = ?4, caps_hit = ?5, input_tokens = ?6,
365                 output_tokens = ?7, cost_usd = ?8, cost_known = ?9 WHERE id = ?1",
366            params![id, r.model, r.account_id, r.read_set, r.caps_hit, r.input_tokens, r.output_tokens, r.cost.unwrap_or(0.0), r.cost.is_some() as i64],
367        )?;
368        Ok(n == 1)
369    }
370
371    /// Record a dream's proposed operations, numbered in the order given, all or none. A dream's proposal is written once:
372    /// a second call for the same dream fails on the `(dream_id, seq)` index.
373    pub fn dream_ops_insert(&self, dream_id: &str, ops: &[DreamOp]) -> Result<(), StoreError> {
374        let mut conn = self.conn.lock().unwrap();
375        let tx = conn.transaction()?;
376        for (i, o) in ops.iter().enumerate() {
377            tx.execute(
378                &format!("INSERT INTO db_dream_ops ({OP_COLS}) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14)"),
379                params![
380                    o.id, dream_id, i as i64, o.op, o.filename, o.merged_from, o.base_hash, o.base_text, o.new_text, o.reason,
381                    o.evidence, o.flags, o.applied_version_id, o.merged_bases,
382                ],
383            )?;
384        }
385        tx.commit()?;
386        Ok(())
387    }
388
389    /// A dream's operations, in the order they were proposed.
390    pub fn dream_ops(&self, dream_id: &str) -> Result<Vec<DreamOp>, StoreError> {
391        let conn = self.conn.lock().unwrap();
392        let mut stmt = conn.prepare(&format!(
393            "SELECT {OP_COLS} FROM db_dream_ops WHERE dream_id = ?1 ORDER BY seq"
394        ))?;
395        let rows = stmt.query_map(params![dream_id], op_from)?;
396        Ok(rows.collect::<Result<Vec<_>, _>>()?)
397    }
398
399    /// Note the memory version an applied operation wrote, so a revert knows what to undo. Only an operation not yet
400    /// applied takes one: `Ok(false)` when it already has a version or does not exist.
401    pub fn dream_op_set_applied(&self, op_id: &str, version_id: &str) -> Result<bool, StoreError> {
402        let conn = self.conn.lock().unwrap();
403        let n = conn.execute(
404            "UPDATE db_dream_ops SET applied_version_id = ?2 WHERE id = ?1 AND applied_version_id = ''",
405            params![op_id, version_id],
406        )?;
407        Ok(n == 1)
408    }
409}
410
411#[cfg(test)]
412#[path = "dreams_tests.rs"]
413mod tests;