Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/b301acebb2160e11 # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#891 (code only) closed derived `b301acebb2160e11` #891 Imported from GitHub aien-dev/aien-sovereign-core-mv#891 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `24c54085457944b73ce373489c69eae77c7eb7b5` · Head `6c8f1dd90b7e6143e743ef6a66f233db79a1b9f6` ### Fetch it A git bundle of the pull request's head, 25821 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/b301acebb2160e11.bundle -o b301acebb2160e11.bundle git fetch b301acebb2160e11.bundle refs/pull/891/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 891 6c8f1dd90b7e6143e743ef6a66f233db79a1b9f6 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":891,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/891","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:12Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index f55624d6..511f3a1f 100644 --- a/.crumb +++ b/.crumb @@ -13,7 +13,7 @@ "generated_policy": "on-demand" }, "invariants": [ - "Crumbs hold only hand-written fields; generated data is derived on demand and never committed. Check: tests/gates/run.sh crumb-verify (gate CRUMB-VERIFY); the hosted CI job AIEN Checks runs crumb verify . with the pinned tool" + "No crumb commits an extensions.generated block; generated data is derived on demand. crumb verify fails on a committed generated block or on a crumb that is not a JSON object, and checks nothing else about which fields a crumb holds. The hosted AIEN Checks job also runs crumb verify . with the pinned tool, but that job is advisory and gates no merge. Check: tests/gates/run.sh crumb-verify (gate CRUMB-VERIFY)" ], "name": "aien-sovereign-core", "purpose": "AIEN Sovereign Core: the Rust host runtime, the loopback OpenAI-compatible HTTP door (aien-serve-http) and the FFI to the omega GPU kernels", diff --git a/crates/aien-cli/src/crumbs.rs b/crates/aien-cli/src/crumbs.rs index cdac8b66..c12b26a0 100644 --- a/crates/aien-cli/src/crumbs.rs +++ b/crates/aien-cli/src/crumbs.rs @@ -159,7 +159,11 @@ fn default_lifecycle() -> String { "permanent".to_string() } +/// A `.crumb` written by this tool. Unknown fields are rejected so that a file +/// carrying anything this tool would drop on save (for example hand-written +/// `invariants`) is treated as foreign and never rewritten. #[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(deny_unknown_fields)] pub struct DirCrumb { pub version: u32, pub dir_path: String, @@ -175,20 +179,13 @@ pub struct DirCrumb { impl DirCrumb { pub fn new(dir: &Path, description: Option<&str>, purpose: Option) -> Self { - let canon = dir - .canonicalize() - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_else(|_| dir.to_string_lossy().to_string()); - - let dir_name = dir - .file_name() - .map(|n| n.to_string_lossy().to_string()) - .unwrap_or_else(|| "/".to_string()); + let (canon, dir_name) = dir_identity(dir); - // Inspect Above - let above = if let Some(parent) = dir.parent() { + // Inspect Above (from the resolved path, so `.` still has a parent) + let canon_path = Path::new(&canon); + let above = if let Some(parent) = canon_path.parent() { let platform = crate::platform::PlatformContext::detect(); - if parent.starts_with(&platform.home_dir) && parent != dir { + if parent.starts_with(&platform.home_dir) && parent != canon_path { let p_canon = parent .canonicalize() .map(|p| p.to_string_lossy().to_string()) @@ -247,69 +244,116 @@ impl DirCrumb { } } +/// Reads `crumb_path`. `Ok(None)`: no file. `Ok(Some)`: a crumb in this tool's +/// `DirCrumb` format. `Err`: a file exists that is not in that format (for +/// example a hand-written schema 1.0.0 crumb) or cannot be read; such a file is +/// never rewritten. +fn read_dir_crumb_file(crumb_path: &Path) -> Result, String> { + match fs::symlink_metadata(crumb_path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(format!("{}: {}", crumb_path.display(), e)), + Ok(_) => {} + } + let content = + read_sidecar(crumb_path).map_err(|e| format!("{}: {}", crumb_path.display(), e))?; + serde_json::from_str::(&content) + .map(Some) + .map_err(|e| format!("{} is not a DirCrumb: {}", crumb_path.display(), e)) +} + +/// Read-only view of a directory whose `.crumb` is not in `DirCrumb` format. +/// The purpose comes from the file's `purpose` string when it has one. +fn foreign_crumb_view(dir: &Path) -> DirCrumb { + let statement = read_sidecar(&dir.join(CRUMB_FILENAME)) + .ok() + .and_then(|c| serde_json::from_str::(&c).ok()) + .and_then(|v| { + v.get("purpose") + .and_then(|p| p.as_str()) + .map(str::to_string) + }); + let purpose = statement.map(|statement| CrumbPurpose { + statement, + created_by: "hand-written .crumb".to_string(), + session_id: String::new(), + created_at: String::new(), + lifecycle: "permanent".to_string(), + }); + let mut crumb = DirCrumb::new( + dir, + Some("Existing .crumb is not in DirCrumb format; shown read-only and never rewritten"), + purpose, + ); + merge_local_crumb(&mut crumb, dir); + crumb +} + +/// Merges ephemeral telemetry from `.crumb.local` into `crumb`. +fn merge_local_crumb(crumb: &mut DirCrumb, dir: &Path) { + let local_data = load_local_crumb(dir); + for h in local_data.history { + if !crumb + .history + .iter() + .any(|existing| existing.crumb_id == h.crumb_id) + { + crumb.history.push(h); + } + } + for w in local_data.whispers { + if !crumb + .whispers + .iter() + .any(|existing| existing.whisper_id == w.whisper_id || existing.message == w.message) + { + crumb.whispers.push(w); + } + } +} + +/// Loads `dir/.crumb`. Seeds and writes a new crumb only when no `.crumb` file +/// exists. A `.crumb` that is not in `DirCrumb` format (a hand-written crumb) +/// is never written; a read-only view is returned instead. pub fn load_or_init_dir_crumb(dir: &Path, purpose_opt: Option) -> DirCrumb { let crumb_path = dir.join(CRUMB_FILENAME); - if crumb_path.exists() { - if let Ok(content) = read_sidecar(&crumb_path) { - match serde_json::from_str::(&content) { - Err(e) => eprintln!( - "Failed to parse DirCrumb at {}: {}", - crumb_path.display(), - e - ), - Ok(mut crumb) => { - // Refresh below items dynamically - let mut below = Vec::new(); - if let Ok(entries) = fs::read_dir(dir) { - for entry in entries.flatten() { - let name = entry.file_name().to_string_lossy().to_string(); - if name.starts_with(".") { - continue; - } - let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false); - below.push(BelowItem { - name, - item_type: if is_dir { - "dir".to_string() - } else { - "file".to_string() - }, - role: String::new(), - }); - } - } - below.sort_by(|a, b| a.name.cmp(&b.name)); - crumb.below = below; - if crumb.purpose.is_none() && purpose_opt.is_some() { - crumb.purpose = purpose_opt.clone(); - save_dir_crumb(&crumb); - } - // Merge ephemeral telemetry from .crumb.local - let local_data = load_local_crumb(dir); - if !local_data.history.is_empty() { - for h in local_data.history { - if !crumb - .history - .iter() - .any(|existing| existing.crumb_id == h.crumb_id) - { - crumb.history.push(h); - } - } + match read_dir_crumb_file(&crumb_path) { + Err(_) => return foreign_crumb_view(dir), + Ok(Some(mut crumb)) => { + // The stored location may be stale (the crumb was moved or copied): + // the directory it was loaded from is authoritative. + let (dir_path, dir_name) = dir_identity(dir); + crumb.dir_path = dir_path; + crumb.dir_name = dir_name; + // Refresh below items dynamically + let mut below = Vec::new(); + if let Ok(entries) = fs::read_dir(dir) { + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if name.starts_with(".") { + continue; } - if !local_data.whispers.is_empty() { - for w in local_data.whispers { - if !crumb.whispers.iter().any(|existing| { - existing.whisper_id == w.whisper_id || existing.message == w.message - }) { - crumb.whispers.push(w); - } - } - } - return crumb; + let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false); + below.push(BelowItem { + name, + item_type: if is_dir { + "dir".to_string() + } else { + "file".to_string() + }, + role: String::new(), + }); } } + below.sort_by(|a, b| a.name.cmp(&b.name)); + crumb.below = below; + if crumb.purpose.is_none() && purpose_opt.is_some() { + crumb.purpose = purpose_opt.clone(); + let _ = save_dir_crumb(dir, &crumb); + } + merge_local_crumb(&mut crumb, dir); + return crumb; } + Ok(None) => {} } // Auto-Sense & Seed if purpose not provided @@ -328,22 +372,40 @@ pub fn load_or_init_dir_crumb(dir: &Path, purpose_opt: Option) -> }; let crumb = DirCrumb::new(dir, None, final_purpose); - save_dir_crumb(&crumb); + let _ = save_dir_crumb(dir, &crumb); crumb } -pub fn save_dir_crumb(crumb: &DirCrumb) { - let dir = Path::new(&crumb.dir_path); +/// Canonical path and name of `dir`, so `.` and relative paths get the real +/// directory name. Falls back to the path as given when it cannot be resolved. +fn dir_identity(dir: &Path) -> (String, String) { + let canon = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()); + let name = canon + .file_name() + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_else(|| "/".to_string()); + (canon.to_string_lossy().to_string(), name) +} + +/// Writes the durable part of `crumb` to `dir/.crumb`, never to the crumb's +/// stored `dir_path`, and records `dir` as its location. Refuses, without +/// writing, when an existing `.crumb` is not in `DirCrumb` format. +pub fn save_dir_crumb(dir: &Path, crumb: &DirCrumb) -> Result<(), String> { let crumb_path = dir.join(CRUMB_FILENAME); + if let Err(e) = read_dir_crumb_file(&crumb_path) { + return Err(format!("refusing to overwrite .crumb: {}", e)); + } // Durable .crumb: keep architectural purpose, above/below, clean of ephemeral churn let mut durable_crumb = crumb.clone(); + let (dir_path, dir_name) = dir_identity(dir); + durable_crumb.dir_path = dir_path; + durable_crumb.dir_name = dir_name; durable_crumb.history = Vec::new(); // Ephemeral history lives in .crumb.local durable_crumb.whispers = Vec::new(); // Whispers live in .crumb.local - if let Ok(json_str) = serde_json::to_string_pretty(&durable_crumb) { - let _ = write_sidecar(&crumb_path, &json_str); - } + let json_str = serde_json::to_string_pretty(&durable_crumb).map_err(|e| e.to_string())?; + write_sidecar(&crumb_path, &json_str).map_err(|e| format!("{}: {}", crumb_path.display(), e)) } /// Records an action in the directory's `.crumb` file and bubbles awareness to parent. @@ -713,6 +775,150 @@ fn auto_sense_directory_purpose(dir: &Path) -> String { mod tests { use super::*; + /// Shape of a hand-written crumb on main (crates/aien-serve-http/.crumb). + const HAND_WRITTEN_CRUMB: &str = r#"{ + "invariants": [ + "The door refuses to bind a non-loopback address. Check: cargo test -p aien-serve-http --test loopback -- --exact non_loopback_bind_is_refused" + ], + "name": "aien-serve-http", + "purpose": "OpenAI-compatible HTTP door for AIEN's own-kernel model serving (OWN-30B cut 4)", + "schema_version": "1.0.0" +} +"#; + + #[test] + fn hand_written_crumb_is_never_rewritten() { + let temp = tempfile::tempdir().expect("temp dir"); + let dir = temp.path(); + fs::create_dir_all(dir.join("src")).expect("create src"); + fs::write(dir.join("Cargo.toml"), "[package]\nname = \"door\"\n").expect("cargo"); + let crumb_path = dir.join(CRUMB_FILENAME); + fs::write(&crumb_path, HAND_WRITTEN_CRUMB).expect("write crumb"); + + // The nest ritual path (nesting.rs) plus sniff, show, record and whisper. + let crumb = load_or_init_dir_crumb(dir, None); + let _ = discover_workspace_crumbs_summary(dir); + let _ = format_dir_crumb_tui(dir); + let _ = sniff_dir_crumb(&dir.join("Cargo.toml"), "Peer-Agent"); + record_directory_crumb("AIEN", "s", dir, "nest", "i", "v"); + leave_dir_whisper("AIEN", dir, None, "hello"); + + assert_eq!( + fs::read_to_string(&crumb_path).expect("read crumb"), + HAND_WRITTEN_CRUMB + ); + assert_eq!( + crumb.purpose.map(|p| p.statement).as_deref(), + Some("OpenAI-compatible HTTP door for AIEN's own-kernel model serving (OWN-30B cut 4)") + ); + } + + #[test] + fn save_refuses_to_overwrite_foreign_crumb() { + let temp = tempfile::tempdir().expect("temp dir"); + let dir = temp.path(); + let crumb_path = dir.join(CRUMB_FILENAME); + + // A hand-written crumb: load gives a view, save refuses, bytes unchanged. + fs::write(&crumb_path, HAND_WRITTEN_CRUMB).expect("write crumb"); + let mut crumb = load_or_init_dir_crumb(dir, None); + crumb.description = "changed".to_string(); + assert!(save_dir_crumb(dir, &crumb).is_err()); + assert_eq!(fs::read_to_string(&crumb_path).unwrap(), HAND_WRITTEN_CRUMB); + + // A DirCrumb with an extra hand-written field: save would drop the + // field, so it is refused too. + let seeded = DirCrumb::new(dir, None, None); + let mut value = serde_json::to_value(&seeded).unwrap(); + value["invariants"] = serde_json::json!(["kept by hand"]); + let mixed = serde_json::to_string_pretty(&value).unwrap(); + fs::write(&crumb_path, &mixed).expect("write mixed crumb"); + assert!(save_dir_crumb(dir, &seeded).is_err()); + assert_eq!(fs::read_to_string(&crumb_path).unwrap(), mixed); + + // A crumb this tool wrote is still saved. + fs::remove_file(&crumb_path).unwrap(); + let fresh = load_or_init_dir_crumb(dir, None); + assert!(fresh.purpose.is_some()); + assert!(save_dir_crumb(dir, &fresh).is_ok()); + } + + #[test] + fn save_writes_where_the_crumb_was_loaded_not_to_stored_dir_path() { + let here_tmp = tempfile::tempdir().expect("here"); + let old_tmp = tempfile::tempdir().expect("old"); + let here = here_tmp.path(); + let old = old_tmp.path(); + + // A DirCrumb moved (or copied) from `old`: its stored dir_path is stale. + let mut moved = DirCrumb::new(old, None, None); + moved.purpose = None; + fs::write( + here.join(CRUMB_FILENAME), + serde_json::to_string_pretty(&moved).unwrap(), + ) + .expect("write moved crumb"); + + // Loading with a purpose fills the missing purpose and saves. + let purpose = CrumbPurpose { + statement: "filled on load".to_string(), + created_by: "test".to_string(), + session_id: "test".to_string(), + created_at: "2026-10-31T00:00:00Z".to_string(), + lifecycle: "permanent".to_string(), + }; + let loaded = load_or_init_dir_crumb(here, Some(purpose)); + + assert!( + !old.join(CRUMB_FILENAME).exists(), + "save wrote to the stale stored dir_path" + ); + let saved: DirCrumb = + serde_json::from_str(&fs::read_to_string(here.join(CRUMB_FILENAME)).unwrap()).unwrap(); + let canon = here.canonicalize().unwrap().to_string_lossy().to_string(); + assert_eq!(saved.dir_path, canon); + assert_eq!(loaded.dir_path, canon); + assert_eq!( + saved.purpose.map(|p| p.statement).as_deref(), + Some("filled on load") + ); + } + + #[test] + fn dir_name_of_dot_is_the_real_directory_name() { + let crumb = DirCrumb::new(Path::new("."), None, None); + let expected = std::env::current_dir() + .unwrap() + .canonicalize() + .unwrap() + .file_name() + .unwrap() + .to_string_lossy() + .to_string(); + assert_eq!(crumb.dir_name, expected); + } + + #[test] + fn crumb_for_dot_has_the_parent_entry() { + let cwd = std::env::current_dir().unwrap().canonicalize().unwrap(); + let home = crate::platform::PlatformContext::detect().home_dir; + let parent = cwd.parent().unwrap(); + let crumb = DirCrumb::new(Path::new("."), None, None); + // The parent entry is written only inside the home directory. A checkout + // outside it (CI, /tmp worktrees) must get none; inside it, "." must get + // the resolved parent, not the empty textual parent of ".". + if parent.starts_with(&home) && parent != cwd { + let above = crumb.above.expect("no parent entry for \".\""); + assert_eq!(above.canonical, parent.to_string_lossy()); + assert_eq!(above.name, parent.file_name().unwrap().to_string_lossy()); + } else { + assert!( + crumb.above.is_none(), + "parent entry outside the home directory" + ); + } + } + /// DRA-47: recording in a workspace root must not bubble into the root's /// parent, which is under `$HOME` but outside the allow list. One level /// down, the parent is the workspace and the bubble stays. diff --git a/crates/aien-cli/src/tools.rs b/crates/aien-cli/src/tools.rs index f7e9978a..801212c1 100644 --- a/crates/aien-cli/src/tools.rs +++ b/crates/aien-cli/src/tools.rs @@ -852,6 +852,7 @@ fn exec_write_file( Err(err) => return bind_err(err), }; let p = held.authorized(); + let mut crumb_error = None; if created_parent { if let Some(parent) = p.parent() { let file_name = p @@ -866,7 +867,7 @@ fn exec_write_file( lifecycle: "permanent".to_string(), }; let crumb = load_or_init_dir_crumb(parent, Some(parent_purpose)); - save_dir_crumb(&crumb); + crumb_error = save_dir_crumb(parent, &crumb).err(); } } @@ -881,6 +882,9 @@ fn exec_write_file( if let Some(notice) = crumb_notice { resp["peer_breadcrumb_notice"] = json!(notice); } + if let Some(err) = crumb_error { + resp["crumb_error"] = json!(err); + } (resp, true) } @@ -1046,7 +1050,9 @@ fn exec_crumb_tool(args: &Value) -> (Value, bool) { }; let mut crumb = load_or_init_dir_crumb(&dir, Some(purpose_obj)); crumb.description = purpose_str.to_string(); - save_dir_crumb(&crumb); + if let Err(err) = save_dir_crumb(&dir, &crumb) { + return (json!({"error": err}), false); + } ( json!({"status": "ok", "message": format!("Initialized .crumb with purpose for {named_dir}")}), true, @@ -1096,7 +1102,7 @@ fn exec_create_dir(path: &str, purpose: &str, lifecycle: Option<&str>) -> (Value let mut crumb = load_or_init_dir_crumb(p, Some(purpose_obj)); crumb.description = purpose.to_string(); - save_dir_crumb(&crumb); + let crumb_error = save_dir_crumb(p, &crumb).err(); // Record scent mark into crumb record_directory_crumb( @@ -1110,16 +1116,17 @@ fn exec_create_dir(path: &str, purpose: &str, lifecycle: Option<&str>) -> (Value let crumb_overview = format_dir_crumb_tui(p); - ( - json!({ - "status": "ok", - "path": path, - "purpose": purpose, - "crumb_created": true, - "directory_crumb": crumb_overview - }), - true, - ) + let mut resp = json!({ + "status": "ok", + "path": path, + "purpose": purpose, + "crumb_created": crumb_error.is_none(), + "directory_crumb": crumb_overview + }); + if let Some(err) = crumb_error { + resp["crumb_error"] = json!(err); + } + (resp, true) } pub fn adapter_dispatch_tool(args: &Value) -> Value { diff --git a/crates/spark-crumbs/src/lib.rs b/crates/spark-crumbs/src/lib.rs index 1cc77d8f..9bfae1b8 100644 --- a/crates/spark-crumbs/src/lib.rs +++ b/crates/spark-crumbs/src/lib.rs @@ -150,7 +150,11 @@ fn default_lifecycle() -> String { "permanent".to_string() } +/// A `.crumb` written by this tool. Unknown fields are rejected so that a file +/// carrying anything this tool would drop on save (for example hand-written +/// `invariants`) is treated as foreign and never rewritten. #[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(deny_unknown_fields)] pub struct DirCrumb { pub version: u32, pub dir_path: String, @@ -166,22 +170,15 @@ pub struct DirCrumb { impl DirCrumb { pub fn new(dir: &Path, description: Option<&str>, purpose: Option) -> Self { - let canon = dir - .canonicalize() - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_else(|_| dir.to_string_lossy().to_string()); - - let dir_name = dir - .file_name() - .map(|n| n.to_string_lossy().to_string()) - .unwrap_or_else(|| "/".to_string()); + let (canon, dir_name) = dir_identity(dir); - // Inspect Above - let above = if let Some(parent) = dir.parent() { + // Inspect Above (from the resolved path, so `.` still has a parent) + let canon_path = Path::new(&canon); + let above = if let Some(parent) = canon_path.parent() { let home = std::env::var("HOME") .or_else(|_| std::env::var("USERPROFILE")) .unwrap_or_default(); - if !home.is_empty() && parent.starts_with(&home) && parent != dir { + if !home.is_empty() && parent.starts_with(&home) && parent != canon_path { let p_canon = parent .canonicalize() .map(|p| p.to_string_lossy().to_string()) @@ -240,69 +237,116 @@ impl DirCrumb { } } +/// Reads `crumb_path`. `Ok(None)`: no file. `Ok(Some)`: a crumb in this tool's +/// `DirCrumb` format. `Err`: a file exists that is not in that format (for +/// example a hand-written schema 1.0.0 crumb) or cannot be read; such a file is +/// never rewritten. +fn read_dir_crumb_file(crumb_path: &Path) -> Result, String> { + match fs::symlink_metadata(crumb_path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(format!("{}: {}", crumb_path.display(), e)), + Ok(_) => {} + } + let content = + fs::read_to_string(crumb_path).map_err(|e| format!("{}: {}", crumb_path.display(), e))?; + serde_json::from_str::(&content) + .map(Some) + .map_err(|e| format!("{} is not a DirCrumb: {}", crumb_path.display(), e)) +} + +/// Read-only view of a directory whose `.crumb` is not in `DirCrumb` format. +/// The purpose comes from the file's `purpose` string when it has one. +fn foreign_crumb_view(dir: &Path) -> DirCrumb { + let statement = fs::read_to_string(dir.join(CRUMB_FILENAME)) + .ok() + .and_then(|c| serde_json::from_str::(&c).ok()) + .and_then(|v| { + v.get("purpose") + .and_then(|p| p.as_str()) + .map(str::to_string) + }); + let purpose = statement.map(|statement| CrumbPurpose { + statement, + created_by: "hand-written .crumb".to_string(), + session_id: String::new(), + created_at: String::new(), + lifecycle: "permanent".to_string(), + }); + let mut crumb = DirCrumb::new( + dir, + Some("Existing .crumb is not in DirCrumb format; shown read-only and never rewritten"), + purpose, + ); + merge_local_crumb(&mut crumb, dir); + crumb +} + +/// Merges ephemeral telemetry from `.crumb.local` into `crumb`. +fn merge_local_crumb(crumb: &mut DirCrumb, dir: &Path) { + let local_data = load_local_crumb(dir); + for h in local_data.history { + if !crumb + .history + .iter() + .any(|existing| existing.crumb_id == h.crumb_id) + { + crumb.history.push(h); + } + } + for w in local_data.whispers { + if !crumb + .whispers + .iter() + .any(|existing| existing.whisper_id == w.whisper_id || existing.message == w.message) + { + crumb.whispers.push(w); + } + } +} + +/// Loads `dir/.crumb`. Seeds and writes a new crumb only when no `.crumb` file +/// exists. A `.crumb` that is not in `DirCrumb` format (a hand-written crumb) +/// is never written; a read-only view is returned instead. pub fn load_or_init_dir_crumb(dir: &Path, purpose_opt: Option) -> DirCrumb { let crumb_path = dir.join(CRUMB_FILENAME); - if crumb_path.exists() { - if let Ok(content) = fs::read_to_string(&crumb_path) { - match serde_json::from_str::(&content) { - Err(e) => eprintln!( - "Failed to parse DirCrumb at {}: {}", - crumb_path.display(), - e - ), - Ok(mut crumb) => { - // Refresh below items dynamically - let mut below = Vec::new(); - if let Ok(entries) = fs::read_dir(dir) { - for entry in entries.flatten() { - let name = entry.file_name().to_string_lossy().to_string(); - if name.starts_with(".") { - continue; - } - let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false); - below.push(BelowItem { - name, - item_type: if is_dir { - "dir".to_string() - } else { - "file".to_string() - }, - role: String::new(), - }); - } - } - below.sort_by(|a, b| a.name.cmp(&b.name)); - crumb.below = below; - if crumb.purpose.is_none() && purpose_opt.is_some() { - crumb.purpose = purpose_opt.clone(); - save_dir_crumb(&crumb); - } - // Merge ephemeral telemetry from .crumb.local - let local_data = load_local_crumb(dir); - if !local_data.history.is_empty() { - for h in local_data.history { - if !crumb - .history - .iter() - .any(|existing| existing.crumb_id == h.crumb_id) - { - crumb.history.push(h); - } - } - } - if !local_data.whispers.is_empty() { - for w in local_data.whispers { - if !crumb.whispers.iter().any(|existing| { - existing.whisper_id == w.whisper_id || existing.message == w.message - }) { - crumb.whispers.push(w); - } - } + match read_dir_crumb_file(&crumb_path) { + Err(_) => return foreign_crumb_view(dir), + Ok(Some(mut crumb)) => { + // The stored location may be stale (the crumb was moved or copied): + // the directory it was loaded from is authoritative. + let (dir_path, dir_name) = dir_identity(dir); + crumb.dir_path = dir_path; + crumb.dir_name = dir_name; + // Refresh below items dynamically + let mut below = Vec::new(); + if let Ok(entries) = fs::read_dir(dir) { + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if name.starts_with(".") { + continue; } - return crumb; + let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false); + below.push(BelowItem { + name, + item_type: if is_dir { + "dir".to_string() + } else { + "file".to_string() + }, + role: String::new(), + }); } } + below.sort_by(|a, b| a.name.cmp(&b.name)); + crumb.below = below; + if crumb.purpose.is_none() && purpose_opt.is_some() { + crumb.purpose = purpose_opt.clone(); + let _ = save_dir_crumb(dir, &crumb); + } + merge_local_crumb(&mut crumb, dir); + return crumb; } + Ok(None) => {} } // Auto-Sense & Seed if purpose not provided @@ -321,22 +365,40 @@ pub fn load_or_init_dir_crumb(dir: &Path, purpose_opt: Option) -> }; let crumb = DirCrumb::new(dir, None, final_purpose); - save_dir_crumb(&crumb); + let _ = save_dir_crumb(dir, &crumb); crumb } -pub fn save_dir_crumb(crumb: &DirCrumb) { - let dir = Path::new(&crumb.dir_path); +/// Canonical path and name of `dir`, so `.` and relative paths get the real +/// directory name. Falls back to the path as given when it cannot be resolved. +fn dir_identity(dir: &Path) -> (String, String) { + let canon = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()); + let name = canon + .file_name() + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_else(|| "/".to_string()); + (canon.to_string_lossy().to_string(), name) +} + +/// Writes the durable part of `crumb` to `dir/.crumb`, never to the crumb's +/// stored `dir_path`, and records `dir` as its location. Refuses, without +/// writing, when an existing `.crumb` is not in `DirCrumb` format. +pub fn save_dir_crumb(dir: &Path, crumb: &DirCrumb) -> Result<(), String> { let crumb_path = dir.join(CRUMB_FILENAME); + if let Err(e) = read_dir_crumb_file(&crumb_path) { + return Err(format!("refusing to overwrite .crumb: {}", e)); + } // Durable .crumb: keep architectural purpose, above/below, clean of ephemeral churn let mut durable_crumb = crumb.clone(); + let (dir_path, dir_name) = dir_identity(dir); + durable_crumb.dir_path = dir_path; + durable_crumb.dir_name = dir_name; durable_crumb.history = Vec::new(); // Ephemeral history lives in .crumb.local durable_crumb.whispers = Vec::new(); // Whispers live in .crumb.local - if let Ok(json_str) = serde_json::to_string_pretty(&durable_crumb) { - let _ = fs::write(&crumb_path, json_str); - } + let json_str = serde_json::to_string_pretty(&durable_crumb).map_err(|e| e.to_string())?; + fs::write(&crumb_path, json_str).map_err(|e| format!("{}: {}", crumb_path.display(), e)) } /// Records an action in the directory's `.crumb` file and bubbles awareness to parent. @@ -811,4 +873,156 @@ mod tests { let _ = fs::remove_dir_all(&temp_dir); } + + /// Shape of a hand-written crumb on main (crates/aien-serve-http/.crumb). + const HAND_WRITTEN_CRUMB: &str = r#"{ + "invariants": [ + "The door refuses to bind a non-loopback address. Check: cargo test -p aien-serve-http --test loopback -- --exact non_loopback_bind_is_refused" + ], + "name": "aien-serve-http", + "purpose": "OpenAI-compatible HTTP door for AIEN's own-kernel model serving (OWN-30B cut 4)", + "schema_version": "1.0.0" +} +"#; + + #[test] + fn hand_written_crumb_is_never_rewritten() { + let temp_dir = + std::env::temp_dir().join(format!("test-handwritten-{}", uuid::Uuid::new_v4())); + fs::create_dir_all(temp_dir.join("src")).expect("create temp dir"); + fs::write(temp_dir.join("Cargo.toml"), "[package]\nname = \"door\"\n").expect("cargo"); + let crumb_path = temp_dir.join(CRUMB_FILENAME); + fs::write(&crumb_path, HAND_WRITTEN_CRUMB).expect("write crumb"); + + let crumb = load_or_init_dir_crumb(&temp_dir, None); + let _ = format_dir_crumb_tui(&temp_dir); + let _ = sniff_dir_crumb(&temp_dir, "Peer-Agent"); + let _ = discover_workspace_crumbs_summary(&temp_dir); + seed_directory_tree(&temp_dir, false, "AIEN", Some("seeded")); + seed_directory_tree(&temp_dir, true, "AIEN", None); + record_crumb_action(&temp_dir, "AIEN", "s", "edit", "Cargo.toml", "i", "v"); + + assert_eq!( + fs::read_to_string(&crumb_path).expect("read crumb"), + HAND_WRITTEN_CRUMB + ); + assert_eq!( + crumb.purpose.map(|p| p.statement).as_deref(), + Some("OpenAI-compatible HTTP door for AIEN's own-kernel model serving (OWN-30B cut 4)") + ); + + let _ = fs::remove_dir_all(&temp_dir); + } + + #[test] + fn save_refuses_to_overwrite_foreign_crumb() { + let temp_dir = std::env::temp_dir().join(format!("test-refuse-{}", uuid::Uuid::new_v4())); + fs::create_dir_all(&temp_dir).expect("create temp dir"); + let crumb_path = temp_dir.join(CRUMB_FILENAME); + + // A hand-written crumb: load gives a view, save refuses, bytes unchanged. + fs::write(&crumb_path, HAND_WRITTEN_CRUMB).expect("write crumb"); + let mut crumb = load_or_init_dir_crumb(&temp_dir, None); + crumb.description = "changed".to_string(); + assert!(save_dir_crumb(&temp_dir, &crumb).is_err()); + assert_eq!(fs::read_to_string(&crumb_path).unwrap(), HAND_WRITTEN_CRUMB); + + // A DirCrumb with an extra hand-written field: save would drop the + // field, so it is refused too. + let seeded = DirCrumb::new(&temp_dir, None, None); + let mut value = serde_json::to_value(&seeded).unwrap(); + value["invariants"] = serde_json::json!(["kept by hand"]); + let mixed = serde_json::to_string_pretty(&value).unwrap(); + fs::write(&crumb_path, &mixed).expect("write mixed crumb"); + assert!(save_dir_crumb(&temp_dir, &seeded).is_err()); + assert_eq!(fs::read_to_string(&crumb_path).unwrap(), mixed); + + // A crumb this tool wrote is still saved. + fs::remove_file(&crumb_path).unwrap(); + let fresh = load_or_init_dir_crumb(&temp_dir, None); + assert!(fresh.purpose.is_some()); + assert!(save_dir_crumb(&temp_dir, &fresh).is_ok()); + + let _ = fs::remove_dir_all(&temp_dir); + } + + #[test] + fn save_writes_where_the_crumb_was_loaded_not_to_stored_dir_path() { + let here = std::env::temp_dir().join(format!("test-here-{}", uuid::Uuid::new_v4())); + let old = std::env::temp_dir().join(format!("test-old-{}", uuid::Uuid::new_v4())); + fs::create_dir_all(&here).expect("create here"); + fs::create_dir_all(&old).expect("create old"); + + // A DirCrumb moved (or copied) from `old`: its stored dir_path is stale. + let mut moved = DirCrumb::new(&old, None, None); + moved.purpose = None; + fs::write( + here.join(CRUMB_FILENAME), + serde_json::to_string_pretty(&moved).unwrap(), + ) + .expect("write moved crumb"); + + // Loading with a purpose fills the missing purpose and saves. + let purpose = CrumbPurpose { + statement: "filled on load".to_string(), + created_by: "test".to_string(), + session_id: "test".to_string(), + created_at: "2026-10-31T00:00:00Z".to_string(), + lifecycle: "permanent".to_string(), + }; + let loaded = load_or_init_dir_crumb(&here, Some(purpose)); + + assert!( + !old.join(CRUMB_FILENAME).exists(), + "save wrote to the stale stored dir_path" + ); + let saved: DirCrumb = + serde_json::from_str(&fs::read_to_string(here.join(CRUMB_FILENAME)).unwrap()).unwrap(); + let canon = here.canonicalize().unwrap().to_string_lossy().to_string(); + assert_eq!(saved.dir_path, canon); + assert_eq!(loaded.dir_path, canon); + assert_eq!( + saved.purpose.map(|p| p.statement).as_deref(), + Some("filled on load") + ); + + let _ = fs::remove_dir_all(&here); + let _ = fs::remove_dir_all(&old); + } + + #[test] + fn dir_name_of_dot_is_the_real_directory_name() { + let crumb = DirCrumb::new(Path::new("."), None, None); + let expected = std::env::current_dir() + .unwrap() + .canonicalize() + .unwrap() + .file_name() + .unwrap() + .to_string_lossy() + .to_string(); + assert_eq!(crumb.dir_name, expected); + } + + #[test] + fn crumb_for_dot_has_the_parent_entry() { + let cwd = std::env::current_dir().unwrap().canonicalize().unwrap(); + let home = std::env::var("HOME").unwrap_or_default(); + let parent = cwd.parent().unwrap(); + let crumb = DirCrumb::new(Path::new("."), None, None); + // The parent entry is written only under HOME. A checkout outside it (CI, + // /tmp worktrees) must get none; under it, "." must get the resolved + // parent, not the empty textual parent of ".". + if !home.is_empty() && parent.starts_with(&home) && parent != cwd { + match crumb.above { + Some(AboveValue::Structured(above)) => { + assert_eq!(above.canonical, parent.to_string_lossy()); + assert_eq!(above.name, parent.file_name().unwrap().to_string_lossy()); + } + other => panic!("no parent entry for \".\": {:?}", other.is_some()), + } + } else { + assert!(crumb.above.is_none(), "parent entry outside HOME"); + } + } } diff --git a/crates/spark-crumbs/src/main.rs b/crates/spark-crumbs/src/main.rs index 78b90a92..0ec68fec 100644 --- a/crates/spark-crumbs/src/main.rs +++ b/crates/spark-crumbs/src/main.rs @@ -91,7 +91,7 @@ enum Commands { #[arg(short, long, default_value = "AIEN", help = "Agent ID")] agent: String, - #[arg(short, long, help = "Action type (e.g. edit, test, build, audit)")] + #[arg(long, help = "Action type (e.g. edit, test, build, audit)")] action: String, #[arg(short, long, help = "Target artifact or file")] @@ -177,3 +177,16 @@ fn main() { } } } + +#[cfg(test)] +mod tests { + use super::Cli; + use clap::CommandFactory; + + #[test] + fn cli_definition_is_valid() { + // Every subcommand, including record, must build without a clap + // debug assertion (record once declared -a for both agent and action). + Cli::command().debug_assert(); + } +} ```