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
aien-sovereign-core-mv / crates / aien-cli / src / crumbs.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | use chrono::{DateTime, Utc}; |
| 17 | use colored::*; |
| 18 | use serde::{Deserialize, Serialize}; |
| 19 | use std::fs; |
| 20 | use std::io::{Read, Write}; |
| 21 | use std::path::Path; |
| 22 | |
| 23 | /// Open a `.crumb` or `.crumb.local` sidecar without following a symlink in |
| 24 | /// its final component. A sidecar planted as a link (say by a cloned repo) |
| 25 | /// must not redirect a crumb read or write outside its directory (DRA-47). |
| 26 | fn open_sidecar(path: &Path, opts: &mut fs::OpenOptions) -> std::io::Result<fs::File> { |
| 27 | #[cfg(unix)] |
| 28 | { |
| 29 | use std::os::unix::fs::OpenOptionsExt; |
| 30 | opts.custom_flags(libc::O_NOFOLLOW); |
| 31 | } |
| 32 | opts.open(path) |
| 33 | } |
| 34 | |
| 35 | fn read_sidecar(path: &Path) -> std::io::Result<String> { |
| 36 | let mut text = String::new(); |
| 37 | open_sidecar(path, fs::OpenOptions::new().read(true))?.read_to_string(&mut text)?; |
| 38 | Ok(text) |
| 39 | } |
| 40 | |
| 41 | fn write_sidecar(path: &Path, text: &str) -> std::io::Result<()> { |
| 42 | open_sidecar( |
| 43 | path, |
| 44 | fs::OpenOptions::new() |
| 45 | .write(true) |
| 46 | .create(true) |
| 47 | .truncate(true), |
| 48 | )? |
| 49 | .write_all(text.as_bytes()) |
| 50 | } |
| 51 | |
| 52 | /// Create a `.crumb` that does not exist yet. An existing entry, including a |
| 53 | /// dangling symlink that `Path::exists` reports as absent, is left alone |
| 54 | /// rather than written through (DRA-47). |
| 55 | pub(crate) fn write_new_crumb(path: &Path, text: &str) -> std::io::Result<()> { |
| 56 | open_sidecar(path, fs::OpenOptions::new().write(true).create_new(true))? |
| 57 | .write_all(text.as_bytes()) |
| 58 | } |
| 59 | |
| 60 | pub const CRUMB_FILENAME: &str = ".crumb"; |
| 61 | |
| 62 | // `.crumb.local` coordination notes (types, identity, locked read-modify-write) have one |
| 63 | // implementation, in spark-crumbs, shared with the `spark-crumbs` CLI |
| 64 | // (core#924). aien-cli already depends on spark-crumbs through spark-hive. |
| 65 | pub use spark_crumbs::local::{ |
| 66 | load_local_crumb, push_history, push_whisper, unique_record_id, AgentIdentity, |
| 67 | CrumbHistoryItem, CrumbWhisper, IdentityError, LocalCrumbError, DEFAULT_TTL_SECS, |
| 68 | }; |
| 69 | |
| 70 | /// This process's agent identity: `AIEN_AGENT_ID`, else |
| 71 | /// `<AIEN_AGENT_NAME or aien-cli>.<AIEN_SESSION_ID or HERMES_SESSION_ID>`, else a |
| 72 | /// generated `aien-cli@<host>.<pid>.<random>`. Never a shared constant. |
| 73 | pub fn agent_identity() -> Result<AgentIdentity, IdentityError> { |
| 74 | spark_crumbs::local::process_identity("aien-cli") |
| 75 | } |
| 76 | |
| 77 | /// `(created_by, session_id)` for a durable `.crumb` purpose. A `.crumb` may |
| 78 | /// be committed, so a generated identity (which names the host and pid) is |
| 79 | /// reduced to its agent name there; `.crumb.local` keeps the full id. |
| 80 | pub fn purpose_author() -> (String, String) { |
| 81 | match agent_identity() { |
| 82 | Ok(id) if id.source != spark_crumbs::local::IdentitySource::Generated => { |
| 83 | (id.agent_id, id.session_id) |
| 84 | } |
| 85 | Ok(id) => ( |
| 86 | id.agent_id |
| 87 | .split('@') |
| 88 | .next() |
| 89 | .unwrap_or("aien-cli") |
| 90 | .to_string(), |
| 91 | String::new(), |
| 92 | ), |
| 93 | Err(_) => ("aien-cli".to_string(), String::new()), |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | #[derive(Serialize, Deserialize, Debug, Clone)] |
| 98 | pub struct AboveInfo { |
| 99 | pub path: String, |
| 100 | pub canonical: String, |
| 101 | pub name: String, |
| 102 | pub role: String, |
| 103 | } |
| 104 | |
| 105 | #[derive(Serialize, Deserialize, Debug, Clone)] |
| 106 | pub struct BelowItem { |
| 107 | pub name: String, |
| 108 | pub item_type: String, // "dir" or "file" |
| 109 | pub role: String, |
| 110 | } |
| 111 | |
| 112 | #[derive(Serialize, Deserialize, Debug, Clone)] |
| 113 | pub struct CrumbPurpose { |
| 114 | pub statement: String, |
| 115 | #[serde(default)] |
| 116 | pub created_by: String, |
| 117 | #[serde(default)] |
| 118 | pub session_id: String, |
| 119 | #[serde(default)] |
| 120 | pub created_at: String, |
| 121 | #[serde(default = "default_lifecycle")] |
| 122 | pub lifecycle: String, // "permanent" | "ephemeral" |
| 123 | } |
| 124 | |
| 125 | fn default_lifecycle() -> String { |
| 126 | "permanent".to_string() |
| 127 | } |
| 128 | |
| 129 | /// A `.crumb` written by this tool. Unknown fields are rejected so that a file |
| 130 | /// carrying anything this tool would drop on save (for example hand-written |
| 131 | /// `invariants`) is treated as foreign and never rewritten. |
| 132 | #[derive(Serialize, Deserialize, Debug, Clone)] |
| 133 | #[serde(deny_unknown_fields)] |
| 134 | pub struct DirCrumb { |
| 135 | pub version: u32, |
| 136 | pub dir_path: String, |
| 137 | pub dir_name: String, |
| 138 | pub description: String, |
| 139 | #[serde(default)] |
| 140 | pub purpose: Option<CrumbPurpose>, |
| 141 | pub above: Option<AboveInfo>, |
| 142 | pub below: Vec<BelowItem>, |
| 143 | pub history: Vec<CrumbHistoryItem>, |
| 144 | pub whispers: Vec<CrumbWhisper>, |
| 145 | } |
| 146 | |
| 147 | impl DirCrumb { |
| 148 | pub fn new(dir: &Path, description: Option<&str>, purpose: Option<CrumbPurpose>) -> Self { |
| 149 | let (canon, dir_name) = dir_identity(dir); |
| 150 | |
| 151 | // Inspect Above (from the resolved path, so `.` still has a parent) |
| 152 | let canon_path = Path::new(&canon); |
| 153 | let above = if let Some(parent) = canon_path.parent() { |
| 154 | let platform = crate::platform::PlatformContext::detect(); |
| 155 | if parent.starts_with(&platform.home_dir) && parent != canon_path { |
| 156 | let p_canon = parent |
| 157 | .canonicalize() |
| 158 | .map(|p| p.to_string_lossy().to_string()) |
| 159 | .unwrap_or_else(|_| parent.to_string_lossy().to_string()); |
| 160 | let p_name = parent |
| 161 | .file_name() |
| 162 | .map(|n| n.to_string_lossy().to_string()) |
| 163 | .unwrap_or_else(|| "home".to_string()); |
| 164 | |
| 165 | Some(AboveInfo { |
| 166 | path: "..".to_string(), |
| 167 | canonical: p_canon, |
| 168 | name: p_name, |
| 169 | role: "Parent directory context".to_string(), |
| 170 | }) |
| 171 | } else { |
| 172 | None |
| 173 | } |
| 174 | } else { |
| 175 | None |
| 176 | }; |
| 177 | |
| 178 | // Inspect Below |
| 179 | let mut below = Vec::new(); |
| 180 | if let Ok(entries) = fs::read_dir(dir) { |
| 181 | for entry in entries.flatten() { |
| 182 | let name = entry.file_name().to_string_lossy().to_string(); |
| 183 | if name.starts_with(".") { |
| 184 | continue; |
| 185 | } |
| 186 | let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false); |
| 187 | below.push(BelowItem { |
| 188 | name, |
| 189 | item_type: if is_dir { |
| 190 | "dir".to_string() |
| 191 | } else { |
| 192 | "file".to_string() |
| 193 | }, |
| 194 | role: String::new(), |
| 195 | }); |
| 196 | } |
| 197 | } |
| 198 | below.sort_by(|a, b| a.name.cmp(&b.name)); |
| 199 | |
| 200 | DirCrumb { |
| 201 | version: 1, |
| 202 | dir_path: canon, |
| 203 | dir_name, |
| 204 | description: description.unwrap_or("Workspace directory").to_string(), |
| 205 | purpose, |
| 206 | above, |
| 207 | below, |
| 208 | history: Vec::new(), |
| 209 | whispers: Vec::new(), |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | /// Reads `crumb_path`. `Ok(None)`: no file. `Ok(Some)`: a crumb in this tool's |
| 215 | /// `DirCrumb` format. `Err`: a file exists that is not in that format (for |
| 216 | /// example a hand-written schema 1.0.0 crumb) or cannot be read; such a file is |
| 217 | /// never rewritten. |
| 218 | fn read_dir_crumb_file(crumb_path: &Path) -> Result<Option<DirCrumb>, String> { |
| 219 | match fs::symlink_metadata(crumb_path) { |
| 220 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 221 | Err(e) => return Err(format!("{}: {}", crumb_path.display(), e)), |
| 222 | Ok(_) => {} |
| 223 | } |
| 224 | let content = |
| 225 | read_sidecar(crumb_path).map_err(|e| format!("{}: {}", crumb_path.display(), e))?; |
| 226 | serde_json::from_str::<DirCrumb>(&content) |
| 227 | .map(Some) |
| 228 | .map_err(|e| format!("{} is not a DirCrumb: {}", crumb_path.display(), e)) |
| 229 | } |
| 230 | |
| 231 | /// Read-only view of a directory whose `.crumb` is not in `DirCrumb` format. |
| 232 | /// The purpose comes from the file's `purpose` string when it has one. |
| 233 | fn foreign_crumb_view(dir: &Path) -> DirCrumb { |
| 234 | let statement = read_sidecar(&dir.join(CRUMB_FILENAME)) |
| 235 | .ok() |
| 236 | .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok()) |
| 237 | .and_then(|v| { |
| 238 | v.get("purpose") |
| 239 | .and_then(|p| p.as_str()) |
| 240 | .map(str::to_string) |
| 241 | }); |
| 242 | let purpose = statement.map(|statement| CrumbPurpose { |
| 243 | statement, |
| 244 | created_by: "hand-written .crumb".to_string(), |
| 245 | session_id: String::new(), |
| 246 | created_at: String::new(), |
| 247 | lifecycle: "permanent".to_string(), |
| 248 | }); |
| 249 | DirCrumb::new( |
| 250 | dir, |
| 251 | Some("Existing .crumb is not in DirCrumb format; shown read-only and never rewritten"), |
| 252 | purpose, |
| 253 | ) |
| 254 | } |
| 255 | |
| 256 | /// Merges ephemeral notes from `.crumb.local` into `crumb`. An unreadable |
| 257 | /// or malformed `.crumb.local` is an error, never an empty peer list. |
| 258 | pub fn merge_local_crumb(crumb: &mut DirCrumb, dir: &Path) -> Result<(), LocalCrumbError> { |
| 259 | let local_data = load_local_crumb(dir)?; |
| 260 | for h in local_data.history { |
| 261 | if !crumb |
| 262 | .history |
| 263 | .iter() |
| 264 | .any(|existing| existing.crumb_id == h.crumb_id) |
| 265 | { |
| 266 | crumb.history.push(h); |
| 267 | } |
| 268 | } |
| 269 | for w in local_data.whispers { |
| 270 | if !crumb |
| 271 | .whispers |
| 272 | .iter() |
| 273 | .any(|existing| existing.whisper_id == w.whisper_id || existing.message == w.message) |
| 274 | { |
| 275 | crumb.whispers.push(w); |
| 276 | } |
| 277 | } |
| 278 | Ok(()) |
| 279 | } |
| 280 | |
| 281 | /// The directory crumb with its `.crumb.local` notes merged in, for |
| 282 | /// display. When the notes cannot be loaded the crumb comes back without |
| 283 | /// it, together with the error, which the caller must show. |
| 284 | pub fn load_dir_crumb_view(dir: &Path) -> (DirCrumb, Option<LocalCrumbError>) { |
| 285 | let mut crumb = load_or_init_dir_crumb(dir, None); |
| 286 | let err = merge_local_crumb(&mut crumb, dir).err(); |
| 287 | (crumb, err) |
| 288 | } |
| 289 | |
| 290 | /// The line a view shows in place of notes it could not read. |
| 291 | pub fn local_state_error_line(err: &LocalCrumbError) -> String { |
| 292 | format!( |
| 293 | "⚠ .crumb.local unavailable (peers unknown, not absent): {}", |
| 294 | err |
| 295 | ) |
| 296 | } |
| 297 | |
| 298 | /// Loads `dir/.crumb` (the durable part only; `.crumb.local` notes are |
| 299 | /// merged by [`merge_local_crumb`] / [`load_dir_crumb_view`]). Seeds and writes |
| 300 | /// a new crumb only when no `.crumb` file exists. A `.crumb` that is not in |
| 301 | /// `DirCrumb` format (a hand-written crumb) is never written; a read-only view |
| 302 | /// is returned instead. |
| 303 | pub fn load_or_init_dir_crumb(dir: &Path, purpose_opt: Option<CrumbPurpose>) -> DirCrumb { |
| 304 | let crumb_path = dir.join(CRUMB_FILENAME); |
| 305 | match read_dir_crumb_file(&crumb_path) { |
| 306 | Err(_) => return foreign_crumb_view(dir), |
| 307 | Ok(Some(mut crumb)) => { |
| 308 | // The stored location may be stale (the crumb was moved or copied): |
| 309 | // the directory it was loaded from is authoritative. |
| 310 | let (dir_path, dir_name) = dir_identity(dir); |
| 311 | crumb.dir_path = dir_path; |
| 312 | crumb.dir_name = dir_name; |
| 313 | // Refresh below items dynamically |
| 314 | let mut below = Vec::new(); |
| 315 | if let Ok(entries) = fs::read_dir(dir) { |
| 316 | for entry in entries.flatten() { |
| 317 | let name = entry.file_name().to_string_lossy().to_string(); |
| 318 | if name.starts_with(".") { |
| 319 | continue; |
| 320 | } |
| 321 | let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false); |
| 322 | below.push(BelowItem { |
| 323 | name, |
| 324 | item_type: if is_dir { |
| 325 | "dir".to_string() |
| 326 | } else { |
| 327 | "file".to_string() |
| 328 | }, |
| 329 | role: String::new(), |
| 330 | }); |
| 331 | } |
| 332 | } |
| 333 | below.sort_by(|a, b| a.name.cmp(&b.name)); |
| 334 | crumb.below = below; |
| 335 | if crumb.purpose.is_none() && purpose_opt.is_some() { |
| 336 | crumb.purpose = purpose_opt.clone(); |
| 337 | let _ = save_dir_crumb(dir, &crumb); |
| 338 | } |
| 339 | return crumb; |
| 340 | } |
| 341 | Ok(None) => {} |
| 342 | } |
| 343 | |
| 344 | // Auto-Sense & Seed if purpose not provided |
| 345 | let final_purpose = match purpose_opt { |
| 346 | Some(p) => Some(p), |
| 347 | None => { |
| 348 | let sensed_statement = auto_sense_directory_purpose(dir); |
| 349 | Some(CrumbPurpose { |
| 350 | statement: sensed_statement, |
| 351 | created_by: "AIEN (Auto-Sensed)".to_string(), |
| 352 | session_id: "auto-sense".to_string(), |
| 353 | created_at: Utc::now().to_rfc3339(), |
| 354 | lifecycle: "permanent".to_string(), |
| 355 | }) |
| 356 | } |
| 357 | }; |
| 358 | |
| 359 | let crumb = DirCrumb::new(dir, None, final_purpose); |
| 360 | let _ = save_dir_crumb(dir, &crumb); |
| 361 | crumb |
| 362 | } |
| 363 | |
| 364 | /// Canonical path and name of `dir`, so `.` and relative paths get the real |
| 365 | /// directory name. Falls back to the path as given when it cannot be resolved. |
| 366 | fn dir_identity(dir: &Path) -> (String, String) { |
| 367 | let canon = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()); |
| 368 | let name = canon |
| 369 | .file_name() |
| 370 | .map(|n| n.to_string_lossy().to_string()) |
| 371 | .unwrap_or_else(|| "/".to_string()); |
| 372 | (canon.to_string_lossy().to_string(), name) |
| 373 | } |
| 374 | |
| 375 | /// Writes the durable part of `crumb` to `dir/.crumb`, never to the crumb's |
| 376 | /// stored `dir_path`, and records `dir` as its location. Refuses, without |
| 377 | /// writing, when an existing `.crumb` is not in `DirCrumb` format. |
| 378 | pub fn save_dir_crumb(dir: &Path, crumb: &DirCrumb) -> Result<(), String> { |
| 379 | let crumb_path = dir.join(CRUMB_FILENAME); |
| 380 | if let Err(e) = read_dir_crumb_file(&crumb_path) { |
| 381 | return Err(format!("refusing to overwrite .crumb: {}", e)); |
| 382 | } |
| 383 | |
| 384 | // Durable .crumb: keep architectural purpose, above/below, clean of ephemeral churn |
| 385 | let mut durable_crumb = crumb.clone(); |
| 386 | let (dir_path, dir_name) = dir_identity(dir); |
| 387 | durable_crumb.dir_path = dir_path; |
| 388 | durable_crumb.dir_name = dir_name; |
| 389 | durable_crumb.history = Vec::new(); // Ephemeral history lives in .crumb.local |
| 390 | durable_crumb.whispers = Vec::new(); // Whispers live in .crumb.local |
| 391 | |
| 392 | let json_str = serde_json::to_string_pretty(&durable_crumb).map_err(|e| e.to_string())?; |
| 393 | write_sidecar(&crumb_path, &json_str).map_err(|e| format!("{}: {}", crumb_path.display(), e)) |
| 394 | } |
| 395 | |
| 396 | /// Records an action in the directory's `.crumb.local` and bubbles awareness to |
| 397 | /// the parent. Each write is one locked read-modify-write. The first failure |
| 398 | /// is returned (a failed bubble after a successful record is still an error). |
| 399 | pub fn record_directory_crumb( |
| 400 | agent_id: &str, |
| 401 | session_id: &str, |
| 402 | target_path: &Path, |
| 403 | action: &str, |
| 404 | intent: &str, |
| 405 | vector: &str, |
| 406 | ) -> Result<(), LocalCrumbError> { |
| 407 | let dir = if target_path.is_dir() { |
| 408 | target_path.to_path_buf() |
| 409 | } else { |
| 410 | target_path.parent().unwrap_or(target_path).to_path_buf() |
| 411 | }; |
| 412 | |
| 413 | let target_name = target_path |
| 414 | .file_name() |
| 415 | .map(|n| n.to_string_lossy().to_string()) |
| 416 | .unwrap_or_else(|| "dir".to_string()); |
| 417 | |
| 418 | let dir_name = dir |
| 419 | .file_name() |
| 420 | .map(|n| n.to_string_lossy().to_string()) |
| 421 | .unwrap_or_else(|| "dir".to_string()); |
| 422 | |
| 423 | let item = CrumbHistoryItem { |
| 424 | crumb_id: unique_record_id("crumb"), |
| 425 | timestamp: Utc::now().to_rfc3339(), |
| 426 | agent_id: agent_id.to_string(), |
| 427 | session_id: session_id.to_string(), |
| 428 | action: action.to_string(), |
| 429 | target: target_name.clone(), |
| 430 | intent: intent.to_string(), |
| 431 | vector: vector.to_string(), |
| 432 | }; |
| 433 | push_history(&dir, item)?; |
| 434 | |
| 435 | // Bubble awareness to the parent's .crumb.local only when that parent is |
| 436 | // itself inside a permitted workspace. |
| 437 | let platform = crate::platform::PlatformContext::detect(); |
| 438 | if let Some(parent) = bubble_parent( |
| 439 | &dir, |
| 440 | &platform.home_dir, |
| 441 | &crate::fs_bind::permitted_workspaces(), |
| 442 | ) { |
| 443 | let bubble_item = CrumbHistoryItem { |
| 444 | crumb_id: unique_record_id("bubble"), |
| 445 | timestamp: Utc::now().to_rfc3339(), |
| 446 | agent_id: agent_id.to_string(), |
| 447 | session_id: session_id.to_string(), |
| 448 | action: format!("sub:{}", action), |
| 449 | target: format!("{}/{}", dir_name, target_name), |
| 450 | intent: intent.to_string(), |
| 451 | vector: vector.to_string(), |
| 452 | }; |
| 453 | push_history(parent, bubble_item)?; |
| 454 | } |
| 455 | Ok(()) |
| 456 | } |
| 457 | |
| 458 | /// Records an action as this process's [`agent_identity`]. |
| 459 | pub fn record_as_self( |
| 460 | target_path: &Path, |
| 461 | action: &str, |
| 462 | intent: &str, |
| 463 | vector: &str, |
| 464 | ) -> Result<(), String> { |
| 465 | let me = agent_identity().map_err(|e| e.to_string())?; |
| 466 | record_directory_crumb( |
| 467 | &me.agent_id, |
| 468 | &me.session_id, |
| 469 | target_path, |
| 470 | action, |
| 471 | intent, |
| 472 | vector, |
| 473 | ) |
| 474 | .map_err(|e| e.to_string()) |
| 475 | } |
| 476 | |
| 477 | /// Sniffs peers of this process's [`agent_identity`]. |
| 478 | pub fn sniff_as_self(target_path: &Path) -> Result<Option<String>, String> { |
| 479 | let me = agent_identity().map_err(|e| e.to_string())?; |
| 480 | sniff_dir_crumb(target_path, &me.agent_id).map_err(|e| e.to_string()) |
| 481 | } |
| 482 | |
| 483 | /// Leaves a whisper from this process's [`agent_identity`]. |
| 484 | pub fn whisper_as_self(dir: &Path, target_file: Option<&str>, message: &str) -> Result<(), String> { |
| 485 | let me = agent_identity().map_err(|e| e.to_string())?; |
| 486 | leave_dir_whisper(&me.agent_id, dir, target_file, message).map_err(|e| e.to_string()) |
| 487 | } |
| 488 | |
| 489 | /// The parent directory a crumb record bubbles into. It must sit under the |
| 490 | /// home directory and inside a permitted workspace: the parent of a workspace |
| 491 | /// root (`~` for `~/workspace`) is outside the allow list (DRA-47). |
| 492 | fn bubble_parent<'a>( |
| 493 | dir: &'a Path, |
| 494 | home: &Path, |
| 495 | workspaces: &[std::path::PathBuf], |
| 496 | ) -> Option<&'a Path> { |
| 497 | let parent = dir.parent().filter(|p| *p != dir)?; |
| 498 | if !parent.starts_with(home) { |
| 499 | return None; |
| 500 | } |
| 501 | crate::safety::validate_workspace_path(parent, workspaces).ok()?; |
| 502 | Some(parent) |
| 503 | } |
| 504 | |
| 505 | /// Leaves a whisper message in a directory .crumb.local file. |
| 506 | pub fn leave_dir_whisper( |
| 507 | from_agent: &str, |
| 508 | dir: &Path, |
| 509 | target_file: Option<&str>, |
| 510 | message: &str, |
| 511 | ) -> Result<(), LocalCrumbError> { |
| 512 | let whisper = CrumbWhisper { |
| 513 | whisper_id: unique_record_id("whisp"), |
| 514 | from_agent: from_agent.to_string(), |
| 515 | timestamp: Utc::now().to_rfc3339(), |
| 516 | target_file: target_file.map(|s| s.to_string()), |
| 517 | message: message.to_string(), |
| 518 | }; |
| 519 | push_whisper(dir, whisper) |
| 520 | } |
| 521 | |
| 522 | /// Sniffs directory crumb and checks for recent actions or whispers on target |
| 523 | /// file by agents other than `current_agent`. `Ok(None)`: no peer activity. |
| 524 | /// `Err`: the notes could not be read, so peers are unknown (not absent). |
| 525 | pub fn sniff_dir_crumb( |
| 526 | target_path: &Path, |
| 527 | current_agent: &str, |
| 528 | ) -> Result<Option<String>, LocalCrumbError> { |
| 529 | let dir = if target_path.is_dir() { |
| 530 | target_path.to_path_buf() |
| 531 | } else { |
| 532 | target_path.parent().unwrap_or(target_path).to_path_buf() |
| 533 | }; |
| 534 | |
| 535 | let mut crumb = load_or_init_dir_crumb(&dir, None); |
| 536 | merge_local_crumb(&mut crumb, &dir)?; |
| 537 | let target_name = target_path |
| 538 | .file_name() |
| 539 | .map(|n| n.to_string_lossy().to_string()) |
| 540 | .unwrap_or_default(); |
| 541 | |
| 542 | let mut notices = Vec::new(); |
| 543 | |
| 544 | // Check history for this target or directory |
| 545 | for item in crumb.history.iter().rev() { |
| 546 | if (item.target == target_name |
| 547 | || item.target.ends_with(&target_name) |
| 548 | || target_path.is_dir()) |
| 549 | && item.agent_id != current_agent |
| 550 | && item.is_active() |
| 551 | { |
| 552 | let elapsed = item.elapsed_secs(); |
| 553 | let el_str = if elapsed < 60 { |
| 554 | format!("{}s ago", elapsed) |
| 555 | } else { |
| 556 | format!("{}m ago", elapsed / 60) |
| 557 | }; |
| 558 | notices.push(format!( |
| 559 | "• [{}] {} on '{}' ({}) - Intent: '{}' -> Vector: '{}'", |
| 560 | item.agent_id, item.action, item.target, el_str, item.intent, item.vector |
| 561 | )); |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | // Check whispers |
| 566 | for w in crumb.whispers.iter().rev() { |
| 567 | if let Ok(parsed) = DateTime::parse_from_rfc3339(&w.timestamp) { |
| 568 | let age = Utc::now().signed_duration_since(parsed.with_timezone(&Utc)); |
| 569 | if age.num_seconds() >= 0 && (age.num_seconds() as u64) < DEFAULT_TTL_SECS * 2 { |
| 570 | if let Some(tf) = &w.target_file { |
| 571 | if tf == &target_name || target_path.is_dir() { |
| 572 | notices.push(format!("💬 [Whisper from {}]: {}", w.from_agent, w.message)); |
| 573 | } |
| 574 | } else { |
| 575 | notices.push(format!("💬 [Whisper from {}]: {}", w.from_agent, w.message)); |
| 576 | } |
| 577 | } |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | if notices.is_empty() { |
| 582 | return Ok(None); |
| 583 | } |
| 584 | |
| 585 | let mut out = format!("🐾 [DIRECTORY CRUMB: {}/.crumb]\n", dir.display()); |
| 586 | if let Some(above) = &crumb.above { |
| 587 | out.push_str(&format!( |
| 588 | " ↑ Above: {} ({})\n", |
| 589 | above.canonical, above.name |
| 590 | )); |
| 591 | } |
| 592 | if let Some(p) = &crumb.purpose { |
| 593 | out.push_str(&format!(" 🎯 Purpose: {}\n", p.statement.cyan())); |
| 594 | } |
| 595 | out.push_str(" Recent Peer History in this directory:\n"); |
| 596 | for n in notices.iter().take(4) { |
| 597 | out.push_str(&format!(" {}\n", n)); |
| 598 | } |
| 599 | out.push_str("─────────────────────────────────────────────────────────────\n"); |
| 600 | Ok(Some(out)) |
| 601 | } |
| 602 | |
| 603 | /// Pretty-prints a rich TUI inspection card for a directory's crumb. |
| 604 | pub fn format_dir_crumb_tui(dir: &Path) -> String { |
| 605 | let (crumb, local_err) = load_dir_crumb_view(dir); |
| 606 | |
| 607 | let mut out = String::new(); |
| 608 | out.push_str(&format!( |
| 609 | "🧭 DIRECTORY CRUMB: {} ({})\n", |
| 610 | crumb.dir_name.bold().cyan(), |
| 611 | crumb.dir_path.dimmed() |
| 612 | )); |
| 613 | out.push_str(&format!(" Description: {}\n", crumb.description)); |
| 614 | if let Some(p) = &crumb.purpose { |
| 615 | out.push_str(&format!( |
| 616 | " 🎯 PURPOSE: {} [{} | by {}]\n", |
| 617 | p.statement.bold().magenta(), |
| 618 | p.lifecycle.cyan(), |
| 619 | p.created_by.yellow() |
| 620 | )); |
| 621 | } |
| 622 | |
| 623 | if let Some(above) = &crumb.above { |
| 624 | out.push_str(&format!( |
| 625 | " ↑ ABOVE: {} [{}]\n", |
| 626 | above.name.bold().yellow(), |
| 627 | above.canonical.dimmed() |
| 628 | )); |
| 629 | } else { |
| 630 | out.push_str(" ↑ ABOVE: [Root workspace boundary]\n"); |
| 631 | } |
| 632 | |
| 633 | let dirs: Vec<&str> = crumb |
| 634 | .below |
| 635 | .iter() |
| 636 | .filter(|i| i.item_type == "dir") |
| 637 | .map(|i| i.name.as_str()) |
| 638 | .collect(); |
| 639 | let files: Vec<&str> = crumb |
| 640 | .below |
| 641 | .iter() |
| 642 | .filter(|i| i.item_type == "file") |
| 643 | .map(|i| i.name.as_str()) |
| 644 | .collect(); |
| 645 | |
| 646 | out.push_str(&format!( |
| 647 | " ↓ BELOW (Subdirectories): [{}]\n", |
| 648 | dirs.join(", ").cyan() |
| 649 | )); |
| 650 | out.push_str(&format!( |
| 651 | " ↓ BELOW (Files): [{}]\n", |
| 652 | files.join(", ").white() |
| 653 | )); |
| 654 | |
| 655 | out.push_str(&format!( |
| 656 | "\n📜 Agent Chronicle in this Directory (Total: {}):\n", |
| 657 | crumb.history.len() |
| 658 | )); |
| 659 | if let Some(err) = &local_err { |
| 660 | out.push_str(&format!(" {}\n", local_state_error_line(err).red())); |
| 661 | } else if crumb.history.is_empty() { |
| 662 | out.push_str(" (No previous actions recorded in this directory)\n"); |
| 663 | } else { |
| 664 | for (i, h) in crumb.history.iter().rev().take(5).enumerate() { |
| 665 | let elapsed = h.elapsed_secs(); |
| 666 | let el_str = if elapsed < 60 { |
| 667 | format!("{}s ago", elapsed) |
| 668 | } else { |
| 669 | format!("{}m ago", elapsed / 60) |
| 670 | }; |
| 671 | out.push_str(&format!( |
| 672 | " {}. [{}] {} '{}' ({})\n Intent: {}\n Vector: {}\n", |
| 673 | i + 1, |
| 674 | h.agent_id.bold().yellow(), |
| 675 | h.action, |
| 676 | h.target.green(), |
| 677 | el_str, |
| 678 | h.intent, |
| 679 | h.vector.dimmed() |
| 680 | )); |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | if !crumb.whispers.is_empty() { |
| 685 | out.push_str("\n💬 Directory Whispers & Intercommunication:\n"); |
| 686 | for w in crumb.whispers.iter().rev().take(3) { |
| 687 | out.push_str(&format!( |
| 688 | " • From [{}]: \"{}\"\n", |
| 689 | w.from_agent.bold().cyan(), |
| 690 | w.message |
| 691 | )); |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | out |
| 696 | } |
| 697 | |
| 698 | /// Discovers directory crumbs for nesting ritual, showing immediate directory topography. |
| 699 | pub fn discover_workspace_crumbs_summary(start_dir: &Path) -> String { |
| 700 | let (crumb, local_err) = load_dir_crumb_view(start_dir); |
| 701 | let mut s = format!( |
| 702 | "[DIRECTORY CRUMB TOPOGRAPHY: {}]\n\ |
| 703 | Current: {} ({})\n", |
| 704 | crumb.dir_name, crumb.dir_path, crumb.description |
| 705 | ); |
| 706 | if let Some(err) = &local_err { |
| 707 | s.push_str(&format!("{}\n", local_state_error_line(err))); |
| 708 | } |
| 709 | |
| 710 | if let Some(above) = &crumb.above { |
| 711 | s.push_str(&format!("↑ Above: {} ({})\n", above.name, above.canonical)); |
| 712 | } |
| 713 | if let Some(p) = &crumb.purpose { |
| 714 | s.push_str(&format!("🎯 Directory Purpose: {}\n", p.statement)); |
| 715 | } |
| 716 | |
| 717 | let subdirs: Vec<&str> = crumb |
| 718 | .below |
| 719 | .iter() |
| 720 | .filter(|i| i.item_type == "dir") |
| 721 | .map(|i| i.name.as_str()) |
| 722 | .collect(); |
| 723 | if !subdirs.is_empty() { |
| 724 | s.push_str(&format!("↓ Below Subdirs: [{}]\n", subdirs.join(", "))); |
| 725 | } |
| 726 | |
| 727 | if !crumb.history.is_empty() { |
| 728 | s.push_str("Recent Actions in this Directory:\n"); |
| 729 | for h in crumb.history.iter().rev().take(3) { |
| 730 | s.push_str(&format!( |
| 731 | "• [{}] {} '{}' - Intent: '{}' -> Vector: '{}'\n", |
| 732 | h.agent_id, h.action, h.target, h.intent, h.vector |
| 733 | )); |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | if !crumb.whispers.is_empty() { |
| 738 | s.push_str("Directory Whispers:\n"); |
| 739 | for w in crumb.whispers.iter().rev().take(2) { |
| 740 | s.push_str(&format!("• [{}] \"{}\"\n", w.from_agent, w.message)); |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | s |
| 745 | } |
| 746 | |
| 747 | fn auto_sense_directory_purpose(dir: &Path) -> String { |
| 748 | let readme = dir.join("README.md"); |
| 749 | if readme.exists() { |
| 750 | if let Ok(c) = fs::read_to_string(&readme) { |
| 751 | for line in c.lines() { |
| 752 | let trimmed = line.trim().trim_start_matches('#').trim(); |
| 753 | if !trimmed.is_empty() { |
| 754 | return format!("Documentation & implementation for {}", trimmed); |
| 755 | } |
| 756 | } |
| 757 | } |
| 758 | } |
| 759 | let cargo = dir.join("Cargo.toml"); |
| 760 | if cargo.exists() { |
| 761 | if let Ok(c) = fs::read_to_string(&cargo) { |
| 762 | for line in c.lines() { |
| 763 | if line.starts_with("name =") { |
| 764 | let name = line |
| 765 | .replace("name =", "") |
| 766 | .replace("\"", "") |
| 767 | .trim() |
| 768 | .to_string(); |
| 769 | return format!("Rust crate codebase: {}", name); |
| 770 | } |
| 771 | } |
| 772 | } |
| 773 | } |
| 774 | let pkg = dir.join("package.json"); |
| 775 | if pkg.exists() { |
| 776 | if let Ok(c) = fs::read_to_string(&pkg) { |
| 777 | if let Ok(val) = serde_json::from_str::<serde_json::Value>(&c) { |
| 778 | if let Some(name) = val.get("name").and_then(|n| n.as_str()) { |
| 779 | return format!("Node/Web package: {}", name); |
| 780 | } |
| 781 | } |
| 782 | } |
| 783 | } |
| 784 | let dir_name = dir |
| 785 | .file_name() |
| 786 | .map(|n| n.to_string_lossy().to_string()) |
| 787 | .unwrap_or_else(|| "workspace".to_string()); |
| 788 | format!("Workspace subsystem directory for {}", dir_name) |
| 789 | } |
| 790 | |
| 791 | #[cfg(test)] |
| 792 | mod tests { |
| 793 | use super::*; |
| 794 | use spark_crumbs::local::LOCAL_CRUMB_FILENAME; |
| 795 | |
| 796 | /// Shape of a hand-written crumb on main (crates/aien-serve-http/.crumb). |
| 797 | const HAND_WRITTEN_CRUMB: &str = r#"{ |
| 798 | "invariants": [ |
| 799 | "The door refuses to bind a non-loopback address. Check: cargo test -p aien-serve-http --test loopback -- --exact non_loopback_bind_is_refused" |
| 800 | ], |
| 801 | "name": "aien-serve-http", |
| 802 | "purpose": "OpenAI-compatible HTTP door for AIEN's own-kernel model serving (OWN-30B cut 4)", |
| 803 | "schema_version": "1.0.0" |
| 804 | } |
| 805 | "#; |
| 806 | |
| 807 | #[test] |
| 808 | fn hand_written_crumb_is_never_rewritten() { |
| 809 | let temp = tempfile::tempdir().expect("temp dir"); |
| 810 | let dir = temp.path(); |
| 811 | fs::create_dir_all(dir.join("src")).expect("create src"); |
| 812 | fs::write(dir.join("Cargo.toml"), "[package]\nname = \"door\"\n").expect("cargo"); |
| 813 | let crumb_path = dir.join(CRUMB_FILENAME); |
| 814 | fs::write(&crumb_path, HAND_WRITTEN_CRUMB).expect("write crumb"); |
| 815 | |
| 816 | // The nest ritual path (nesting.rs) plus sniff, show, record and whisper. |
| 817 | let crumb = load_or_init_dir_crumb(dir, None); |
| 818 | let _ = discover_workspace_crumbs_summary(dir); |
| 819 | let _ = format_dir_crumb_tui(dir); |
| 820 | let _ = sniff_dir_crumb(&dir.join("Cargo.toml"), "Peer-Agent"); |
| 821 | record_directory_crumb("Nest-Writer", "s", dir, "nest", "i", "v").expect("record"); |
| 822 | leave_dir_whisper("Nest-Writer", dir, None, "hello").expect("whisper"); |
| 823 | |
| 824 | assert_eq!( |
| 825 | fs::read_to_string(&crumb_path).expect("read crumb"), |
| 826 | HAND_WRITTEN_CRUMB |
| 827 | ); |
| 828 | assert_eq!( |
| 829 | crumb.purpose.map(|p| p.statement).as_deref(), |
| 830 | Some("OpenAI-compatible HTTP door for AIEN's own-kernel model serving (OWN-30B cut 4)") |
| 831 | ); |
| 832 | } |
| 833 | |
| 834 | #[test] |
| 835 | fn save_refuses_to_overwrite_foreign_crumb() { |
| 836 | let temp = tempfile::tempdir().expect("temp dir"); |
| 837 | let dir = temp.path(); |
| 838 | let crumb_path = dir.join(CRUMB_FILENAME); |
| 839 | |
| 840 | // A hand-written crumb: load gives a view, save refuses, bytes unchanged. |
| 841 | fs::write(&crumb_path, HAND_WRITTEN_CRUMB).expect("write crumb"); |
| 842 | let mut crumb = load_or_init_dir_crumb(dir, None); |
| 843 | crumb.description = "changed".to_string(); |
| 844 | assert!(save_dir_crumb(dir, &crumb).is_err()); |
| 845 | assert_eq!(fs::read_to_string(&crumb_path).unwrap(), HAND_WRITTEN_CRUMB); |
| 846 | |
| 847 | // A DirCrumb with an extra hand-written field: save would drop the |
| 848 | // field, so it is refused too. |
| 849 | let seeded = DirCrumb::new(dir, None, None); |
| 850 | let mut value = serde_json::to_value(&seeded).unwrap(); |
| 851 | value["invariants"] = serde_json::json!(["kept by hand"]); |
| 852 | let mixed = serde_json::to_string_pretty(&value).unwrap(); |
| 853 | fs::write(&crumb_path, &mixed).expect("write mixed crumb"); |
| 854 | assert!(save_dir_crumb(dir, &seeded).is_err()); |
| 855 | assert_eq!(fs::read_to_string(&crumb_path).unwrap(), mixed); |
| 856 | |
| 857 | // A crumb this tool wrote is still saved. |
| 858 | fs::remove_file(&crumb_path).unwrap(); |
| 859 | let fresh = load_or_init_dir_crumb(dir, None); |
| 860 | assert!(fresh.purpose.is_some()); |
| 861 | assert!(save_dir_crumb(dir, &fresh).is_ok()); |
| 862 | } |
| 863 | |
| 864 | #[test] |
| 865 | fn save_writes_where_the_crumb_was_loaded_not_to_stored_dir_path() { |
| 866 | let here_tmp = tempfile::tempdir().expect("here"); |
| 867 | let old_tmp = tempfile::tempdir().expect("old"); |
| 868 | let here = here_tmp.path(); |
| 869 | let old = old_tmp.path(); |
| 870 | |
| 871 | // A DirCrumb moved (or copied) from `old`: its stored dir_path is stale. |
| 872 | let mut moved = DirCrumb::new(old, None, None); |
| 873 | moved.purpose = None; |
| 874 | fs::write( |
| 875 | here.join(CRUMB_FILENAME), |
| 876 | serde_json::to_string_pretty(&moved).unwrap(), |
| 877 | ) |
| 878 | .expect("write moved crumb"); |
| 879 | |
| 880 | // Loading with a purpose fills the missing purpose and saves. |
| 881 | let purpose = CrumbPurpose { |
| 882 | statement: "filled on load".to_string(), |
| 883 | created_by: "test".to_string(), |
| 884 | session_id: "test".to_string(), |
| 885 | created_at: "2026-10-31T00:00:00Z".to_string(), |
| 886 | lifecycle: "permanent".to_string(), |
| 887 | }; |
| 888 | let loaded = load_or_init_dir_crumb(here, Some(purpose)); |
| 889 | |
| 890 | assert!( |
| 891 | !old.join(CRUMB_FILENAME).exists(), |
| 892 | "save wrote to the stale stored dir_path" |
| 893 | ); |
| 894 | let saved: DirCrumb = |
| 895 | serde_json::from_str(&fs::read_to_string(here.join(CRUMB_FILENAME)).unwrap()).unwrap(); |
| 896 | let canon = here.canonicalize().unwrap().to_string_lossy().to_string(); |
| 897 | assert_eq!(saved.dir_path, canon); |
| 898 | assert_eq!(loaded.dir_path, canon); |
| 899 | assert_eq!( |
| 900 | saved.purpose.map(|p| p.statement).as_deref(), |
| 901 | Some("filled on load") |
| 902 | ); |
| 903 | } |
| 904 | |
| 905 | #[test] |
| 906 | fn dir_name_of_dot_is_the_real_directory_name() { |
| 907 | let crumb = DirCrumb::new(Path::new("."), None, None); |
| 908 | let expected = std::env::current_dir() |
| 909 | .unwrap() |
| 910 | .canonicalize() |
| 911 | .unwrap() |
| 912 | .file_name() |
| 913 | .unwrap() |
| 914 | .to_string_lossy() |
| 915 | .to_string(); |
| 916 | assert_eq!(crumb.dir_name, expected); |
| 917 | } |
| 918 | |
| 919 | #[test] |
| 920 | fn crumb_for_dot_has_the_parent_entry() { |
| 921 | let cwd = std::env::current_dir().unwrap().canonicalize().unwrap(); |
| 922 | let home = crate::platform::PlatformContext::detect().home_dir; |
| 923 | let parent = cwd.parent().unwrap(); |
| 924 | let crumb = DirCrumb::new(Path::new("."), None, None); |
| 925 | // The parent entry is written only inside the home directory. A checkout |
| 926 | // outside it (CI, /tmp worktrees) must get none; inside it, "." must get |
| 927 | // the resolved parent, not the empty textual parent of ".". |
| 928 | if parent.starts_with(&home) && parent != cwd { |
| 929 | let above = crumb.above.expect("no parent entry for \".\""); |
| 930 | assert_eq!(above.canonical, parent.to_string_lossy()); |
| 931 | assert_eq!(above.name, parent.file_name().unwrap().to_string_lossy()); |
| 932 | } else { |
| 933 | assert!( |
| 934 | crumb.above.is_none(), |
| 935 | "parent entry outside the home directory" |
| 936 | ); |
| 937 | } |
| 938 | } |
| 939 | |
| 940 | /// DRA-47: recording in a workspace root must not bubble into the root's |
| 941 | /// parent, which is under `$HOME` but outside the allow list. One level |
| 942 | /// down, the parent is the workspace and the bubble stays. |
| 943 | #[test] |
| 944 | fn bubble_stays_inside_a_permitted_workspace() { |
| 945 | let tmp = tempfile::tempdir().unwrap(); |
| 946 | let home = tmp.path().canonicalize().unwrap(); |
| 947 | let ws = home.join("workspace"); |
| 948 | std::fs::create_dir_all(ws.join("sub")).unwrap(); |
| 949 | let workspaces = vec![ws.clone()]; |
| 950 | assert_eq!(bubble_parent(&ws, &home, &workspaces), None); |
| 951 | assert_eq!( |
| 952 | bubble_parent(&ws.join("sub"), &home, &workspaces), |
| 953 | Some(ws.as_path()) |
| 954 | ); |
| 955 | let elsewhere = tempfile::tempdir().unwrap(); |
| 956 | let elsewhere = elsewhere.path().canonicalize().unwrap().join("sub"); |
| 957 | assert_eq!(bubble_parent(&elsewhere, &home, &workspaces), None); |
| 958 | } |
| 959 | |
| 960 | const RACE_DIR_ENV: &str = "AIEN_CRUMB_RACE_CHILD_DIR"; |
| 961 | const RACE_K: usize = 6; |
| 962 | |
| 963 | fn local_counts(dir: &Path) -> (usize, usize) { |
| 964 | let text = fs::read_to_string(dir.join(LOCAL_CRUMB_FILENAME)).expect("read .crumb.local"); |
| 965 | let v: serde_json::Value = serde_json::from_str(&text).expect("parse .crumb.local"); |
| 966 | let n = |k: &str| v[k].as_array().map(|a| a.len()).unwrap_or(0); |
| 967 | (n("history"), n("whispers")) |
| 968 | } |
| 969 | |
| 970 | /// Child half of the process race below: a no-op unless the parent |
| 971 | /// re-executes this test binary with the race directory in the environment. |
| 972 | #[test] |
| 973 | fn race_child_writer() { |
| 974 | let Ok(dir) = std::env::var(RACE_DIR_ENV) else { |
| 975 | return; |
| 976 | }; |
| 977 | let dir = std::path::PathBuf::from(dir); |
| 978 | let me = std::process::id(); |
| 979 | for k in 0..RACE_K { |
| 980 | record_directory_crumb( |
| 981 | &format!("proc{me}"), |
| 982 | "s", |
| 983 | &dir.join("f.rs"), |
| 984 | "edit", |
| 985 | &format!("p{me}k{k}"), |
| 986 | "v", |
| 987 | ) |
| 988 | .expect("record"); |
| 989 | if k < 3 { |
| 990 | leave_dir_whisper(&format!("proc{me}"), &dir, None, &format!("p{me}k{k}")) |
| 991 | .expect("whisper"); |
| 992 | } |
| 993 | } |
| 994 | } |
| 995 | |
| 996 | /// core#924: N threads plus M processes append K history entries (and 3 |
| 997 | /// whispers) each at the same time; nothing may be lost. |
| 998 | #[test] |
| 999 | fn concurrent_threads_and_processes_lose_no_update() { |
| 1000 | const N: usize = 4; |
| 1001 | const M: usize = 4; |
| 1002 | let tmp = tempfile::tempdir().unwrap(); |
| 1003 | let dir = tmp.path().join("work"); |
| 1004 | fs::create_dir_all(&dir).unwrap(); |
| 1005 | let exe = std::env::current_exe().unwrap(); |
| 1006 | let barrier = std::sync::Arc::new(std::sync::Barrier::new(N + M)); |
| 1007 | let mut handles = Vec::new(); |
| 1008 | for t in 0..N { |
| 1009 | let (dir, barrier) = (dir.clone(), barrier.clone()); |
| 1010 | handles.push(std::thread::spawn(move || { |
| 1011 | barrier.wait(); |
| 1012 | for k in 0..RACE_K { |
| 1013 | record_directory_crumb( |
| 1014 | &format!("thread{t}"), |
| 1015 | "s", |
| 1016 | &dir.join("f.rs"), |
| 1017 | "edit", |
| 1018 | &format!("t{t}k{k}"), |
| 1019 | "v", |
| 1020 | ) |
| 1021 | .expect("record"); |
| 1022 | if k < 3 { |
| 1023 | leave_dir_whisper(&format!("thread{t}"), &dir, None, &format!("t{t}k{k}")) |
| 1024 | .expect("whisper"); |
| 1025 | } |
| 1026 | } |
| 1027 | })); |
| 1028 | } |
| 1029 | for _ in 0..M { |
| 1030 | let (dir, barrier, exe) = (dir.clone(), barrier.clone(), exe.clone()); |
| 1031 | handles.push(std::thread::spawn(move || { |
| 1032 | barrier.wait(); |
| 1033 | let out = std::process::Command::new(exe) |
| 1034 | .args(["crumbs::tests::race_child_writer", "--exact", "--nocapture"]) |
| 1035 | .env(RACE_DIR_ENV, &dir) |
| 1036 | .output() |
| 1037 | .expect("spawn child"); |
| 1038 | assert!(out.status.success(), "child failed: {:?}", out); |
| 1039 | })); |
| 1040 | } |
| 1041 | for h in handles { |
| 1042 | h.join().unwrap(); |
| 1043 | } |
| 1044 | let (history, whispers) = local_counts(&dir); |
| 1045 | println!( |
| 1046 | "RACE aien-cli history expected {} got {}; whispers expected {} got {}", |
| 1047 | (N + M) * RACE_K, |
| 1048 | history, |
| 1049 | (N + M) * 3, |
| 1050 | whispers |
| 1051 | ); |
| 1052 | assert_eq!(history, (N + M) * RACE_K, "lost history updates"); |
| 1053 | assert_eq!(whispers, (N + M) * 3, "lost whisper updates"); |
| 1054 | } |
| 1055 | |
| 1056 | /// core#924: two workers with their own identities see each other's |
| 1057 | /// records in sniff and never their own. The process identity is never a |
| 1058 | /// shared constant. |
| 1059 | #[test] |
| 1060 | fn distinct_workers_see_each_other() { |
| 1061 | let tmp = tempfile::tempdir().unwrap(); |
| 1062 | let dir = tmp.path().join("work"); |
| 1063 | fs::create_dir_all(&dir).unwrap(); |
| 1064 | let file = dir.join("shared.rs"); |
| 1065 | fs::write(&file, "fn main() {}\n").unwrap(); |
| 1066 | let worker = |session: &str| { |
| 1067 | let env = |k: &str| match k { |
| 1068 | "AIEN_AGENT_NAME" => Some("worker".to_string()), |
| 1069 | "AIEN_SESSION_ID" => Some(session.to_string()), |
| 1070 | _ => None, |
| 1071 | }; |
| 1072 | spark_crumbs::local::resolve_identity_with(&env, "aien-cli").unwrap() |
| 1073 | }; |
| 1074 | let (a, b) = (worker("s1"), worker("s2")); |
| 1075 | assert_ne!(a.agent_id, b.agent_id); |
| 1076 | for (who, intent) in [(&a, "edit by s1"), (&b, "edit by s2")] { |
| 1077 | record_directory_crumb(&who.agent_id, &who.session_id, &file, "edit", intent, "v") |
| 1078 | .expect("record"); |
| 1079 | } |
| 1080 | let seen_by_a = sniff_dir_crumb(&file, &a.agent_id).unwrap().unwrap(); |
| 1081 | let seen_by_b = sniff_dir_crumb(&file, &b.agent_id).unwrap().unwrap(); |
| 1082 | assert!(seen_by_a.contains("edit by s2") && !seen_by_a.contains("edit by s1")); |
| 1083 | assert!(seen_by_b.contains("edit by s1") && !seen_by_b.contains("edit by s2")); |
| 1084 | |
| 1085 | let me = agent_identity().expect("process identity"); |
| 1086 | for constant in spark_crumbs::local::SHARED_CONSTANT_IDENTITIES { |
| 1087 | assert_ne!(me.agent_id, constant); |
| 1088 | assert_ne!(me.session_id, constant); |
| 1089 | } |
| 1090 | } |
| 1091 | |
| 1092 | /// core#924: malformed or unreadable notes are an error for sniff, |
| 1093 | /// record and whisper, a visible line in the views, and is never |
| 1094 | /// overwritten. |
| 1095 | #[test] |
| 1096 | fn broken_local_state_is_an_error_not_an_empty_peer_list() { |
| 1097 | let tmp = tempfile::tempdir().unwrap(); |
| 1098 | let dir = tmp.path().join("work"); |
| 1099 | fs::create_dir_all(&dir).unwrap(); |
| 1100 | let local = dir.join(LOCAL_CRUMB_FILENAME); |
| 1101 | fs::write(&local, "{ \"history\": [").unwrap(); |
| 1102 | assert!(sniff_dir_crumb(&dir.join("f.rs"), "peer").is_err()); |
| 1103 | assert!(record_directory_crumb("w", "s", &dir.join("f.rs"), "edit", "i", "v").is_err()); |
| 1104 | assert!(leave_dir_whisper("w", &dir, None, "m").is_err()); |
| 1105 | assert!(format_dir_crumb_tui(&dir).contains(".crumb.local unavailable")); |
| 1106 | assert!(discover_workspace_crumbs_summary(&dir).contains(".crumb.local unavailable")); |
| 1107 | assert_eq!(fs::read_to_string(&local).unwrap(), "{ \"history\": ["); |
| 1108 | |
| 1109 | #[cfg(unix)] |
| 1110 | { |
| 1111 | use std::os::unix::fs::PermissionsExt; |
| 1112 | fs::write(&local, "{}").unwrap(); |
| 1113 | fs::set_permissions(&local, fs::Permissions::from_mode(0o000)).unwrap(); |
| 1114 | if fs::read(&local).is_err() { |
| 1115 | assert!(sniff_dir_crumb(&dir.join("f.rs"), "peer").is_err()); |
| 1116 | assert!(leave_dir_whisper("w", &dir, None, "m").is_err()); |
| 1117 | } |
| 1118 | fs::set_permissions(&local, fs::Permissions::from_mode(0o644)).unwrap(); |
| 1119 | fs::remove_file(&local).unwrap(); |
| 1120 | fs::set_permissions(&dir, fs::Permissions::from_mode(0o555)).unwrap(); |
| 1121 | if fs::write(dir.join("probe"), "x").is_err() { |
| 1122 | assert!(leave_dir_whisper("w", &dir, None, "m").is_err()); |
| 1123 | assert!(!local.exists()); |
| 1124 | } |
| 1125 | fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap(); |
| 1126 | } |
| 1127 | } |
| 1128 | |
| 1129 | /// core#924: the shared constant identity is gone from every crumb |
| 1130 | /// caller in this crate. |
| 1131 | #[test] |
| 1132 | fn crumb_callers_carry_no_constant_identity() { |
| 1133 | let sources = [ |
| 1134 | ("tools.rs", include_str!("tools.rs")), |
| 1135 | ("hooks.rs", include_str!("hooks.rs")), |
| 1136 | ("commands.rs", include_str!("commands.rs")), |
| 1137 | ("nesting.rs", include_str!("nesting.rs")), |
| 1138 | ]; |
| 1139 | let banned = [ |
| 1140 | "\"active-session\"", |
| 1141 | "\"session-hook\"", |
| 1142 | "\"tool-call\"", |
| 1143 | "(p, \"AIEN\")", |
| 1144 | "_whisper(\"AIEN\"", |
| 1145 | "created_by: \"AIEN\".to_string()", |
| 1146 | "\"actor\": \"AIEN\"", |
| 1147 | ]; |
| 1148 | let mut hits = Vec::new(); |
| 1149 | for (name, text) in sources { |
| 1150 | for b in banned { |
| 1151 | if text.contains(b) { |
| 1152 | hits.push(format!("{name}: {b}")); |
| 1153 | } |
| 1154 | } |
| 1155 | // `record_directory_crumb(` followed by a literal "AIEN" agent. |
| 1156 | let squashed: String = text.split_whitespace().collect(); |
| 1157 | if squashed.contains("record_directory_crumb(\"AIEN\"") { |
| 1158 | hits.push(format!("{name}: record_directory_crumb(\"AIEN\"")); |
| 1159 | } |
| 1160 | } |
| 1161 | assert!(hits.is_empty(), "constant identity in: {hits:?}"); |
| 1162 | } |
| 1163 | |
| 1164 | /// DRA-47: `init_sandbox` writes a fresh worktree's `.crumb` only when |
| 1165 | /// `exists()` is false, which a dangling symlink committed by the repo |
| 1166 | /// also reports. The write must not follow either kind of link. |
| 1167 | #[cfg(unix)] |
| 1168 | #[test] |
| 1169 | fn new_crumb_is_not_written_through_a_symlink() { |
| 1170 | use std::os::unix::fs::symlink; |
| 1171 | let outside = tempfile::tempdir_in("/dev/shm").unwrap(); |
| 1172 | let out = outside.path().canonicalize().unwrap(); |
| 1173 | let existing = out.join("existing"); |
| 1174 | std::fs::write(&existing, "VICTIM").unwrap(); |
| 1175 | let missing = out.join("missing"); |
| 1176 | let sandbox = tempfile::tempdir().unwrap(); |
| 1177 | let dangling = sandbox.path().join("dangling.crumb"); |
| 1178 | let linked = sandbox.path().join("linked.crumb"); |
| 1179 | symlink(&missing, &dangling).unwrap(); |
| 1180 | symlink(&existing, &linked).unwrap(); |
| 1181 | assert!(!dangling.exists(), "a dangling link reads as absent"); |
| 1182 | |
| 1183 | let _ = write_new_crumb(&dangling, "SANDBOX_CRUMB"); |
| 1184 | let _ = write_new_crumb(&linked, "SANDBOX_CRUMB"); |
| 1185 | let mut escaped = Vec::new(); |
| 1186 | if missing.symlink_metadata().is_ok() { |
| 1187 | escaped.push(format!("created {}", missing.display())); |
| 1188 | } |
| 1189 | if std::fs::read_to_string(&existing).unwrap() != "VICTIM" { |
| 1190 | escaped.push(format!("rewrote {}", existing.display())); |
| 1191 | } |
| 1192 | assert!(escaped.is_empty(), "{}", escaped.join("; ")); |
| 1193 | |
| 1194 | // Control: a plain absent path is created with the content. |
| 1195 | let fresh = sandbox.path().join(".crumb"); |
| 1196 | write_new_crumb(&fresh, "SANDBOX_CRUMB").unwrap(); |
| 1197 | assert_eq!(std::fs::read_to_string(&fresh).unwrap(), "SANDBOX_CRUMB"); |
| 1198 | } |
| 1199 | } |