agentmux_srv_core/backend/memory/
dream_proposal.rs1use serde::Deserialize;
22use serde_json::json;
23
24use crate::backend::storage::dreams::{op, DreamOp};
25
26pub mod label {
29 pub const PERSON: &str = "person";
30 pub const AGENT: &str = "agent";
31 pub const MEMORY: &str = "memory";
32}
33
34pub 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
45pub const MIN_QUOTE_CHARS: usize = 12;
47const MAX_REASON_CHARS: usize = 300;
49const MAX_QUOTES: usize = 6;
51const MAX_QUOTE_CHARS: usize = 400;
52const MAX_NAME_CHARS: usize = 128;
53
54#[derive(Debug, Clone)]
56pub struct MemoryFile {
57 pub name: String,
58 pub hash: String,
59 pub text: String,
60}
61
62#[derive(Debug, Clone)]
65pub struct Source {
66 pub label: &'static str,
67 pub name: String,
68 pub text: String,
69}
70
71pub struct Context<'a> {
73 pub files: &'a [MemoryFile],
74 pub omitted: &'a [String],
77 pub sources: &'a [Source],
78 pub protected: &'a [String],
80 pub max_file_bytes: usize,
82 pub max_ops: usize,
84}
85
86#[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
127fn 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
135pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157struct Added<'a> {
158 line: &'a str,
159 in_code: bool,
160}
161
162fn marks_code(line: &str) -> bool {
164 let low = line.to_lowercase();
165 low.contains("```") || low.contains("~~~") || low.contains("<pre") || low.contains("<code")
166}
167
168fn 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
193fn 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
222fn 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
242pub 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
270fn 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
349pub 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;