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 / nesting.rs

228 lines · 10952 bytes Raw Blame History
1use colored::*;
2use chrono::Utc;
3use std::fs::{self, OpenOptions};
4use std::io::Write;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7use reqwest::Client;
8use serde_json::json;
9
10use crate::crumbs::{discover_workspace_crumbs_summary, record_directory_crumb, load_or_init_dir_crumb};
11use crate::hive::hive_roster;
12use crate::telemetry::get_gpu_telemetry;
13
14pub struct NestingReport {
15 pub hostname: String,
16 pub user: String,
17 pub gpu_info: String,
18 pub disk_free: String,
19 pub seats_status: Vec<(String, bool)>,
20 pub hive_active_count: usize,
21 pub pending_parks_count: usize,
22 pub scent_marked: bool,
23 pub grounding_context: String,
24}
25
26pub async fn perform_nesting_ritual(session_id: &str, print_tui: bool) -> NestingReport {
27 let client = Client::builder()
28 .timeout(std::time::Duration::from_secs(2))
29 .build()
30 .unwrap_or_default();
31
32 // 1. Circle & Survey Surroundings (Hardware, user, disk, seats)
33 let hostname = std::env::var("HOSTNAME").unwrap_or_else(|_| {
34 Command::new("hostname")
35 .output()
36 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
37 .unwrap_or_else(|_| "spark-b87b".to_string())
38 });
39 let user = std::env::var("USER").unwrap_or_else(|_| "drakestapleton".to_string());
40
41 let gpu = get_gpu_telemetry();
42 let gpu_info = format!("{} ({}°C, {} MB / {} MB)", gpu.name, gpu.temp_c, gpu.used_mb, gpu.total_mb);
43
44 let disk_free = Command::new("df")
45 .args(["-h", "/home/drakestapleton"])
46 .output()
47 .map(|o| {
48 let s = String::from_utf8_lossy(&o.stdout);
49 s.lines().nth(1).and_then(|l| l.split_whitespace().nth(3)).unwrap_or("unknown").to_string()
50 })
51 .unwrap_or_else(|_| "unknown".to_string());
52
53 // Check service seats
54 let mut seats_status = Vec::new();
55 let seat_18006 = client.get("http://127.0.0.1:18006/v1/models").send().await.map(|r| r.status().is_success()).unwrap_or(false);
56 seats_status.push(("Model (18006)".to_string(), seat_18006));
57
58 let judge_18082 = client.get("http://127.0.0.1:18082/v1/models").send().await.map(|r| r.status().is_success()).unwrap_or(false);
59 seats_status.push(("Judge (18082)".to_string(), judge_18082));
60
61 let cortex_18080 = client.get("http://127.0.0.1:18080/health").send().await.map(|r| r.status().is_success()).unwrap_or(false);
62 seats_status.push(("Cortex (18080)".to_string(), cortex_18080));
63
64 let dream_18085 = client.get("http://127.0.0.1:18085/health").send().await.map(|r| r.status().is_success()).unwrap_or(false);
65 seats_status.push(("Dream (18085)".to_string(), dream_18085));
66
67 // Strict Hard-Block Readiness Verification
68 let mut critical_failures = Vec::new();
69 if !hostname.contains("spark") && hostname != "localhost" {
70 critical_failures.push(format!("Host identity mismatch: detected {}, expected spark-b87b", hostname));
71 }
72 if user != "drakestapleton" && user != "root" {
73 critical_failures.push(format!("User identity error: running as {}, must operate as drakestapleton", user));
74 }
75 if !seat_18006 {
76 critical_failures.push("Critical Seat Down: Model Seat (port 18006 / Nemotron-3.5) is offline".to_string());
77 }
78 if !judge_18082 {
79 critical_failures.push("Critical Seat Down: JSpace Truth Judge (port 18082 / Llama-3.2) is offline".to_string());
80 }
81 if !cortex_18080 {
82 critical_failures.push("Critical Seat Down: Spark Cortex Memory (port 18080) is offline".to_string());
83 }
84
85 if !critical_failures.is_empty() {
86 eprintln!("\n{}", "❌ NESTING RITUAL FAILED: CRITICAL HARD-BLOCK TRIGGERED".red().bold());
87 eprintln!("{}", "The agent cannot settle or take ungrounded actions because required environmental anchors are down:".red());
88 for err in &critical_failures {
89 eprintln!(" ✖ {}", err.bold().red());
90 }
91 eprintln!("\n{}", "Aborting startup to prevent ungrounded or misdirected execution.".yellow());
92 std::process::exit(1);
93 }
94
95 // 2. Check the Wind (Hive swarm activity, pulse, vibe & parked notes)
96 let pulse_path = Path::new("/home/drakestapleton/basecamp/hive-pulse.json");
97 let (pulse_coherence, pulse_vibe, _pulse_status) = if pulse_path.exists() {
98 if let Ok(c) = fs::read_to_string(pulse_path) {
99 if let Ok(v) = serde_json::from_str::<serde_json::Value>(&c) {
100 let coh = v.get("coherence_score").and_then(serde_json::Value::as_u64).unwrap_or(95);
101 let vibe = v.get("vibe_summary").and_then(serde_json::Value::as_str).unwrap_or("Harmonious forward vector").to_string();
102 let st = v.get("pulse_status").and_then(serde_json::Value::as_str).unwrap_or("harmonious").to_string();
103 (Some(coh), Some(vibe), Some(st))
104 } else { (None, None, None) }
105 } else { (None, None, None) }
106 } else { (None, None, None) };
107 let roster_text = hive_roster();
108 let hive_active_count = if roster_text.contains("idle") || roster_text.contains("Empty") || roster_text.contains("0") {
109 0
110 } else {
111 roster_text.lines().filter(|l| l.contains("running") || l.contains("busy")).count()
112 };
113
114 let park_dir = Path::new("/home/drakestapleton/atlas-prime-workspace/park");
115 let pending_parks_count = if park_dir.exists() {
116 fs::read_dir(park_dir).map(|r| r.count()).unwrap_or(0)
117 } else {
118 0
119 };
120
121 // 3. Hierarchical Directory Crumb Inspection & Scent-Drop
122 let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/home/drakestapleton"));
123 let dir_crumb = load_or_init_dir_crumb(&cwd, None);
124 let crumb_topography = discover_workspace_crumbs_summary(&cwd);
125
126 // Record presence into directory crumb
127 record_directory_crumb(
128 "AIEN",
129 session_id,
130 &cwd,
131 "signin",
132 "Operator session initiation",
133 "Awaiting operator command",
134 );
135
136 // 4. Leave Scent (Record presence in basecamp/events.jsonl)
137 let events_path = Path::new("/home/drakestapleton/basecamp/events.jsonl");
138 let mut scent_marked = false;
139 let event_entry = json!({
140 "event": "agent_nesting",
141 "timestamp": Utc::now().to_rfc3339(),
142 "session_id": session_id,
143 "actor": "AIEN",
144 "mask": "AIEN",
145 "user": user,
146 "host": hostname,
147 "cwd": cwd.to_string_lossy().to_string(),
148 "status": "grounded",
149 "gpu_temp_c": gpu.temp_c,
150 "disk_free": disk_free
151 });
152
153 if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(events_path) {
154 if writeln!(f, "{}", event_entry).is_ok() {
155 scent_marked = true;
156 }
157 }
158
159 // 5. Flatten the Terrain (Build Context & Render TUI)
160 let grounding_context = format!(
161 "[NESTING RITUAL RECORD - GROUNDING SEQUENCE]\n\
162 Host: {} | Operator: {} | Disk Free: {}\n\
163 GPU: {}\n\
164 Seats Verified: Model(18006)={}, Judge(18082)={}, Cortex(18080)={}, Dream(18085)={}\n\
165 Swarm Status: {} active peer cell(s) | Pending Park Notes: {}\n\
166 Hive Pulse & Vibe: Coherence={}%, Vibe={}\n\
167 Scent Registered: basecamp/events.jsonl ({})\n\n\
168 {}\n\n\
169 Operating Rule: Consult the directory crumb topography above. Before modifying files, declare your vector and verify boundaries.",
170 hostname, user, disk_free, gpu_info,
171 seat_18006, judge_18082, cortex_18080, dream_18085,
172 hive_active_count, pending_parks_count,
173 pulse_coherence.unwrap_or(95), pulse_vibe.as_deref().unwrap_or("Aligned and focused"),
174 session_id, crumb_topography
175 );
176
177 if print_tui {
178 println!("{}", "╭─────────────────────────────────────────────────────────────╮".cyan());
179 println!("│ {} │", "🐕 NESTING RITUAL (Agent Grounding Initiation)".bold().yellow());
180 println!("{}", "├─────────────────────────────────────────────────────────────┤".cyan());
181 println!("│ {} {} ({})", "Circle Terrain:".bold().white(), hostname.green(), user.cyan());
182 println!("│ ├─ NVMe Disk Free: {} available", disk_free.green());
183 println!("│ ├─ GB10 GPU: {}°C | {} MB / {} MB", gpu.temp_c, gpu.used_mb, gpu.total_mb);
184 print!("│ └─ Seats Online: ");
185 for (name, ok) in &seats_status {
186 if *ok {
187 print!("{}✓ ", name.green());
188 } else {
189 print!("{}✗ ", name.red());
190 }
191 }
192 println!();
193 println!("│ {} {} active hive cell(s) | {} park note(s)", "Check the Wind:".bold().white(), hive_active_count, pending_parks_count);
194 if let (Some(coh), Some(vibe)) = (&pulse_coherence, &pulse_vibe) {
195 println!("│ ├─ Hive Pulse: {} (Coherence: {}%)", "💚 Heartbeat Active".bold().green(), coh);
196 println!("│ ├─ Hive Vibe: {}", vibe.italic().magenta());
197 }
198
199 let above_str = dir_crumb.above.as_ref().map(|a| a.name.clone()).unwrap_or_else(|| "Root".to_string());
200 let subdirs: Vec<&str> = dir_crumb.below.iter().filter(|i| i.item_type == "dir").map(|i| i.name.as_str()).collect();
201 let subdirs_str = if subdirs.is_empty() { "none".to_string() } else { subdirs.join(", ") };
202
203 println!("│ {} Directory: {} (.crumb)", "Directory Crumb:".bold().white(), dir_crumb.dir_name.cyan());
204 if let Some(p) = &dir_crumb.purpose {
205 println!("│ ├─ Purpose: {}", p.statement.italic().cyan());
206 }
207 println!("│ ├─ Above: {}", above_str.yellow());
208 println!("│ ├─ Below: [{}]", subdirs_str.white());
209 println!("│ └─ Local History: {} recorded action(s)", dir_crumb.history.len());
210
211 println!("│ {} Presence signed into directory .crumb & basecamp", "Leave Scent:".bold().white());
212 println!("│ {} Workspace anchored, topography loaded, vector set.", "Flatten Terrain:".bold().white());
213 println!("{}", "╰─────────────────────────────────────────────────────────────╯".cyan());
214 println!("{}", "✓ Grounding complete. Directory crumb topography active. Ready.\n".dimmed());
215 }
216
217 NestingReport {
218 hostname,
219 user,
220 gpu_info,
221 disk_free,
222 seats_status,
223 hive_active_count,
224 pending_parks_count,
225 scent_marked,
226 grounding_context,
227 }
228}