Skip to main content

agentmux_srv/server/app_api/
dream_exec.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Apply, reject and revert a personal-memory dream (docs/specs/SPEC_DREAMS_BACKGROUND_MEMORY_ORGANIZING_2026_11_27.md
5//! §2.6, §9; build step 3). The plan, what each file must be like and what to do to it, is `memory::dream_apply`; this
6//! runs it.
7//!
8//! Each file write is the ordinary versioned write, with the version recorded first and the label `dream` set here by
9//! srv (a caller can never name it: `source_for_caller`), so the drift detector finds the file matching its latest
10//! version and records nothing, history and diff show the dream's change as a version, and a revert is one more version.
11//! A removal deletes the file and its mirror row; the memory record notes it at the next reconcile, as it does a file
12//! the agent removed. Global Memory is not here: its entries are rows, not files.
13//!
14//! The plan is checked before anything runs and each file again just before it is touched. A step whose file is already
15//! as the step leaves it is not run again, so an apply or a revert that stops half way (an I/O error) is finished by
16//! running it again. An operation is noted as applied as soon as its files are done; a half-applied dream cannot be
17//! rejected.
18
19use std::collections::HashMap;
20use std::path::Path;
21use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
22
23use serde_json::json;
24
25use super::{AppState, SelfOwner};
26use crate::backend::memory::dream_apply::{plan_apply, plan_revert, Change, Expect, Plan, Step};
27use crate::backend::storage::agent_native_memory_versions::content_hash;
28use crate::backend::storage::dreams::{memory_kind, state as dstate, Dream, DreamOp};
29
30/// The sentinel an operation that only removed files notes as the version it wrote (it wrote none).
31pub(crate) const REMOVED: &str = "removed";
32
33/// One decision about a dream at a time. The RPC engine runs requests at once (two windows, a double click), and an
34/// apply that is checked as `ready`, writes files and only then moves the dream must not meet a reject that sees no
35/// applied operation yet: the files would change under a rejected dream, which a revert (it needs `applied`) cannot undo.
36/// The guard is held to the end of the apply, reject or revert.
37fn decision_lock(dream_id: &str) -> Arc<Mutex<()>> {
38    static LOCKS: OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> = OnceLock::new();
39    let mut held = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
40    // A dream nobody is deciding about holds no lock: the map keeps only those in use.
41    held.retain(|_, lock| Arc::strong_count(lock) > 1);
42    held.entry(dream_id.to_string()).or_default().clone()
43}
44
45fn guard(lock: &Arc<Mutex<()>>) -> MutexGuard<'_, ()> {
46    lock.lock().unwrap_or_else(|p| p.into_inner())
47}
48
49/// How an apply or a revert ended.
50#[derive(Debug, PartialEq, Eq)]
51pub(crate) enum Ran {
52    /// Every step ran; the dream moved on.
53    Done { steps: usize },
54    /// These files are not as the plan needs them: nothing was changed by this call and the dream did not move.
55    Stale(Vec<String>),
56}
57
58fn load(state: &AppState, dream_id: &str, label: &str) -> Result<(Dream, Vec<DreamOp>), String> {
59    let dream = state
60        .id_store
61        .dream_get(dream_id)
62        .map_err(|e| format!("{label}: store: {e}"))?
63        .ok_or_else(|| format!("{label}: dream {dream_id} not found"))?;
64    if dream.memory_kind != memory_kind::PERSONAL {
65        return Err(format!("{label}: only a personal memory's dream can be run from here"));
66    }
67    let ops = state.id_store.dream_ops(dream_id).map_err(|e| format!("{label}: store: {e}"))?;
68    Ok((dream, ops))
69}
70
71/// Move the dream, or say why not. A false answer means another call moved it first.
72fn move_to(state: &AppState, d: &Dream, from: &str, to: &str, by: &str, now_ms: i64, label: &str) -> Result<(), String> {
73    match state.id_store.dream_move(&d.id, from, to, "", by, now_ms) {
74        Ok(true) => Ok(()),
75        Ok(false) => Err(format!("{label}: the dream is no longer {from}")),
76        Err(e) => Err(format!("{label}: store: {e}")),
77    }
78}
79
80/// The hash of a live memory file, `None` when it does not exist. Never the mirror: the files are what apply changes.
81fn live_hash(dir: &Path, file: &str) -> Result<Option<String>, String> {
82    let path = dir.join(file);
83    match std::fs::symlink_metadata(&path) {
84        Ok(m) if m.file_type().is_file() => {
85            use std::io::Read;
86            let mut buf = Vec::new();
87            std::fs::File::open(&path)
88                .and_then(|f| f.take(crate::server::native_memory_handlers::MAX_MEMORY_FILE_BYTES).read_to_end(&mut buf))
89                .map_err(|e| format!("{file}: {e}"))?;
90            Ok(Some(content_hash(&String::from_utf8_lossy(&buf))))
91        }
92        Ok(_) => Err(format!("{file} is not a regular file")),
93        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
94        Err(e) => Err(format!("{file}: {e}")),
95    }
96}
97
98/// Every file the operations name, as it is now.
99fn read_heads(dir: &Path, ops: &[DreamOp]) -> Result<std::collections::HashMap<String, Option<String>>, String> {
100    let mut heads = std::collections::HashMap::new();
101    for o in ops {
102        let merged: Vec<String> = serde_json::from_str(&o.merged_from).unwrap_or_default();
103        for f in std::iter::once(&o.filename).chain(merged.iter()) {
104            if !heads.contains_key(f) {
105                crate::server::native_memory_handlers::validate_memory_filename(f)?;
106                heads.insert(f.clone(), live_hash(dir, f)?);
107            }
108        }
109    }
110    Ok(heads)
111}
112
113/// Write `content` as `file`'s next version and into the folder; returns the version's id.
114fn put(state: &AppState, owner_id: &str, dir: &Path, file: &str, content: &str, source: &str, detail: &str) -> Result<(), String> {
115    std::fs::create_dir_all(dir).map_err(|e| format!("{file}: mkdir: {e}"))?;
116    // The version first, as the write path does: the drift detector then finds the file matching its latest version.
117    let version = state
118        .id_store
119        .agent_native_memory_version_insert(owner_id, file, content, source, detail, "")
120        .map_err(|e| format!("{file}: version: {e}"))?;
121    crate::backend::memory::reconcile::record_agentmux_write(owner_id, dir, file, content.as_bytes(), source, detail);
122    let dest = dir.join(file);
123    let tmp = dir.join(format!(".{}.{}.tmp", file, uuid::Uuid::new_v4()));
124    if let Err(e) = std::fs::write(&tmp, content) {
125        let _ = std::fs::remove_file(&tmp);
126        return Err(format!("{file}: write: {e}"));
127    }
128    if let Err(e) = std::fs::rename(&tmp, &dest) {
129        let _ = std::fs::remove_file(&tmp);
130        return Err(format!("{file}: rename: {e}"));
131    }
132    let meta = std::fs::metadata(&dest).ok();
133    let size = meta.as_ref().map(|m| m.len() as i64).unwrap_or(content.len() as i64);
134    let mtime = meta
135        .and_then(|m| m.modified().ok())
136        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
137        .map(|d| d.as_millis() as i64)
138        .unwrap_or(0);
139    let kind = crate::server::native_memory_handlers::parse_memory_frontmatter_type(content);
140    if let Err(e) = state.id_store.agent_native_memory_upsert(owner_id, file, content, kind.as_deref(), &dest.to_string_lossy(), size, mtime) {
141        tracing::warn!(file, error = %e, "dream: mirror upsert failed (non-fatal)");
142    }
143    Ok(())
144}
145
146/// Remove `file` and its mirror row. A file already gone is not an error.
147fn take_away(state: &AppState, owner_id: &str, dir: &Path, file: &str) -> Result<(), String> {
148    match std::fs::remove_file(dir.join(file)) {
149        Ok(()) => {}
150        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
151        Err(e) => return Err(format!("{file}: remove: {e}")),
152    }
153    if let Err(e) = state.id_store.agent_native_memory_delete(owner_id, file) {
154        tracing::warn!(file, error = %e, "dream: mirror delete failed (non-fatal)");
155    }
156    Ok(())
157}
158
159/// Run one step after checking its file once more.
160fn run_step(state: &AppState, owner_id: &str, dir: &Path, s: &Step, source: &str, detail: &str) -> Result<(), String> {
161    let now = live_hash(dir, &s.file)?;
162    let as_planned = match &s.expect {
163        Expect::Absent => now.is_none(),
164        Expect::Hash(h) => now.as_deref().is_some_and(|n| n.eq_ignore_ascii_case(h)),
165    };
166    if !as_planned {
167        return Err(format!("{} changed while the dream was being applied", s.file));
168    }
169    match &s.change {
170        Change::Write(text) => put(state, owner_id, dir, &s.file, text, source, detail),
171        Change::Delete => take_away(state, owner_id, dir, &s.file),
172    }
173}
174
175/// What an applied operation notes: the version that wrote its file, else that it only removed files.
176fn note_for(state: &AppState, owner_id: &str, o: &DreamOp) -> String {
177    if o.op == crate::backend::storage::dreams::op::REMOVE {
178        return REMOVED.to_string();
179    }
180    match state.id_store.agent_native_memory_version_latest(owner_id, &o.filename) {
181        Ok(Some(v)) if v.content_hash == content_hash(&o.new_text) => v.id,
182        _ => REMOVED.to_string(),
183    }
184}
185
186/// Run `steps`, one operation's steps after another's. `after_op` is told as each operation's steps finish.
187fn run_steps(
188    state: &AppState,
189    owner_id: &str,
190    dir: &Path,
191    steps: &[Step],
192    source: &str,
193    detail_of: &dyn Fn(&str) -> String,
194    mut after_op: impl FnMut(&str) -> Result<(), String>,
195) -> Result<(), String> {
196    let mut i = 0;
197    while i < steps.len() {
198        let op_id = steps[i].op_id.clone();
199        while i < steps.len() && steps[i].op_id == op_id {
200            run_step(state, owner_id, dir, &steps[i], source, &detail_of(&op_id))?;
201            i += 1;
202        }
203        after_op(&op_id)?;
204    }
205    Ok(())
206}
207
208fn publish(state: &AppState, owner_id: &str) {
209    state.broker.publish_event_for::<crate::backend::mps_events::AgentMemoryChanged>(owner_id, &(), vec![], 0);
210}
211
212/// The owner and the folder a dream's files are in.
213fn place(state: &AppState, d: &Dream, label: &str) -> Result<(String, std::path::PathBuf), String> {
214    if d.agent_id.is_empty() {
215        return Err(format!("{label}: the dream names no agent"));
216    }
217    let owner = SelfOwner::Uid(&d.agent_id);
218    let owner_id = owner.owner_id(&state.mstore).map_err(|e| format!("{label}: {e}"))?;
219    let dir = owner.dir_for_write(&state.mstore).map_err(|e| format!("{label}: {e}"))?;
220    Ok((owner_id, dir))
221}
222
223/// Apply a `ready` dream, whole or not at all. `Stale` when a file is not as the pass read it: nothing is changed.
224pub(crate) fn dream_apply_impl(state: &AppState, dream_id: &str, decided_by: &str, now_ms: i64) -> Result<Ran, String> {
225    const L: &str = "dream.apply";
226    let lock = decision_lock(dream_id);
227    let _one = guard(&lock);
228    let (dream, ops) = load(state, dream_id, L)?;
229    if dream.state != dstate::READY {
230        return Err(format!("{L}: the dream is {}, not ready for review", dream.state));
231    }
232    let (owner_id, dir) = place(state, &dream, L)?;
233    // An apply that stopped half way is resumed: only the operations not yet applied are planned, and of those only the
234    // steps not yet done run.
235    let todo: Vec<DreamOp> = ops.iter().filter(|o| o.applied_version_id.is_empty()).cloned().collect();
236    let heads = read_heads(&dir, &todo).map_err(|e| format!("{L}: {e}"))?;
237    let steps = match plan_apply(&todo, &|f| heads.get(f).cloned().flatten()) {
238        Plan::Ready(s) => s,
239        Plan::Stale(files) => return Ok(Ran::Stale(files)),
240        Plan::Malformed(why) => return Err(format!("{L}: {why}")),
241    };
242    let n = steps.len();
243    let result = run_steps(
244        state,
245        &owner_id,
246        &dir,
247        &steps,
248        "dream",
249        &|op_id| json!({ "dream_id": dream.id, "op_id": op_id }).to_string(),
250        |op_id| match todo.iter().find(|o| o.id == op_id) {
251            Some(o) => state
252                .id_store
253                .dream_op_set_applied(op_id, &note_for(state, &owner_id, o))
254                .map(|_| ())
255                .map_err(|e| format!("store: {e}")),
256            None => Ok(()),
257        },
258    );
259    publish(state, &owner_id);
260    result.map_err(|e| format!("{L}: stopped part way ({e}); apply again to finish"))?;
261    // An operation whose steps were all done already (by the run that stopped) has none left to run: note it now.
262    for o in &todo {
263        state.id_store.dream_op_set_applied(&o.id, &note_for(state, &owner_id, o)).map_err(|e| format!("{L}: store: {e}"))?;
264    }
265    move_to(state, &dream, dstate::READY, dstate::APPLIED, decided_by, now_ms, L)?;
266    Ok(Ran::Done { steps: n })
267}
268
269/// Reject a `ready` dream: nothing is written. A half-applied dream cannot be rejected.
270pub(crate) fn dream_reject_impl(state: &AppState, dream_id: &str, decided_by: &str, now_ms: i64) -> Result<(), String> {
271    const L: &str = "dream.reject";
272    let lock = decision_lock(dream_id);
273    let _one = guard(&lock);
274    let (dream, ops) = load_any(state, dream_id, L)?;
275    if ops.iter().any(|o| !o.applied_version_id.is_empty()) {
276        return Err(format!("{L}: the dream is partly applied: apply it again to finish, or revert it"));
277    }
278    move_to(state, &dream, dstate::READY, dstate::REJECTED, decided_by, now_ms, L)
279}
280
281/// A dream of either kind, for a decision that writes no files.
282fn load_any(state: &AppState, dream_id: &str, label: &str) -> Result<(Dream, Vec<DreamOp>), String> {
283    let dream = state
284        .id_store
285        .dream_get(dream_id)
286        .map_err(|e| format!("{label}: store: {e}"))?
287        .ok_or_else(|| format!("{label}: dream {dream_id} not found"))?;
288    let ops = state.id_store.dream_ops(dream_id).map_err(|e| format!("{label}: store: {e}"))?;
289    Ok((dream, ops))
290}
291
292/// Revert an `applied` dream: each file back as the pass read it, as new versions (`revert`), while each file is still
293/// what the dream left. `Stale` names a file that was edited since: nothing is changed.
294pub(crate) fn dream_revert_impl(state: &AppState, dream_id: &str, decided_by: &str, now_ms: i64) -> Result<Ran, String> {
295    const L: &str = "dream.revert";
296    let lock = decision_lock(dream_id);
297    let _one = guard(&lock);
298    let (dream, ops) = load(state, dream_id, L)?;
299    if dream.state != dstate::APPLIED {
300        return Err(format!("{L}: the dream is {}, not applied", dream.state));
301    }
302    let (owner_id, dir) = place(state, &dream, L)?;
303    let heads = read_heads(&dir, &ops).map_err(|e| format!("{L}: {e}"))?;
304    let steps = match plan_revert(&ops, &|f| heads.get(f).cloned().flatten()) {
305        Plan::Ready(s) => s,
306        Plan::Stale(files) => return Ok(Ran::Stale(files)),
307        Plan::Malformed(why) => return Err(format!("{L}: {why}")),
308    };
309    let n = steps.len();
310    let result = run_steps(
311        state,
312        &owner_id,
313        &dir,
314        &steps,
315        "revert",
316        &|_| json!({ "reverted_dream": dream.id }).to_string(),
317        |_| Ok(()),
318    );
319    publish(state, &owner_id);
320    result.map_err(|e| format!("{L}: stopped part way ({e}); revert again to finish"))?;
321    move_to(state, &dream, dstate::APPLIED, dstate::REVERTED, decided_by, now_ms, L)?;
322    Ok(Ran::Done { steps: n })
323}
324
325#[cfg(test)]
326#[path = "tests/dream_exec_tests.rs"]
327mod tests;