interplane.Get Omega
Read in your language

aien-sovereign-core

Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core / crates / aien-cli / src / crumbs.rs

554 lines · 20341 bytes Raw Blame History
1use chrono::{DateTime, Utc};
2use colored::*;
3use serde::{Deserialize, Serialize};
4use std::fs;
5
6use std::path::Path;
7
8pub const CRUMB_FILENAME: &str = ".crumb";
9pub const LOCAL_CRUMB_FILENAME: &str = ".crumb.local";
10
11#[derive(Serialize, Deserialize, Debug, Clone, Default)]
12pub struct LocalCrumbData {
13 #[serde(default)]
14 pub history: Vec<CrumbHistoryItem>,
15 #[serde(default)]
16 pub whispers: Vec<CrumbWhisper>,
17}
18
19pub 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::<LocalCrumbData>(&c) {
24 return data;
25 }
26 }
27 }
28 LocalCrumbData::default()
29}
30
31pub 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
38pub const DEFAULT_TTL_SECS: u64 = 1800; // 30 minutes
39
40#[derive(Serialize, Deserialize, Debug, Clone)]
41pub 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)]
49pub struct BelowItem {
50 pub name: String,
51 pub item_type: String, // "dir" or "file"
52 pub role: String,
53}
54
55#[derive(Serialize, Deserialize, Debug, Clone)]
56pub struct CrumbHistoryItem {
57 pub crumb_id: String,
58 pub timestamp: String,
59 pub agent_id: String,
60 pub session_id: String,
61 pub action: String, // "signin", "view", "edit", "create", "test"
62 pub target: String,
63 pub intent: String,
64 pub vector: String,
65}
66
67impl CrumbHistoryItem {
68 pub fn elapsed_secs(&self) -> u64 {
69 if let Ok(parsed) = DateTime::parse_from_rfc3339(&self.timestamp) {
70 let age = Utc::now().signed_duration_since(parsed.with_timezone(&Utc));
71 age.num_seconds().max(0) as u64
72 } else {
73 0
74 }
75 }
76
77 pub fn is_active(&self) -> bool {
78 self.elapsed_secs() < DEFAULT_TTL_SECS
79 }
80}
81
82#[derive(Serialize, Deserialize, Debug, Clone)]
83pub struct CrumbWhisper {
84 #[serde(default)]
85 pub whisper_id: String,
86 pub from_agent: String,
87 pub timestamp: String,
88 #[serde(default)]
89 pub target_file: Option<String>,
90 pub message: String,
91}
92
93#[derive(Serialize, Deserialize, Debug, Clone)]
94pub struct CrumbPurpose {
95 pub statement: String,
96 #[serde(default)]
97 pub created_by: String,
98 #[serde(default)]
99 pub session_id: String,
100 #[serde(default)]
101 pub created_at: String,
102 #[serde(default = "default_lifecycle")]
103 pub lifecycle: String, // "permanent" | "ephemeral"
104}
105
106fn default_lifecycle() -> String {
107 "permanent".to_string()
108}
109
110#[derive(Serialize, Deserialize, Debug, Clone)]
111pub struct DirCrumb {
112 pub version: u32,
113 pub dir_path: String,
114 pub dir_name: String,
115 pub description: String,
116 #[serde(default)]
117 pub purpose: Option<CrumbPurpose>,
118 pub above: Option<AboveInfo>,
119 pub below: Vec<BelowItem>,
120 pub history: Vec<CrumbHistoryItem>,
121 pub whispers: Vec<CrumbWhisper>,
122}
123
124impl DirCrumb {
125 pub fn new(dir: &Path, description: Option<&str>, purpose: Option<CrumbPurpose>) -> Self {
126 let canon = dir
127 .canonicalize()
128 .map(|p| p.to_string_lossy().to_string())
129 .unwrap_or_else(|_| dir.to_string_lossy().to_string());
130
131 let dir_name = dir
132 .file_name()
133 .map(|n| n.to_string_lossy().to_string())
134 .unwrap_or_else(|| "/".to_string());
135
136 // Inspect Above
137 let above = if let Some(parent) = dir.parent() {
138 if parent.starts_with("/home/drakestapleton") && parent != dir {
139 let p_canon = parent
140 .canonicalize()
141 .map(|p| p.to_string_lossy().to_string())
142 .unwrap_or_else(|_| parent.to_string_lossy().to_string());
143 let p_name = parent
144 .file_name()
145 .map(|n| n.to_string_lossy().to_string())
146 .unwrap_or_else(|| "home".to_string());
147
148 Some(AboveInfo {
149 path: "..".to_string(),
150 canonical: p_canon,
151 name: p_name,
152 role: "Parent directory context".to_string(),
153 })
154 } else {
155 None
156 }
157 } else {
158 None
159 };
160
161 // Inspect Below
162 let mut below = Vec::new();
163 if let Ok(entries) = fs::read_dir(dir) {
164 for entry in entries.flatten() {
165 let name = entry.file_name().to_string_lossy().to_string();
166 if name.starts_with(".") {
167 continue;
168 }
169 let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
170 below.push(BelowItem {
171 name,
172 item_type: if is_dir { "dir".to_string() } else { "file".to_string() },
173 role: String::new(),
174 });
175 }
176 }
177 below.sort_by(|a, b| a.name.cmp(&b.name));
178
179 DirCrumb {
180 version: 1,
181 dir_path: canon,
182 dir_name,
183 description: description.unwrap_or("Workspace directory").to_string(),
184 purpose,
185 above,
186 below,
187 history: Vec::new(),
188 whispers: Vec::new(),
189 }
190 }
191}
192
193pub fn load_or_init_dir_crumb(dir: &Path, purpose_opt: Option<CrumbPurpose>) -> DirCrumb {
194 let crumb_path = dir.join(CRUMB_FILENAME);
195 if crumb_path.exists() {
196 if let Ok(content) = fs::read_to_string(&crumb_path) {
197 match serde_json::from_str::<DirCrumb>(&content) {
198 Err(e) => eprintln!("Failed to parse DirCrumb at {}: {}", crumb_path.display(), e),
199 Ok(mut crumb) => {
200 // Refresh below items dynamically
201 let mut below = Vec::new();
202 if let Ok(entries) = fs::read_dir(dir) {
203 for entry in entries.flatten() {
204 let name = entry.file_name().to_string_lossy().to_string();
205 if name.starts_with(".") {
206 continue;
207 }
208 let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
209 below.push(BelowItem {
210 name,
211 item_type: if is_dir { "dir".to_string() } else { "file".to_string() },
212 role: String::new(),
213 });
214 }
215 }
216 below.sort_by(|a, b| a.name.cmp(&b.name));
217 crumb.below = below;
218 if crumb.purpose.is_none() && purpose_opt.is_some() {
219 crumb.purpose = purpose_opt.clone();
220 save_dir_crumb(&crumb);
221 }
222 // Merge ephemeral telemetry from .crumb.local
223 let local_data = load_local_crumb(dir);
224 if !local_data.history.is_empty() {
225 for h in local_data.history {
226 if !crumb.history.iter().any(|existing| existing.crumb_id == h.crumb_id) {
227 crumb.history.push(h);
228 }
229 }
230 }
231 if !local_data.whispers.is_empty() {
232 for w in local_data.whispers {
233 if !crumb.whispers.iter().any(|existing| existing.whisper_id == w.whisper_id || existing.message == w.message) {
234 crumb.whispers.push(w);
235 }
236 }
237 }
238 return crumb;
239 }
240 }
241 }
242 }
243
244 // Auto-Sense & Seed if purpose not provided
245 let final_purpose = match purpose_opt {
246 Some(p) => Some(p),
247 None => {
248 let sensed_statement = auto_sense_directory_purpose(dir);
249 Some(CrumbPurpose {
250 statement: sensed_statement,
251 created_by: "AIEN (Auto-Sensed)".to_string(),
252 session_id: "auto-sense".to_string(),
253 created_at: Utc::now().to_rfc3339(),
254 lifecycle: "permanent".to_string(),
255 })
256 }
257 };
258
259 let crumb = DirCrumb::new(dir, None, final_purpose);
260 save_dir_crumb(&crumb);
261 crumb
262}
263
264pub fn save_dir_crumb(crumb: &DirCrumb) {
265 let dir = Path::new(&crumb.dir_path);
266 let crumb_path = dir.join(CRUMB_FILENAME);
267
268 // Durable .crumb: keep architectural purpose, above/below, clean of ephemeral churn
269 let mut durable_crumb = crumb.clone();
270 durable_crumb.history = Vec::new(); // Ephemeral history lives in .crumb.local
271 durable_crumb.whispers = Vec::new(); // Whispers live in .crumb.local
272
273 if let Ok(json_str) = serde_json::to_string_pretty(&durable_crumb) {
274 let _ = fs::write(&crumb_path, json_str);
275 }
276}
277
278/// Records an action in the directory's `.crumb` file and bubbles awareness to parent.
279pub fn record_directory_crumb(
280 agent_id: &str,
281 session_id: &str,
282 target_path: &Path,
283 action: &str,
284 intent: &str,
285 vector: &str,
286) {
287 let dir = if target_path.is_dir() {
288 target_path.to_path_buf()
289 } else {
290 target_path.parent().unwrap_or(target_path).to_path_buf()
291 };
292
293 let target_name = target_path
294 .file_name()
295 .map(|n| n.to_string_lossy().to_string())
296 .unwrap_or_else(|| "dir".to_string());
297
298 let dir_name = dir.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dir".to_string());
299 let mut local_data = load_local_crumb(&dir);
300
301 let item = CrumbHistoryItem {
302 crumb_id: format!("crumb-{}", Utc::now().timestamp_nanos_opt().unwrap_or(0)),
303 timestamp: Utc::now().to_rfc3339(),
304 agent_id: agent_id.to_string(),
305 session_id: session_id.to_string(),
306 action: action.to_string(),
307 target: target_name.clone(),
308 intent: intent.to_string(),
309 vector: vector.to_string(),
310 };
311
312 local_data.history.push(item);
313 if local_data.history.len() > 50 {
314 local_data.history.drain(0..local_data.history.len() - 50);
315 }
316 save_local_crumb(&dir, &local_data);
317
318 // If dir has a parent within project workspace, bubble awareness to parent .crumb.local
319 if let Some(parent) = dir.parent() {
320 if parent.starts_with("/home/drakestapleton") && parent != dir {
321 let mut parent_local = load_local_crumb(parent);
322 let bubble_item = CrumbHistoryItem {
323 crumb_id: format!("bubble-{}", Utc::now().timestamp_nanos_opt().unwrap_or(0)),
324 timestamp: Utc::now().to_rfc3339(),
325 agent_id: agent_id.to_string(),
326 session_id: session_id.to_string(),
327 action: format!("sub:{}", action),
328 target: format!("{}/{}", dir_name, target_name),
329 intent: intent.to_string(),
330 vector: vector.to_string(),
331 };
332 parent_local.history.push(bubble_item);
333 if parent_local.history.len() > 50 {
334 parent_local.history.drain(0..parent_local.history.len() - 50);
335 }
336 save_local_crumb(parent, &parent_local);
337 }
338 }
339}
340
341/// Leaves a whisper message in a directory .crumb.local file.
342pub fn leave_dir_whisper(
343 from_agent: &str,
344 dir: &Path,
345 target_file: Option<&str>,
346 message: &str,
347) {
348 let mut local_data = load_local_crumb(dir);
349 let whisper = CrumbWhisper {
350 whisper_id: format!("whisp-{}", Utc::now().timestamp_nanos_opt().unwrap_or(0)),
351 from_agent: from_agent.to_string(),
352 timestamp: Utc::now().to_rfc3339(),
353 target_file: target_file.map(|s| s.to_string()),
354 message: message.to_string(),
355 };
356 local_data.whispers.push(whisper);
357 if local_data.whispers.len() > 30 {
358 local_data.whispers.drain(0..local_data.whispers.len() - 30);
359 }
360 save_local_crumb(dir, &local_data);
361}
362
363/// Sniffs directory crumb and checks for recent actions or whispers on target file.
364pub fn sniff_dir_crumb(target_path: &Path, current_agent: &str) -> Option<String> {
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 crumb = load_or_init_dir_crumb(&dir, None);
372 let target_name = target_path
373 .file_name()
374 .map(|n| n.to_string_lossy().to_string())
375 .unwrap_or_default();
376
377 let mut notices = Vec::new();
378
379 // Check history for this target or directory
380 for item in crumb.history.iter().rev() {
381 if (item.target == target_name || item.target.ends_with(&target_name) || target_path.is_dir())
382 && item.agent_id != current_agent
383 && item.is_active()
384 {
385 let elapsed = item.elapsed_secs();
386 let el_str = if elapsed < 60 {
387 format!("{}s ago", elapsed)
388 } else {
389 format!("{}m ago", elapsed / 60)
390 };
391 notices.push(format!(
392 "• [{}] {} on '{}' ({}) - Intent: '{}' -> Vector: '{}'",
393 item.agent_id, item.action, item.target, el_str, item.intent, item.vector
394 ));
395 }
396 }
397
398 // Check whispers
399 for w in crumb.whispers.iter().rev() {
400 if let Ok(parsed) = DateTime::parse_from_rfc3339(&w.timestamp) {
401 let age = Utc::now().signed_duration_since(parsed.with_timezone(&Utc));
402 if age.num_seconds() >= 0 && (age.num_seconds() as u64) < DEFAULT_TTL_SECS * 2 {
403 if let Some(tf) = &w.target_file {
404 if tf == &target_name || target_path.is_dir() {
405 notices.push(format!("šŸ’¬ [Whisper from {}]: {}", w.from_agent, w.message));
406 }
407 } else {
408 notices.push(format!("šŸ’¬ [Whisper from {}]: {}", w.from_agent, w.message));
409 }
410 }
411 }
412 }
413
414 if notices.is_empty() {
415 return None;
416 }
417
418 let mut out = format!("🐾 [DIRECTORY CRUMB: {}/.crumb]\n", dir.display());
419 if let Some(above) = &crumb.above {
420 out.push_str(&format!(" ↑ Above: {} ({})\n", above.canonical, above.name));
421 }
422 if let Some(p) = &crumb.purpose {
423 out.push_str(&format!(" šŸŽÆ Purpose: {}\n", p.statement.cyan()));
424 }
425 out.push_str(" Recent Peer History in this directory:\n");
426 for n in notices.iter().take(4) {
427 out.push_str(&format!(" {}\n", n));
428 }
429 out.push_str("─────────────────────────────────────────────────────────────\n");
430 Some(out)
431}
432
433/// Pretty-prints a rich TUI inspection card for a directory's crumb.
434pub fn format_dir_crumb_tui(dir: &Path) -> String {
435 let crumb = load_or_init_dir_crumb(dir, None);
436
437 let mut out = String::new();
438 out.push_str(&format!("🧭 DIRECTORY CRUMB: {} ({})\n", crumb.dir_name.bold().cyan(), crumb.dir_path.dimmed()));
439 out.push_str(&format!(" Description: {}\n", crumb.description));
440 if let Some(p) = &crumb.purpose {
441 out.push_str(&format!(" šŸŽÆ PURPOSE: {} [{} | by {}]\n", p.statement.bold().magenta(), p.lifecycle.cyan(), p.created_by.yellow()));
442 }
443
444 if let Some(above) = &crumb.above {
445 out.push_str(&format!(" ↑ ABOVE: {} [{}]\n", above.name.bold().yellow(), above.canonical.dimmed()));
446 } else {
447 out.push_str(" ↑ ABOVE: [Root workspace boundary]\n");
448 }
449
450 let dirs: Vec<&str> = crumb.below.iter().filter(|i| i.item_type == "dir").map(|i| i.name.as_str()).collect();
451 let files: Vec<&str> = crumb.below.iter().filter(|i| i.item_type == "file").map(|i| i.name.as_str()).collect();
452
453 out.push_str(&format!(" ↓ BELOW (Subdirectories): [{}]\n", dirs.join(", ").cyan()));
454 out.push_str(&format!(" ↓ BELOW (Files): [{}]\n", files.join(", ").white()));
455
456 out.push_str(&format!("\nšŸ“œ Agent Chronicle in this Directory (Total: {}):\n", crumb.history.len()));
457 if crumb.history.is_empty() {
458 out.push_str(" (No previous actions recorded in this directory)\n");
459 } else {
460 for (i, h) in crumb.history.iter().rev().take(5).enumerate() {
461 let elapsed = h.elapsed_secs();
462 let el_str = if elapsed < 60 { format!("{}s ago", elapsed) } else { format!("{}m ago", elapsed / 60) };
463 out.push_str(&format!(
464 " {}. [{}] {} '{}' ({})\n Intent: {}\n Vector: {}\n",
465 i + 1, h.agent_id.bold().yellow(), h.action, h.target.green(), el_str, h.intent, h.vector.dimmed()
466 ));
467 }
468 }
469
470 if !crumb.whispers.is_empty() {
471 out.push_str("\nšŸ’¬ Directory Whispers & Intercommunication:\n");
472 for w in crumb.whispers.iter().rev().take(3) {
473 out.push_str(&format!(" • From [{}]: \"{}\"\n", w.from_agent.bold().cyan(), w.message));
474 }
475 }
476
477 out
478}
479
480/// Discovers directory crumbs for nesting ritual, showing immediate directory topography.
481pub fn discover_workspace_crumbs_summary(start_dir: &Path) -> String {
482 let crumb = load_or_init_dir_crumb(start_dir, None);
483 let mut s = format!(
484 "[DIRECTORY CRUMB TOPOGRAPHY: {}]\n\
485 Current: {} ({})\n",
486 crumb.dir_name, crumb.dir_path, crumb.description
487 );
488
489 if let Some(above) = &crumb.above {
490 s.push_str(&format!("↑ Above: {} ({})\n", above.name, above.canonical));
491 }
492 if let Some(p) = &crumb.purpose {
493 s.push_str(&format!("šŸŽÆ Directory Purpose: {}\n", p.statement));
494 }
495
496 let subdirs: Vec<&str> = crumb.below.iter().filter(|i| i.item_type == "dir").map(|i| i.name.as_str()).collect();
497 if !subdirs.is_empty() {
498 s.push_str(&format!("↓ Below Subdirs: [{}]\n", subdirs.join(", ")));
499 }
500
501 if !crumb.history.is_empty() {
502 s.push_str("Recent Actions in this Directory:\n");
503 for h in crumb.history.iter().rev().take(3) {
504 s.push_str(&format!("• [{}] {} '{}' - Intent: '{}' -> Vector: '{}'\n", h.agent_id, h.action, h.target, h.intent, h.vector));
505 }
506 }
507
508 if !crumb.whispers.is_empty() {
509 s.push_str("Directory Whispers:\n");
510 for w in crumb.whispers.iter().rev().take(2) {
511 s.push_str(&format!("• [{}] \"{}\"\n", w.from_agent, w.message));
512 }
513 }
514
515 s
516}
517
518
519fn auto_sense_directory_purpose(dir: &Path) -> String {
520 let readme = dir.join("README.md");
521 if readme.exists() {
522 if let Ok(c) = fs::read_to_string(&readme) {
523 for line in c.lines() {
524 let trimmed = line.trim().trim_start_matches('#').trim();
525 if !trimmed.is_empty() {
526 return format!("Documentation & implementation for {}", trimmed);
527 }
528 }
529 }
530 }
531 let cargo = dir.join("Cargo.toml");
532 if cargo.exists() {
533 if let Ok(c) = fs::read_to_string(&cargo) {
534 for line in c.lines() {
535 if line.starts_with("name =") {
536 let name = line.replace("name =", "").replace("\"", "").trim().to_string();
537 return format!("Rust crate codebase: {}", name);
538 }
539 }
540 }
541 }
542 let pkg = dir.join("package.json");
543 if pkg.exists() {
544 if let Ok(c) = fs::read_to_string(&pkg) {
545 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&c) {
546 if let Some(name) = val.get("name").and_then(|n| n.as_str()) {
547 return format!("Node/Web package: {}", name);
548 }
549 }
550 }
551 }
552 let dir_name = dir.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "workspace".to_string());
553 format!("Workspace subsystem directory for {}", dir_name)
554}