interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / spark-crumbs / src / lib.rs

1045 lines · 37813 bytes Raw Blame History
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
16use chrono::{DateTime, Utc};
17use colored::*;
18use serde::{Deserialize, Serialize};
19use std::fs;
20
21use std::path::Path;
22
23pub mod local;
24
25pub use local::{
26 load_local_crumb, process_identity, resolve_identity, save_local_crumb, update_local_crumb,
27 AgentIdentity, CrumbHistoryItem, CrumbWhisper, IdentityError, LocalCrumbData, LocalCrumbError,
28 LocalCrumbErrorKind, DEFAULT_TTL_SECS, LOCAL_CRUMB_FILENAME,
29};
30
31pub const CRUMB_FILENAME: &str = ".crumb";
32
33#[derive(Serialize, Deserialize, Debug, Clone)]
34pub struct AboveInfo {
35 pub path: String,
36 pub canonical: String,
37 pub name: String,
38 pub role: String,
39}
40
41#[derive(Serialize, Deserialize, Debug, Clone)]
42#[serde(untagged)]
43pub enum AboveValue {
44 Structured(AboveInfo),
45 Path(String),
46}
47
48impl AboveValue {
49 pub fn to_above_info(&self) -> AboveInfo {
50 match self {
51 AboveValue::Structured(a) => a.clone(),
52 AboveValue::Path(p) => {
53 let path = std::path::Path::new(p);
54 let name = path
55 .file_name()
56 .map(|n| n.to_string_lossy().to_string())
57 .unwrap_or_else(|| "above".to_string());
58 AboveInfo {
59 path: "..".to_string(),
60 canonical: p.clone(),
61 name,
62 role: "Parent directory context".to_string(),
63 }
64 }
65 }
66 }
67}
68
69#[derive(Serialize, Deserialize, Debug, Clone)]
70pub struct BelowItem {
71 pub name: String,
72 pub item_type: String, // "dir" or "file"
73 pub role: String,
74}
75
76#[derive(Serialize, Deserialize, Debug, Clone)]
77pub struct CrumbPurpose {
78 pub statement: String,
79 #[serde(default)]
80 pub created_by: String,
81 #[serde(default)]
82 pub session_id: String,
83 #[serde(default)]
84 pub created_at: String,
85 #[serde(default = "default_lifecycle")]
86 pub lifecycle: String, // "permanent" | "ephemeral"
87}
88
89fn default_lifecycle() -> String {
90 "permanent".to_string()
91}
92
93/// A `.crumb` written by this tool. Unknown fields are rejected so that a file
94/// carrying anything this tool would drop on save (for example hand-written
95/// `invariants`) is treated as foreign and never rewritten.
96#[derive(Serialize, Deserialize, Debug, Clone)]
97#[serde(deny_unknown_fields)]
98pub struct DirCrumb {
99 pub version: u32,
100 pub dir_path: String,
101 pub dir_name: String,
102 pub description: String,
103 #[serde(default)]
104 pub purpose: Option<CrumbPurpose>,
105 pub above: Option<AboveValue>,
106 pub below: Vec<BelowItem>,
107 pub history: Vec<CrumbHistoryItem>,
108 pub whispers: Vec<CrumbWhisper>,
109}
110
111impl DirCrumb {
112 pub fn new(dir: &Path, description: Option<&str>, purpose: Option<CrumbPurpose>) -> Self {
113 let (canon, dir_name) = dir_identity(dir);
114
115 // Inspect Above (from the resolved path, so `.` still has a parent)
116 let canon_path = Path::new(&canon);
117 let above = if let Some(parent) = canon_path.parent() {
118 let home = std::env::var("HOME")
119 .or_else(|_| std::env::var("USERPROFILE"))
120 .unwrap_or_default();
121 if !home.is_empty() && parent.starts_with(&home) && parent != canon_path {
122 let p_canon = parent
123 .canonicalize()
124 .map(|p| p.to_string_lossy().to_string())
125 .unwrap_or_else(|_| parent.to_string_lossy().to_string());
126 let p_name = parent
127 .file_name()
128 .map(|n| n.to_string_lossy().to_string())
129 .unwrap_or_else(|| "home".to_string());
130
131 Some(AboveInfo {
132 path: "..".to_string(),
133 canonical: p_canon,
134 name: p_name,
135 role: "Parent directory context".to_string(),
136 })
137 } else {
138 None
139 }
140 } else {
141 None
142 };
143
144 // Inspect Below
145 let mut below = Vec::new();
146 if let Ok(entries) = fs::read_dir(dir) {
147 for entry in entries.flatten() {
148 let name = entry.file_name().to_string_lossy().to_string();
149 if name.starts_with(".") {
150 continue;
151 }
152 let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
153 below.push(BelowItem {
154 name,
155 item_type: if is_dir {
156 "dir".to_string()
157 } else {
158 "file".to_string()
159 },
160 role: String::new(),
161 });
162 }
163 }
164 below.sort_by(|a, b| a.name.cmp(&b.name));
165
166 DirCrumb {
167 version: 1,
168 dir_path: canon,
169 dir_name,
170 description: description.unwrap_or("Workspace directory").to_string(),
171 purpose,
172 above: above.map(AboveValue::Structured),
173 below,
174 history: Vec::new(),
175 whispers: Vec::new(),
176 }
177 }
178}
179
180/// Reads `crumb_path`. `Ok(None)`: no file. `Ok(Some)`: a crumb in this tool's
181/// `DirCrumb` format. `Err`: a file exists that is not in that format (for
182/// example a hand-written schema 1.0.0 crumb) or cannot be read; such a file is
183/// never rewritten.
184fn read_dir_crumb_file(crumb_path: &Path) -> Result<Option<DirCrumb>, String> {
185 match fs::symlink_metadata(crumb_path) {
186 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
187 Err(e) => return Err(format!("{}: {}", crumb_path.display(), e)),
188 Ok(_) => {}
189 }
190 let content =
191 fs::read_to_string(crumb_path).map_err(|e| format!("{}: {}", crumb_path.display(), e))?;
192 serde_json::from_str::<DirCrumb>(&content)
193 .map(Some)
194 .map_err(|e| format!("{} is not a DirCrumb: {}", crumb_path.display(), e))
195}
196
197/// Read-only view of a directory whose `.crumb` is not in `DirCrumb` format.
198/// The purpose comes from the file's `purpose` string when it has one.
199fn foreign_crumb_view(dir: &Path) -> DirCrumb {
200 let statement = fs::read_to_string(dir.join(CRUMB_FILENAME))
201 .ok()
202 .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
203 .and_then(|v| {
204 v.get("purpose")
205 .and_then(|p| p.as_str())
206 .map(str::to_string)
207 });
208 let purpose = statement.map(|statement| CrumbPurpose {
209 statement,
210 created_by: "hand-written .crumb".to_string(),
211 session_id: String::new(),
212 created_at: String::new(),
213 lifecycle: "permanent".to_string(),
214 });
215 DirCrumb::new(
216 dir,
217 Some("Existing .crumb is not in DirCrumb format; shown read-only and never rewritten"),
218 purpose,
219 )
220}
221
222/// Merges ephemeral notes from `.crumb.local` into `crumb`. An unreadable
223/// or malformed `.crumb.local` is an error, never an empty peer list.
224pub fn merge_local_crumb(crumb: &mut DirCrumb, dir: &Path) -> Result<(), LocalCrumbError> {
225 let local_data = load_local_crumb(dir)?;
226 for h in local_data.history {
227 if !crumb
228 .history
229 .iter()
230 .any(|existing| existing.crumb_id == h.crumb_id)
231 {
232 crumb.history.push(h);
233 }
234 }
235 for w in local_data.whispers {
236 if !crumb
237 .whispers
238 .iter()
239 .any(|existing| existing.whisper_id == w.whisper_id || existing.message == w.message)
240 {
241 crumb.whispers.push(w);
242 }
243 }
244 Ok(())
245}
246
247/// The directory crumb with its `.crumb.local` notes merged in, for
248/// display. When the notes cannot be loaded the crumb comes back without
249/// it, together with the error, which the caller must show.
250pub fn load_dir_crumb_view(dir: &Path) -> (DirCrumb, Option<LocalCrumbError>) {
251 let mut crumb = load_or_init_dir_crumb(dir, None);
252 let err = merge_local_crumb(&mut crumb, dir).err();
253 (crumb, err)
254}
255
256/// Loads `dir/.crumb` (the durable part only; `.crumb.local` notes are
257/// merged by [`merge_local_crumb`] / [`load_dir_crumb_view`]). Seeds and writes
258/// a new crumb only when no `.crumb` file exists. A `.crumb` that is not in
259/// `DirCrumb` format (a hand-written crumb) is never written; a read-only view
260/// is returned instead.
261pub fn load_or_init_dir_crumb(dir: &Path, purpose_opt: Option<CrumbPurpose>) -> DirCrumb {
262 let crumb_path = dir.join(CRUMB_FILENAME);
263 match read_dir_crumb_file(&crumb_path) {
264 Err(_) => return foreign_crumb_view(dir),
265 Ok(Some(mut crumb)) => {
266 // The stored location may be stale (the crumb was moved or copied):
267 // the directory it was loaded from is authoritative.
268 let (dir_path, dir_name) = dir_identity(dir);
269 crumb.dir_path = dir_path;
270 crumb.dir_name = dir_name;
271 // Refresh below items dynamically
272 let mut below = Vec::new();
273 if let Ok(entries) = fs::read_dir(dir) {
274 for entry in entries.flatten() {
275 let name = entry.file_name().to_string_lossy().to_string();
276 if name.starts_with(".") {
277 continue;
278 }
279 let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
280 below.push(BelowItem {
281 name,
282 item_type: if is_dir {
283 "dir".to_string()
284 } else {
285 "file".to_string()
286 },
287 role: String::new(),
288 });
289 }
290 }
291 below.sort_by(|a, b| a.name.cmp(&b.name));
292 crumb.below = below;
293 if crumb.purpose.is_none() && purpose_opt.is_some() {
294 crumb.purpose = purpose_opt.clone();
295 let _ = save_dir_crumb(dir, &crumb);
296 }
297 return crumb;
298 }
299 Ok(None) => {}
300 }
301
302 // Auto-Sense & Seed if purpose not provided
303 let final_purpose = match purpose_opt {
304 Some(p) => Some(p),
305 None => {
306 let sensed_statement = auto_sense_directory_purpose(dir);
307 Some(CrumbPurpose {
308 statement: sensed_statement,
309 created_by: "AIEN (Auto-Sensed)".to_string(),
310 session_id: "auto-sense".to_string(),
311 created_at: Utc::now().to_rfc3339(),
312 lifecycle: "permanent".to_string(),
313 })
314 }
315 };
316
317 let crumb = DirCrumb::new(dir, None, final_purpose);
318 let _ = save_dir_crumb(dir, &crumb);
319 crumb
320}
321
322/// Canonical path and name of `dir`, so `.` and relative paths get the real
323/// directory name. Falls back to the path as given when it cannot be resolved.
324fn dir_identity(dir: &Path) -> (String, String) {
325 let canon = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
326 let name = canon
327 .file_name()
328 .map(|n| n.to_string_lossy().to_string())
329 .unwrap_or_else(|| "/".to_string());
330 (canon.to_string_lossy().to_string(), name)
331}
332
333/// Writes the durable part of `crumb` to `dir/.crumb`, never to the crumb's
334/// stored `dir_path`, and records `dir` as its location. Refuses, without
335/// writing, when an existing `.crumb` is not in `DirCrumb` format.
336pub fn save_dir_crumb(dir: &Path, crumb: &DirCrumb) -> Result<(), String> {
337 let crumb_path = dir.join(CRUMB_FILENAME);
338 if let Err(e) = read_dir_crumb_file(&crumb_path) {
339 return Err(format!("refusing to overwrite .crumb: {}", e));
340 }
341
342 // Durable .crumb: keep architectural purpose, above/below, clean of ephemeral churn
343 let mut durable_crumb = crumb.clone();
344 let (dir_path, dir_name) = dir_identity(dir);
345 durable_crumb.dir_path = dir_path;
346 durable_crumb.dir_name = dir_name;
347 durable_crumb.history = Vec::new(); // Ephemeral history lives in .crumb.local
348 durable_crumb.whispers = Vec::new(); // Whispers live in .crumb.local
349
350 let json_str = serde_json::to_string_pretty(&durable_crumb).map_err(|e| e.to_string())?;
351 fs::write(&crumb_path, json_str).map_err(|e| format!("{}: {}", crumb_path.display(), e))
352}
353
354/// Records an action in the directory's `.crumb.local` and bubbles awareness to
355/// the parent. Each write is one locked read-modify-write. The first failure
356/// is returned (a failed bubble after a successful record is still an error).
357pub fn record_directory_crumb(
358 agent_id: &str,
359 session_id: &str,
360 target_path: &Path,
361 action: &str,
362 intent: &str,
363 vector: &str,
364) -> Result<(), LocalCrumbError> {
365 let dir = if target_path.is_dir() {
366 target_path.to_path_buf()
367 } else {
368 target_path.parent().unwrap_or(target_path).to_path_buf()
369 };
370
371 let target_name = target_path
372 .file_name()
373 .map(|n| n.to_string_lossy().to_string())
374 .unwrap_or_else(|| "dir".to_string());
375
376 let dir_name = dir
377 .file_name()
378 .map(|n| n.to_string_lossy().to_string())
379 .unwrap_or_else(|| "dir".to_string());
380
381 let item = CrumbHistoryItem {
382 crumb_id: local::unique_record_id("crumb"),
383 timestamp: Utc::now().to_rfc3339(),
384 agent_id: agent_id.to_string(),
385 session_id: session_id.to_string(),
386 action: action.to_string(),
387 target: target_name.clone(),
388 intent: intent.to_string(),
389 vector: vector.to_string(),
390 };
391 local::push_history(&dir, item)?;
392
393 // If dir has a parent within project workspace, bubble awareness to parent .crumb.local
394 if let Some(parent) = dir.parent() {
395 let home = std::env::var("HOME")
396 .or_else(|_| std::env::var("USERPROFILE"))
397 .unwrap_or_default();
398 if !home.is_empty() && parent.starts_with(&home) && parent != dir {
399 let bubble_item = CrumbHistoryItem {
400 crumb_id: local::unique_record_id("bubble"),
401 timestamp: Utc::now().to_rfc3339(),
402 agent_id: agent_id.to_string(),
403 session_id: session_id.to_string(),
404 action: format!("sub:{}", action),
405 target: format!("{}/{}", dir_name, target_name),
406 intent: intent.to_string(),
407 vector: vector.to_string(),
408 };
409 local::push_history(parent, bubble_item)?;
410 }
411 }
412 Ok(())
413}
414
415/// Leaves a whisper message in a directory .crumb.local file.
416pub fn leave_dir_whisper(
417 from_agent: &str,
418 dir: &Path,
419 target_file: Option<&str>,
420 message: &str,
421) -> Result<(), LocalCrumbError> {
422 let whisper = CrumbWhisper {
423 whisper_id: local::unique_record_id("whisp"),
424 from_agent: from_agent.to_string(),
425 timestamp: Utc::now().to_rfc3339(),
426 target_file: target_file.map(|s| s.to_string()),
427 message: message.to_string(),
428 };
429 local::push_whisper(dir, whisper)
430}
431
432/// Sniffs directory crumb and checks for recent actions or whispers on target
433/// file by agents other than `current_agent`. `Ok(None)`: no peer activity.
434/// `Err`: the notes could not be read, so peers are unknown (not absent).
435pub fn sniff_dir_crumb(
436 target_path: &Path,
437 current_agent: &str,
438) -> Result<Option<String>, LocalCrumbError> {
439 let dir = if target_path.is_dir() {
440 target_path.to_path_buf()
441 } else {
442 target_path.parent().unwrap_or(target_path).to_path_buf()
443 };
444
445 let mut crumb = load_or_init_dir_crumb(&dir, None);
446 merge_local_crumb(&mut crumb, &dir)?;
447 let target_name = target_path
448 .file_name()
449 .map(|n| n.to_string_lossy().to_string())
450 .unwrap_or_default();
451
452 let mut notices = Vec::new();
453
454 // Check history for this target or directory
455 for item in crumb.history.iter().rev() {
456 if (item.target == target_name
457 || item.target.ends_with(&target_name)
458 || target_path.is_dir())
459 && item.agent_id != current_agent
460 && item.is_active()
461 {
462 let elapsed = item.elapsed_secs();
463 let el_str = if elapsed < 60 {
464 format!("{}s ago", elapsed)
465 } else {
466 format!("{}m ago", elapsed / 60)
467 };
468 notices.push(format!(
469 "• [{}] {} on '{}' ({}) - Intent: '{}' -> Vector: '{}'",
470 item.agent_id, item.action, item.target, el_str, item.intent, item.vector
471 ));
472 }
473 }
474
475 // Check whispers
476 for w in crumb.whispers.iter().rev() {
477 if let Ok(parsed) = DateTime::parse_from_rfc3339(&w.timestamp) {
478 let age = Utc::now().signed_duration_since(parsed.with_timezone(&Utc));
479 if age.num_seconds() >= 0 && (age.num_seconds() as u64) < DEFAULT_TTL_SECS * 2 {
480 if let Some(tf) = &w.target_file {
481 if tf == &target_name || target_path.is_dir() {
482 notices.push(format!("šŸ’¬ [Whisper from {}]: {}", w.from_agent, w.message));
483 }
484 } else {
485 notices.push(format!("šŸ’¬ [Whisper from {}]: {}", w.from_agent, w.message));
486 }
487 }
488 }
489 }
490
491 if notices.is_empty() {
492 return Ok(None);
493 }
494
495 let mut out = format!("🐾 [DIRECTORY CRUMB: {}/.crumb]\n", dir.display());
496 if let Some(above_raw) = &crumb.above {
497 let above = above_raw.to_above_info();
498 out.push_str(&format!(
499 " ↑ Above: {} ({})\n",
500 above.canonical, above.name
501 ));
502 }
503 if let Some(p) = &crumb.purpose {
504 out.push_str(&format!(" šŸŽÆ Purpose: {}\n", p.statement.cyan()));
505 }
506 out.push_str(" Recent Peer History in this directory:\n");
507 for n in notices.iter().take(4) {
508 out.push_str(&format!(" {}\n", n));
509 }
510 out.push_str("─────────────────────────────────────────────────────────────\n");
511 Ok(Some(out))
512}
513
514/// The line a view shows in place of notes it could not read.
515pub fn local_state_error_line(err: &LocalCrumbError) -> String {
516 format!(
517 "⚠ .crumb.local unavailable (peers unknown, not absent): {}",
518 err
519 )
520}
521
522/// Pretty-prints a rich TUI inspection card for a directory's crumb. A
523/// `.crumb.local` error is shown in the card; use [`dir_crumb_card`] to also
524/// receive it.
525pub fn format_dir_crumb_tui(dir: &Path) -> String {
526 dir_crumb_card(dir).0
527}
528
529/// [`format_dir_crumb_tui`] plus the `.crumb.local` error the card shows, if
530/// any, so a command can print the card and still fail.
531pub fn dir_crumb_card(dir: &Path) -> (String, Option<LocalCrumbError>) {
532 let (crumb, local_err) = load_dir_crumb_view(dir);
533
534 let mut out = String::new();
535 out.push_str(&format!(
536 "🧭 DIRECTORY CRUMB: {} ({})\n",
537 crumb.dir_name.bold().cyan(),
538 crumb.dir_path.dimmed()
539 ));
540 out.push_str(&format!(" Description: {}\n", crumb.description));
541 if let Some(p) = &crumb.purpose {
542 out.push_str(&format!(
543 " šŸŽÆ PURPOSE: {} [{} | by {}]\n",
544 p.statement.bold().magenta(),
545 p.lifecycle.cyan(),
546 p.created_by.yellow()
547 ));
548 }
549
550 if let Some(above_raw) = &crumb.above {
551 let above = above_raw.to_above_info();
552 out.push_str(&format!(
553 " ↑ ABOVE: {} [{}]\n",
554 above.name.bold().yellow(),
555 above.canonical.dimmed()
556 ));
557 } else {
558 out.push_str(" ↑ ABOVE: [Root workspace boundary]\n");
559 }
560
561 let dirs: Vec<&str> = crumb
562 .below
563 .iter()
564 .filter(|i| i.item_type == "dir")
565 .map(|i| i.name.as_str())
566 .collect();
567 let files: Vec<&str> = crumb
568 .below
569 .iter()
570 .filter(|i| i.item_type == "file")
571 .map(|i| i.name.as_str())
572 .collect();
573
574 out.push_str(&format!(
575 " ↓ BELOW (Subdirectories): [{}]\n",
576 dirs.join(", ").cyan()
577 ));
578 out.push_str(&format!(
579 " ↓ BELOW (Files): [{}]\n",
580 files.join(", ").white()
581 ));
582
583 out.push_str(&format!(
584 "\nšŸ“œ Agent Chronicle in this Directory (Total: {}):\n",
585 crumb.history.len()
586 ));
587 if let Some(err) = &local_err {
588 out.push_str(&format!(" {}\n", local_state_error_line(err).red()));
589 } else if crumb.history.is_empty() {
590 out.push_str(" (No previous actions recorded in this directory)\n");
591 } else {
592 for (i, h) in crumb.history.iter().rev().take(5).enumerate() {
593 let elapsed = h.elapsed_secs();
594 let el_str = if elapsed < 60 {
595 format!("{}s ago", elapsed)
596 } else {
597 format!("{}m ago", elapsed / 60)
598 };
599 out.push_str(&format!(
600 " {}. [{}] {} '{}' ({})\n Intent: {}\n Vector: {}\n",
601 i + 1,
602 h.agent_id.bold().yellow(),
603 h.action,
604 h.target.green(),
605 el_str,
606 h.intent,
607 h.vector.dimmed()
608 ));
609 }
610 }
611
612 if !crumb.whispers.is_empty() {
613 out.push_str("\nšŸ’¬ Directory Whispers & Intercommunication:\n");
614 for w in crumb.whispers.iter().rev().take(3) {
615 out.push_str(&format!(
616 " • From [{}]: \"{}\"\n",
617 w.from_agent.bold().cyan(),
618 w.message
619 ));
620 }
621 }
622
623 (out, local_err)
624}
625
626/// Discovers directory crumbs for nesting ritual, showing immediate directory topography.
627pub fn discover_workspace_crumbs_summary(start_dir: &Path) -> String {
628 let (crumb, local_err) = load_dir_crumb_view(start_dir);
629 let mut s = format!(
630 "[DIRECTORY CRUMB TOPOGRAPHY: {}]\n\
631 Current: {} ({})\n",
632 crumb.dir_name, crumb.dir_path, crumb.description
633 );
634 if let Some(err) = &local_err {
635 s.push_str(&format!("{}\n", local_state_error_line(err)));
636 }
637
638 if let Some(above_raw) = &crumb.above {
639 let above = above_raw.to_above_info();
640 s.push_str(&format!("↑ Above: {} ({})\n", above.name, above.canonical));
641 }
642 if let Some(p) = &crumb.purpose {
643 s.push_str(&format!("šŸŽÆ Directory Purpose: {}\n", p.statement));
644 }
645
646 let subdirs: Vec<&str> = crumb
647 .below
648 .iter()
649 .filter(|i| i.item_type == "dir")
650 .map(|i| i.name.as_str())
651 .collect();
652 if !subdirs.is_empty() {
653 s.push_str(&format!("↓ Below Subdirs: [{}]\n", subdirs.join(", ")));
654 }
655
656 if !crumb.history.is_empty() {
657 s.push_str("Recent Actions in this Directory:\n");
658 for h in crumb.history.iter().rev().take(3) {
659 s.push_str(&format!(
660 "• [{}] {} '{}' - Intent: '{}' -> Vector: '{}'\n",
661 h.agent_id, h.action, h.target, h.intent, h.vector
662 ));
663 }
664 }
665
666 if !crumb.whispers.is_empty() {
667 s.push_str("Directory Whispers:\n");
668 for w in crumb.whispers.iter().rev().take(2) {
669 s.push_str(&format!("• [{}] \"{}\"\n", w.from_agent, w.message));
670 }
671 }
672
673 s
674}
675
676fn auto_sense_directory_purpose(dir: &Path) -> String {
677 let readme = dir.join("README.md");
678 if readme.exists() {
679 if let Ok(c) = fs::read_to_string(&readme) {
680 for line in c.lines() {
681 let trimmed = line.trim().trim_start_matches('#').trim();
682 if !trimmed.is_empty() {
683 return format!("Documentation & implementation for {}", trimmed);
684 }
685 }
686 }
687 }
688 let cargo = dir.join("Cargo.toml");
689 if cargo.exists() {
690 if let Ok(c) = fs::read_to_string(&cargo) {
691 for line in c.lines() {
692 if line.starts_with("name =") {
693 let name = line
694 .replace("name =", "")
695 .replace("\"", "")
696 .trim()
697 .to_string();
698 return format!("Rust crate codebase: {}", name);
699 }
700 }
701 }
702 }
703 let pkg = dir.join("package.json");
704 if pkg.exists() {
705 if let Ok(c) = fs::read_to_string(&pkg) {
706 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&c) {
707 if let Some(name) = val.get("name").and_then(|n| n.as_str()) {
708 return format!("Node/Web package: {}", name);
709 }
710 }
711 }
712 }
713 let dir_name = dir
714 .file_name()
715 .map(|n| n.to_string_lossy().to_string())
716 .unwrap_or_else(|| "workspace".to_string());
717 format!("Workspace subsystem directory for {}", dir_name)
718}
719
720/// Seeds `.crumb` files and optionally plants `whisper` in each seeded
721/// directory. Returns the number of directories seeded; a failed whisper
722/// stops the walk and is returned.
723///
724/// Known limitation, out of scope for core#924 (`.crumb.local` notes): a
725/// failure to write the durable `.crumb` itself is not reported, because
726/// [`load_or_init_dir_crumb`] discards its save result and many read paths
727/// share it. The count is of directories visited, not of `.crumb` files
728/// written. Only `.crumb.local` (whisper) and identity errors fail a seed.
729pub fn seed_directory_tree(
730 root: &Path,
731 recursive: bool,
732 agent: &str,
733 whisper: Option<&str>,
734) -> Result<usize, LocalCrumbError> {
735 let mut count = 0;
736 if !recursive {
737 load_or_init_dir_crumb(root, None);
738 if let Some(msg) = whisper {
739 leave_dir_whisper(agent, root, None, msg)?;
740 }
741 return Ok(1);
742 }
743
744 for entry in walkdir::WalkDir::new(root)
745 .min_depth(0)
746 .max_depth(6)
747 .into_iter()
748 .filter_entry(|e| {
749 let name = e.file_name().to_string_lossy();
750 !name.starts_with('.') && name != "target" && name != "node_modules"
751 })
752 .flatten()
753 {
754 if entry.file_type().is_dir() {
755 let path = entry.path();
756 load_or_init_dir_crumb(path, None);
757 if let Some(msg) = whisper {
758 leave_dir_whisper(agent, path, None, msg)?;
759 }
760 count += 1;
761 }
762 }
763 Ok(count)
764}
765
766pub fn sniff_crumb(
767 target_path: &Path,
768 current_agent: &str,
769) -> Result<Option<String>, LocalCrumbError> {
770 sniff_dir_crumb(target_path, current_agent)
771}
772
773pub fn add_crumb_whisper(
774 dir: &Path,
775 from_agent: &str,
776 message: &str,
777 target_file: Option<&str>,
778) -> Result<(), LocalCrumbError> {
779 leave_dir_whisper(from_agent, dir, target_file, message)
780}
781
782pub fn record_crumb_action(
783 dir: &Path,
784 agent_id: &str,
785 session_id: &str,
786 action: &str,
787 target: &str,
788 intent: &str,
789 vector: &str,
790) -> Result<(), LocalCrumbError> {
791 record_directory_crumb(
792 agent_id,
793 session_id,
794 &dir.join(target),
795 action,
796 intent,
797 vector,
798 )
799}
800
801#[cfg(test)]
802mod tests {
803 use super::*;
804
805 #[test]
806 fn test_crumb_lifecycle_and_whisper() {
807 let temp_dir = std::env::temp_dir().join(format!("test-crumb-{}", uuid::Uuid::new_v4()));
808 fs::create_dir_all(&temp_dir).expect("create temp dir");
809
810 let crumb = load_or_init_dir_crumb(&temp_dir, None);
811 assert!(crumb.purpose.is_some());
812
813 record_directory_crumb(
814 "Atlas-Prime",
815 "test-session-01",
816 &temp_dir.join("lib.rs"),
817 "edit",
818 "Verify crumb persistence",
819 "Testing spark-crumbs subsystem",
820 )
821 .expect("record");
822
823 leave_dir_whisper(
824 "Whisper-Writer",
825 &temp_dir,
826 Some("lib.rs"),
827 "Verification lock acquired",
828 )
829 .expect("whisper");
830
831 let sniff = sniff_dir_crumb(&temp_dir.join("lib.rs"), "Peer-Agent").expect("sniff");
832 assert!(sniff.is_some());
833 let sniff_str = sniff.unwrap();
834 assert!(sniff_str.contains("Atlas-Prime"));
835 assert!(sniff_str.contains("Verification lock"));
836
837 let _ = fs::remove_dir_all(&temp_dir);
838 }
839
840 /// core#924: a malformed `.crumb.local` is an error in sniff and a visible
841 /// warning in the views, never an empty peer list.
842 #[test]
843 fn malformed_local_state_is_surfaced_by_every_view() {
844 let temp_dir = std::env::temp_dir().join(format!("test-bad-{}", uuid::Uuid::new_v4()));
845 fs::create_dir_all(&temp_dir).expect("create temp dir");
846 fs::write(temp_dir.join(LOCAL_CRUMB_FILENAME), "{ broken").unwrap();
847 let err = sniff_dir_crumb(&temp_dir.join("lib.rs"), "Peer-Agent").unwrap_err();
848 assert_eq!(err.kind(), LocalCrumbErrorKind::Malformed);
849 assert!(format_dir_crumb_tui(&temp_dir).contains(".crumb.local unavailable"));
850 assert!(discover_workspace_crumbs_summary(&temp_dir).contains(".crumb.local unavailable"));
851 assert!(record_crumb_action(&temp_dir, "a", "s", "edit", "lib.rs", "i", "v").is_err());
852 assert!(add_crumb_whisper(&temp_dir, "a", "m", None).is_err());
853 assert!(seed_directory_tree(&temp_dir, false, "a", Some("m")).is_err());
854 assert_eq!(
855 fs::read_to_string(temp_dir.join(LOCAL_CRUMB_FILENAME)).unwrap(),
856 "{ broken"
857 );
858 let _ = fs::remove_dir_all(&temp_dir);
859 }
860
861 #[test]
862 fn test_seed_directory_tree() {
863 let temp_dir = std::env::temp_dir().join(format!("test-seed-{}", uuid::Uuid::new_v4()));
864 let sub = temp_dir.join("sub");
865 fs::create_dir_all(&sub).expect("create sub dir");
866
867 let count =
868 seed_directory_tree(&temp_dir, true, "Seed-Writer", Some("Seeded tree")).expect("seed");
869 assert!(count >= 2);
870
871 let _ = fs::remove_dir_all(&temp_dir);
872 }
873
874 #[test]
875 fn test_format_tui_card() {
876 let temp_dir = std::env::temp_dir().join(format!("test-tui-{}", uuid::Uuid::new_v4()));
877 fs::create_dir_all(&temp_dir).expect("create temp dir");
878
879 let card = format_dir_crumb_tui(&temp_dir);
880 assert!(card.contains("DIRECTORY CRUMB"));
881
882 let _ = fs::remove_dir_all(&temp_dir);
883 }
884
885 /// Shape of a hand-written crumb on main (crates/aien-serve-http/.crumb).
886 const HAND_WRITTEN_CRUMB: &str = r#"{
887 "invariants": [
888 "The door refuses to bind a non-loopback address. Check: cargo test -p aien-serve-http --test loopback -- --exact non_loopback_bind_is_refused"
889 ],
890 "name": "aien-serve-http",
891 "purpose": "OpenAI-compatible HTTP door for AIEN's own-kernel model serving (OWN-30B cut 4)",
892 "schema_version": "1.0.0"
893}
894"#;
895
896 #[test]
897 fn hand_written_crumb_is_never_rewritten() {
898 let temp_dir =
899 std::env::temp_dir().join(format!("test-handwritten-{}", uuid::Uuid::new_v4()));
900 fs::create_dir_all(temp_dir.join("src")).expect("create temp dir");
901 fs::write(temp_dir.join("Cargo.toml"), "[package]\nname = \"door\"\n").expect("cargo");
902 let crumb_path = temp_dir.join(CRUMB_FILENAME);
903 fs::write(&crumb_path, HAND_WRITTEN_CRUMB).expect("write crumb");
904
905 let crumb = load_or_init_dir_crumb(&temp_dir, None);
906 let _ = format_dir_crumb_tui(&temp_dir);
907 let _ = sniff_dir_crumb(&temp_dir, "Peer-Agent");
908 let _ = discover_workspace_crumbs_summary(&temp_dir);
909 seed_directory_tree(&temp_dir, false, "Seed-Writer", Some("seeded")).expect("seed");
910 seed_directory_tree(&temp_dir, true, "Seed-Writer", None).expect("seed");
911 record_crumb_action(
912 &temp_dir,
913 "Edit-Writer",
914 "s",
915 "edit",
916 "Cargo.toml",
917 "i",
918 "v",
919 )
920 .expect("record");
921
922 assert_eq!(
923 fs::read_to_string(&crumb_path).expect("read crumb"),
924 HAND_WRITTEN_CRUMB
925 );
926 assert_eq!(
927 crumb.purpose.map(|p| p.statement).as_deref(),
928 Some("OpenAI-compatible HTTP door for AIEN's own-kernel model serving (OWN-30B cut 4)")
929 );
930
931 let _ = fs::remove_dir_all(&temp_dir);
932 }
933
934 #[test]
935 fn save_refuses_to_overwrite_foreign_crumb() {
936 let temp_dir = std::env::temp_dir().join(format!("test-refuse-{}", uuid::Uuid::new_v4()));
937 fs::create_dir_all(&temp_dir).expect("create temp dir");
938 let crumb_path = temp_dir.join(CRUMB_FILENAME);
939
940 // A hand-written crumb: load gives a view, save refuses, bytes unchanged.
941 fs::write(&crumb_path, HAND_WRITTEN_CRUMB).expect("write crumb");
942 let mut crumb = load_or_init_dir_crumb(&temp_dir, None);
943 crumb.description = "changed".to_string();
944 assert!(save_dir_crumb(&temp_dir, &crumb).is_err());
945 assert_eq!(fs::read_to_string(&crumb_path).unwrap(), HAND_WRITTEN_CRUMB);
946
947 // A DirCrumb with an extra hand-written field: save would drop the
948 // field, so it is refused too.
949 let seeded = DirCrumb::new(&temp_dir, None, None);
950 let mut value = serde_json::to_value(&seeded).unwrap();
951 value["invariants"] = serde_json::json!(["kept by hand"]);
952 let mixed = serde_json::to_string_pretty(&value).unwrap();
953 fs::write(&crumb_path, &mixed).expect("write mixed crumb");
954 assert!(save_dir_crumb(&temp_dir, &seeded).is_err());
955 assert_eq!(fs::read_to_string(&crumb_path).unwrap(), mixed);
956
957 // A crumb this tool wrote is still saved.
958 fs::remove_file(&crumb_path).unwrap();
959 let fresh = load_or_init_dir_crumb(&temp_dir, None);
960 assert!(fresh.purpose.is_some());
961 assert!(save_dir_crumb(&temp_dir, &fresh).is_ok());
962
963 let _ = fs::remove_dir_all(&temp_dir);
964 }
965
966 #[test]
967 fn save_writes_where_the_crumb_was_loaded_not_to_stored_dir_path() {
968 let here = std::env::temp_dir().join(format!("test-here-{}", uuid::Uuid::new_v4()));
969 let old = std::env::temp_dir().join(format!("test-old-{}", uuid::Uuid::new_v4()));
970 fs::create_dir_all(&here).expect("create here");
971 fs::create_dir_all(&old).expect("create old");
972
973 // A DirCrumb moved (or copied) from `old`: its stored dir_path is stale.
974 let mut moved = DirCrumb::new(&old, None, None);
975 moved.purpose = None;
976 fs::write(
977 here.join(CRUMB_FILENAME),
978 serde_json::to_string_pretty(&moved).unwrap(),
979 )
980 .expect("write moved crumb");
981
982 // Loading with a purpose fills the missing purpose and saves.
983 let purpose = CrumbPurpose {
984 statement: "filled on load".to_string(),
985 created_by: "test".to_string(),
986 session_id: "test".to_string(),
987 created_at: "2026-10-31T00:00:00Z".to_string(),
988 lifecycle: "permanent".to_string(),
989 };
990 let loaded = load_or_init_dir_crumb(&here, Some(purpose));
991
992 assert!(
993 !old.join(CRUMB_FILENAME).exists(),
994 "save wrote to the stale stored dir_path"
995 );
996 let saved: DirCrumb =
997 serde_json::from_str(&fs::read_to_string(here.join(CRUMB_FILENAME)).unwrap()).unwrap();
998 let canon = here.canonicalize().unwrap().to_string_lossy().to_string();
999 assert_eq!(saved.dir_path, canon);
1000 assert_eq!(loaded.dir_path, canon);
1001 assert_eq!(
1002 saved.purpose.map(|p| p.statement).as_deref(),
1003 Some("filled on load")
1004 );
1005
1006 let _ = fs::remove_dir_all(&here);
1007 let _ = fs::remove_dir_all(&old);
1008 }
1009
1010 #[test]
1011 fn dir_name_of_dot_is_the_real_directory_name() {
1012 let crumb = DirCrumb::new(Path::new("."), None, None);
1013 let expected = std::env::current_dir()
1014 .unwrap()
1015 .canonicalize()
1016 .unwrap()
1017 .file_name()
1018 .unwrap()
1019 .to_string_lossy()
1020 .to_string();
1021 assert_eq!(crumb.dir_name, expected);
1022 }
1023
1024 #[test]
1025 fn crumb_for_dot_has_the_parent_entry() {
1026 let cwd = std::env::current_dir().unwrap().canonicalize().unwrap();
1027 let home = std::env::var("HOME").unwrap_or_default();
1028 let parent = cwd.parent().unwrap();
1029 let crumb = DirCrumb::new(Path::new("."), None, None);
1030 // The parent entry is written only under HOME. A checkout outside it (CI,
1031 // /tmp worktrees) must get none; under it, "." must get the resolved
1032 // parent, not the empty textual parent of ".".
1033 if !home.is_empty() && parent.starts_with(&home) && parent != cwd {
1034 match crumb.above {
1035 Some(AboveValue::Structured(above)) => {
1036 assert_eq!(above.canonical, parent.to_string_lossy());
1037 assert_eq!(above.name, parent.file_name().unwrap().to_string_lossy());
1038 }
1039 other => panic!("no parent entry for \".\": {:?}", other.is_some()),
1040 }
1041 } else {
1042 assert!(crumb.above.is_none(), "parent entry outside HOME");
1043 }
1044 }
1045}