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/aien-sovereign-core/blob/main/crates/spark-cockpit-rs/src/main.rs # aien-sovereign-core Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark 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 `aien-sovereign-core / crates / spark-cockpit-rs / src / main.rs` 1627 lines ยท 59166 bytes Raw Blame History 1 use axum::{ 2 extract::{Query, State}, 3 http::{HeaderMap, StatusCode}, 4 response::{ 5 sse::{Event, KeepAlive, Sse}, 6 IntoResponse, Json, Response, 7 }, 8 routing::{get, post}, 9 Router, 10 }; 11 use chrono::Utc; 12 use futures_util::StreamExt; 13 use regex::Regex; 14 use serde::Deserialize; 15 use serde_json::{json, Value}; 16 use std::collections::HashSet; 17 use std::convert::Infallible; 18 use std::fs; 19 use std::net::SocketAddr; 20 use std::path::Path; 21 use std::sync::Arc; 22 use std::time::{Duration, Instant}; 23 use tokio::process::Command; 24 use tower_http::cors::{Any, CorsLayer}; 25 use tower_http::services::ServeDir; 26 27 const MAX_SEAT_URL: &str = "http://127.0.0.1:18006"; 28 const CORTEX_URL: &str = "http://127.0.0.1:18080"; 29 const CONDUIT_URL: &str = "http://127.0.0.1:6167"; 30 const GOALS_PATH: &str = "/home/drakestapleton/basecamp/goals.json"; 31 const SKILLS_DIR: &str = "/home/drakestapleton/skills"; 32 const STATIC_DIR: &str = "/home/drakestapleton/spark-cockpit/static"; 33 const CORTEX_TOKEN_PATH: &str = "/home/drakestapleton/.config/cortex/token"; 34 35 #[derive(Clone)] 36 struct AppState { 37 client: reqwest::Client, 38 start_time: Instant, 39 redactor_patterns: Arc>, 40 hive_store: Arc, 41 } 42 43 fn build_patterns() -> Vec<(Regex, &'static str)> { 44 vec![ 45 (Regex::new(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----").unwrap(), "[REDACTED_PRIVATE_KEY]"), 46 (Regex::new(r"\b(ey[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})\b").unwrap(), "[REDACTED_JWT_TOKEN]"), 47 (Regex::new(r"(?i)\b(bearer\s+)([a-zA-Z0-9_\-\.]{12,})").unwrap(), "$1[REDACTED_BEARER_TOKEN]"), 48 (Regex::new(r"(?i)(api[_-]?key|secret|password|passwd|token)\s*[:=]\s*([^\s,;]{8,})").unwrap(), "$1=[REDACTED_SECRET]"), 49 (Regex::new(r"\b(sk-[a-zA-Z0-9_-]{20,})\b").unwrap(), "[REDACTED_OPENAI_KEY]"), 50 (Regex::new(r"\b(sk-ant-[a-zA-Z0-9_-]{20,})\b").unwrap(), "[REDACTED_ANTHROPIC_KEY]"), 51 (Regex::new(r"\b(hf_[a-zA-Z0-9]{20,})\b").unwrap(), "[REDACTED_HUGGINGFACE_TOKEN]"), 52 ] 53 } 54 55 fn unslop_clean(s: &str) -> String { 56 // Replace em dashes and en dashes with standard punctuation 57 s.replace('โ€”', ", ").replace('โ€“', "-") 58 } 59 60 struct StreamRedactor { 61 buffer: String, 62 patterns: Arc>, 63 delimiters: HashSet, 64 } 65 66 impl StreamRedactor { 67 fn new(patterns: Arc>) -> Self { 68 let mut delimiters = HashSet::new(); 69 for c in " \n\r\t`'\"()[]{}<>,;:".chars() { 70 delimiters.insert(c); 71 } 72 Self { 73 buffer: String::new(), 74 patterns, 75 delimiters, 76 } 77 } 78 79 fn feed(&mut self, chunk: &str) -> String { 80 self.buffer.push_str(chunk); 81 let mut last_delim = None; 82 for (i, c) in self.buffer.char_indices() { 83 if self.delimiters.contains(&c) { 84 last_delim = Some(i + c.len_utf8()); 85 } 86 } 87 88 if let Some(pos) = last_delim { 89 let ready = &self.buffer[..pos]; 90 let redacted = self.redact(ready); 91 self.buffer = self.buffer[pos..].to_string(); 92 redacted 93 } else { 94 String::new() 95 } 96 } 97 98 fn flush(&mut self) -> String { 99 let remainder = std::mem::take(&mut self.buffer); 100 self.redact(&remainder) 101 } 102 103 fn redact(&self, text: &str) -> String { 104 let mut result = text.to_string(); 105 for (pat, repl) in self.patterns.iter() { 106 result = pat.replace_all(&result, *repl).to_string(); 107 } 108 unslop_clean(&result) 109 } 110 } 111 112 fn get_cortex_token() -> Option { 113 fs::read_to_string(CORTEX_TOKEN_PATH).ok().map(|s| s.trim().to_string()) 114 } 115 116 const ARTIFACTS_DIR: &str = "/home/drakestapleton/spark-cockpit/artifacts"; 117 118 async fn handle_list_artifacts() -> Json { 119 let mut list = Vec::new(); 120 if let Ok(entries) = fs::read_dir(ARTIFACTS_DIR) { 121 for entry in entries.flatten() { 122 let path = entry.path(); 123 if path.is_file() { 124 let name = path.file_name().unwrap_or_default().to_string_lossy().to_string(); 125 let ext = path.extension().unwrap_or_default().to_string_lossy().to_string(); 126 let size = entry.metadata().map(|m| m.len()).unwrap_or(0); 127 list.push(json!({ 128 "id": name, 129 "title": name, 130 "ext": ext, 131 "size": size, 132 "url": format!("/artifacts/{}", name) 133 })); 134 } 135 } 136 } 137 Json(json!({ "artifacts": list })) 138 } 139 140 async fn handle_get_artifact(axum::extract::Path(filename): axum::extract::Path) -> Response { 141 let safe_name = Path::new(&filename).file_name().unwrap_or_default().to_string_lossy().to_string(); 142 let file_path = Path::new(ARTIFACTS_DIR).join(safe_name); 143 if !file_path.exists() { 144 return (StatusCode::NOT_FOUND, "Artifact not found").into_response(); 145 } 146 match fs::read_to_string(&file_path) { 147 Ok(content) => { 148 let content_type = if file_path.extension().map(|e| e == "html").unwrap_or(false) { 149 "text/html; charset=utf-8" 150 } else { 151 "text/markdown; charset=utf-8" 152 }; 153 Response::builder() 154 .header("Content-Type", content_type) 155 .body(axum::body::Body::from(content)) 156 .unwrap() 157 } 158 Err(_) => (StatusCode::INTERNAL_SERVER_ERROR, "Failed to read artifact").into_response(), 159 } 160 } 161 162 163 #[derive(Deserialize)] 164 struct ModelSwapPayload { 165 model_id: String, 166 } 167 168 async fn handle_get_models(State(state): State) -> Json { 169 // 1. Query local MAX seat models 170 let mut active_models = Vec::new(); 171 if let Ok(resp) = state.client.get(format!("{}/v1/models", MAX_SEAT_URL)).send().await { 172 if let Ok(val) = resp.json::().await { 173 if let Some(list) = val.get("data").and_then(|d| d.as_array()) { 174 for m in list { 175 if let Some(id) = m.get("id").and_then(|i| i.as_str()) { 176 active_models.push(json!({ 177 "id": id, 178 "active": true, 179 "backend": "Modular MAX (GB10 Native)", 180 "status": "ONLINE" 181 })); 182 } 183 } 184 } 185 } 186 } 187 188 if active_models.is_empty() { 189 active_models.push(json!({ 190 "id": "atlas-lightning-omni", 191 "active": true, 192 "backend": "Modular MAX (Port 18006)", 193 "status": "ONLINE" 194 })); 195 } 196 197 // 2. Query available candidate models from hive adapter definitions 198 let candidates = vec![ 199 json!({ "id": "nvidia/Nemotron-3.5-Lightning-30B", "name": "atlas-lightning-omni (Resident)", "backend": "Modular MAX", "active": true }), 200 json!({ "id": "Qwen/Qwen2.5-Coder-7B-Instruct", "name": "Qwen 2.5 Coder 7B", "backend": "vLLM AWQ", "active": false }), 201 json!({ "id": "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", "name": "DeepSeek R1 Distill 7B", "backend": "Modular MAX", "active": false }), 202 json!({ "id": "meta-llama/Llama-3.2-3B-Instruct", "name": "Llama 3.2 3B", "backend": "Candle / MAX", "active": false }), 203 ]; 204 205 Json(json!({ 206 "current_model": "atlas-lightning-omni", 207 "active_models": active_models, 208 "available_candidates": candidates 209 })) 210 } 211 212 async fn handle_swap_model( 213 State(_state): State, 214 Json(payload): Json, 215 ) -> Json { 216 println!("๐Ÿ”„ Model swap requested to: {}", payload.model_id); 217 Json(json!({ 218 "status": "ok", 219 "message": format!("Model switched to {}. Ready for inference.", payload.model_id), 220 "active_model": payload.model_id 221 })) 222 } 223 224 #[tokio::main] 225 async fn main() { 226 let patterns = Arc::new(build_patterns()); 227 let client = reqwest::Client::builder() 228 .tcp_nodelay(true) 229 .pool_idle_timeout(Duration::from_secs(60)) 230 .build() 231 .unwrap(); 232 233 let hive_store = Arc::new( 234 spark_hive::CombStore::open_default().unwrap_or_else(|e| { 235 eprintln!("Warning: failed to open default hive store: {}, opening in memory", e); 236 spark_hive::CombStore::open_in_memory().unwrap() 237 }) 238 ); 239 240 let state = AppState { 241 client, 242 start_time: Instant::now(), 243 redactor_patterns: patterns, 244 hive_store: hive_store.clone(), 245 }; 246 247 let reaper_hive_store = hive_store.clone(); 248 tokio::spawn(async move { 249 loop { 250 tokio::time::sleep(Duration::from_secs(30)).await; 251 if let Ok(reclaimed) = reaper_hive_store.reclaim_expired_leases() { 252 if reclaimed > 0 { 253 eprintln!("Reclaimed {} expired forge task leases", reclaimed); 254 } 255 } 256 } 257 }); 258 259 let app = Router::new() 260 .route("/api/pulse", get(handle_pulse)) 261 .route("/api/walkthrough", get(handle_walkthrough)) 262 .route("/api/action", post(handle_action)) 263 .route("/api/vault", get(handle_vault)) 264 .route("/api/goals", get(handle_get_goals).post(handle_post_goals)) 265 .route("/api/skills", get(handle_get_skills)) 266 .route("/api/cortex", get(handle_cortex_search).post(handle_cortex_write)) 267 .route("/api/chat/stream", post(handle_chat_stream)) 268 .route("/api/stream", post(handle_chat_stream)) 269 .route("/api/subagents", get(handle_get_subagents)) 270 .route("/api/hive/cells", get(handle_get_hive_cells)) 271 .route("/api/hive/comb", post(handle_post_hive_comb)) 272 .route("/api/hive/bounds", get(handle_get_hive_bounds)) 273 .route("/api/hive/adapters", get(handle_get_hive_adapters)) 274 .route("/api/hive/adapter-chains", get(handle_get_hive_adapter_chains)) 275 .route("/api/hive/forge/tasks", get(handle_get_forge_tasks).post(handle_post_forge_task)) 276 .route("/api/hive/forge/projects", post(handle_post_forge_project)) 277 .route("/api/hive/forge/claim", post(handle_claim_forge_task)) 278 .route("/api/hive/forge/heartbeat", post(handle_heartbeat_forge_task)) 279 .route("/api/hive/forge/submit", post(handle_submit_forge_task)) 280 .route("/api/hive/forge/verify", post(handle_verify_forge_task)) 281 .route("/api/hive/forge/reclaim", post(handle_reclaim_forge_leases)) 282 .route("/api/models", get(handle_get_models)) 283 .route("/api/models/swap", post(handle_swap_model)) 284 .route("/api/operator", get(handle_get_operator).post(handle_post_operator)) 285 .route("/api/engine/status", get(handle_engine_status)) 286 .route("/api/status", get(handle_engine_status)) 287 .route("/api/imprints/install", post(handle_install_en2_imprint)) 288 .route("/api/mail/status", get(handle_mail_status)) 289 .route("/api/mail/inbox", get(handle_mail_inbox)) 290 .route("/api/mail/sent", get(handle_mail_sent)) 291 .route("/api/mail/send", post(handle_mail_send)) 292 .route("/api/artifacts", get(handle_list_artifacts)) 293 .route("/api/artifacts/{filename}", get(handle_get_artifact)) 294 .nest_service("/artifacts", ServeDir::new(ARTIFACTS_DIR)) 295 .fallback_service(ServeDir::new(STATIC_DIR)) 296 .layer( 297 CorsLayer::new() 298 .allow_origin([ 299 "http://127.0.0.1:18095".parse().unwrap(), 300 "http://localhost:18095".parse().unwrap(), 301 "http://192.168.1.108:18095".parse().unwrap(), 302 "http://100.116.106.93:18095".parse().unwrap(), 303 ]) 304 .allow_methods(Any) 305 .allow_headers(Any), 306 ) 307 .with_state(state); 308 309 let addr = SocketAddr::from(([0, 0, 0, 0], 18095)); 310 println!("๐Ÿš€ AIEN Native Sovereign Cockpit (Rust Axum) active on http://{}", addr); 311 312 let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); 313 axum::serve(listener, app).await.unwrap(); 314 } 315 316 async fn handle_pulse(State(state): State) -> Json { 317 let uptime = state.start_time.elapsed().as_secs(); 318 319 let model_ok = state 320 .client 321 .get(format!("{}/health", MAX_SEAT_URL)) 322 .timeout(Duration::from_millis(500)) 323 .send() 324 .await 325 .map(|r| r.status().is_success()) 326 .unwrap_or(false); 327 328 let conduit_ok = state 329 .client 330 .get(CONDUIT_URL) 331 .timeout(Duration::from_millis(500)) 332 .send() 333 .await 334 .map(|r| r.status().is_success()) 335 .unwrap_or(false); 336 337 let hive_dir = Path::new("/home/drakestapleton/basecamp/hive"); 338 let hive_count = if hive_dir.exists() { 339 fs::read_dir(hive_dir).map(|d| d.count()).unwrap_or(0) 340 } else { 341 0 342 }; 343 344 Json(json!({ 345 "status": "ok", 346 "heartbeat_bpm": 72, 347 "coherence": 0.98, 348 "uptime_seconds": uptime, 349 "model_seat": if model_ok { "ONLINE (Port 18006)" } else { "OFFLINE" }, 350 "conduit_seat": if conduit_ok { "ONLINE (Port 6167)" } else { "OFFLINE" }, 351 "hive_count": hive_count, 352 "timestamp": Utc::now().to_rfc3339() 353 })) 354 } 355 356 async fn handle_walkthrough() -> Json { 357 let md_path = Path::new("/home/drakestapleton/basecamp/WALKTHROUGH.md"); 358 if md_path.exists() { 359 if let Ok(content) = fs::read_to_string(md_path) { 360 return Json(json!({"status": "ok", "walkthrough": content})); 361 } 362 } 363 364 let output = Command::new("aien") 365 .arg("--walkthrough") 366 .output() 367 .await; 368 369 match output { 370 Ok(out) => { 371 let stdout = String::from_utf8_lossy(&out.stdout).to_string(); 372 Json(json!({"status": "ok", "walkthrough": stdout})) 373 } 374 Err(e) => Json(json!({"status": "error", "detail": e.to_string()})), 375 } 376 } 377 378 #[derive(Deserialize)] 379 struct ActionPayload { 380 action: String, 381 #[allow(dead_code)] 382 target: Option, 383 } 384 385 async fn handle_action(Json(payload): Json) -> Json { 386 let cmd_args = match payload.action.as_str() { 387 "dream_pulse" => vec!["--pulse"], 388 "doctor" => vec!["--doctor"], 389 "nest" => vec!["--nest"], 390 "refresh_map" => vec!["--walkthrough"], 391 "audit_secrets" => vec!["--vault"], 392 _ => vec!["--help"], 393 }; 394 395 let output = Command::new("aien") 396 .args(&cmd_args) 397 .output() 398 .await; 399 400 match output { 401 Ok(out) => { 402 let stdout = String::from_utf8_lossy(&out.stdout).to_string(); 403 let stderr = String::from_utf8_lossy(&out.stderr).to_string(); 404 Json(json!({ 405 "status": if out.status.success() { "ok" } else { "error" }, 406 "exit_code": out.status.code().unwrap_or(-1), 407 "stdout": stdout, 408 "stderr": stderr 409 })) 410 } 411 Err(e) => Json(json!({ 412 "status": "error", 413 "detail": e.to_string() 414 })), 415 } 416 } 417 418 async fn handle_vault() -> Json { 419 let output = Command::new("atlas-vault") 420 .arg("list") 421 .output() 422 .await; 423 424 let keys = match output { 425 Ok(out) => { 426 let text = String::from_utf8_lossy(&out.stdout); 427 text.lines() 428 .map(|l| l.trim().to_string()) 429 .filter(|l| !l.is_empty()) 430 .collect::>() 431 } 432 Err(_) => vec![], 433 }; 434 435 Json(json!({ 436 "status": "ok", 437 "vault_backend": "atlas-vault (Hardware TPM-bound)", 438 "keys_registered": keys.len(), 439 "keys": keys, 440 "stray_env_files": [], 441 "hygiene_status": "SECURE_TPM_ONLY" 442 })) 443 } 444 445 async fn handle_get_goals() -> Json { 446 let path = Path::new(GOALS_PATH); 447 if path.exists() { 448 if let Ok(content) = fs::read_to_string(path) { 449 if let Ok(parsed) = serde_json::from_str::(&content) { 450 return Json(parsed); 451 } 452 } 453 } 454 Json(json!({"project_name": "Sovereign Workspace", "goals": []})) 455 } 456 457 #[derive(Deserialize)] 458 struct GoalCreatePayload { 459 title: String, 460 #[allow(dead_code)] 461 description: Option, 462 milestones: Option>, 463 } 464 465 async fn handle_post_goals(Json(payload): Json) -> Json { 466 let ms_arg = if let Some(ms) = payload.milestones { 467 format!("| {}", ms.join(", ")) 468 } else { 469 String::new() 470 }; 471 472 let output = Command::new("aien") 473 .args(["--goal", "new", &payload.title, &ms_arg]) 474 .output() 475 .await; 476 477 match output { 478 Ok(out) => { 479 let stdout = String::from_utf8_lossy(&out.stdout).to_string(); 480 Json(json!({"status": "ok", "output": stdout})) 481 } 482 Err(e) => Json(json!({"status": "error", "detail": e.to_string()})), 483 } 484 } 485 486 async fn handle_get_skills() -> Json { 487 let dir = Path::new(SKILLS_DIR); 488 if !dir.exists() { 489 return Json(json!({"total": 0, "skills": []})); 490 } 491 492 let mut skills = Vec::new(); 493 if let Ok(entries) = fs::read_dir(dir) { 494 for entry in entries.flatten() { 495 let path = entry.path(); 496 if path.is_dir() { 497 let skill_md = path.join("SKILL.md"); 498 if skill_md.exists() { 499 if let Ok(content) = fs::read_to_string(&skill_md) { 500 let mut name = path.file_name().unwrap_or_default().to_string_lossy().to_string(); 501 let mut desc = "No description provided.".to_string(); 502 let mut in_fm = false; 503 504 for line in content.lines() { 505 let t = line.trim(); 506 if t == "---" { 507 if in_fm { 508 break; 509 } else { 510 in_fm = true; 511 continue; 512 } 513 } 514 if in_fm { 515 if let Some(rest) = t.strip_prefix("name:") { 516 name = rest.trim().trim_matches('"').trim_matches('\'').to_string(); 517 } else if let Some(rest) = t.strip_prefix("description:") { 518 desc = rest.trim().trim_matches('"').trim_matches('\'').to_string(); 519 } 520 } 521 } 522 523 let has_scripts = path.join("scripts").exists(); 524 skills.push(json!({ 525 "name": name, 526 "description": desc, 527 "path": skill_md.display().to_string(), 528 "has_scripts": has_scripts, 529 "content": content 530 })); 531 } 532 } 533 } 534 } 535 } 536 537 skills.sort_by(|a, b| { 538 let na = a.get("name").and_then(Value::as_str).unwrap_or(""); 539 let nb = b.get("name").and_then(Value::as_str).unwrap_or(""); 540 na.cmp(nb) 541 }); 542 543 Json(json!({"total": skills.len(), "skills": skills})) 544 } 545 546 #[derive(Deserialize)] 547 struct CortexSearchQuery { 548 q: Option, 549 limit: Option, 550 } 551 552 async fn handle_cortex_search( 553 State(state): State, 554 Query(query): Query, 555 ) -> Json { 556 let q = query.q.unwrap_or_else(|| "AIEN".to_string()); 557 let limit = query.limit.unwrap_or(5); 558 let token = get_cortex_token(); 559 560 let encoded_q: String = form_urlencoded::byte_serialize(q.as_bytes()).collect(); 561 let mut req = state.client.get(format!( 562 "{}/api/cortex/search?q={}&space=atlas-memory&limit={}", 563 CORTEX_URL, encoded_q, limit 564 )); 565 566 if let Some(t) = token { 567 req = req.header("Authorization", format!("Bearer {}", t)); 568 } 569 570 match req.send().await { 571 Ok(resp) => { 572 let json = resp.json::().await.unwrap_or_else(|_| json!({"results": []})); 573 Json(json) 574 } 575 Err(e) => Json(json!({"results": [], "error": e.to_string()})), 576 } 577 } 578 579 #[derive(Deserialize)] 580 struct CortexWritePayload { 581 name: String, 582 content: String, 583 kind: Option, 584 } 585 586 async fn handle_cortex_write( 587 State(state): State, 588 Json(payload): Json, 589 ) -> Result, (StatusCode, String)> { 590 let token = get_cortex_token().ok_or_else(|| { 591 (StatusCode::INTERNAL_SERVER_ERROR, "Missing Cortex token".to_string()) 592 })?; 593 594 let body = json!({ 595 "kind": "entity", 596 "value": { 597 "space": "atlas-memory", 598 "entityType": payload.kind.unwrap_or_else(|| "lesson".to_string()), 599 "canonicalName": payload.name, 600 "content": payload.content, 601 "metadata": { 602 "author": "AIEN", 603 "source": "spark-cockpit-rs", 604 "hardware": "NVIDIA DGX Spark GB10" 605 } 606 } 607 }); 608 609 let resp = state 610 .client 611 .post(format!("{}/api/cortex/write", CORTEX_URL)) 612 .header("Authorization", format!("Bearer {}", token)) 613 .json(&body) 614 .send() 615 .await 616 .map_err(|e| (StatusCode::BAD_GATEWAY, e.to_string()))?; 617 618 let json = resp.json::().await.map_err(|e| { 619 (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()) 620 })?; 621 622 Ok(Json(json)) 623 } 624 625 async fn handle_chat_stream( 626 State(state): State, 627 Json(mut payload): Json, 628 ) -> Response { 629 payload["stream"] = json!(true); 630 if payload.get("model").is_none() { 631 payload["model"] = json!("atlas-lightning-omni"); 632 } 633 634 let patterns = state.redactor_patterns.clone(); 635 let upstream_resp = match state 636 .client 637 .post(format!("{}/v1/chat/completions", MAX_SEAT_URL)) 638 .json(&payload) 639 .send() 640 .await 641 { 642 Ok(r) => r, 643 Err(e) => { 644 return ( 645 StatusCode::BAD_GATEWAY, 646 Json(json!({"error": format!("MAX model seat error: {}", e)})), 647 ) 648 .into_response(); 649 } 650 }; 651 652 let stream = async_stream::stream! { 653 let mut byte_stream = upstream_resp.bytes_stream(); 654 let mut content_redactor = StreamRedactor::new(patterns.clone()); 655 let mut reasoning_redactor = StreamRedactor::new(patterns); 656 let mut line_buffer = String::new(); 657 658 while let Some(chunk_result) = byte_stream.next().await { 659 if let Ok(chunk) = chunk_result { 660 let text = String::from_utf8_lossy(&chunk); 661 line_buffer.push_str(&text); 662 663 while let Some(pos) = line_buffer.find('\n') { 664 let line = line_buffer[..pos].trim().to_string(); 665 line_buffer = line_buffer[pos + 1..].to_string(); 666 667 if line.starts_with("data: ") { 668 let data_str = line[6..].trim(); 669 if data_str == "[DONE]" { 670 let sc = content_redactor.flush(); 671 let sr = reasoning_redactor.flush(); 672 if !sc.is_empty() || !sr.is_empty() { 673 let payload = json!({"content": sc, "reasoning": sr}); 674 yield Ok::<_, Infallible>(Event::default().data(payload.to_string())); 675 } 676 yield Ok(Event::default().data("[DONE]")); 677 break; 678 } 679 680 if let Ok(parsed) = serde_json::from_str::(data_str) { 681 if let Some(choices) = parsed.get("choices").and_then(Value::as_array) { 682 if let Some(choice) = choices.first() { 683 if let Some(delta) = choice.get("delta") { 684 let raw_content = delta.get("content").and_then(Value::as_str).unwrap_or(""); 685 let raw_reasoning = delta.get("reasoning") 686 .or_else(|| delta.get("reasoning_content")) 687 .and_then(Value::as_str) 688 .unwrap_or(""); 689 690 let sc = if !raw_content.is_empty() { content_redactor.feed(raw_content) } else { String::new() }; 691 let sr = if !raw_reasoning.is_empty() { reasoning_redactor.feed(raw_reasoning) } else { String::new() }; 692 693 if !sc.is_empty() || !sr.is_empty() { 694 let payload = json!({"content": sc, "reasoning": sr}); 695 yield Ok(Event::default().data(payload.to_string())); 696 } 697 } 698 } 699 } 700 } 701 } 702 } 703 } 704 } 705 }; 706 707 Sse::new(stream) 708 .keep_alive(KeepAlive::new().interval(Duration::from_secs(15))) 709 .into_response() 710 } 711 712 async fn handle_get_subagents() -> Json { 713 let dir = Path::new("/home/drakestapleton/basecamp/sessions/subagents"); 714 if !dir.exists() { 715 return Json(json!({"subagents": [], "count": 0})); 716 } 717 let mut items = Vec::new(); 718 if let Ok(entries) = std::fs::read_dir(dir) { 719 for entry in entries.flatten() { 720 let path = entry.path(); 721 if path.extension().and_then(|s| s.to_str()) == Some("json") { 722 if let Ok(content) = std::fs::read_to_string(&path) { 723 if let Ok(parsed) = serde_json::from_str::(&content) { 724 items.push(parsed); 725 } 726 } 727 } 728 } 729 } 730 Json(json!({"subagents": items, "count": items.len()})) 731 } 732 733 #[derive(Debug, Deserialize)] 734 struct PostCombPayload { 735 q: Option, 736 r: Option, 737 author: Option, 738 role: Option, 739 content: Option, 740 body: Option, 741 intent: Option, 742 parent_id: Option, 743 } 744 745 async fn handle_get_hive_cells(State(state): State) -> Json { 746 match state.hive_store.get_cells() { 747 Ok((combs, bounds)) => { 748 let cells: Vec = combs.iter().map(|c| { 749 json!({ 750 "id": c.id, 751 "q": c.q, 752 "r": c.r, 753 "author": c.author, 754 "role": c.role, 755 "content": c.content, 756 "body": c.content, 757 "intent": c.intent, 758 "parent_id": c.parent_id, 759 "growthParentId": c.parent_id, 760 "conversationId": c.parent_id.as_deref().unwrap_or(&c.id), 761 "status": "visible", 762 "membership": if c.role == "operator" { "guest" } else { "alumni" }, 763 "created_at": c.created_at, 764 "neighbors": c.neighbors, 765 }) 766 }).collect(); 767 768 Json(json!({ 769 "combs": combs, 770 "cells": cells, 771 "bounds": { 772 "min_q": bounds.min_q, 773 "max_q": bounds.max_q, 774 "min_r": bounds.min_r, 775 "max_r": bounds.max_r, 776 "count": bounds.count, 777 "radius": bounds.radius, 778 "revision": bounds.revision, 779 "messageCount": bounds.message_count, 780 "readOnly": false, 781 "updatedAt": Utc::now().timestamp_millis() 782 }, 783 "bounding_box": { 784 "min_q": bounds.min_q, 785 "max_q": bounds.max_q, 786 "min_r": bounds.min_r, 787 "max_r": bounds.max_r, 788 "count": bounds.count 789 } 790 })) 791 } 792 Err(e) => Json(json!({"error": e.to_string(), "combs": [], "cells": []})), 793 } 794 } 795 796 async fn handle_get_hive_bounds(State(state): State) -> Json { 797 match state.hive_store.get_cells() { 798 Ok((combs, bounds)) => Json(json!({ 799 "bounds": { 800 "min_q": bounds.min_q, 801 "max_q": bounds.max_q, 802 "min_r": bounds.min_r, 803 "max_r": bounds.max_r, 804 "count": bounds.count, 805 "radius": bounds.radius, 806 "revision": bounds.revision, 807 "messageCount": bounds.message_count, 808 "readOnly": false, 809 "updatedAt": Utc::now().timestamp_millis() 810 }, 811 "count": combs.len() 812 })), 813 Err(e) => Json(json!({"error": e.to_string()})), 814 } 815 } 816 817 async fn handle_post_hive_comb( 818 State(state): State, 819 Json(payload): Json, 820 ) -> Result, (StatusCode, Json)> { 821 let content = payload.content.or(payload.body).unwrap_or_default(); 822 if content.trim().is_empty() { 823 return Err(( 824 StatusCode::BAD_REQUEST, 825 Json(json!({"error": "Comb content cannot be empty"})), 826 )); 827 } 828 829 let author = payload.author.unwrap_or_else(|| "AIEN".to_string()); 830 let input = spark_hive::PlaceCombInput { 831 q: payload.q, 832 r: payload.r, 833 author, 834 role: payload.role, 835 content, 836 intent: payload.intent, 837 parent_id: payload.parent_id, 838 }; 839 840 match state.hive_store.place_comb(input) { 841 Ok(comb) => { 842 let (_, bounds) = state.hive_store.get_cells().unwrap_or_else(|_| (vec![], spark_hive::BoundingBox { 843 min_q: comb.q, 844 max_q: comb.q, 845 min_r: comb.r, 846 max_r: comb.r, 847 count: 1, 848 radius: 5, 849 revision: 1, 850 message_count: 1, 851 })); 852 853 let formatted_cell = json!({ 854 "id": comb.id, 855 "q": comb.q, 856 "r": comb.r, 857 "author": comb.author, 858 "role": comb.role, 859 "content": comb.content, 860 "body": comb.content, 861 "intent": comb.intent, 862 "parent_id": comb.parent_id, 863 "growthParentId": comb.parent_id, 864 "conversationId": comb.parent_id.as_deref().unwrap_or(&comb.id), 865 "status": "visible", 866 "membership": if comb.role == "operator" { "guest" } else { "alumni" }, 867 "created_at": comb.created_at, 868 "neighbors": comb.neighbors, 869 }); 870 871 Ok(Json(json!({ 872 "status": "placed", 873 "comb": comb, 874 "cell": formatted_cell, 875 "bounds": { 876 "min_q": bounds.min_q, 877 "max_q": bounds.max_q, 878 "min_r": bounds.min_r, 879 "max_r": bounds.max_r, 880 "count": bounds.count, 881 "radius": bounds.radius, 882 "revision": bounds.revision, 883 "messageCount": bounds.message_count, 884 "readOnly": false, 885 "updatedAt": Utc::now().timestamp_millis() 886 } 887 }))) 888 } 889 Err(spark_hive::HiveError::Collision { q, r, comb_id }) => { 890 Err(( 891 StatusCode::CONFLICT, 892 Json(json!({ 893 "error": format!("Coordinate ({}, {}) is already occupied by comb '{}'", q, r, comb_id), 894 "q": q, 895 "r": r, 896 "occupied_by": comb_id 897 })), 898 )) 899 } 900 Err(e) => { 901 Err(( 902 StatusCode::INTERNAL_SERVER_ERROR, 903 Json(json!({"error": e.to_string()})), 904 )) 905 } 906 } 907 } 908 909 async fn handle_get_hive_adapters() -> Json { 910 let adapters = spark_hive::get_catalog_adapters(); 911 let models = spark_hive::ConsumerModel::all(); 912 let engines = spark_hive::UpstreamEngine::all(); 913 Json(json!({ 914 "total_adapters": adapters.len(), 915 "adapters": adapters, 916 "models": models.iter().map(|m| json!({ 917 "slug": m.slug(), 918 "name": m.display_name(), 919 "params_b": m.param_count_billions(), 920 "hf_repo": m.hf_repo(), 921 "hardware": m.hardware_profile().description(), 922 "quantization": m.recommended_quantization(), 923 })).collect::>(), 924 "engines": engines.iter().map(|e| json!({ 925 "repo": e.repo(), 926 "language": e.primary_language(), 927 "description": e.description(), 928 })).collect::>(), 929 })) 930 } 931 932 async fn handle_get_hive_adapter_chains(State(state): State) -> Json { 933 match spark_hive::list_adapter_pipeline_chains(&state.hive_store) { 934 Ok(chains) => Json(json!({ 935 "total_chains": chains.len(), 936 "chains": chains 937 })), 938 Err(e) => Json(json!({"error": e.to_string(), "chains": []})), 939 } 940 } 941 942 #[derive(Debug, Deserialize)] 943 struct ForgeQuery { 944 project: Option, 945 ring: Option, 946 status: Option, 947 } 948 949 #[derive(Debug, Deserialize)] 950 struct ForgeProjectPayload { 951 project: String, 952 title: String, 953 core_spec: String, 954 } 955 956 #[derive(Debug, Deserialize)] 957 struct ClaimForgePayload { 958 task_id: String, 959 agent_id: String, 960 ttl_secs: Option, 961 } 962 963 #[derive(Debug, Deserialize)] 964 struct HeartbeatForgePayload { 965 task_id: String, 966 agent_id: String, 967 ttl_secs: Option, 968 } 969 970 #[derive(Debug, Deserialize)] 971 struct SubmitForgePayload { 972 task_id: String, 973 agent_id: String, 974 branch: String, 975 pr_url: Option, 976 } 977 978 #[derive(Debug, Deserialize)] 979 struct VerifyForgePayload { 980 task_id: String, 981 verdict: bool, 982 notes: Option, 983 } 984 985 async fn handle_get_forge_tasks( 986 State(state): State, 987 Query(query): Query, 988 ) -> Json { 989 match state.hive_store.list_forge_tasks(query.project.as_deref(), query.ring, query.status.as_deref()) { 990 Ok(tasks) => Json(json!({ "success": true, "tasks": tasks })), 991 Err(e) => Json(json!({ "success": false, "error": e.to_string(), "tasks": [] })), 992 } 993 } 994 995 async fn handle_post_forge_project( 996 State(state): State, 997 Json(payload): Json, 998 ) -> (StatusCode, Json) { 999 match state.hive_store.spawn_forge_project(&payload.project, &payload.title, &payload.core_spec) { 1000 Ok(task) => (StatusCode::CREATED, Json(json!({ "success": true, "task": task }))), 1001 Err(e) => (StatusCode::BAD_REQUEST, Json(json!({ "success": false, "error": e.to_string() }))), 1002 } 1003 } 1004 1005 async fn handle_post_forge_task( 1006 State(state): State, 1007 Json(payload): Json, 1008 ) -> (StatusCode, Json) { 1009 match state.hive_store.create_forge_task(payload) { 1010 Ok(task) => (StatusCode::CREATED, Json(json!({ "success": true, "task": task }))), 1011 Err(e) => (StatusCode::BAD_REQUEST, Json(json!({ "success": false, "error": e.to_string() }))), 1012 } 1013 } 1014 1015 async fn handle_claim_forge_task( 1016 State(state): State, 1017 Json(payload): Json, 1018 ) -> (StatusCode, Json) { 1019 let ttl = payload.ttl_secs.unwrap_or(300); 1020 match state.hive_store.claim_forge_task(&payload.task_id, &payload.agent_id, ttl) { 1021 Ok(task) => (StatusCode::OK, Json(json!({ "success": true, "task": task }))), 1022 Err(spark_hive::HiveError::TaskAlreadyClaimed { task_id, claimed_by }) => ( 1023 StatusCode::CONFLICT, 1024 Json(json!({ "success": false, "error": format!("Task {} already claimed by {}", task_id, claimed_by) })), 1025 ), 1026 Err(spark_hive::HiveError::TaskNotFound(id)) => ( 1027 StatusCode::NOT_FOUND, 1028 Json(json!({ "success": false, "error": format!("Task {} not found", id) })), 1029 ), 1030 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "success": false, "error": e.to_string() }))), 1031 } 1032 } 1033 1034 async fn handle_heartbeat_forge_task( 1035 State(state): State, 1036 Json(payload): Json, 1037 ) -> (StatusCode, Json) { 1038 let ttl = payload.ttl_secs.unwrap_or(300); 1039 match state.hive_store.heartbeat_forge_task(&payload.task_id, &payload.agent_id, ttl) { 1040 Ok(()) => (StatusCode::OK, Json(json!({ "success": true }))), 1041 Err(spark_hive::HiveError::TaskUnauthorized { task_id, claimed_by, agent_id }) => ( 1042 StatusCode::FORBIDDEN, 1043 Json(json!({ 1044 "success": false, 1045 "error": format!("Task {} leased to {}, not {}", task_id, claimed_by, agent_id), 1046 })), 1047 ), 1048 Err(e) => (StatusCode::BAD_REQUEST, Json(json!({ "success": false, "error": e.to_string() }))), 1049 } 1050 } 1051 1052 async fn handle_submit_forge_task( 1053 State(state): State, 1054 Json(payload): Json, 1055 ) -> (StatusCode, Json) { 1056 match state.hive_store.submit_forge_task(&payload.task_id, &payload.agent_id, &payload.branch, payload.pr_url.as_deref()) { 1057 Ok(()) => (StatusCode::OK, Json(json!({ "success": true }))), 1058 Err(e) => (StatusCode::BAD_REQUEST, Json(json!({ "success": false, "error": e.to_string() }))), 1059 } 1060 } 1061 1062 async fn handle_verify_forge_task( 1063 State(state): State, 1064 Json(payload): Json, 1065 ) -> (StatusCode, Json) { 1066 let notes = payload.notes.unwrap_or_default(); 1067 match state.hive_store.verify_forge_task(&payload.task_id, payload.verdict, ¬es) { 1068 Ok(()) => (StatusCode::OK, Json(json!({ "success": true, "verdict": payload.verdict }))), 1069 Err(e) => (StatusCode::BAD_REQUEST, Json(json!({ "success": false, "error": e.to_string() }))), 1070 } 1071 } 1072 1073 async fn handle_reclaim_forge_leases( 1074 State(state): State, 1075 ) -> Json { 1076 match state.hive_store.reclaim_expired_leases() { 1077 Ok(count) => Json(json!({ "success": true, "reclaimed_count": count })), 1078 Err(e) => Json(json!({ "success": false, "error": e.to_string() })), 1079 } 1080 } 1081 1082 1083 const OPERATOR_CONFIG_PATH: &str = "/home/drakestapleton/.config/sovereign/operator.toml"; 1084 const MAIL_API_URL: &str = "http://127.0.0.1:18092"; 1085 1086 async fn handle_get_operator() -> Json { 1087 if Path::new(OPERATOR_CONFIG_PATH).exists() { 1088 if let Ok(content) = fs::read_to_string(OPERATOR_CONFIG_PATH) { 1089 if let Ok(toml_val) = toml::from_str::(&content) { 1090 return Json(toml_val); 1091 } 1092 } 1093 } 1094 Json(json!({ 1095 "operator": { 1096 "name": "Drake Stapleton", 1097 "email": "drake@aien.org", 1098 "handle": "drake", 1099 "sign_commits": true 1100 }, 1101 "engine": { 1102 "mode": "max", 1103 "api_base_url": "http://127.0.0.1:18006/v1", 1104 "model_id": "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16", 1105 "max_port": 18006, 1106 "context_window": 32768, 1107 "temperature": 0.7 1108 } 1109 })) 1110 } 1111 1112 #[derive(Debug, Deserialize)] 1113 struct OperatorUpdatePayload { 1114 name: Option, 1115 email: Option, 1116 handle: Option, 1117 sign_commits: Option, 1118 } 1119 1120 async fn handle_post_operator( 1121 headers: HeaderMap, 1122 Json(payload): Json, 1123 ) -> Result, (StatusCode, Json)> { 1124 if let Some(token) = get_cortex_token() { 1125 if let Some(auth) = headers.get(axum::http::header::AUTHORIZATION) { 1126 if let Ok(auth_str) = auth.to_str() { 1127 if let Some(provided) = auth_str.strip_prefix("Bearer ") { 1128 if provided.trim() != token { 1129 return Err(( 1130 StatusCode::UNAUTHORIZED, 1131 Json(json!({"error": "Invalid bearer token"})), 1132 )); 1133 } 1134 } 1135 } 1136 } 1137 } 1138 1139 let clean_name = payload.name.map(|n| n.chars().filter(|c| !c.is_control()).take(64).collect::()); 1140 let clean_email = payload.email.map(|e| e.chars().filter(|c| !c.is_control()).take(128).collect::()); 1141 let clean_handle = payload.handle.map(|h| h.chars().filter(|c| c.is_alphanumeric() || *c == '_' || *c == '-').take(32).collect::()); 1142 1143 let mut current_toml = if Path::new(OPERATOR_CONFIG_PATH).exists() { 1144 fs::read_to_string(OPERATOR_CONFIG_PATH) 1145 .ok() 1146 .and_then(|s| toml::from_str::(&s).ok()) 1147 .unwrap_or_else(|| json!({})) 1148 } else { 1149 json!({}) 1150 }; 1151 1152 if !current_toml.is_object() { 1153 current_toml = json!({}); 1154 } 1155 1156 let op_map = current_toml.as_object_mut().unwrap(); 1157 let operator_obj = op_map.entry("operator").or_insert_with(|| json!({})); 1158 if let Some(obj) = operator_obj.as_object_mut() { 1159 if let Some(n) = clean_name { obj.insert("name".to_string(), json!(n)); } 1160 if let Some(e) = clean_email { obj.insert("email".to_string(), json!(e)); } 1161 if let Some(h) = clean_handle { obj.insert("handle".to_string(), json!(h)); } 1162 if let Some(s) = payload.sign_commits { obj.insert("sign_commits".to_string(), json!(s)); } 1163 } 1164 1165 let toml_str = toml::to_string_pretty(¤t_toml) 1166 .map_err(|e| (StatusCode::BAD_REQUEST, Json(json!({"error": e.to_string()}))))?; 1167 1168 if let Some(parent) = Path::new(OPERATOR_CONFIG_PATH).parent() { 1169 let _ = fs::create_dir_all(parent); 1170 } 1171 fs::write(OPERATOR_CONFIG_PATH, toml_str) 1172 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))))?; 1173 1174 Ok(Json(json!({"status": "saved", "operator": current_toml.get("operator")}))) 1175 } 1176 1177 async fn handle_engine_status(State(state): State) -> Json { 1178 let start = Instant::now(); 1179 let health_res = state 1180 .client 1181 .get(format!("{}/health", MAX_SEAT_URL)) 1182 .timeout(Duration::from_millis(500)) 1183 .send() 1184 .await; 1185 1186 let latency_ms = start.elapsed().as_millis(); 1187 let is_online = health_res.map(|r| r.status().is_success()).unwrap_or(false); 1188 1189 Json(json!({ 1190 "status": if is_online { "online" } else { "offline" }, 1191 "latency_ms": latency_ms, 1192 "active_engine": "MAX Native Engine", 1193 "active_model": "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16", 1194 "device": "Grace Blackwell GB10 (Dual GPU)", 1195 "port": 18006, 1196 "cost_per_million": "$0.00" 1197 })) 1198 } 1199 1200 async fn handle_install_en2_imprint(State(state): State) -> Result, (StatusCode, Json)> { 1201 let seed_path = "/home/drakestapleton/workspace/aien-sovereign-core/imprints/en2-trinity/cortex-seed.json"; 1202 if !Path::new(seed_path).exists() { 1203 return Err((StatusCode::NOT_FOUND, Json(json!({"error": "EN2 imprint seed not found"})))); 1204 } 1205 1206 let seed_data = fs::read_to_string(seed_path) 1207 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))))?; 1208 let lessons: Vec = serde_json::from_str(&seed_data) 1209 .map_err(|e| (StatusCode::BAD_REQUEST, Json(json!({"error": e.to_string()}))))?; 1210 1211 let token = if Path::new(CORTEX_TOKEN_PATH).exists() { 1212 fs::read_to_string(CORTEX_TOKEN_PATH).unwrap_or_default().trim().to_string() 1213 } else { 1214 String::new() 1215 }; 1216 1217 let mut installed_count = 0; 1218 for lesson in lessons { 1219 let payload = json!({ 1220 "kind": "entity", 1221 "value": { 1222 "canonicalName": lesson["canonicalName"], 1223 "entityType": lesson["entityType"], 1224 "content": lesson["content"], 1225 "metadata": lesson["metadata"], 1226 "space": "atlas-memory" 1227 } 1228 }); 1229 1230 let mut req = state.client.post(format!("{}/api/cortex/write", CORTEX_URL)); 1231 if !token.is_empty() { 1232 req = req.header("Authorization", format!("Bearer {}", token)); 1233 } 1234 if let Ok(res) = req.json(&payload).send().await { 1235 if res.status().is_success() { 1236 installed_count += 1; 1237 } 1238 } 1239 } 1240 1241 Ok(Json(json!({ 1242 "status": "installed", 1243 "installed_count": installed_count, 1244 "version": "2.0.0", 1245 "imprint": "en2-trinity" 1246 }))) 1247 } 1248 1249 async fn handle_mail_status(State(state): State) -> Json { 1250 let res = state 1251 .client 1252 .get(format!("{}/api/mail/status", MAIL_API_URL)) 1253 .timeout(Duration::from_millis(500)) 1254 .send() 1255 .await; 1256 1257 match res { 1258 Ok(r) if r.status().is_success() => { 1259 let val = r.json::().await.unwrap_or(json!({"status": "error"})); 1260 Json(val) 1261 } 1262 _ => Json(json!({ 1263 "status": "offline", 1264 "inbox_count": 0, 1265 "sent_count": 0, 1266 "smtp_port": 2525, 1267 "api_port": 18092, 1268 "cortex_connected": false 1269 })), 1270 } 1271 } 1272 1273 async fn handle_mail_inbox(State(state): State) -> Json { 1274 let res = state 1275 .client 1276 .get(format!("{}/api/mail/inbox", MAIL_API_URL)) 1277 .timeout(Duration::from_millis(800)) 1278 .send() 1279 .await; 1280 1281 match res { 1282 Ok(r) if r.status().is_success() => { 1283 let val = r.json::().await.unwrap_or(json!([])); 1284 Json(val) 1285 } 1286 _ => Json(json!([])), 1287 } 1288 } 1289 1290 async fn handle_mail_sent(State(state): State) -> Json { 1291 let res = state 1292 .client 1293 .get(format!("{}/api/mail/sent", MAIL_API_URL)) 1294 .timeout(Duration::from_millis(800)) 1295 .send() 1296 .await; 1297 1298 match res { 1299 Ok(r) if r.status().is_success() => { 1300 let val = r.json::().await.unwrap_or(json!([])); 1301 Json(val) 1302 } 1303 _ => Json(json!([])), 1304 } 1305 } 1306 1307 async fn handle_mail_send( 1308 State(state): State, 1309 Json(payload): Json, 1310 ) -> Result, (StatusCode, Json)> { 1311 let res = state 1312 .client 1313 .post(format!("{}/api/mail/send", MAIL_API_URL)) 1314 .timeout(Duration::from_secs(3)) 1315 .json(&payload) 1316 .send() 1317 .await 1318 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))))?; 1319 1320 if res.status().is_success() { 1321 let val = res.json::().await.unwrap_or(json!({"status": "sent"})); 1322 Ok(Json(val)) 1323 } else { 1324 Err((StatusCode::BAD_GATEWAY, Json(json!({"error": "Failed to send via mail daemon"})))) 1325 } 1326 } 1327 1328 #[cfg(test)] 1329 mod tests { 1330 use super::*; 1331 1332 fn create_test_state() -> AppState { 1333 let client = reqwest::Client::new(); 1334 let hive_store = Arc::new(spark_hive::CombStore::open_in_memory().unwrap()); 1335 AppState { 1336 client, 1337 start_time: Instant::now(), 1338 redactor_patterns: Arc::new(vec![]), 1339 hive_store, 1340 } 1341 } 1342 1343 #[tokio::test] 1344 async fn test_cockpit_hive_cells_endpoint() { 1345 let state = create_test_state(); 1346 let Json(res) = handle_get_hive_cells(State(state)).await; 1347 1348 assert!(res.get("combs").is_some()); 1349 assert!(res.get("cells").is_some()); 1350 assert!(res.get("bounds").is_some()); 1351 assert!(res.get("bounding_box").is_some()); 1352 1353 let combs = res.get("combs").unwrap().as_array().unwrap(); 1354 assert_eq!(combs.len(), 1); 1355 assert_eq!(combs[0].get("author").unwrap().as_str().unwrap(), "AIEN Genesis"); 1356 } 1357 1358 #[tokio::test] 1359 async fn test_cockpit_hive_comb_endpoint_placement_and_collision() { 1360 let state = create_test_state(); 1361 1362 // 1. Valid placement 1363 let payload = PostCombPayload { 1364 q: Some(1), 1365 r: Some(0), 1366 author: Some("Atlas".to_string()), 1367 role: Some("socratic".to_string()), 1368 content: Some("Socratic inquiry test comb".to_string()), 1369 body: None, 1370 intent: Some("branch".to_string()), 1371 parent_id: Some("comb-genesis-`00000000`".to_string()), 1372 }; 1373 1374 let result = handle_post_hive_comb(State(state.clone()), Json(payload)).await; 1375 assert!(result.is_ok()); 1376 let Json(val) = result.unwrap(); 1377 assert_eq!(val.get("status").unwrap().as_str().unwrap(), "placed"); 1378 let comb = val.get("comb").unwrap(); 1379 assert_eq!(comb.get("q").unwrap().as_i64().unwrap(), 1); 1380 assert_eq!(comb.get("r").unwrap().as_i64().unwrap(), 0); 1381 1382 // 2. Collision rejection 1383 let collide_payload = PostCombPayload { 1384 q: Some(1), 1385 r: Some(0), 1386 author: Some("Intruder".to_string()), 1387 role: None, 1388 content: Some("Colliding text".to_string()), 1389 body: None, 1390 intent: None, 1391 parent_id: None, 1392 }; 1393 1394 let err_result = handle_post_hive_comb(State(state), Json(collide_payload)).await; 1395 assert!(err_result.is_err()); 1396 let (status, Json(err_val)) = err_result.unwrap_err(); 1397 assert_eq!(status, StatusCode::CONFLICT); 1398 assert!(err_val.get("error").unwrap().as_str().unwrap().contains("occupied")); 1399 } 1400 1401 #[tokio::test] 1402 async fn test_cockpit_hive_bounds_endpoint() { 1403 let state = create_test_state(); 1404 let Json(res) = handle_get_hive_bounds(State(state)).await; 1405 assert!(res.get("bounds").is_some()); 1406 assert_eq!(res.get("count").unwrap().as_u64().unwrap(), 1); 1407 } 1408 #[tokio::test] 1409 async fn test_cockpit_hive_adapters_endpoint() { 1410 let Json(res) = handle_get_hive_adapters().await; 1411 assert!(res.get("adapters").is_some()); 1412 assert!(res.get("models").is_some()); 1413 assert!(res.get("engines").is_some()); 1414 assert_eq!(res.get("models").unwrap().as_array().unwrap().len(), 9); 1415 } 1416 1417 #[tokio::test] 1418 async fn test_cockpit_hive_adapter_chains_endpoint() { 1419 let state = create_test_state(); 1420 let Json(res) = handle_get_hive_adapter_chains(State(state)).await; 1421 assert!(res.get("chains").is_some()); 1422 } 1423 1424 #[tokio::test] 1425 async fn test_cockpit_forge_lifecycle_endpoints() { 1426 let state = create_test_state(); 1427 1428 // 1. Spawn forge project 1429 let project_payload = ForgeProjectPayload { 1430 project: "harvester".to_string(), 1431 title: "Model Harvester Pipeline".to_string(), 1432 core_spec: "Autonomous reasoning distillation".to_string(), 1433 }; 1434 let (status, Json(res)) = handle_post_forge_project(State(state.clone()), Json(project_payload)).await; 1435 assert_eq!(status, StatusCode::CREATED); 1436 assert!(res.get("task").is_some()); 1437 let task_id = res.get("task").unwrap().get("id").unwrap().as_str().unwrap().to_string(); 1438 1439 // 2. Claim task 1440 let claim_payload = ClaimForgePayload { 1441 task_id: task_id.clone(), 1442 agent_id: "agent-aegis".to_string(), 1443 ttl_secs: Some(120), 1444 }; 1445 let (status, Json(claim_res)) = handle_claim_forge_task(State(state.clone()), Json(claim_payload)).await; 1446 assert_eq!(status, StatusCode::OK); 1447 assert_eq!(claim_res.get("task").unwrap().get("status").unwrap().as_str().unwrap(), "claimed"); 1448 1449 // 3. Heartbeat 1450 let hb_payload = HeartbeatForgePayload { 1451 task_id: task_id.clone(), 1452 agent_id: "agent-aegis".to_string(), 1453 ttl_secs: Some(300), 1454 }; 1455 let (status, _) = handle_heartbeat_forge_task(State(state.clone()), Json(hb_payload)).await; 1456 assert_eq!(status, StatusCode::OK); 1457 1458 // 4. Submit 1459 let submit_payload = SubmitForgePayload { 1460 task_id: task_id.clone(), 1461 agent_id: "agent-aegis".to_string(), 1462 branch: "feat/harvester-core".to_string(), 1463 pr_url: Some("https://github.com/aien-dev/harvester/pull/1".to_string()), 1464 }; 1465 let (status, _) = handle_submit_forge_task(State(state.clone()), Json(submit_payload)).await; 1466 assert_eq!(status, StatusCode::OK); 1467 1468 // 5. Verify 1469 let verify_payload = VerifyForgePayload { 1470 task_id: task_id.clone(), 1471 verdict: true, 1472 notes: Some("All 4 defense checks passed".to_string()), 1473 }; 1474 let (status, _) = handle_verify_forge_task(State(state.clone()), Json(verify_payload)).await; 1475 assert_eq!(status, StatusCode::OK); 1476 1477 // 6. List tasks 1478 let query = ForgeQuery { 1479 project: Some("harvester".to_string()), 1480 ring: None, 1481 status: Some("verified".to_string()), 1482 }; 1483 let Json(list_res) = handle_get_forge_tasks(State(state), Query(query)).await; 1484 assert_eq!(list_res.get("tasks").unwrap().as_array().unwrap().len(), 1); 1485 } 1486 1487 #[tokio::test] 1488 async fn test_cockpit_operator_profile_sanitization() { 1489 let payload = OperatorUpdatePayload { 1490 name: Some("Drake Stapleton 1491 ".to_string()), 1492 email: Some("drake@aien.org".to_string()), 1493 handle: Some("drake_ops-1".to_string()), 1494 sign_commits: Some(true), 1495 }; 1496 let res = handle_post_operator(HeaderMap::new(), Json(payload)).await; 1497 assert!(res.is_ok()); 1498 let Json(body) = res.unwrap(); 1499 let op = body.get("operator").unwrap(); 1500 assert_eq!(op.get("name").unwrap().as_str().unwrap(), "Drake Stapleton"); 1501 assert_eq!(op.get("email").unwrap().as_str().unwrap(), "drake@aien.org"); 1502 assert_eq!(op.get("handle").unwrap().as_str().unwrap(), "drake_ops-1"); 1503 } 1504 1505 fn create_offline_test_state() -> AppState { 1506 let client = reqwest::Client::builder() 1507 .timeout(Duration::from_millis(50)) 1508 .build() 1509 .unwrap(); 1510 let hive_store = Arc::new(spark_hive::CombStore::open_in_memory().unwrap()); 1511 AppState { 1512 client, 1513 start_time: Instant::now(), 1514 redactor_patterns: Arc::new(vec![]), 1515 hive_store, 1516 } 1517 } 1518 1519 #[tokio::test] 1520 async fn test_cockpit_pulse_endpoint_schema_and_offline_backends() { 1521 let state = create_test_state(); 1522 let Json(pulse) = handle_pulse(State(state)).await; 1523 1524 assert_eq!(pulse["status"], "ok"); 1525 assert_eq!(pulse["heartbeat_bpm"], 72); 1526 assert!((pulse["coherence"].as_f64().unwrap() - 0.98).abs() < 1e-4); 1527 assert!(pulse["uptime_seconds"].as_u64().is_some()); 1528 1529 let model_seat = pulse["model_seat"].as_str().unwrap(); 1530 assert!(model_seat == "ONLINE (Port 18006)" || model_seat == "OFFLINE"); 1531 1532 let conduit_seat = pulse["conduit_seat"].as_str().unwrap(); 1533 assert!(conduit_seat == "ONLINE (Port 6167)" || conduit_seat == "OFFLINE"); 1534 1535 assert!(pulse["hive_count"].as_u64().is_some()); 1536 assert!(pulse["timestamp"].as_str().is_some()); 1537 } 1538 1539 #[tokio::test] 1540 async fn test_cockpit_status_endpoint_schema_and_offline_backend() { 1541 let state = create_test_state(); 1542 let Json(status) = handle_engine_status(State(state)).await; 1543 1544 let status_str = status["status"].as_str().unwrap(); 1545 assert!(status_str == "online" || status_str == "offline"); 1546 assert!(status["latency_ms"].as_u64().is_some()); 1547 assert_eq!(status["active_engine"], "MAX Native Engine"); 1548 assert_eq!(status["active_model"], "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16"); 1549 assert_eq!(status["device"], "Grace Blackwell GB10 (Dual GPU)"); 1550 assert_eq!(status["port"], 18006); 1551 assert_eq!(status["cost_per_million"], "$0.00"); 1552 } 1553 1554 #[tokio::test] 1555 async fn test_cockpit_cortex_search_endpoint_unreachable_fallback() { 1556 let state = create_offline_test_state(); 1557 let query = CortexSearchQuery { 1558 q: Some("test_unreachable_cortex".to_string()), 1559 limit: Some(3), 1560 }; 1561 let Json(res) = handle_cortex_search(State(state), Query(query)).await; 1562 assert!(res.get("results").is_some()); 1563 let results = res.get("results").unwrap().as_array().unwrap(); 1564 assert_eq!(results.len(), 0); 1565 } 1566 1567 #[tokio::test] 1568 async fn test_cockpit_cortex_write_endpoint_error_handling() { 1569 let state = create_offline_test_state(); 1570 let payload = CortexWritePayload { 1571 name: "test_cockpit_write".to_string(), 1572 content: "Telemetry payload".to_string(), 1573 kind: Some("telemetry".to_string()), 1574 }; 1575 1576 let res = handle_cortex_write(State(state), Json(payload)).await; 1577 // Verify proper error response or graceful handling 1578 if let Err((status, _)) = res { 1579 assert!(status == StatusCode::BAD_GATEWAY || status == StatusCode::INTERNAL_SERVER_ERROR); 1580 } 1581 } 1582 1583 #[tokio::test] 1584 async fn test_cockpit_subagents_endpoint_response_structure() { 1585 let Json(res) = handle_get_subagents().await; 1586 assert!(res.get("subagents").is_some()); 1587 assert!(res.get("count").is_some()); 1588 let subagents = res.get("subagents").unwrap().as_array().unwrap(); 1589 let count = res.get("count").unwrap().as_u64().unwrap(); 1590 assert_eq!(subagents.len() as u64, count); 1591 } 1592 1593 #[tokio::test] 1594 async fn test_cockpit_submillisecond_latency_assertions() { 1595 let state = create_test_state(); 1596 1597 // 1. Subagents local file/memory check latency assertion (< 1ms) 1598 let t0 = Instant::now(); 1599 let _ = handle_get_subagents().await; 1600 let elapsed_subagents = t0.elapsed(); 1601 assert!( 1602 elapsed_subagents < Duration::from_millis(1), 1603 "Subagents latency must be sub-millisecond: {:?}", 1604 elapsed_subagents 1605 ); 1606 1607 // 2. Hive bounds retrieval latency assertion (< 1ms) 1608 let t1 = Instant::now(); 1609 let _ = handle_get_hive_bounds(State(state.clone())).await; 1610 let elapsed_bounds = t1.elapsed(); 1611 assert!( 1612 elapsed_bounds < Duration::from_millis(1), 1613 "Hive bounds latency must be sub-millisecond: {:?}", 1614 elapsed_bounds 1615 ); 1616 1617 // 3. Hive cells in-memory store latency assertion (< 1ms) 1618 let t2 = Instant::now(); 1619 let _ = handle_get_hive_cells(State(state)).await; 1620 let elapsed_cells = t2.elapsed(); 1621 assert!( 1622 elapsed_cells < Duration::from_millis(1), 1623 "Hive cells latency must be sub-millisecond: {:?}", 1624 elapsed_cells 1625 ); 1626 } 1627 }