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 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}
430const DEFAULT_HARNESSES: [&str; 3] = ["claude", "codex", "opencode"];
432fn normalized(bundle: &Value) -> Value {
433 json!({"name":bundle["name"],"version":bundle["version"],"owner":bundle["owner"],"roles":bundle["roles"],
434 "hooks":bundle["hooks"].as_array().map(|rows| rows.iter().map(|r| json!({
435 "event":r["event"],"command":r["command"],"matcher":r["matcher"],"timeout":r["timeout"],"harnesses":r.get("harnesses").cloned().unwrap_or_else(|| json!(DEFAULT_HARNESSES))})).collect::<Vec<_>>())})
436}
437fn as_listed(file: &Value, listed: &Value) -> Value {
443 let default = DEFAULT_HARNESSES;
447 let mut out = file.clone();
448 if let Some(hooks) = out["hooks"].as_array_mut() {
449 for (i, hook) in hooks.iter_mut().enumerate() {
452 if hook.get("harnesses").is_none() {
453 if let Some(h) = listed["hooks"].get(i).and_then(|l| l.get("harnesses")) {
454 let widens = h
455 .as_array()
456 .is_some_and(|names| default.iter().all(|d| names.iter().any(|n| n == d)));
457 if widens {
458 hook["harnesses"] = h.clone();
459 }
460 }
461 }
462 }
463 }
464 out
465}
466fn registered(plan: &Plan, listed: &Value) -> Result<Value> {
472 let name = listed["name"]
473 .as_str()
474 .context("owner bundle name missing")?;
475 if !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
476 bail!("invalid bundle name");
477 }
478 match read(&plan.root.join("hook-bundles").join(format!("{name}.json")))? {
479 Some(raw) => Ok(serde_json::from_str(&raw)?),
480 None => Ok(listed.clone()),
481 }
482}
483const REBASED: &str = "rebased-changes.json";
484pub fn changes(directory: &Path, plan: &Plan) -> Result<Vec<Change>> {
487 let mut out = plan.changes.clone();
488 if let Some(text) = read(&directory.join(REBASED))? {
489 let rebased: Vec<Change> = serde_json::from_str(&text)?;
490 for r in rebased {
491 match out.iter_mut().find(|c| c.path == r.path) {
492 Some(slot) => *slot = r,
493 None => bail!("rebased change is outside this plan: {}", r.path.display()),
494 }
495 }
496 }
497 Ok(out)
498}
499fn lines(text: &str) -> Vec<&str> {
500 text.split_inclusive('\n').collect()
501}
502fn rebase(change: &Change, now: &str) -> Option<Change> {
511 let before = lines(change.before.as_deref()?);
512 let after = lines(&change.after);
513 let prefix = before
514 .iter()
515 .zip(&after)
516 .take_while(|(a, b)| a == b)
517 .count();
518 let suffix = before[prefix..]
519 .iter()
520 .rev()
521 .zip(after[prefix..].iter().rev())
522 .take_while(|(a, b)| a == b)
523 .count();
524 if prefix + suffix != before.len() || after.len() <= before.len() {
525 return None;
526 }
527 let block = &after[prefix..after.len() - suffix];
528 let current = lines(now);
529 let mut at = Vec::with_capacity(block.len());
530 for line in block {
531 let hits: Vec<usize> = (0..current.len())
532 .filter(|&i| current[i] == *line)
533 .collect();
534 if hits.len() != 1 || at.last().is_some_and(|&last| hits[0] <= last) {
535 return None;
536 }
537 at.push(hits[0]);
538 }
539 let (first, last) = (*at.first()?, *at.last()?);
542 if (first..=last)
543 .filter(|i| !at.contains(i))
544 .any(|i| current[i].trim_start().starts_with('['))
545 {
546 return None;
547 }
548 let headers = |ls: &[&str], end: usize| -> Vec<String> {
553 ls[..end]
554 .iter()
555 .filter(|l| l.trim_start().starts_with('['))
556 .map(|l| l.trim().to_string())
557 .collect()
558 };
559 if headers(¤t, first) != headers(&after, prefix) {
560 return None;
561 }
562 let kept: String = current
563 .iter()
564 .enumerate()
565 .filter(|(i, _)| !at.contains(i))
566 .map(|(_, l)| *l)
567 .collect();
568 Some(Change {
569 path: change.path.clone(),
570 before: Some(kept),
571 after: now.to_string(),
572 })
573}
574fn journal(directory: &Path, phase: &str) -> Result<()> {
575 private_write(
576 &directory.join("state.json"),
577 &serde_json::to_vec(&json!({"schema":1,"phase":phase,
578 "at":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs_f64()}))?,
579 )
580}
581fn lock(directory: &Path) -> Result<fs::File> {
582 use std::os::unix::fs::OpenOptionsExt;
583 let path = directory.join("apply.lock");
584 if fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink() || !m.is_file()) {
585 bail!("invalid memory lifecycle lock");
586 }
587 let file = fs::OpenOptions::new()
588 .read(true)
589 .write(true)
590 .create(true)
591 .truncate(false)
592 .mode(0o600)
593 .open(path)?;
594 file.try_lock_exclusive()
595 .context("another memory lifecycle operation is running")?;
596 Ok(file)
597}
598pub fn check_tools(plan: &Plan, runner: &mut impl Runner) -> Result<()> {
599 let requests=concat!("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{},\"clientInfo\":{\"name\":\"tambo-memory-verify\",\"version\":\"1\"}}}\n",
600 "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n",
601 "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}\n");
602 let response = runner.input("cy", &["mcp".into()], requests)?;
603 let rows: Vec<Value> = response
604 .lines()
605 .filter(|l| !l.trim().is_empty())
606 .map(serde_json::from_str)
607 .collect::<std::result::Result<_, _>>()?;
608 let init = rows
609 .iter()
610 .find(|r| r["id"] == 1)
611 .context("MCP initialization response missing")?;
612 let list = rows
613 .iter()
614 .find(|r| r["id"] == 2)
615 .context("MCP tools response missing")?;
616 if init["result"]["serverInfo"]["name"] != "camayoc-memory"
617 || list["result"]["tools"] != plan.expected_tools
618 {
619 bail!("installed Camayoc tool schemas differ from reviewed producer revision");
620 }
621 Ok(())
622}
623fn exact_bundles(plan: &Plan, directory: &Path, current: &[Value], prior: &[Value]) -> Result<()> {
624 for (i, wanted) in plan.bundles.iter().enumerate() {
625 let name = wanted["name"].as_str().context("bundle name missing")?;
626 let old = prior.iter().find(|r| r["name"] == name);
627 if let Some(old) = old {
628 let backup: Value = serde_json::from_str(
629 &read(&directory.join(format!("prior-{i}.json")))?
630 .context("prior bundle backup missing")?,
631 )?;
632 if &backup != old {
633 bail!("prior bundle backup changed; preserve it for inspection");
634 }
635 }
636 if current.iter().any(|r| r["name"] == name) {
637 let raw: Value = serde_json::from_str(
638 &read(&plan.root.join("hook-bundles").join(format!("{name}.json")))?
639 .context("owner bundle bytes unavailable")?,
640 )?;
641 if raw != *wanted && old != Some(&raw) {
642 bail!("registered bundle bytes changed; preserve operator edits");
643 }
644 }
645 }
646 Ok(())
647}
648pub fn apply(directory: &Path, runner: &mut impl Runner) -> Result<()> {
649 let plan = load(directory)?;
650 let _lock = lock(directory)?;
651 check_existing_redirect(&plan.harness_configs)?;
652 let saved = directory.join("registry-before.json");
653 let current = existing(&plan, runner)?;
654 if !saved.exists() {
655 if current.iter().any(|r| r["name"] == BUNDLE_NAME) {
656 bail!("memory bundle already owned by another plan; restore it first");
657 }
658 let mut snapshot = current.clone();
659 for (i, wanted) in plan.bundles.iter().enumerate() {
660 if let Some(prior) = current.iter().find(|r| r["name"] == wanted["name"]) {
661 let name = prior["name"]
662 .as_str()
663 .context("owner bundle name missing")?;
664 if !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
665 bail!("invalid bundle name");
666 }
667 let raw = read(&plan.root.join("hook-bundles").join(format!("{name}.json")))?
668 .context("exact prior bundle unavailable; no lossless rollback")?;
669 let value: Value = serde_json::from_str(&raw)?;
670 if normalized(&as_listed(&value, prior)) != normalized(prior) {
671 bail!("owner registry changed during snapshot");
672 }
673 if let Some(slot) = snapshot.iter_mut().find(|r| r["name"] == wanted["name"]) {
674 *slot = value;
675 }
676 private_write(&directory.join(format!("prior-{i}.json")), raw.as_bytes())?;
677 }
678 }
679 private_write(&saved, &serde_json::to_vec(&snapshot)?)?;
680 }
681 let prior: Vec<Value> = serde_json::from_slice(&fs::read(&saved)?)?;
682 for (i, wanted) in plan.bundles.iter().enumerate() {
683 let path = directory.join(format!("bundle-{i}.json"));
684 if serde_json::from_slice::<Value>(&fs::read(&path)?)? != *wanted {
685 bail!("staged bundle differs from reviewed plan");
686 }
687 if let Some(listed) = current.iter().find(|r| r["name"] == wanted["name"]) {
688 let now = registered(&plan, listed)?;
689 if normalized(&now) != normalized(wanted)
690 && prior
691 .iter()
692 .find(|r| r["name"] == wanted["name"])
693 .map(normalized)
694 .as_ref()
695 != Some(&normalized(&now))
696 {
697 bail!("registered bundle changed since plan application");
698 }
699 }
700 }
701 exact_bundles(&plan, directory, ¤t, &prior)?;
702 let resuming = read(&directory.join("state.json"))?
706 .and_then(|text| serde_json::from_str::<Value>(&text).ok())
707 .is_some_and(|state| state["phase"] == "applying");
708 let mut changes = changes(directory, &plan)?;
709 let mut rebased = Vec::new();
710 for c in changes.iter_mut() {
711 let now = read(&c.path)?;
712 if now != c.before && now.as_deref() != Some(c.after.as_str()) {
713 match now
714 .as_deref()
715 .filter(|_| resuming)
716 .and_then(|n| rebase(c, n))
717 {
718 Some(r) => {
719 *c = r;
720 rebased.push(c.clone());
721 }
722 None => bail!(
723 "configuration changed since plan review: {}",
724 c.path.display()
725 ),
726 }
727 }
728 }
729 for args in [
730 vec!["--version"],
731 vec!["record", "decision", "--help"],
732 vec!["record", "directive", "--help"],
733 vec!["record", "preference", "--help"],
734 vec!["record", "handoff", "--help"],
735 vec!["record", "reference", "--help"],
736 vec!["hook", "memory-redirect", "--help"],
737 vec!["flush", "--help"],
738 ] {
739 runner.run("cy", &args.iter().map(|s| (*s).to_string()).collect::<Vec<_>>())
740 .context("install a current Camayoc CLI with its generated memory tools before applying this plan")?;
741 }
742 let help = runner.run("cy", &["flush".into(), "--help".into()])?;
743 if !help.contains("--hook") {
744 bail!("Camayoc lacks bounded hook replay; update it before applying");
745 }
746 runner.run(
747 "cy",
748 &["hook".into(), "session-end".into(), "--help".into()],
749 )?;
750 runner.run(
751 "bobbin",
752 &["hook".into(), "memory-refresh".into(), "--help".into()],
753 )?;
754 check_tools(&plan, runner)?;
755 let created = directory.join("created-skill-directories.json");
756 let restored = read(&directory.join("state.json"))?
757 .and_then(|text| serde_json::from_str::<Value>(&text).ok())
758 .is_some_and(|state| state["phase"] == "restored");
759 if !created.exists() || restored {
760 let missing: Vec<_> = plan
761 .skill_directories
762 .iter()
763 .filter(|p| !p.exists())
764 .collect();
765 private_write(&created, &serde_json::to_vec(&missing)?)?;
766 }
767 if !rebased.is_empty() {
768 let mut all: Vec<Change> = match read(&directory.join(REBASED))? {
769 Some(text) => serde_json::from_str(&text)?,
770 None => Vec::new(),
771 };
772 for r in rebased {
773 all.retain(|c| c.path != r.path);
774 all.push(r);
775 }
776 private_write(&directory.join(REBASED), &serde_json::to_vec_pretty(&all)?)?;
777 }
778 journal(directory, "applying")?;
779 for c in &changes {
780 if read(&c.path)?.as_deref() != Some(c.after.as_str()) {
781 private_write(&c.path, c.after.as_bytes())?;
782 }
783 }
784 for (i, bundle) in plan.bundles.iter().enumerate() {
785 let path = directory.join(format!("bundle-{i}.json"));
786 let _ = bundle;
787 st(
788 &plan,
789 &[
790 "ops",
791 "hooks",
792 "register",
793 path.to_str().context("non-UTF8 plan path")?,
794 ],
795 runner,
796 )?;
797 }
798 let receipt: Value =
799 serde_json::from_str(&st(&plan, &["ops", "provision", "--json"], runner)?)?;
800 if receipt["version"] != 1
801 || receipt["owner"] != "shantytown"
802 || !receipt["agents"].as_array().is_some_and(|a| !a.is_empty())
803 {
804 bail!("settings owner returned no verified nonempty registration receipt");
805 }
806 for c in &changes {
807 if read(&c.path)?.as_deref() != Some(c.after.as_str()) {
808 bail!("configuration read-back differs");
809 }
810 }
811 for wanted in &plan.bundles {
812 let name = wanted["name"].as_str().context("bundle has no name")?;
813 let raw = read(&plan.root.join("hook-bundles").join(format!("{name}.json")))?
814 .context("registered bundle missing on read-back")?;
815 if serde_json::from_str::<Value>(&raw)? != *wanted {
816 bail!("registered bundle read-back differs");
817 }
818 }
819 journal(directory, "applied")
820}
821
822pub fn restore(directory: &Path, runner: &mut impl Runner) -> Result<()> {
823 let plan = load(directory)?;
824 let _lock = lock(directory)?;
825 let created_dirs: Vec<PathBuf> = match read(&directory.join("created-skill-directories.json"))?
826 {
827 Some(text) => serde_json::from_str(&text)?,
828 None => Vec::new(),
829 };
830 if created_dirs
831 .iter()
832 .any(|p| !plan.skill_directories.contains(p))
833 {
834 bail!("created skill directory is outside this plan");
835 }
836 let saved: Vec<Value> = serde_json::from_slice(
837 &fs::read(directory.join("registry-before.json")).context("plan was never applied")?,
838 )?;
839 let current = existing(&plan, runner)?;
840 let mut changes = changes(directory, &plan)?;
843 for c in changes.iter_mut() {
844 let now = read(&c.path)?;
845 if now != c.before && now.as_deref() != Some(c.after.as_str()) {
846 match now.as_deref().and_then(|n| rebase(c, n)) {
847 Some(r) => *c = r,
848 None => bail!(
849 "preserve edited configuration; restore refused: {}",
850 c.path.display()
851 ),
852 }
853 }
854 }
855 for wanted in &plan.bundles {
856 if let Some(listed) = current.iter().find(|r| r["name"] == wanted["name"]) {
857 let now = registered(&plan, listed)?;
858 let prior = saved.iter().find(|r| r["name"] == wanted["name"]);
859 if normalized(&now) != normalized(wanted)
860 && prior.map(normalized).as_ref() != Some(&normalized(&now))
861 {
862 bail!("registered bundle changed; restore refused");
863 }
864 }
865 }
866 exact_bundles(&plan, directory, ¤t, &saved)?;
867 journal(directory, "restoring")?;
868 for (i, wanted) in plan.bundles.iter().enumerate() {
869 let name = wanted["name"].as_str().context("bundle has no name")?;
870 if let Some(old) = saved.iter().find(|r| r["name"] == name) {
871 let path = directory.join(format!("prior-{i}.json"));
874 let _ = old;
875 if !path.exists() {
876 bail!("exact prior bundle required for lossless restore");
877 }
878 st(
879 &plan,
880 &[
881 "ops",
882 "hooks",
883 "register",
884 path.to_str().context("non-UTF8 path")?,
885 ],
886 runner,
887 )?;
888 } else if current.iter().any(|r| r["name"] == name) {
889 st(&plan, &["ops", "hooks", "unregister", name], runner)?;
890 }
891 }
892 for c in &changes {
893 if read(&c.path)? == c.before {
894 continue;
895 }
896 if let Some(before) = &c.before {
897 private_write(&c.path, before.as_bytes())?;
898 } else if c.path.exists() {
899 fs::remove_file(&c.path)?;
900 }
901 }
902 for path in created_dirs {
903 match fs::symlink_metadata(&path) {
904 Ok(meta) if meta.is_dir() && fs::read_dir(&path)?.next().is_none() => {
905 fs::remove_dir(&path)?
906 }
907 Ok(_) => {}
908 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
909 Err(error) => return Err(error.into()),
910 }
911 }
912 st(&plan, &["ops", "provision", "--json"], runner)?;
913 journal(directory, "restored")
914}
915
916pub fn check_existing_redirect(paths: &[PathBuf]) -> Result<()> {
919 fn command(value: &Value) -> bool {
920 match value {
921 Value::Object(fields) => fields.iter().any(|(key, val)| {
922 (key == "command"
923 && val
924 .as_str()
925 .is_some_and(|s| s.contains("hook memory-redirect")))
926 || command(val)
927 }),
928 Value::Array(values) => values.iter().any(command),
929 _ => false,
930 }
931 }
932 for path in paths {
933 let Some(text) = read(path)? else {
934 continue;
935 };
936 if text.contains("# >>> tambo: camayoc memory-redirect hook") {
937 bail!("standalone memory redirect installed in {}; uninstall it with scripts/memory-redirect-hook.py before planning/applying", path.display());
938 }
939 let value: Value = if path.extension().is_some_and(|s| s == "json") {
940 serde_json::from_str(&text).context("parse existing Claude settings")?
941 } else {
942 serde_json::to_value(
943 text.parse::<toml::Value>()
944 .context("parse existing Codex settings")?,
945 )?
946 };
947 if command(&value) {
948 bail!("standalone memory redirect installed in {}; uninstall it with scripts/memory-redirect-hook.py before planning/applying", path.display());
949 }
950 }
951 Ok(())
952}
953#[cfg(test)]
954mod rebase_tests {
955 use super::*;
956 fn change(before: &str, after: &str) -> Change {
957 Change {
958 path: PathBuf::from("t.toml"),
959 before: Some(before.into()),
960 after: after.into(),
961 }
962 }
963 #[test]
964 fn a_repeated_array_header_above_the_block_refuses() {
965 let c = change("[[a]]\nx = 1\n", "[[a]]\nx = 1\nnew = 2\n");
968 assert!(rebase(&c, "[[a]]\nx = 1\n[[a]]\nnew = 2\n").is_none());
969 let r = rebase(&c, "[[a]]\nx = 1\n# note\nnew = 2\n").unwrap();
971 assert_eq!(r.before.as_deref(), Some("[[a]]\nx = 1\n# note\n"));
972 }
973}