Skip to main content

agentmux_srv_core/backend/memory/
dream_apply.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What applying a dream's proposal, or reverting it, would do to a memory's files (SPEC_DREAMS §2.6, §9).
5//!
6//! A pure plan over the proposal's operations and the files' heads as they are now. It reads nothing and writes nothing:
7//! the caller (srv) reads the heads, runs the steps as ordinary versioned writes with `source = dream`, and moves the
8//! dream. The plan is all or nothing: if any file a step touches is not as the pass read it, no step is returned and the
9//! files that changed are named, so a pass never overwrites a newer version.
10
11use crate::backend::storage::agent_native_memory_versions::content_hash;
12use crate::backend::storage::dreams::{op, DreamOp};
13
14/// What a file must be like for a step to run.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum Expect {
17    /// The file does not exist.
18    Absent,
19    /// The file exists and its content hashes to this.
20    Hash(String),
21}
22
23/// What a step does to its file.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub enum Change {
26    Write(String),
27    Delete,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Step {
32    /// The operation this step belongs to: the one whose `applied_version_id` a write notes.
33    pub op_id: String,
34    pub file: String,
35    pub expect: Expect,
36    pub change: Change,
37    /// What the file is like once the step has run. A file already like this is a step done by an earlier, interrupted
38    /// run: it is left out of the plan, so an apply or a revert that stopped half way is finished by running it again.
39    pub target: Expect,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Plan {
44    /// Every step may run, in this order.
45    Ready(Vec<Step>),
46    /// These files are not as the pass read them (or, for a revert, as the dream left them): nothing runs.
47    Stale(Vec<String>),
48    /// The record cannot be planned from (unreadable lists, a file named twice, a merge with no record of a file it
49    /// removes): nothing runs.
50    Malformed(String),
51}
52
53/// A file's content hash now, or `None` when it does not exist.
54pub type Heads<'a> = &'a dyn Fn(&str) -> Option<String>;
55
56struct MergedBase {
57    file: String,
58    hash: String,
59    text: String,
60}
61
62fn merged_bases(o: &DreamOp) -> Result<Vec<MergedBase>, String> {
63    let names: Vec<String> = serde_json::from_str(&o.merged_from).map_err(|e| format!("{}: merged_from: {e}", o.id))?;
64    let bases: Vec<serde_json::Value> =
65        serde_json::from_str(&o.merged_bases).map_err(|e| format!("{}: merged_bases: {e}", o.id))?;
66    let mut out = Vec::new();
67    for name in &names {
68        let b = bases
69            .iter()
70            .find(|b| b["file"].as_str() == Some(name.as_str()))
71            .ok_or_else(|| format!("{}: no record of {name}, which the merge removes", o.id))?;
72        out.push(MergedBase {
73            file: name.clone(),
74            hash: b["hash"].as_str().unwrap_or_default().to_string(),
75            text: b["text"].as_str().unwrap_or_default().to_string(),
76        });
77    }
78    Ok(out)
79}
80
81fn expect_base(hash: &str) -> Expect {
82    if hash.is_empty() {
83        Expect::Absent
84    } else {
85        Expect::Hash(hash.to_string())
86    }
87}
88
89fn step(o: &DreamOp, file: &str, expect: Expect, change: Change) -> Step {
90    let target = match &change {
91        Change::Write(text) => Expect::Hash(content_hash(text)),
92        Change::Delete => Expect::Absent,
93    };
94    Step { op_id: o.id.clone(), file: file.to_string(), expect, change, target }
95}
96
97fn holds(now: &Option<String>, e: &Expect) -> bool {
98    match e {
99        Expect::Absent => now.is_none(),
100        Expect::Hash(h) => now.as_deref().is_some_and(|n| n.eq_ignore_ascii_case(h)),
101    }
102}
103
104/// The steps that apply `ops`, if every file they touch is as the pass read it.
105pub fn plan_apply(ops: &[DreamOp], heads: Heads) -> Plan {
106    let mut steps = Vec::new();
107    for o in ops {
108        match o.op.as_str() {
109            op::ADD => steps.push(step(o, &o.filename, Expect::Absent, Change::Write(o.new_text.clone()))),
110            op::REWRITE => steps.push(step(o, &o.filename, expect_base(&o.base_hash), Change::Write(o.new_text.clone()))),
111            op::REMOVE => steps.push(step(o, &o.filename, expect_base(&o.base_hash), Change::Delete)),
112            op::MERGE => {
113                steps.push(step(o, &o.filename, expect_base(&o.base_hash), Change::Write(o.new_text.clone())));
114                match merged_bases(o) {
115                    Ok(bases) => {
116                        steps.extend(bases.iter().map(|b| step(o, &b.file, Expect::Hash(b.hash.clone()), Change::Delete)))
117                    }
118                    Err(e) => return Plan::Malformed(e),
119                }
120            }
121            other => return Plan::Malformed(format!("{}: unknown operation {other:?}", o.id)),
122        }
123    }
124    settle(steps, heads)
125}
126
127/// The steps that undo what `ops` applied, if every file is still as the dream left it. Only an operation that was
128/// applied (it noted the version it wrote) is undone.
129pub fn plan_revert(ops: &[DreamOp], heads: Heads) -> Plan {
130    let mut steps = Vec::new();
131    for o in ops.iter().filter(|o| !o.applied_version_id.is_empty()) {
132        let left = Expect::Hash(content_hash(&o.new_text));
133        match o.op.as_str() {
134            op::ADD => steps.push(step(o, &o.filename, left, Change::Delete)),
135            op::REWRITE => steps.push(step(o, &o.filename, left, Change::Write(o.base_text.clone()))),
136            op::REMOVE => steps.push(step(o, &o.filename, Expect::Absent, Change::Write(o.base_text.clone()))),
137            op::MERGE => {
138                let back = if o.base_hash.is_empty() { Change::Delete } else { Change::Write(o.base_text.clone()) };
139                steps.push(step(o, &o.filename, left, back));
140                match merged_bases(o) {
141                    Ok(bases) => {
142                        steps.extend(bases.into_iter().map(|b| step(o, &b.file, Expect::Absent, Change::Write(b.text))))
143                    }
144                    Err(e) => return Plan::Malformed(e),
145                }
146            }
147            other => return Plan::Malformed(format!("{}: unknown operation {other:?}", o.id)),
148        }
149    }
150    settle(steps, heads)
151}
152
153/// Check the steps against the heads: a file named twice is malformed, a step already done is left out, a file that is
154/// neither as the step expects nor as it leaves it is stale.
155fn settle(steps: Vec<Step>, heads: Heads) -> Plan {
156    let mut seen: Vec<&str> = Vec::new();
157    for s in &steps {
158        if seen.contains(&s.file.as_str()) {
159            return Plan::Malformed(format!("{} is touched by more than one step", s.file));
160        }
161        seen.push(&s.file);
162    }
163    let mut todo = Vec::new();
164    let mut stale = Vec::new();
165    for s in steps {
166        let now = heads(&s.file);
167        if holds(&now, &s.target) {
168            continue;
169        }
170        if holds(&now, &s.expect) {
171            todo.push(s);
172        } else {
173            stale.push(s.file);
174        }
175    }
176    if stale.is_empty() {
177        Plan::Ready(todo)
178    } else {
179        Plan::Stale(stale)
180    }
181}
182
183#[cfg(test)]
184#[path = "dream_apply_tests.rs"]
185mod tests;