Skip to main content

agentmux_srv_core/backend/memory/
dream_proposal.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a Dreams pass's model answer becomes: a checked list of file operations (SPEC_DREAMS §2.5, §4, §6).
5//!
6//! The model has no tools and one turn; its answer is data. This module is where that data is held to the rules before
7//! anything is recorded or shown: the schema, the names it may touch, the size of what it writes, and whether each
8//! claim is backed by a quote that really is in a source the prompt carried. It runs no model, reads no file and
9//! writes nothing: the caller hands it the answer, the memory's files and the trusted sources, and gets the
10//! operations back (or the reason an operation was dropped).
11//!
12//! What it decides, so the model's behaviour is never relied on:
13//! - an operation on a name that is not a plain `.md` file, on a protected file, or on a file twice, is dropped;
14//! - a claim (an added, rewritten or merged text) with no quote that is a literal substring of a trusted source is
15//!   flagged `unsupported`; a quote of the model's own invention counts for nothing;
16//! - text the pass adds that looks like a command, a URL, a credential, a marker block, a rule that widens what an
17//!   agent may do, or a change to an identity or permission note, is flagged `risky:*`.
18//!
19//! A flagged operation is still recorded, so a person sees it with its label; it never applies on its own.
20
21use serde::Deserialize;
22use serde_json::json;
23
24use crate::backend::storage::dreams::{op, DreamOp};
25
26/// Where a quote came from. Only these are trusted: untrusted text is never in the prompt (§6.1), so nothing can be
27/// cited from it.
28pub mod label {
29    pub const PERSON: &str = "person";
30    pub const AGENT: &str = "agent";
31    pub const MEMORY: &str = "memory";
32}
33
34/// What an operation is marked with (the strings the Dreams pane shows).
35pub mod flag {
36    pub const UNSUPPORTED: &str = "unsupported";
37    pub const RISKY_COMMAND: &str = "risky:command";
38    pub const RISKY_URL: &str = "risky:url";
39    pub const RISKY_CREDENTIAL: &str = "risky:credential";
40    pub const RISKY_MARKER: &str = "risky:marker";
41    pub const RISKY_PERMISSION: &str = "risky:permission";
42    pub const RISKY_IDENTITY: &str = "risky:identity";
43}
44
45/// A quote shorter than this (trimmed, in characters) proves nothing: it would be found in any text.
46pub const MIN_QUOTE_CHARS: usize = 12;
47/// The longest reason kept, in characters.
48const MAX_REASON_CHARS: usize = 300;
49/// The longest evidence list kept per operation, and the longest quote kept in it.
50const MAX_QUOTES: usize = 6;
51const MAX_QUOTE_CHARS: usize = 400;
52const MAX_NAME_CHARS: usize = 128;
53
54/// One file of the memory as the pass read it. `hash` is the version the pass saw, which apply checks again.
55#[derive(Debug, Clone)]
56pub struct MemoryFile {
57    pub name: String,
58    pub hash: String,
59    pub text: String,
60}
61
62/// Text the prompt carried, under the label srv gave it. `name` is what a quote cites it by: a memory file's name, or
63/// a session's id.
64#[derive(Debug, Clone)]
65pub struct Source {
66    pub label: &'static str,
67    pub name: String,
68    pub text: String,
69}
70
71/// What the answer is held against.
72pub struct Context<'a> {
73    pub files: &'a [MemoryFile],
74    /// Names of files that exist but were not in the prompt (the input cap left them out). They can be neither read
75    /// from nor written to, and a new file may not take their name.
76    pub omitted: &'a [String],
77    pub sources: &'a [Source],
78    /// Files the pass may not touch (a system-tier Global Memory entry).
79    pub protected: &'a [String],
80    /// The most a written file may hold, in bytes.
81    pub max_file_bytes: usize,
82    /// The most operations an answer may carry.
83    pub max_ops: usize,
84}
85
86/// An operation that was dropped, and why. `index` is its place in the model's list.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Dropped {
89    pub index: usize,
90    pub why: String,
91}
92
93#[derive(Debug, Default)]
94pub struct Outcome {
95    pub ops: Vec<DreamOp>,
96    pub dropped: Vec<Dropped>,
97}
98
99#[derive(Deserialize)]
100#[serde(deny_unknown_fields)]
101struct Answer {
102    ops: Vec<Wanted>,
103}
104
105#[derive(Deserialize)]
106#[serde(deny_unknown_fields)]
107struct Wanted {
108    op: String,
109    file: String,
110    #[serde(default)]
111    merged_from: Vec<String>,
112    #[serde(default)]
113    new_text: String,
114    #[serde(default)]
115    reason: String,
116    #[serde(default)]
117    evidence: Vec<Quote>,
118}
119
120#[derive(Deserialize)]
121#[serde(deny_unknown_fields)]
122struct Quote {
123    source: String,
124    quote: String,
125}
126
127/// The answer without a code fence around it, when the model wrapped it in one.
128fn unfenced(raw: &str) -> &str {
129    let t = raw.trim();
130    let Some(rest) = t.strip_prefix("```") else { return t };
131    let rest = rest.split_once('\n').map_or(rest, |(_, body)| body);
132    rest.trim_end().strip_suffix("```").unwrap_or(rest).trim()
133}
134
135/// A memory file name the pass may touch: a plain `.md` name, no folder, no dot-file, no traversal.
136pub fn valid_name(name: &str) -> bool {
137    let ok_chars = name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
138    !name.is_empty()
139        && name.chars().count() <= MAX_NAME_CHARS
140        && ok_chars
141        && !name.starts_with('.')
142        && !name.contains("..")
143        && name.ends_with(".md")
144        && name.len() > ".md".len()
145}
146
147fn clip(s: &str, max_chars: usize) -> String {
148    s.chars().take(max_chars).collect()
149}
150
151/// A line the pass adds, and whether it is code: at or after the first code fence of the new text, or indented as
152/// code. It is conservative on purpose: a code block is what a reader may run, and Markdown has many ways to write
153/// one (any fence character and length, indented, inside a list or a quote, an HTML `<pre>`), so the scan does not
154/// try to tell where one ends or what language it is. Once the text opens a code block, every line the pass adds
155/// from there on asks for a person.
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157struct Added<'a> {
158    line: &'a str,
159    in_code: bool,
160}
161
162/// Whether a line opens or marks code: a fence run of backticks or tildes anywhere in it, or an HTML code tag.
163fn marks_code(line: &str) -> bool {
164    let low = line.to_lowercase();
165    low.contains("```") || low.contains("~~~") || low.contains("<pre") || low.contains("<code")
166}
167
168/// The lines of `new` that neither `base` nor the files merged into it already had: what the pass adds. A line the
169/// file already had is not new, even inside a code block.
170fn added_lines<'a>(new: &'a str, before: &[&str]) -> Vec<Added<'a>> {
171    let mut opened = false;
172    let mut out = Vec::new();
173    for raw in new.lines() {
174        opened |= marks_code(raw);
175        let line = raw.trim();
176        if line.is_empty() || before.iter().any(|b| b.lines().any(|x| x.trim() == line)) {
177            continue;
178        }
179        let indented = raw.starts_with("    ") || raw.starts_with('\t');
180        out.push(Added { line, in_code: opened || indented });
181    }
182    out
183}
184
185const COMMAND_MARKS: [&str; 10] = [
186    "curl ", "wget ", "| sh", "| bash", "rm -rf", "sudo ", "powershell ", "invoke-expression", "iex ", "eval ",
187];
188const MARKER_MARKS: [&str; 6] = ["[jekt", "[broadcast", "[agentmux]", "[bulletin", "[jekt-quoted", "[broadcast-quoted"];
189const WIDENING_MARKS: [&str; 8] =
190    ["without asking", "without confirm", "don't ask", "do not ask", "bypass", "skip the approval", "auto-approve", "always allow"];
191const IDENTITY_NAMES: [&str; 4] = ["identity", "permission", "persona", "soul"];
192
193/// The `risky:*` flags the added lines earn.
194fn risks(added: &[Added]) -> Vec<&'static str> {
195    let mut out = Vec::new();
196    for Added { line, in_code } in added {
197        let low = line.to_lowercase();
198        let hits = [
199            (*in_code || low.starts_with("$ ") || COMMAND_MARKS.iter().any(|m| low.contains(m)), flag::RISKY_COMMAND),
200            (low.contains("http://") || low.contains("https://"), flag::RISKY_URL),
201            (agentmux_common::redact::redact_secrets(line) != *line, flag::RISKY_CREDENTIAL),
202            (MARKER_MARKS.iter().any(|m| low.contains(m)), flag::RISKY_MARKER),
203            (
204                WIDENING_MARKS.iter().any(|m| low.contains(m)) || ((low.contains("always") || low.contains("never")) && low.contains("permission")),
205                flag::RISKY_PERMISSION,
206            ),
207        ];
208        for (hit, f) in hits {
209            if hit && !out.contains(&f) {
210                out.push(f);
211            }
212        }
213    }
214    out
215}
216
217fn identity_note(name: &str) -> bool {
218    let low = name.to_lowercase();
219    IDENTITY_NAMES.iter().any(|n| low.contains(n))
220}
221
222/// Checks each quote against the source it cites; returns the evidence as it is kept (with whether it held) and
223/// whether at least one held. A quote is kept cut to a bounded length, and only its checked form is trusted.
224fn check_quotes(quotes: &[Quote], sources: &[Source]) -> (Vec<serde_json::Value>, bool) {
225    let mut kept = Vec::new();
226    let mut any = false;
227    for q in quotes.iter().take(MAX_QUOTES) {
228        let source = sources.iter().find(|s| s.name == q.source);
229        let long_enough = q.quote.trim().chars().count() >= MIN_QUOTE_CHARS;
230        let held = long_enough && source.is_some_and(|s| s.text.contains(q.quote.trim()));
231        any |= held;
232        kept.push(json!({
233            "source": clip(&q.source, MAX_NAME_CHARS),
234            "label": source.map_or("unknown", |s| s.label),
235            "quote": clip(q.quote.trim(), MAX_QUOTE_CHARS),
236            "checked": held,
237        }));
238    }
239    (kept, any)
240}
241
242/// The model's answer, checked. `Err` when it is not the schema at all or carries more operations than allowed: the
243/// whole answer is discarded. Otherwise each operation is kept (with its flags) or dropped (with why).
244pub fn validate(raw: &str, dream_id: &str, ctx: &Context) -> Result<Outcome, String> {
245    let answer: Answer = serde_json::from_str(unfenced(raw)).map_err(|e| format!("not the schema: {e}"))?;
246    if answer.ops.len() > ctx.max_ops {
247        return Err(format!("{} operations, at most {} allowed", answer.ops.len(), ctx.max_ops));
248    }
249    let mut out = Outcome::default();
250    let mut touched: Vec<String> = Vec::new();
251    for (index, w) in answer.ops.iter().enumerate() {
252        match check_one(w, ctx, &touched) {
253            Ok(mut o) => {
254                touched.push(w.file.clone());
255                touched.extend(w.merged_from.iter().cloned());
256                o.id = format!("{dream_id}-op{index}");
257                o.dream_id = dream_id.to_string();
258                out.ops.push(o);
259            }
260            Err(why) => out.dropped.push(Dropped { index, why }),
261        }
262    }
263    Ok(out)
264}
265
266fn existing<'a>(ctx: &'a Context, name: &str) -> Option<&'a MemoryFile> {
267    ctx.files.iter().find(|f| f.name == name)
268}
269
270/// One wanted operation against the rules; `touched` is every name an earlier kept operation used.
271fn check_one(w: &Wanted, ctx: &Context, touched: &[String]) -> Result<DreamOp, String> {
272    if !matches!(w.op.as_str(), op::ADD | op::MERGE | op::REWRITE | op::REMOVE) {
273        return Err(format!("unknown operation {:?}", clip(&w.op, 24)));
274    }
275    let names: Vec<&String> = std::iter::once(&w.file).chain(w.merged_from.iter()).collect();
276    if let Some(bad) = names.iter().find(|n| !valid_name(n)) {
277        return Err(format!("not a memory file name: {:?}", clip(bad, 40)));
278    }
279    if let Some(p) = names.iter().find(|n| ctx.protected.contains(n)) {
280        return Err(format!("{p} is protected"));
281    }
282    if let Some(o) = names.iter().find(|n| ctx.omitted.contains(n)) {
283        return Err(format!("{o} exists but was not read"));
284    }
285    if let Some(t) = names.iter().find(|n| touched.contains(n)) {
286        return Err(format!("{t} is already touched by another operation"));
287    }
288    let base = existing(ctx, &w.file);
289    let writes = w.op != op::REMOVE;
290    match (w.op.as_str(), base) {
291        (op::ADD, Some(_)) => return Err(format!("{} already exists", w.file)),
292        (op::REWRITE | op::REMOVE, None) => return Err(format!("{} does not exist", w.file)),
293        _ => {}
294    }
295    if w.op == op::MERGE && w.merged_from.is_empty() {
296        return Err("a merge names the files it merges".into());
297    }
298    if w.op != op::MERGE && !w.merged_from.is_empty() {
299        return Err("only a merge names files it merges".into());
300    }
301    if let Some(m) = w.merged_from.iter().find(|m| existing(ctx, m).is_none() || **m == w.file) {
302        return Err(format!("{m} cannot be merged"));
303    }
304    if writes && w.new_text.trim().is_empty() {
305        return Err("a write with no text".into());
306    }
307    if writes && w.new_text.len() > ctx.max_file_bytes {
308        return Err(format!("{} is over the {} byte limit", w.file, ctx.max_file_bytes));
309    }
310    if w.op == op::REWRITE && base.is_some_and(|b| b.text == w.new_text) {
311        return Err("no change".into());
312    }
313    Ok(build(w, ctx, base))
314}
315
316fn build(w: &Wanted, ctx: &Context, base: Option<&MemoryFile>) -> DreamOp {
317    let writes = w.op != op::REMOVE;
318    let mut flags: Vec<&str> = Vec::new();
319    let (evidence, supported) = check_quotes(&w.evidence, ctx.sources);
320    if writes && !supported {
321        flags.push(flag::UNSUPPORTED);
322    }
323    if writes {
324        let merged_texts: Vec<&str> = w.merged_from.iter().filter_map(|m| existing(ctx, m)).map(|f| f.text.as_str()).collect();
325        let before: Vec<&str> = base.map(|b| b.text.as_str()).into_iter().chain(merged_texts).collect();
326        flags.extend(risks(&added_lines(&w.new_text, &before)));
327    }
328    if identity_note(&w.file) || w.merged_from.iter().any(|m| identity_note(m)) {
329        flags.push(flag::RISKY_IDENTITY);
330    }
331    DreamOp {
332        id: String::new(),
333        dream_id: String::new(),
334        seq: 0,
335        op: w.op.clone(),
336        filename: w.file.clone(),
337        merged_from: json!(w.merged_from).to_string(),
338        base_hash: base.map(|b| b.hash.clone()).unwrap_or_default(),
339        base_text: base.map(|b| b.text.clone()).unwrap_or_default(),
340        new_text: if writes { w.new_text.clone() } else { String::new() },
341        reason: clip(w.reason.trim(), MAX_REASON_CHARS),
342        evidence: json!(evidence).to_string(),
343        flags: json!(flags).to_string(),
344        applied_version_id: String::new(),
345        merged_bases: json!(w.merged_from.iter().filter_map(|m| existing(ctx, m)).map(|f| json!({"file": f.name, "hash": f.hash, "text": f.text})).collect::<Vec<_>>()).to_string(),
346    }
347}
348
349/// Whether an operation can only be applied by a person: it carries any flag.
350pub fn needs_person(flags_json: &str) -> bool {
351    serde_json::from_str::<Vec<String>>(flags_json).map_or(true, |f| !f.is_empty())
352}
353
354#[cfg(test)]
355#[path = "dream_proposal_tests.rs"]
356mod tests;