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/spark-crumbs/blob/main/src/lib.rs # spark-crumbs Deterministic append-only operational event ledger Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `spark-crumbs / src / lib.rs` 693 lines ยท 24591 bytes Raw Blame History 1 use chrono::{DateTime, Utc}; 2 use colored::*; 3 use serde::{Deserialize, Serialize}; 4 use std::fs; 5 6 use std::path::Path; 7 8 pub const CRUMB_FILENAME: &str = ".crumb"; 9 pub const LOCAL_CRUMB_FILENAME: &str = ".crumb.local"; 10 11 #[derive(Serialize, Deserialize, Debug, Clone, Default)] 12 pub struct LocalCrumbData { 13 #[serde(default)] 14 pub history: Vec, 15 #[serde(default)] 16 pub whispers: Vec, 17 } 18 19 pub fn load_local_crumb(dir: &Path) -> LocalCrumbData { 20 let local_path = dir.join(LOCAL_CRUMB_FILENAME); 21 if local_path.exists() { 22 if let Ok(c) = fs::read_to_string(&local_path) { 23 if let Ok(data) = serde_json::from_str::(&c) { 24 return data; 25 } 26 } 27 } 28 LocalCrumbData::default() 29 } 30 31 pub fn save_local_crumb(dir: &Path, data: &LocalCrumbData) { 32 let local_path = dir.join(LOCAL_CRUMB_FILENAME); 33 if let Ok(json_str) = serde_json::to_string_pretty(data) { 34 let _ = fs::write(&local_path, json_str); 35 } 36 } 37 38 pub const DEFAULT_TTL_SECS: u64 = 1800; // 30 minutes 39 40 #[derive(Serialize, Deserialize, Debug, Clone)] 41 pub struct AboveInfo { 42 pub path: String, 43 pub canonical: String, 44 pub name: String, 45 pub role: String, 46 } 47 48 #[derive(Serialize, Deserialize, Debug, Clone)] 49 #[serde(untagged)] 50 pub enum AboveValue { 51 Structured(AboveInfo), 52 Path(String), 53 } 54 55 impl AboveValue { 56 pub fn to_above_info(&self) -> AboveInfo { 57 match self { 58 AboveValue::Structured(a) => a.clone(), 59 AboveValue::Path(p) => { 60 let path = std::path::Path::new(p); 61 let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "above".to_string()); 62 AboveInfo { 63 path: "..".to_string(), 64 canonical: p.clone(), 65 name, 66 role: "Parent directory context".to_string(), 67 } 68 } 69 } 70 } 71 } 72 73 74 #[derive(Serialize, Deserialize, Debug, Clone)] 75 pub struct BelowItem { 76 pub name: String, 77 pub item_type: String, // "dir" or "file" 78 pub role: String, 79 } 80 81 #[derive(Serialize, Deserialize, Debug, Clone)] 82 pub struct CrumbHistoryItem { 83 pub crumb_id: String, 84 pub timestamp: String, 85 pub agent_id: String, 86 pub session_id: String, 87 pub action: String, // "signin", "view", "edit", "create", "test" 88 pub target: String, 89 pub intent: String, 90 pub vector: String, 91 } 92 93 impl CrumbHistoryItem { 94 pub fn elapsed_secs(&self) -> u64 { 95 if let Ok(parsed) = DateTime::parse_from_rfc3339(&self.timestamp) { 96 let age = Utc::now().signed_duration_since(parsed.with_timezone(&Utc)); 97 age.num_seconds().max(0) as u64 98 } else { 99 0 100 } 101 } 102 103 pub fn is_active(&self) -> bool { 104 self.elapsed_secs() < DEFAULT_TTL_SECS 105 } 106 } 107 108 #[derive(Serialize, Deserialize, Debug, Clone)] 109 pub struct CrumbWhisper { 110 #[serde(default)] 111 pub whisper_id: String, 112 pub from_agent: String, 113 pub timestamp: String, 114 #[serde(default)] 115 pub target_file: Option, 116 pub message: String, 117 } 118 119 #[derive(Serialize, Deserialize, Debug, Clone)] 120 pub struct CrumbPurpose { 121 pub statement: String, 122 #[serde(default)] 123 pub created_by: String, 124 #[serde(default)] 125 pub session_id: String, 126 #[serde(default)] 127 pub created_at: String, 128 #[serde(default = "default_lifecycle")] 129 pub lifecycle: String, // "permanent" | "ephemeral" 130 } 131 132 fn default_lifecycle() -> String { 133 "permanent".to_string() 134 } 135 136 #[derive(Serialize, Deserialize, Debug, Clone)] 137 pub struct DirCrumb { 138 pub version: u32, 139 pub dir_path: String, 140 pub dir_name: String, 141 pub description: String, 142 #[serde(default)] 143 pub purpose: Option, 144 pub above: Option, 145 pub below: Vec, 146 pub history: Vec, 147 pub whispers: Vec, 148 } 149 150 impl DirCrumb { 151 pub fn new(dir: &Path, description: Option<&str>, purpose: Option) -> Self { 152 let canon = dir 153 .canonicalize() 154 .map(|p| p.to_string_lossy().to_string()) 155 .unwrap_or_else(|_| dir.to_string_lossy().to_string()); 156 157 let dir_name = dir 158 .file_name() 159 .map(|n| n.to_string_lossy().to_string()) 160 .unwrap_or_else(|| "/".to_string()); 161 162 // Inspect Above 163 let above = if let Some(parent) = dir.parent() { 164 if parent.starts_with("/home/drakestapleton") && parent != dir { 165 let p_canon = parent 166 .canonicalize() 167 .map(|p| p.to_string_lossy().to_string()) 168 .unwrap_or_else(|_| parent.to_string_lossy().to_string()); 169 let p_name = parent 170 .file_name() 171 .map(|n| n.to_string_lossy().to_string()) 172 .unwrap_or_else(|| "home".to_string()); 173 174 Some(AboveInfo { 175 path: "..".to_string(), 176 canonical: p_canon, 177 name: p_name, 178 role: "Parent directory context".to_string(), 179 }) 180 } else { 181 None 182 } 183 } else { 184 None 185 }; 186 187 // Inspect Below 188 let mut below = Vec::new(); 189 if let Ok(entries) = fs::read_dir(dir) { 190 for entry in entries.flatten() { 191 let name = entry.file_name().to_string_lossy().to_string(); 192 if name.starts_with(".") { 193 continue; 194 } 195 let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false); 196 below.push(BelowItem { 197 name, 198 item_type: if is_dir { "dir".to_string() } else { "file".to_string() }, 199 role: String::new(), 200 }); 201 } 202 } 203 below.sort_by(|a, b| a.name.cmp(&b.name)); 204 205 DirCrumb { 206 version: 1, 207 dir_path: canon, 208 dir_name, 209 description: description.unwrap_or("Workspace directory").to_string(), 210 purpose, 211 above: above.map(AboveValue::Structured), 212 below, 213 history: Vec::new(), 214 whispers: Vec::new(), 215 } 216 } 217 } 218 219 pub fn load_or_init_dir_crumb(dir: &Path, purpose_opt: Option) -> DirCrumb { 220 let crumb_path = dir.join(CRUMB_FILENAME); 221 if crumb_path.exists() { 222 if let Ok(content) = fs::read_to_string(&crumb_path) { 223 match serde_json::from_str::(&content) { 224 Err(e) => eprintln!("Failed to parse DirCrumb at {}: {}", crumb_path.display(), e), 225 Ok(mut crumb) => { 226 // Refresh below items dynamically 227 let mut below = Vec::new(); 228 if let Ok(entries) = fs::read_dir(dir) { 229 for entry in entries.flatten() { 230 let name = entry.file_name().to_string_lossy().to_string(); 231 if name.starts_with(".") { 232 continue; 233 } 234 let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false); 235 below.push(BelowItem { 236 name, 237 item_type: if is_dir { "dir".to_string() } else { "file".to_string() }, 238 role: String::new(), 239 }); 240 } 241 } 242 below.sort_by(|a, b| a.name.cmp(&b.name)); 243 crumb.below = below; 244 if crumb.purpose.is_none() && purpose_opt.is_some() { 245 crumb.purpose = purpose_opt.clone(); 246 save_dir_crumb(&crumb); 247 } 248 // Merge ephemeral telemetry from .crumb.local 249 let local_data = load_local_crumb(dir); 250 if !local_data.history.is_empty() { 251 for h in local_data.history { 252 if !crumb.history.iter().any(|existing| existing.crumb_id == h.crumb_id) { 253 crumb.history.push(h); 254 } 255 } 256 } 257 if !local_data.whispers.is_empty() { 258 for w in local_data.whispers { 259 if !crumb.whispers.iter().any(|existing| existing.whisper_id == w.whisper_id || existing.message == w.message) { 260 crumb.whispers.push(w); 261 } 262 } 263 } 264 return crumb; 265 } 266 } 267 } 268 } 269 270 // Auto-Sense & Seed if purpose not provided 271 let final_purpose = match purpose_opt { 272 Some(p) => Some(p), 273 None => { 274 let sensed_statement = auto_sense_directory_purpose(dir); 275 Some(CrumbPurpose { 276 statement: sensed_statement, 277 created_by: "AIEN (Auto-Sensed)".to_string(), 278 session_id: "auto-sense".to_string(), 279 created_at: Utc::now().to_rfc3339(), 280 lifecycle: "permanent".to_string(), 281 }) 282 } 283 }; 284 285 let crumb = DirCrumb::new(dir, None, final_purpose); 286 save_dir_crumb(&crumb); 287 crumb 288 } 289 290 pub fn save_dir_crumb(crumb: &DirCrumb) { 291 let dir = Path::new(&crumb.dir_path); 292 let crumb_path = dir.join(CRUMB_FILENAME); 293 294 // Durable .crumb: keep architectural purpose, above/below, clean of ephemeral churn 295 let mut durable_crumb = crumb.clone(); 296 durable_crumb.history = Vec::new(); // Ephemeral history lives in .crumb.local 297 durable_crumb.whispers = Vec::new(); // Whispers live in .crumb.local 298 299 if let Ok(json_str) = serde_json::to_string_pretty(&durable_crumb) { 300 let _ = fs::write(&crumb_path, json_str); 301 } 302 } 303 304 /// Records an action in the directory's `.crumb` file and bubbles awareness to parent. 305 pub fn record_directory_crumb( 306 agent_id: &str, 307 session_id: &str, 308 target_path: &Path, 309 action: &str, 310 intent: &str, 311 vector: &str, 312 ) { 313 let dir = if target_path.is_dir() { 314 target_path.to_path_buf() 315 } else { 316 target_path.parent().unwrap_or(target_path).to_path_buf() 317 }; 318 319 let target_name = target_path 320 .file_name() 321 .map(|n| n.to_string_lossy().to_string()) 322 .unwrap_or_else(|| "dir".to_string()); 323 324 let dir_name = dir.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dir".to_string()); 325 let mut local_data = load_local_crumb(&dir); 326 327 let item = CrumbHistoryItem { 328 crumb_id: format!("crumb-{}", Utc::now().timestamp_nanos_opt().unwrap_or(0)), 329 timestamp: Utc::now().to_rfc3339(), 330 agent_id: agent_id.to_string(), 331 session_id: session_id.to_string(), 332 action: action.to_string(), 333 target: target_name.clone(), 334 intent: intent.to_string(), 335 vector: vector.to_string(), 336 }; 337 338 local_data.history.push(item); 339 if local_data.history.len() > 50 { 340 local_data.history.drain(0..local_data.history.len() - 50); 341 } 342 save_local_crumb(&dir, &local_data); 343 344 // If dir has a parent within project workspace, bubble awareness to parent .crumb.local 345 if let Some(parent) = dir.parent() { 346 if parent.starts_with("/home/drakestapleton") && parent != dir { 347 let mut parent_local = load_local_crumb(parent); 348 let bubble_item = CrumbHistoryItem { 349 crumb_id: format!("bubble-{}", Utc::now().timestamp_nanos_opt().unwrap_or(0)), 350 timestamp: Utc::now().to_rfc3339(), 351 agent_id: agent_id.to_string(), 352 session_id: session_id.to_string(), 353 action: format!("sub:{}", action), 354 target: format!("{}/{}", dir_name, target_name), 355 intent: intent.to_string(), 356 vector: vector.to_string(), 357 }; 358 parent_local.history.push(bubble_item); 359 if parent_local.history.len() > 50 { 360 parent_local.history.drain(0..parent_local.history.len() - 50); 361 } 362 save_local_crumb(parent, &parent_local); 363 } 364 } 365 } 366 367 /// Leaves a whisper message in a directory .crumb.local file. 368 pub fn leave_dir_whisper( 369 from_agent: &str, 370 dir: &Path, 371 target_file: Option<&str>, 372 message: &str, 373 ) { 374 let mut local_data = load_local_crumb(dir); 375 let whisper = CrumbWhisper { 376 whisper_id: format!("whisp-{}", Utc::now().timestamp_nanos_opt().unwrap_or(0)), 377 from_agent: from_agent.to_string(), 378 timestamp: Utc::now().to_rfc3339(), 379 target_file: target_file.map(|s| s.to_string()), 380 message: message.to_string(), 381 }; 382 local_data.whispers.push(whisper); 383 if local_data.whispers.len() > 30 { 384 local_data.whispers.drain(0..local_data.whispers.len() - 30); 385 } 386 save_local_crumb(dir, &local_data); 387 } 388 389 /// Sniffs directory crumb and checks for recent actions or whispers on target file. 390 pub fn sniff_dir_crumb(target_path: &Path, current_agent: &str) -> Option { 391 let dir = if target_path.is_dir() { 392 target_path.to_path_buf() 393 } else { 394 target_path.parent().unwrap_or(target_path).to_path_buf() 395 }; 396 397 let crumb = load_or_init_dir_crumb(&dir, None); 398 let target_name = target_path 399 .file_name() 400 .map(|n| n.to_string_lossy().to_string()) 401 .unwrap_or_default(); 402 403 let mut notices = Vec::new(); 404 405 // Check history for this target or directory 406 for item in crumb.history.iter().rev() { 407 if (item.target == target_name || item.target.ends_with(&target_name) || target_path.is_dir()) 408 && item.agent_id != current_agent 409 && item.is_active() 410 { 411 let elapsed = item.elapsed_secs(); 412 let el_str = if elapsed < 60 { 413 format!("{}s ago", elapsed) 414 } else { 415 format!("{}m ago", elapsed / 60) 416 }; 417 notices.push(format!( 418 "โ€ข [{}] {} on '{}' ({}) - Intent: '{}' -> Vector: '{}'", 419 item.agent_id, item.action, item.target, el_str, item.intent, item.vector 420 )); 421 } 422 } 423 424 // Check whispers 425 for w in crumb.whispers.iter().rev() { 426 if let Ok(parsed) = DateTime::parse_from_rfc3339(&w.timestamp) { 427 let age = Utc::now().signed_duration_since(parsed.with_timezone(&Utc)); 428 if age.num_seconds() >= 0 && (age.num_seconds() as u64) < DEFAULT_TTL_SECS * 2 { 429 if let Some(tf) = &w.target_file { 430 if tf == &target_name || target_path.is_dir() { 431 notices.push(format!("๐Ÿ’ฌ [Whisper from {}]: {}", w.from_agent, w.message)); 432 } 433 } else { 434 notices.push(format!("๐Ÿ’ฌ [Whisper from {}]: {}", w.from_agent, w.message)); 435 } 436 } 437 } 438 } 439 440 if notices.is_empty() { 441 return None; 442 } 443 444 let mut out = format!("๐Ÿพ [DIRECTORY CRUMB: {}/.crumb]\n", dir.display()); 445 if let Some(above_raw) = &crumb.above { let above = above_raw.to_above_info(); 446 out.push_str(&format!(" โ†‘ Above: {} ({})\n", above.canonical, above.name)); 447 } 448 if let Some(p) = &crumb.purpose { 449 out.push_str(&format!(" ๐ŸŽฏ Purpose: {}\n", p.statement.cyan())); 450 } 451 out.push_str(" Recent Peer History in this directory:\n"); 452 for n in notices.iter().take(4) { 453 out.push_str(&format!(" {}\n", n)); 454 } 455 out.push_str("โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n"); 456 Some(out) 457 } 458 459 /// Pretty-prints a rich TUI inspection card for a directory's crumb. 460 pub fn format_dir_crumb_tui(dir: &Path) -> String { 461 let crumb = load_or_init_dir_crumb(dir, None); 462 463 let mut out = String::new(); 464 out.push_str(&format!("๐Ÿงญ DIRECTORY CRUMB: {} ({})\n", crumb.dir_name.bold().cyan(), crumb.dir_path.dimmed())); 465 out.push_str(&format!(" Description: {}\n", crumb.description)); 466 if let Some(p) = &crumb.purpose { 467 out.push_str(&format!(" ๐ŸŽฏ PURPOSE: {} [{} | by {}]\n", p.statement.bold().magenta(), p.lifecycle.cyan(), p.created_by.yellow())); 468 } 469 470 if let Some(above_raw) = &crumb.above { let above = above_raw.to_above_info(); 471 out.push_str(&format!(" โ†‘ ABOVE: {} [{}]\n", above.name.bold().yellow(), above.canonical.dimmed())); 472 } else { 473 out.push_str(" โ†‘ ABOVE: [Root workspace boundary]\n"); 474 } 475 476 let dirs: Vec<&str> = crumb.below.iter().filter(|i| i.item_type == "dir").map(|i| i.name.as_str()).collect(); 477 let files: Vec<&str> = crumb.below.iter().filter(|i| i.item_type == "file").map(|i| i.name.as_str()).collect(); 478 479 out.push_str(&format!(" โ†“ BELOW (Subdirectories): [{}]\n", dirs.join(", ").cyan())); 480 out.push_str(&format!(" โ†“ BELOW (Files): [{}]\n", files.join(", ").white())); 481 482 out.push_str(&format!("\n๐Ÿ“œ Agent Chronicle in this Directory (Total: {}):\n", crumb.history.len())); 483 if crumb.history.is_empty() { 484 out.push_str(" (No previous actions recorded in this directory)\n"); 485 } else { 486 for (i, h) in crumb.history.iter().rev().take(5).enumerate() { 487 let elapsed = h.elapsed_secs(); 488 let el_str = if elapsed < 60 { format!("{}s ago", elapsed) } else { format!("{}m ago", elapsed / 60) }; 489 out.push_str(&format!( 490 " {}. [{}] {} '{}' ({})\n Intent: {}\n Vector: {}\n", 491 i + 1, h.agent_id.bold().yellow(), h.action, h.target.green(), el_str, h.intent, h.vector.dimmed() 492 )); 493 } 494 } 495 496 if !crumb.whispers.is_empty() { 497 out.push_str("\n๐Ÿ’ฌ Directory Whispers & Intercommunication:\n"); 498 for w in crumb.whispers.iter().rev().take(3) { 499 out.push_str(&format!(" โ€ข From [{}]: \"{}\"\n", w.from_agent.bold().cyan(), w.message)); 500 } 501 } 502 503 out 504 } 505 506 /// Discovers directory crumbs for nesting ritual, showing immediate directory topography. 507 pub fn discover_workspace_crumbs_summary(start_dir: &Path) -> String { 508 let crumb = load_or_init_dir_crumb(start_dir, None); 509 let mut s = format!( 510 "[DIRECTORY CRUMB TOPOGRAPHY: {}]\n\ 511 Current: {} ({})\n", 512 crumb.dir_name, crumb.dir_path, crumb.description 513 ); 514 515 if let Some(above_raw) = &crumb.above { let above = above_raw.to_above_info(); 516 s.push_str(&format!("โ†‘ Above: {} ({})\n", above.name, above.canonical)); 517 } 518 if let Some(p) = &crumb.purpose { 519 s.push_str(&format!("๐ŸŽฏ Directory Purpose: {}\n", p.statement)); 520 } 521 522 let subdirs: Vec<&str> = crumb.below.iter().filter(|i| i.item_type == "dir").map(|i| i.name.as_str()).collect(); 523 if !subdirs.is_empty() { 524 s.push_str(&format!("โ†“ Below Subdirs: [{}]\n", subdirs.join(", "))); 525 } 526 527 if !crumb.history.is_empty() { 528 s.push_str("Recent Actions in this Directory:\n"); 529 for h in crumb.history.iter().rev().take(3) { 530 s.push_str(&format!("โ€ข [{}] {} '{}' - Intent: '{}' -> Vector: '{}'\n", h.agent_id, h.action, h.target, h.intent, h.vector)); 531 } 532 } 533 534 if !crumb.whispers.is_empty() { 535 s.push_str("Directory Whispers:\n"); 536 for w in crumb.whispers.iter().rev().take(2) { 537 s.push_str(&format!("โ€ข [{}] \"{}\"\n", w.from_agent, w.message)); 538 } 539 } 540 541 s 542 } 543 544 545 fn auto_sense_directory_purpose(dir: &Path) -> String { 546 let readme = dir.join("README.md"); 547 if readme.exists() { 548 if let Ok(c) = fs::read_to_string(&readme) { 549 for line in c.lines() { 550 let trimmed = line.trim().trim_start_matches('#').trim(); 551 if !trimmed.is_empty() { 552 return format!("Documentation & implementation for {}", trimmed); 553 } 554 } 555 } 556 } 557 let cargo = dir.join("Cargo.toml"); 558 if cargo.exists() { 559 if let Ok(c) = fs::read_to_string(&cargo) { 560 for line in c.lines() { 561 if line.starts_with("name =") { 562 let name = line.replace("name =", "").replace("\"", "").trim().to_string(); 563 return format!("Rust crate codebase: {}", name); 564 } 565 } 566 } 567 } 568 let pkg = dir.join("package.json"); 569 if pkg.exists() { 570 if let Ok(c) = fs::read_to_string(&pkg) { 571 if let Ok(val) = serde_json::from_str::(&c) { 572 if let Some(name) = val.get("name").and_then(|n| n.as_str()) { 573 return format!("Node/Web package: {}", name); 574 } 575 } 576 } 577 } 578 let dir_name = dir.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "workspace".to_string()); 579 format!("Workspace subsystem directory for {}", dir_name) 580 } 581 582 pub fn seed_directory_tree(root: &Path, recursive: bool, agent: &str, whisper: Option<&str>) -> usize { 583 let mut count = 0; 584 if !recursive { 585 load_or_init_dir_crumb(root, None); 586 if let Some(msg) = whisper { 587 leave_dir_whisper(agent, root, None, msg); 588 } 589 return 1; 590 } 591 592 for entry in walkdir::WalkDir::new(root) 593 .min_depth(0) 594 .max_depth(6) 595 .into_iter() 596 .filter_entry(|e| { 597 let name = e.file_name().to_string_lossy(); 598 !name.starts_with('.') && name != "target" && name != "node_modules" 599 }) 600 .flatten() 601 { 602 if entry.file_type().is_dir() { 603 let path = entry.path(); 604 load_or_init_dir_crumb(path, None); 605 if let Some(msg) = whisper { 606 leave_dir_whisper(agent, path, None, msg); 607 } 608 count += 1; 609 } 610 } 611 count 612 } 613 614 pub fn sniff_crumb(target_path: &Path, current_agent: &str) -> Option { 615 sniff_dir_crumb(target_path, current_agent) 616 } 617 618 pub fn add_crumb_whisper(dir: &Path, from_agent: &str, message: &str, target_file: Option<&str>) { 619 leave_dir_whisper(from_agent, dir, target_file, message); 620 } 621 622 pub fn record_crumb_action( 623 dir: &Path, 624 agent_id: &str, 625 session_id: &str, 626 action: &str, 627 target: &str, 628 intent: &str, 629 vector: &str, 630 ) { 631 record_directory_crumb(agent_id, session_id, &dir.join(target), action, intent, vector); 632 } 633 634 #[cfg(test)] 635 mod tests { 636 use super::*; 637 638 #[test] 639 fn test_crumb_lifecycle_and_whisper() { 640 let temp_dir = std::env::temp_dir().join(format!("test-crumb-{}", uuid::Uuid::new_v4())); 641 fs::create_dir_all(&temp_dir).expect("create temp dir"); 642 643 let crumb = load_or_init_dir_crumb(&temp_dir, None); 644 assert!(crumb.purpose.is_some()); 645 646 record_directory_crumb( 647 "Atlas-Prime", 648 "test-session-01", 649 &temp_dir.join("lib.rs"), 650 "edit", 651 "Verify crumb persistence", 652 "Testing spark-crumbs subsystem", 653 ); 654 655 leave_dir_whisper( 656 "AIEN", 657 &temp_dir, 658 Some("lib.rs"), 659 "Verification lock acquired", 660 ); 661 662 let sniff = sniff_dir_crumb(&temp_dir.join("lib.rs"), "Peer-Agent"); 663 assert!(sniff.is_some()); 664 let sniff_str = sniff.unwrap(); 665 assert!(sniff_str.contains("Atlas-Prime")); 666 assert!(sniff_str.contains("Verification lock")); 667 668 let _ = fs::remove_dir_all(&temp_dir); 669 } 670 671 #[test] 672 fn test_seed_directory_tree() { 673 let temp_dir = std::env::temp_dir().join(format!("test-seed-{}", uuid::Uuid::new_v4())); 674 let sub = temp_dir.join("sub"); 675 fs::create_dir_all(&sub).expect("create sub dir"); 676 677 let count = seed_directory_tree(&temp_dir, true, "AIEN", Some("Seeded tree")); 678 assert!(count >= 2); 679 680 let _ = fs::remove_dir_all(&temp_dir); 681 } 682 683 #[test] 684 fn test_format_tui_card() { 685 let temp_dir = std::env::temp_dir().join(format!("test-tui-{}", uuid::Uuid::new_v4())); 686 fs::create_dir_all(&temp_dir).expect("create temp dir"); 687 688 let card = format_dir_crumb_tui(&temp_dir); 689 assert!(card.contains("DIRECTORY CRUMB")); 690 691 let _ = fs::remove_dir_all(&temp_dir); 692 } 693 }