Skip to main content

caboodle/agent_memory/
lifecycle.rs

1use anyhow::{bail, Context, Result};
2use fs2::FileExt;
3use serde::{Deserialize, Serialize};
4use serde_json::{json, Value};
5use sha2::{Digest, Sha256};
6use std::{
7    fs,
8    io::Write,
9    path::{Path, PathBuf},
10    process::Command,
11};
12
13use super::BUNDLE_NAME;
14
15pub trait Runner {
16    fn run(&mut self, program: &str, args: &[String]) -> Result<String>;
17    fn input(&mut self, _program: &str, _args: &[String], _body: &str) -> Result<String> {
18        bail!("runner cannot exchange stdio metadata");
19    }
20    fn report(&mut self, program: &str, args: &[String]) -> Result<String> {
21        self.run(program, args)
22    }
23}
24pub struct System;
25impl Runner for System {
26    fn run(&mut self, program: &str, args: &[String]) -> Result<String> {
27        let out = Command::new(program)
28            .args(args)
29            .output()
30            .with_context(|| format!("start {program}"))?;
31        if !out.status.success() {
32            bail!(
33                "{program} refused or failed (exit {:?}); no success claimed",
34                out.status.code()
35            );
36        }
37        String::from_utf8(out.stdout).context("command returned non-UTF8 output")
38    }
39    fn input(&mut self, program: &str, args: &[String], body: &str) -> Result<String> {
40        use std::{
41            io::Read,
42            process::Stdio,
43            time::{Duration, Instant},
44        };
45        let mut child = Command::new(program)
46            .args(args)
47            .stdin(Stdio::piped())
48            .stdout(Stdio::piped())
49            .stderr(Stdio::null())
50            .spawn()?;
51        if let Err(error) = child
52            .stdin
53            .take()
54            .context("no metadata stdin")?
55            .write_all(body.as_bytes())
56        {
57            let _ = child.kill();
58            let _ = child.wait();
59            return Err(error.into());
60        }
61        let stdout = child.stdout.take().context("no metadata stdout")?;
62        let reader = std::thread::spawn(move || {
63            let mut out = Vec::new();
64            stdout
65                .take(4 * 1024 * 1024 + 1)
66                .read_to_end(&mut out)
67                .map(|_| out)
68        });
69        let deadline = Instant::now() + Duration::from_secs(10);
70        let status = loop {
71            match child.try_wait() {
72                Ok(Some(status)) => break status,
73                Ok(None) if Instant::now() < deadline => {
74                    std::thread::sleep(Duration::from_millis(20))
75                }
76                _ => {
77                    let _ = child.kill();
78                    let _ = child.wait();
79                    let _ = reader.join();
80                    bail!("stdio metadata probe failed or exceeded deadline");
81                }
82            }
83        };
84        let out = reader
85            .join()
86            .map_err(|_| anyhow::anyhow!("metadata reader failed"))??;
87        if !status.success() || out.len() > 4 * 1024 * 1024 {
88            bail!("stdio metadata probe refused or exceeded output bound");
89        }
90        String::from_utf8(out).context("metadata response is not UTF8")
91    }
92    fn report(&mut self, program: &str, args: &[String]) -> Result<String> {
93        let out = Command::new(program)
94            .args(args)
95            .output()
96            .context("read owner report")?;
97        if !matches!(out.status.code(), Some(0..=2)) {
98            bail!("owner check could not run");
99        }
100        String::from_utf8(out.stdout).context("owner returned non-UTF8 report")
101    }
102}
103
104#[derive(Clone, Serialize, Deserialize)]
105#[serde(deny_unknown_fields)]
106pub struct Change {
107    pub path: PathBuf,
108    pub before: Option<String>,
109    pub after: String,
110}
111#[derive(Clone, Serialize, Deserialize)]
112#[serde(deny_unknown_fields)]
113pub struct Plan {
114    pub schema: u32,
115    pub root: PathBuf,
116    pub source_revision: String,
117    pub redirect_mode: super::RedirectMode,
118    pub harness_configs: Vec<PathBuf>,
119    pub skill_directories: Vec<PathBuf>,
120    pub changes: Vec<Change>,
121    pub bundles: Vec<Value>,
122    pub expected_tools: Value,
123    pub id: String,
124}
125
126pub fn digest(bytes: &[u8]) -> String {
127    format!("{:x}", Sha256::digest(bytes))
128}
129fn plan_id(p: &Plan) -> Result<String> {
130    let mut clone = p.clone();
131    clone.id.clear();
132    Ok(digest(&serde_json::to_vec(&clone)?))
133}
134fn read(path: &Path) -> Result<Option<String>> {
135    match fs::symlink_metadata(path) {
136        Ok(m) if !m.is_file() || m.file_type().is_symlink() => bail!(
137            "configuration destination must be a regular file: {}",
138            path.display()
139        ),
140        Ok(m) if m.len() > 4 * 1024 * 1024 => bail!("configuration exceeds 4MiB bound"),
141        Ok(_) => Ok(Some(
142            fs::read_to_string(path).context("read configuration")?,
143        )),
144        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
145        Err(e) => Err(e).context("inspect configuration destination"),
146    }
147}
148fn absolute(path: &Path) -> Result<PathBuf> {
149    let full = if path.is_absolute() {
150        path.to_path_buf()
151    } else {
152        std::env::current_dir()?.join(path)
153    };
154    if full
155        .components()
156        .any(|c| matches!(c, std::path::Component::ParentDir))
157    {
158        bail!("paths must not contain parent traversals");
159    }
160    if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink()) {
161        bail!("refusing symlink destination");
162    }
163    let mut ancestor = full.clone();
164    let mut tail = Vec::new();
165    while fs::symlink_metadata(&ancestor).is_err() {
166        tail.push(
167            ancestor
168                .file_name()
169                .context("path has no existing ancestor")?
170                .to_os_string(),
171        );
172        ancestor = ancestor
173            .parent()
174            .context("path has no existing ancestor")?
175            .to_path_buf();
176    }
177    let mut canonical = ancestor.canonicalize()?;
178    for part in tail.into_iter().rev() {
179        canonical.push(part);
180    }
181    Ok(canonical)
182}
183pub fn private_write(path: &Path, body: &[u8]) -> Result<()> {
184    use std::os::unix::fs::PermissionsExt;
185    let parent = path.parent().context("file has no parent")?;
186    fs::create_dir_all(parent)?;
187    if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
188        bail!("refusing symlink destination");
189    }
190    let mut file = tempfile::NamedTempFile::new_in(parent)?;
191    let mode = fs::metadata(path)
192        .map(|m| m.permissions().mode() & 0o777)
193        .unwrap_or(0o600);
194    file.as_file()
195        .set_permissions(fs::Permissions::from_mode(mode))?;
196    file.write_all(body)?;
197    file.as_file().sync_all()?;
198    file.persist(path).map_err(|e| e.error)?;
199    fs::File::open(parent)?.sync_all()?;
200    Ok(())
201}
202
203pub struct Create<'a> {
204    pub root: &'a Path,
205    pub bobbin: &'a Path,
206    pub person: &'a str,
207    pub output: &'a Path,
208    pub source: &'a Path,
209    pub claude_home: &'a Path,
210    pub codex_home: &'a Path,
211    pub issuer_name: Option<&'a str>,
212    pub redirect_mode: super::RedirectMode,
213}
214pub fn create(options: Create<'_>, runner: &mut impl Runner) -> Result<()> {
215    let Create {
216        root,
217        bobbin,
218        person,
219        output,
220        source,
221        claude_home,
222        codex_home,
223        issuer_name,
224        redirect_mode,
225    } = options;
226    use std::os::unix::fs::DirBuilderExt;
227    let output = absolute(output)?;
228    if output.exists() {
229        bail!("plan output already exists; retain it for review/resume");
230    }
231    let root = absolute(root)?;
232    let harness_configs = vec![
233        absolute(&claude_home.join("settings.json"))?,
234        absolute(&codex_home.join("config.toml"))?,
235    ];
236    check_existing_redirect(&harness_configs)?;
237    let mut skill_directories = Vec::new();
238    let mut changes = Vec::new();
239    let crew_path = root.join("shantytown.toml");
240    let bobbin = absolute(bobbin)?;
241    let crew_before = read(&crew_path)?;
242    let bobbin_before = read(&bobbin)?;
243    let (mut crew, config) = super::render_with_mode(
244        crew_before.as_deref().unwrap_or(""),
245        bobbin_before.as_deref().unwrap_or(""),
246        person,
247        redirect_mode,
248    )?;
249    let capture_path = output.join("capture.json");
250    let mut document: toml_edit::DocumentMut = crew.parse()?;
251    document["env"]["CAMAYOC_CAPTURE_CONFIG"] =
252        toml_edit::value(capture_path.display().to_string());
253    crew = document.to_string();
254    let mut issuers = serde_json::Map::new();
255    if let Some(name) = issuer_name {
256        if name.trim().is_empty() || name.len() > 128 || name.chars().any(char::is_control) {
257            bail!("invalid issuer name");
258        }
259        issuers.insert(name.to_string(), json!(person));
260    }
261    changes.push(Change {
262        path: capture_path,
263        before: None,
264        after: serde_json::to_string_pretty(&json!({"prompt_author":person,"issuers":issuers}))?,
265    });
266    changes.push(Change {
267        path: crew_path,
268        before: crew_before,
269        after: crew,
270    });
271    changes.push(Change {
272        path: bobbin,
273        before: bobbin_before,
274        after: config,
275    });
276    // Read producer-generated surfaces from one exact immutable Git tree, not
277    // from mutable working-tree files or a separately maintained Tambo template.
278    let source = absolute(source)?;
279    let revision = runner
280        .run(
281            "git",
282            &[
283                "-C".into(),
284                source.display().to_string(),
285                "rev-parse".into(),
286                "HEAD".into(),
287            ],
288        )?
289        .trim()
290        .to_string();
291    if revision.len() != 40 || !revision.bytes().all(|b| b.is_ascii_hexdigit()) {
292        bail!("source has no full Git revision");
293    }
294    for (relative, destination) in [
295        (
296            "skills/camayoc-memory/SKILL.md",
297            claude_home.join("skills/camayoc-memory/SKILL.md"),
298        ),
299        (
300            ".agents/skills/camayoc-memory/SKILL.md",
301            codex_home.join("skills/camayoc-memory/SKILL.md"),
302        ),
303    ] {
304        let after = runner.run(
305            "git",
306            &[
307                "-C".into(),
308                source.display().to_string(),
309                "show".into(),
310                format!("{revision}:{relative}"),
311            ],
312        )?;
313        if after.len() > 1024 * 1024 || !after.contains("cy record") {
314            bail!("source does not contain the generated memory skill");
315        }
316        let path = absolute(&destination)?;
317        skill_directories.push(
318            path.parent()
319                .context("skill has no directory")?
320                .to_path_buf(),
321        );
322        changes.push(Change {
323            before: read(&path)?,
324            path,
325            after,
326        });
327    }
328    let catalogue = runner.run(
329        "git",
330        &[
331            "-C".into(),
332            source.display().to_string(),
333            "show".into(),
334            format!("{revision}:camayoc_cli/data/mcp-tools.json"),
335        ],
336    )?;
337    if catalogue.len() > 4 * 1024 * 1024 {
338        bail!("producer tool catalogue exceeds bound");
339    }
340    let catalogue: Value = serde_json::from_str(&catalogue)?;
341    if catalogue["schema"] != "camayoc-mcp-tools/1"
342        || catalogue["server"] != "camayoc-memory"
343        || !catalogue["tools"].as_array().is_some_and(|t| !t.is_empty())
344    {
345        bail!("unsupported producer catalogue");
346    }
347    let mut paths = std::collections::BTreeSet::new();
348    for change in &changes {
349        if !paths.insert(&change.path) {
350            bail!("memory destinations overlap");
351        }
352    }
353    let candidate = runner
354        .run("bobbin", &["hooks".into(), "bundle".into()])
355        .ok();
356    let bobbin_bundle =
357        crate::tool_bundles::resolve_with(&crate::hook_bundles::selected(["bobbin"]), |_| {
358            candidate.clone()
359        });
360    let mut plan = Plan {
361        schema: 1,
362        root,
363        source_revision: revision,
364        redirect_mode,
365        harness_configs,
366        skill_directories,
367        changes,
368        expected_tools: catalogue["tools"].clone(),
369        bundles: vec![
370            serde_json::from_str(&bobbin_bundle[0].1)?,
371            super::hooks::bundle(&output, redirect_mode),
372        ],
373        id: String::new(),
374    };
375    plan.id = plan_id(&plan)?;
376    fs::DirBuilder::new()
377        .recursive(true)
378        .mode(0o700)
379        .create(&output)?;
380    private_write(
381        &output.join("plan.json"),
382        &serde_json::to_vec_pretty(&plan)?,
383    )?;
384    for (i, bundle) in plan.bundles.iter().enumerate() {
385        private_write(
386            &output.join(format!("bundle-{i}.json")),
387            &serde_json::to_vec_pretty(bundle)?,
388        )?;
389    }
390    Ok(())
391}
392
393pub fn load(directory: &Path) -> Result<Plan> {
394    use std::os::unix::fs::{MetadataExt, PermissionsExt};
395    let path = directory.join("plan.json");
396    let meta = fs::symlink_metadata(&path)?;
397    let dir = fs::symlink_metadata(directory)?;
398    if meta.file_type().is_symlink()
399        || !meta.is_file()
400        || meta.len() > 16 * 1024 * 1024
401        || meta.permissions().mode() & 0o077 != 0
402        || dir.file_type().is_symlink()
403        || !dir.is_dir()
404        || dir.permissions().mode() & 0o077 != 0
405        || dir.uid() != meta.uid()
406    {
407        bail!("memory plan must be private regular data in its private directory");
408    }
409    let plan: Plan = serde_json::from_slice(&fs::read(path)?)?;
410    if plan.schema != 1 || plan.id != plan_id(&plan)? {
411        bail!("memory plan digest/schema does not match; regenerate for review");
412    }
413    Ok(plan)
414}
415fn st(plan: &Plan, args: &[&str], runner: &mut impl Runner) -> Result<String> {
416    let mut argv = vec!["--root".into(), plan.root.display().to_string()];
417    argv.extend(args.iter().map(|s| (*s).to_string()));
418    runner.run("st", &argv)
419}
420fn existing(plan: &Plan, runner: &mut impl Runner) -> Result<Vec<Value>> {
421    let v: Value = serde_json::from_str(&st(plan, &["ops", "hooks", "list", "--json"], runner)?)?;
422    if !v["errors"].as_array().is_some_and(Vec::is_empty) {
423        bail!("settings-owner registry unreadable");
424    }
425    Ok(v["bundles"]
426        .as_array()
427        .context("owner returned no bundles")?
428        .clone())
429}
430fn normalized(bundle: &Value) -> Value {
431    json!({"name":bundle["name"],"version":bundle["version"],"owner":bundle["owner"],"roles":bundle["roles"],
432        "hooks":bundle["hooks"].as_array().map(|rows| rows.iter().map(|r| json!({
433            "event":r["event"],"command":r["command"],"matcher":r["matcher"],"timeout":r["timeout"],"harnesses":r.get("harnesses").cloned().unwrap_or_else(|| json!(["claude","codex","opencode"]))})).collect::<Vec<_>>())})
434}
435/// The bundle as the owner registry holds it on disk, for drift checks. The
436/// owner's `hooks list` fills defaults (a hook with no `harnesses` is listed
437/// with every harness the owner supports, which grew when st learned agy), so
438/// comparing listings flagged an untouched bundle as changed (aegis-9uq.1).
439/// The registered file keeps absent fields absent; the listing is the fallback.
440fn registered(plan: &Plan, listed: &Value) -> Result<Value> {
441    let name = listed["name"]
442        .as_str()
443        .context("owner bundle name missing")?;
444    if !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
445        bail!("invalid bundle name");
446    }
447    match read(&plan.root.join("hook-bundles").join(format!("{name}.json")))? {
448        Some(raw) => Ok(serde_json::from_str(&raw)?),
449        None => Ok(listed.clone()),
450    }
451}
452const REBASED: &str = "rebased-changes.json";
453/// The plan's changes, with any target rebased on resume (see `rebase`)
454/// replaced by its recorded before/after. plan.json itself is never rewritten.
455pub fn changes(directory: &Path, plan: &Plan) -> Result<Vec<Change>> {
456    let mut out = plan.changes.clone();
457    if let Some(text) = read(&directory.join(REBASED))? {
458        let rebased: Vec<Change> = serde_json::from_str(&text)?;
459        for r in rebased {
460            match out.iter_mut().find(|c| c.path == r.path) {
461                Some(slot) => *slot = r,
462                None => bail!("rebased change is outside this plan: {}", r.path.display()),
463            }
464        }
465    }
466    Ok(out)
467}
468fn lines(text: &str) -> Vec<&str> {
469    text.split_inclusive('\n').collect()
470}
471/// Resume an interrupted apply over a target edited since review (aegis-9uq.1):
472/// only when the reviewed change is ONE block of inserted lines and every
473/// inserted line is present exactly once in the current bytes, in the reviewed
474/// order (operators may have added lines around or between them; measured on
475/// the Mac plan), and no line between them opens a TOML table (`[`), and the table headers
476/// above them are exactly the ones they were reviewed under. The new before is the current file without those lines, so a
477/// later restore removes only the reviewed lines and keeps the operator's
478/// edits; the new after is the current file. Anything else refuses.
479fn rebase(change: &Change, now: &str) -> Option<Change> {
480    let before = lines(change.before.as_deref()?);
481    let after = lines(&change.after);
482    let prefix = before
483        .iter()
484        .zip(&after)
485        .take_while(|(a, b)| a == b)
486        .count();
487    let suffix = before[prefix..]
488        .iter()
489        .rev()
490        .zip(after[prefix..].iter().rev())
491        .take_while(|(a, b)| a == b)
492        .count();
493    if prefix + suffix != before.len() || after.len() <= before.len() {
494        return None;
495    }
496    let block = &after[prefix..after.len() - suffix];
497    let current = lines(now);
498    let mut at = Vec::with_capacity(block.len());
499    for line in block {
500        let hits: Vec<usize> = (0..current.len())
501            .filter(|&i| current[i] == *line)
502            .collect();
503        if hits.len() != 1 || at.last().is_some_and(|&last| hits[0] <= last) {
504            return None;
505        }
506        at.push(hits[0]);
507    }
508    // A TOML table header between reviewed lines would move the later ones into
509    // another table while read-back still matched (malcolm, tambo#321 review).
510    let (first, last) = (*at.first()?, *at.last()?);
511    if (first..=last)
512        .filter(|i| !at.contains(i))
513        .any(|i| current[i].trim_start().starts_with('['))
514    {
515        return None;
516    }
517    // So would a header inserted above the block: the reviewed lines must still
518    // sit under the table they were reviewed under (malcolm, tambo#323 F2). The
519    // whole header list is compared, not only the nearest one, because an extra
520    // repeated `[[array]]` header reads the same but opens a new element (F4).
521    let headers = |ls: &[&str], end: usize| -> Vec<String> {
522        ls[..end]
523            .iter()
524            .filter(|l| l.trim_start().starts_with('['))
525            .map(|l| l.trim().to_string())
526            .collect()
527    };
528    if headers(&current, first) != headers(&after, prefix) {
529        return None;
530    }
531    let kept: String = current
532        .iter()
533        .enumerate()
534        .filter(|(i, _)| !at.contains(i))
535        .map(|(_, l)| *l)
536        .collect();
537    Some(Change {
538        path: change.path.clone(),
539        before: Some(kept),
540        after: now.to_string(),
541    })
542}
543fn journal(directory: &Path, phase: &str) -> Result<()> {
544    private_write(
545        &directory.join("state.json"),
546        &serde_json::to_vec(&json!({"schema":1,"phase":phase,
547        "at":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs_f64()}))?,
548    )
549}
550fn lock(directory: &Path) -> Result<fs::File> {
551    use std::os::unix::fs::OpenOptionsExt;
552    let path = directory.join("apply.lock");
553    if fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink() || !m.is_file()) {
554        bail!("invalid memory lifecycle lock");
555    }
556    let file = fs::OpenOptions::new()
557        .read(true)
558        .write(true)
559        .create(true)
560        .truncate(false)
561        .mode(0o600)
562        .open(path)?;
563    file.try_lock_exclusive()
564        .context("another memory lifecycle operation is running")?;
565    Ok(file)
566}
567pub fn check_tools(plan: &Plan, runner: &mut impl Runner) -> Result<()> {
568    let requests=concat!("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"clientInfo\":{\"name\":\"tambo-memory-verify\",\"version\":\"1\"}}}\n",
569        "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n",
570        "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}\n");
571    let response = runner.input("cy", &["mcp".into()], requests)?;
572    let rows: Vec<Value> = response
573        .lines()
574        .filter(|l| !l.trim().is_empty())
575        .map(serde_json::from_str)
576        .collect::<std::result::Result<_, _>>()?;
577    let init = rows
578        .iter()
579        .find(|r| r["id"] == 1)
580        .context("MCP initialization response missing")?;
581    let list = rows
582        .iter()
583        .find(|r| r["id"] == 2)
584        .context("MCP tools response missing")?;
585    if init["result"]["serverInfo"]["name"] != "camayoc-memory"
586        || list["result"]["tools"] != plan.expected_tools
587    {
588        bail!("installed Camayoc tool schemas differ from reviewed producer revision");
589    }
590    Ok(())
591}
592fn exact_bundles(plan: &Plan, directory: &Path, current: &[Value], prior: &[Value]) -> Result<()> {
593    for (i, wanted) in plan.bundles.iter().enumerate() {
594        let name = wanted["name"].as_str().context("bundle name missing")?;
595        let old = prior.iter().find(|r| r["name"] == name);
596        if let Some(old) = old {
597            let backup: Value = serde_json::from_str(
598                &read(&directory.join(format!("prior-{i}.json")))?
599                    .context("prior bundle backup missing")?,
600            )?;
601            if &backup != old {
602                bail!("prior bundle backup changed; preserve it for inspection");
603            }
604        }
605        if current.iter().any(|r| r["name"] == name) {
606            let raw: Value = serde_json::from_str(
607                &read(&plan.root.join("hook-bundles").join(format!("{name}.json")))?
608                    .context("owner bundle bytes unavailable")?,
609            )?;
610            if raw != *wanted && old != Some(&raw) {
611                bail!("registered bundle bytes changed; preserve operator edits");
612            }
613        }
614    }
615    Ok(())
616}
617pub fn apply(directory: &Path, runner: &mut impl Runner) -> Result<()> {
618    let plan = load(directory)?;
619    let _lock = lock(directory)?;
620    check_existing_redirect(&plan.harness_configs)?;
621    let saved = directory.join("registry-before.json");
622    let current = existing(&plan, runner)?;
623    if !saved.exists() {
624        if current.iter().any(|r| r["name"] == BUNDLE_NAME) {
625            bail!("memory bundle already owned by another plan; restore it first");
626        }
627        let mut snapshot = current.clone();
628        for (i, wanted) in plan.bundles.iter().enumerate() {
629            if let Some(prior) = current.iter().find(|r| r["name"] == wanted["name"]) {
630                let name = prior["name"]
631                    .as_str()
632                    .context("owner bundle name missing")?;
633                if !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
634                    bail!("invalid bundle name");
635                }
636                let raw = read(&plan.root.join("hook-bundles").join(format!("{name}.json")))?
637                    .context("exact prior bundle unavailable; no lossless rollback")?;
638                let value: Value = serde_json::from_str(&raw)?;
639                if normalized(&value) != normalized(prior) {
640                    bail!("owner registry changed during snapshot");
641                }
642                if let Some(slot) = snapshot.iter_mut().find(|r| r["name"] == wanted["name"]) {
643                    *slot = value;
644                }
645                private_write(&directory.join(format!("prior-{i}.json")), raw.as_bytes())?;
646            }
647        }
648        private_write(&saved, &serde_json::to_vec(&snapshot)?)?;
649    }
650    let prior: Vec<Value> = serde_json::from_slice(&fs::read(&saved)?)?;
651    for (i, wanted) in plan.bundles.iter().enumerate() {
652        let path = directory.join(format!("bundle-{i}.json"));
653        if serde_json::from_slice::<Value>(&fs::read(&path)?)? != *wanted {
654            bail!("staged bundle differs from reviewed plan");
655        }
656        if let Some(listed) = current.iter().find(|r| r["name"] == wanted["name"]) {
657            let now = registered(&plan, listed)?;
658            if normalized(&now) != normalized(wanted)
659                && prior
660                    .iter()
661                    .find(|r| r["name"] == wanted["name"])
662                    .map(normalized)
663                    .as_ref()
664                    != Some(&normalized(&now))
665            {
666                bail!("registered bundle changed since plan application");
667            }
668        }
669    }
670    exact_bundles(&plan, directory, &current, &prior)?;
671    // Every target is checked before the first write, including on resume.
672    // An interrupted apply (phase "applying") may resume over a target edited
673    // since review when the reviewed lines are still present (`rebase`).
674    let resuming = read(&directory.join("state.json"))?
675        .and_then(|text| serde_json::from_str::<Value>(&text).ok())
676        .is_some_and(|state| state["phase"] == "applying");
677    let mut changes = changes(directory, &plan)?;
678    let mut rebased = Vec::new();
679    for c in changes.iter_mut() {
680        let now = read(&c.path)?;
681        if now != c.before && now.as_deref() != Some(c.after.as_str()) {
682            match now
683                .as_deref()
684                .filter(|_| resuming)
685                .and_then(|n| rebase(c, n))
686            {
687                Some(r) => {
688                    *c = r;
689                    rebased.push(c.clone());
690                }
691                None => bail!(
692                    "configuration changed since plan review: {}",
693                    c.path.display()
694                ),
695            }
696        }
697    }
698    for args in [
699        vec!["--version"],
700        vec!["record", "decision", "--help"],
701        vec!["record", "directive", "--help"],
702        vec!["record", "preference", "--help"],
703        vec!["record", "handoff", "--help"],
704        vec!["record", "reference", "--help"],
705        vec!["hook", "memory-redirect", "--help"],
706        vec!["flush", "--help"],
707    ] {
708        runner.run("cy", &args.iter().map(|s| (*s).to_string()).collect::<Vec<_>>())
709            .context("install a current Camayoc CLI with its generated memory tools before applying this plan")?;
710    }
711    let help = runner.run("cy", &["flush".into(), "--help".into()])?;
712    if !help.contains("--hook") {
713        bail!("Camayoc lacks bounded hook replay; update it before applying");
714    }
715    runner.run(
716        "cy",
717        &["hook".into(), "session-end".into(), "--help".into()],
718    )?;
719    runner.run(
720        "bobbin",
721        &["hook".into(), "memory-refresh".into(), "--help".into()],
722    )?;
723    check_tools(&plan, runner)?;
724    let created = directory.join("created-skill-directories.json");
725    let restored = read(&directory.join("state.json"))?
726        .and_then(|text| serde_json::from_str::<Value>(&text).ok())
727        .is_some_and(|state| state["phase"] == "restored");
728    if !created.exists() || restored {
729        let missing: Vec<_> = plan
730            .skill_directories
731            .iter()
732            .filter(|p| !p.exists())
733            .collect();
734        private_write(&created, &serde_json::to_vec(&missing)?)?;
735    }
736    if !rebased.is_empty() {
737        let mut all: Vec<Change> = match read(&directory.join(REBASED))? {
738            Some(text) => serde_json::from_str(&text)?,
739            None => Vec::new(),
740        };
741        for r in rebased {
742            all.retain(|c| c.path != r.path);
743            all.push(r);
744        }
745        private_write(&directory.join(REBASED), &serde_json::to_vec_pretty(&all)?)?;
746    }
747    journal(directory, "applying")?;
748    for c in &changes {
749        if read(&c.path)?.as_deref() != Some(c.after.as_str()) {
750            private_write(&c.path, c.after.as_bytes())?;
751        }
752    }
753    for (i, bundle) in plan.bundles.iter().enumerate() {
754        let path = directory.join(format!("bundle-{i}.json"));
755        let _ = bundle;
756        st(
757            &plan,
758            &[
759                "ops",
760                "hooks",
761                "register",
762                path.to_str().context("non-UTF8 plan path")?,
763            ],
764            runner,
765        )?;
766    }
767    let receipt: Value =
768        serde_json::from_str(&st(&plan, &["ops", "provision", "--json"], runner)?)?;
769    if receipt["version"] != 1
770        || receipt["owner"] != "shantytown"
771        || !receipt["agents"].as_array().is_some_and(|a| !a.is_empty())
772    {
773        bail!("settings owner returned no verified nonempty registration receipt");
774    }
775    for c in &changes {
776        if read(&c.path)?.as_deref() != Some(c.after.as_str()) {
777            bail!("configuration read-back differs");
778        }
779    }
780    for wanted in &plan.bundles {
781        let name = wanted["name"].as_str().context("bundle has no name")?;
782        let raw = read(&plan.root.join("hook-bundles").join(format!("{name}.json")))?
783            .context("registered bundle missing on read-back")?;
784        if serde_json::from_str::<Value>(&raw)? != *wanted {
785            bail!("registered bundle read-back differs");
786        }
787    }
788    journal(directory, "applied")
789}
790
791pub fn restore(directory: &Path, runner: &mut impl Runner) -> Result<()> {
792    let plan = load(directory)?;
793    let _lock = lock(directory)?;
794    let created_dirs: Vec<PathBuf> = match read(&directory.join("created-skill-directories.json"))?
795    {
796        Some(text) => serde_json::from_str(&text)?,
797        None => Vec::new(),
798    };
799    if created_dirs
800        .iter()
801        .any(|p| !plan.skill_directories.contains(p))
802    {
803        bail!("created skill directory is outside this plan");
804    }
805    let saved: Vec<Value> = serde_json::from_slice(
806        &fs::read(directory.join("registry-before.json")).context("plan was never applied")?,
807    )?;
808    let current = existing(&plan, runner)?;
809    // A target edited since this plan wrote it is restored by removing only the
810    // reviewed lines (`rebase`), keeping the operator's edits (aegis-9uq.1).
811    let mut changes = changes(directory, &plan)?;
812    for c in changes.iter_mut() {
813        let now = read(&c.path)?;
814        if now != c.before && now.as_deref() != Some(c.after.as_str()) {
815            match now.as_deref().and_then(|n| rebase(c, n)) {
816                Some(r) => *c = r,
817                None => bail!(
818                    "preserve edited configuration; restore refused: {}",
819                    c.path.display()
820                ),
821            }
822        }
823    }
824    for wanted in &plan.bundles {
825        if let Some(listed) = current.iter().find(|r| r["name"] == wanted["name"]) {
826            let now = registered(&plan, listed)?;
827            let prior = saved.iter().find(|r| r["name"] == wanted["name"]);
828            if normalized(&now) != normalized(wanted)
829                && prior.map(normalized).as_ref() != Some(&normalized(&now))
830            {
831                bail!("registered bundle changed; restore refused");
832            }
833        }
834    }
835    exact_bundles(&plan, directory, &current, &saved)?;
836    journal(directory, "restoring")?;
837    for (i, wanted) in plan.bundles.iter().enumerate() {
838        let name = wanted["name"].as_str().context("bundle has no name")?;
839        if let Some(old) = saved.iter().find(|r| r["name"] == name) {
840            // list receipts omit evidence; restoring from them would lose it.
841            // The exact original bundle is saved separately before registration.
842            let path = directory.join(format!("prior-{i}.json"));
843            let _ = old;
844            if !path.exists() {
845                bail!("exact prior bundle required for lossless restore");
846            }
847            st(
848                &plan,
849                &[
850                    "ops",
851                    "hooks",
852                    "register",
853                    path.to_str().context("non-UTF8 path")?,
854                ],
855                runner,
856            )?;
857        } else if current.iter().any(|r| r["name"] == name) {
858            st(&plan, &["ops", "hooks", "unregister", name], runner)?;
859        }
860    }
861    for c in &changes {
862        if read(&c.path)? == c.before {
863            continue;
864        }
865        if let Some(before) = &c.before {
866            private_write(&c.path, before.as_bytes())?;
867        } else if c.path.exists() {
868            fs::remove_file(&c.path)?;
869        }
870    }
871    for path in created_dirs {
872        match fs::symlink_metadata(&path) {
873            Ok(meta) if meta.is_dir() && fs::read_dir(&path)?.next().is_none() => {
874                fs::remove_dir(&path)?
875            }
876            Ok(_) => {}
877            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
878            Err(error) => return Err(error.into()),
879        }
880    }
881    st(&plan, &["ops", "provision", "--json"], runner)?;
882    journal(directory, "restored")
883}
884
885/// Refuse standalone #202 installations before adding an owner-managed hook.
886/// Parse commands, so JSON escapes or TOML quoting cannot hide a duplicate.
887pub fn check_existing_redirect(paths: &[PathBuf]) -> Result<()> {
888    fn command(value: &Value) -> bool {
889        match value {
890            Value::Object(fields) => fields.iter().any(|(key, val)| {
891                (key == "command"
892                    && val
893                        .as_str()
894                        .is_some_and(|s| s.contains("hook memory-redirect")))
895                    || command(val)
896            }),
897            Value::Array(values) => values.iter().any(command),
898            _ => false,
899        }
900    }
901    for path in paths {
902        let Some(text) = read(path)? else {
903            continue;
904        };
905        if text.contains("# >>> tambo: camayoc memory-redirect hook") {
906            bail!("standalone memory redirect installed in {}; uninstall it with scripts/memory-redirect-hook.py before planning/applying", path.display());
907        }
908        let value: Value = if path.extension().is_some_and(|s| s == "json") {
909            serde_json::from_str(&text).context("parse existing Claude settings")?
910        } else {
911            serde_json::to_value(
912                text.parse::<toml::Value>()
913                    .context("parse existing Codex settings")?,
914            )?
915        };
916        if command(&value) {
917            bail!("standalone memory redirect installed in {}; uninstall it with scripts/memory-redirect-hook.py before planning/applying", path.display());
918        }
919    }
920    Ok(())
921}
922#[cfg(test)]
923mod rebase_tests {
924    use super::*;
925    fn change(before: &str, after: &str) -> Change {
926        Change {
927            path: PathBuf::from("t.toml"),
928            before: Some(before.into()),
929            after: after.into(),
930        }
931    }
932    #[test]
933    fn a_repeated_array_header_above_the_block_refuses() {
934        // malcolm, tambo#324 F4: an extra "[[a]]" above the block has the same
935        // text as the reviewed nearest header but opens a new element.
936        let c = change("[[a]]\nx = 1\n", "[[a]]\nx = 1\nnew = 2\n");
937        assert!(rebase(&c, "[[a]]\nx = 1\n[[a]]\nnew = 2\n").is_none());
938        // Control: an operator comment in the same place still rebases.
939        let r = rebase(&c, "[[a]]\nx = 1\n# note\nnew = 2\n").unwrap();
940        assert_eq!(r.before.as_deref(), Some("[[a]]\nx = 1\n# note\n"));
941    }
942}