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-mv/blob/main/crates/spark-dream/src/lib.rs # 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 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-mv / crates / spark-dream / src / lib.rs` 749 lines ยท 28197 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 16 use aien_localhttp::Client; 17 use chrono::{DateTime, Utc}; 18 use serde::{Deserialize, Serialize}; 19 use serde_json::{json, Value}; 20 use std::fs; 21 use std::path::{Path, PathBuf}; 22 use std::time::Duration; 23 24 pub const DEFAULT_CORTEX_URL: &str = "http://127.0.0.1:18080"; 25 pub const DEFAULT_MODEL_URL: &str = "http://127.0.0.1:18006"; 26 27 #[derive(Debug, Clone, Serialize, Deserialize)] 28 pub struct DreamState { 29 pub daemon_running: bool, 30 pub current_phase: String, 31 pub last_cycle_timestamp: Option, 32 pub cycles_completed: u64, 33 pub facts_committed: u64, 34 pub proposals_staged: u64, 35 pub facts_rejected: u64, 36 pub hive_pulse: Option, 37 } 38 39 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] 40 pub struct CandidateItem { 41 pub source: String, 42 pub text: String, 43 pub item_type: String, // operational_fact, soul_proposal, discovery, learned_procedure, lesson 44 pub canonical_name: String, 45 pub metadata: Value, 46 } 47 48 /// Extracts a structured candidate item from varied markdown note layouts. 49 /// Handles frontmatter, markdown headers, bullet findings, and unstructured raw notes. 50 /// Recovers gracefully from malformed frontmatter and empty content. 51 pub fn extract_discovery_from_markdown(path: &Path, raw_content: &str) -> Option { 52 let trimmed = raw_content.trim(); 53 if trimmed.is_empty() { 54 return None; 55 } 56 57 let file_stem = path 58 .file_stem() 59 .map(|s| s.to_string_lossy().to_string()) 60 .unwrap_or_else(|| "unknown_note".to_string()); 61 62 let source = path.to_string_lossy().to_string(); 63 64 // 1. Check for YAML-style frontmatter delimiter 65 if let Some(after_first) = trimmed.strip_prefix("---") { 66 if let Some(closing_idx) = after_first.find("\n---") { 67 let frontmatter_block = &after_first[..closing_idx]; 68 let body_block = after_first[closing_idx + 4..].trim(); 69 70 let mut title: Option = None; 71 let mut entity_type: Option = None; 72 let mut tags: Vec = Vec::new(); 73 let mut custom_meta = serde_json::Map::new(); 74 75 for line in frontmatter_block.lines() { 76 let l = line.trim(); 77 if l.is_empty() || l.starts_with('#') { 78 continue; 79 } 80 if let Some((k, v)) = l.split_once(':') { 81 let key = k.trim().to_lowercase(); 82 let val = v.trim().trim_matches('"').trim_matches('\'').to_string(); 83 match key.as_str() { 84 "title" | "canonical_name" | "name" => title = Some(val), 85 "type" | "entity_type" | "kind" => entity_type = Some(val), 86 "tags" => { 87 let clean_val = val.trim_matches('[').trim_matches(']'); 88 for t in clean_val.split(',') { 89 let tag_clean = t.trim().trim_matches('"').trim_matches('\''); 90 if !tag_clean.is_empty() { 91 tags.push(tag_clean.to_string()); 92 } 93 } 94 } 95 _ => { 96 custom_meta.insert(key, json!(val)); 97 } 98 } 99 } 100 } 101 102 let canonical_name = title.unwrap_or_else(|| format!("parked-{}", file_stem)); 103 let item_type = entity_type.unwrap_or_else(|| "discovery".to_string()); 104 let mut meta_obj = json!({ 105 "source": source, 106 "consolidated_at": Utc::now().to_rfc3339(), 107 "layout": "frontmatter", 108 }); 109 110 if !tags.is_empty() { 111 meta_obj["tags"] = json!(tags); 112 } 113 for (k, v) in custom_meta { 114 meta_obj[k] = v; 115 } 116 117 let text = if body_block.is_empty() { 118 frontmatter_block.trim().to_string() 119 } else { 120 body_block.to_string() 121 }; 122 123 return Some(CandidateItem { 124 source, 125 text, 126 item_type, 127 canonical_name, 128 metadata: meta_obj, 129 }); 130 } 131 // If unclosed frontmatter fence, fall through to heading or raw extraction 132 } 133 134 // 2. Check for markdown top-level headings: # Heading 135 for line in trimmed.lines() { 136 let l = line.trim(); 137 if l.starts_with("# ") { 138 let heading_text = l.trim_start_matches("# ").trim(); 139 let clean_heading = heading_text 140 .trim_start_matches("Discovery:") 141 .trim_start_matches("discovery:") 142 .trim_start_matches("Lesson:") 143 .trim_start_matches("lesson:") 144 .trim_start_matches("Procedure:") 145 .trim(); 146 147 let item_type = if heading_text.to_lowercase().contains("lesson") { 148 "lesson".to_string() 149 } else if heading_text.to_lowercase().contains("procedure") { 150 "learned_procedure".to_string() 151 } else { 152 "discovery".to_string() 153 }; 154 155 let canonical_name = if !clean_heading.is_empty() { 156 clean_heading.to_string() 157 } else { 158 format!("parked-{}", file_stem) 159 }; 160 161 return Some(CandidateItem { 162 source, 163 text: trimmed.to_string(), 164 item_type, 165 canonical_name, 166 metadata: json!({ 167 "source": path.to_string_lossy().to_string(), 168 "consolidated_at": Utc::now().to_rfc3339(), 169 "layout": "heading" 170 }), 171 }); 172 } 173 } 174 175 // 3. Check for bullet list finding layout (- Finding: / - Solution:) 176 let mut finding: Option = None; 177 for line in trimmed.lines() { 178 let l = line.trim(); 179 if l.starts_with("- finding:") || l.starts_with("- Finding:") || l.starts_with("* Finding:") 180 { 181 if let Some((_, val)) = l.split_once(':') { 182 finding = Some(val.trim().to_string()); 183 break; 184 } 185 } 186 } 187 188 if let Some(f) = finding { 189 return Some(CandidateItem { 190 source, 191 text: trimmed.to_string(), 192 item_type: "discovery".to_string(), 193 canonical_name: f, 194 metadata: json!({ 195 "source": path.to_string_lossy().to_string(), 196 "consolidated_at": Utc::now().to_rfc3339(), 197 "layout": "bullet_finding" 198 }), 199 }); 200 } 201 202 // 4. Default unstructured raw note layout 203 Some(CandidateItem { 204 source, 205 text: trimmed.to_string(), 206 item_type: "discovery".to_string(), 207 canonical_name: format!("parked-{}", file_stem), 208 metadata: json!({ 209 "source": path.to_string_lossy().to_string(), 210 "consolidated_at": Utc::now().to_rfc3339(), 211 "layout": "raw" 212 }), 213 }) 214 } 215 216 /// Evaluates whether the workstation state constitutes an idle consolidation window. 217 pub fn is_idle(gpu_util: u32, idle_secs: u64, idle_threshold: u64) -> bool { 218 gpu_util <= 5 && idle_secs >= idle_threshold 219 } 220 221 #[derive(Debug, Clone)] 222 pub struct DreamEngine { 223 pub base_dir: PathBuf, 224 pub sessions_dir: PathBuf, 225 pub park_dir: PathBuf, 226 pub inbox_dir: PathBuf, 227 pub dream_dir: PathBuf, 228 pub cortex_url: String, 229 pub cortex_token_path: PathBuf, 230 pub client: Client, 231 } 232 233 impl DreamEngine { 234 pub fn new(base_dir: PathBuf) -> Self { 235 let sessions_dir = base_dir.join("sessions"); 236 let inbox_dir = base_dir.join("inbox"); 237 let dream_dir = base_dir.join("aien-dream"); 238 let home = std::env::var("HOME") 239 .or_else(|_| std::env::var("USERPROFILE")) 240 .map(PathBuf::from) 241 .unwrap_or_else(|_| PathBuf::from(".")); 242 let park_dir = home.join("atlas-prime-workspace/park"); 243 let cortex_token_path = home.join(".config/cortex/token"); 244 245 let client = Client::builder().timeout(Duration::from_secs(10)).build(); 246 247 Self { 248 base_dir, 249 sessions_dir, 250 park_dir, 251 inbox_dir, 252 dream_dir, 253 cortex_url: DEFAULT_CORTEX_URL.to_string(), 254 cortex_token_path, 255 client, 256 } 257 } 258 259 pub fn with_cortex_url(mut self, url: String) -> Self { 260 self.cortex_url = url; 261 self 262 } 263 264 pub fn with_park_dir(mut self, dir: PathBuf) -> Self { 265 self.park_dir = dir; 266 self 267 } 268 269 pub fn get_token_secure(&self) -> String { 270 // First try hardware TPM vault environment 271 if let Ok(t) = std::env::var("CORTEX_TOKEN") { 272 if !t.trim().is_empty() { 273 return t.trim().to_string(); 274 } 275 } 276 self.get_cortex_token() 277 } 278 279 pub fn get_cortex_token(&self) -> String { 280 fs::read_to_string(&self.cortex_token_path) 281 .unwrap_or_default() 282 .trim() 283 .to_string() 284 } 285 286 /// Read GPU telemetry directly from nvidia-smi / /proc without python overhead 287 pub async fn get_gpu_utilization(&self) -> u32 { 288 let output = tokio::process::Command::new("nvidia-smi") 289 .args([ 290 "--query-gpu=utilization.gpu", 291 "--format=csv,noheader,nounits", 292 ]) 293 .output() 294 .await; 295 296 if let Ok(out) = output { 297 let s = String::from_utf8_lossy(&out.stdout); 298 if let Some(val) = s.lines().next().and_then(|l| l.trim().parse::().ok()) { 299 return val; 300 } 301 } 302 0 303 } 304 305 /// Check last activity timestamp across active session files 306 pub fn get_last_session_activity(&self) -> Option> { 307 let mut latest: Option> = None; 308 if let Ok(entries) = fs::read_dir(&self.sessions_dir) { 309 for entry in entries.flatten() { 310 if let Ok(meta) = entry.metadata() { 311 if let Ok(mtime) = meta.modified() { 312 let dt: DateTime = mtime.into(); 313 if latest.map(|l| dt > l).unwrap_or(true) { 314 latest = Some(dt); 315 } 316 } 317 } 318 } 319 } 320 latest 321 } 322 323 /// Commit verified fact to Cortex Memory (port 18080) 324 pub async fn commit_to_cortex( 325 &self, 326 entity_type: &str, 327 canonical_name: &str, 328 content: &str, 329 metadata: &Value, 330 ) -> Result { 331 let token = self.get_token_secure(); 332 let payload = json!({ 333 "kind": "entity", 334 "value": { 335 "canonicalName": canonical_name, 336 "entityType": entity_type, 337 "content": content, 338 "metadata": metadata, 339 "space": "atlas-memory" 340 } 341 }); 342 343 let resp = self 344 .client 345 .post(format!("{}/api/cortex/write", self.cortex_url)) 346 .header("Authorization", format!("Bearer {}", token)) 347 .header("Content-Type", "application/json") 348 .json(&payload) 349 .send() 350 .await 351 .map_err(|e| format!("Cortex request failed: {}", e))?; 352 353 if resp.status().is_success() { 354 let res_json = resp 355 .json::() 356 .await 357 .unwrap_or_else(|_| json!({"status": "ok"})); 358 Ok(res_json) 359 } else { 360 Err(format!("Cortex returned status {}", resp.status())) 361 } 362 } 363 364 /// Consolidate uncommitted knowledge from parked notes and sessions 365 pub async fn execute_dream_cycle(&self) -> Result { 366 let mut committed = 0; 367 let staged = 0; 368 let mut rejected = 0; 369 370 fs::create_dir_all(&self.inbox_dir).map_err(|e| e.to_string())?; 371 fs::create_dir_all(&self.dream_dir).map_err(|e| e.to_string())?; 372 373 // 1. Scan Park notes 374 if self.park_dir.exists() { 375 if let Ok(entries) = fs::read_dir(&self.park_dir) { 376 for entry in entries.flatten() { 377 let path = entry.path(); 378 if path.is_file() && path.extension().map(|e| e == "md").unwrap_or(false) { 379 if let Ok(content) = fs::read_to_string(&path) { 380 if content.trim().is_empty() { 381 continue; 382 } 383 384 if let Some(item) = extract_discovery_from_markdown(&path, &content) { 385 match self 386 .commit_to_cortex( 387 &item.item_type, 388 &item.canonical_name, 389 &item.text, 390 &item.metadata, 391 ) 392 .await 393 { 394 Ok(_) => { 395 committed += 1; 396 // Archive parked note 397 let archive_name = format!( 398 "{}.consolidated", 399 path.file_name().unwrap().to_string_lossy() 400 ); 401 let _ = 402 fs::rename(&path, path.with_file_name(archive_name)); 403 } 404 Err(_) => { 405 rejected += 1; 406 } 407 } 408 } 409 } 410 } 411 } 412 } 413 } 414 415 // 2. Compute state summary 416 let state = DreamState { 417 daemon_running: true, 418 current_phase: "idle".to_string(), 419 last_cycle_timestamp: Some(Utc::now().to_rfc3339()), 420 cycles_completed: 1, 421 facts_committed: committed, 422 proposals_staged: staged, 423 facts_rejected: rejected, 424 hive_pulse: Some(json!({ 425 "heartbeat": "synchronous", 426 "timestamp": Utc::now().to_rfc3339() 427 })), 428 }; 429 430 // Write state file 431 let state_path = self.dream_dir.join("state.json"); 432 let _ = fs::write(&state_path, serde_json::to_string_pretty(&state).unwrap()); 433 434 Ok(state) 435 } 436 } 437 438 #[cfg(test)] 439 mod tests { 440 use super::*; 441 use axum::{routing::post, Json, Router}; 442 use std::sync::atomic::{AtomicUsize, Ordering}; 443 use std::sync::Arc; 444 use uuid::Uuid; 445 446 #[test] 447 fn test_extract_discovery_from_frontmatter_layout() { 448 let path = PathBuf::from("/tmp/note_frontmatter.md"); 449 let content = r#"--- 450 title: NVFP4 Checkpoint Loader Fix 451 type: learned_procedure 452 tags: [vllm, max, quantization] 453 subsystem: neural_weights 454 --- 455 # Implementation Overview 456 Directly map fp4 quantized tensor blocks without conversion overhead."#; 457 458 let item = extract_discovery_from_markdown(&path, content).expect("extracted item"); 459 assert_eq!(item.canonical_name, "NVFP4 Checkpoint Loader Fix"); 460 assert_eq!(item.item_type, "learned_procedure"); 461 assert_eq!(item.metadata["layout"], "frontmatter"); 462 assert_eq!(item.metadata["subsystem"], "neural_weights"); 463 let tags = item.metadata["tags"].as_array().unwrap(); 464 assert_eq!(tags.len(), 3); 465 assert_eq!(tags[0], "vllm"); 466 assert!(item 467 .text 468 .contains("Directly map fp4 quantized tensor blocks")); 469 assert!(!item.text.contains("subsystem: neural_weights")); 470 } 471 472 #[test] 473 fn test_extract_discovery_from_heading_layout() { 474 let path = PathBuf::from("/tmp/note_heading.md"); 475 let content = r#"# Discovery: Grace Blackwell GB10 Topology 476 Discovered unified 128GB LPDDR5X bus between CPU and dual Blackwell GPUs."#; 477 478 let item = extract_discovery_from_markdown(&path, content).expect("extracted item"); 479 assert_eq!(item.canonical_name, "Grace Blackwell GB10 Topology"); 480 assert_eq!(item.item_type, "discovery"); 481 assert_eq!(item.metadata["layout"], "heading"); 482 assert!(item.text.contains("unified 128GB LPDDR5X")); 483 } 484 485 #[test] 486 fn test_extract_discovery_from_bullet_layout() { 487 let path = PathBuf::from("/tmp/note_bullet.md"); 488 let content = r#"- Finding: SQLite WAL checkpoint stalls under massive bulk insert 489 - Solution: Run PRAGMA wal_checkpoint(TRUNCATE) before consolidation 490 - Verification: 100% pass rate"#; 491 492 let item = extract_discovery_from_markdown(&path, content).expect("extracted item"); 493 assert_eq!( 494 item.canonical_name, 495 "SQLite WAL checkpoint stalls under massive bulk insert" 496 ); 497 assert_eq!(item.item_type, "discovery"); 498 assert_eq!(item.metadata["layout"], "bullet_finding"); 499 } 500 501 #[test] 502 fn test_extract_discovery_from_raw_unstructured_layout() { 503 let path = PathBuf::from("/tmp/parked-hotfix-123.md"); 504 let content = "Fixed zero-length embedding cosine calculation crash."; 505 506 let item = extract_discovery_from_markdown(&path, content).expect("extracted item"); 507 assert_eq!(item.canonical_name, "parked-parked-hotfix-123"); 508 assert_eq!(item.item_type, "discovery"); 509 assert_eq!(item.metadata["layout"], "raw"); 510 assert_eq!( 511 item.text, 512 "Fixed zero-length embedding cosine calculation crash." 513 ); 514 } 515 516 #[test] 517 fn test_extract_discovery_malformed_frontmatter_recovery() { 518 let path = PathBuf::from("/tmp/malformed.md"); 519 let content = r#"--- 520 unclosed frontmatter fence without closing delimiter 521 # Actual Title Here 522 Valid body content that must not be discarded."#; 523 524 let item = extract_discovery_from_markdown(&path, content).expect("recovers cleanly"); 525 assert_eq!(item.canonical_name, "Actual Title Here"); 526 assert!(item 527 .text 528 .contains("Valid body content that must not be discarded")); 529 } 530 531 #[test] 532 fn test_scanner_ignores_non_markdown_and_zero_byte_files() { 533 let path_txt = PathBuf::from("/tmp/random.txt"); 534 let path_png = PathBuf::from("/tmp/diagram.png"); 535 let path_empty = PathBuf::from("/tmp/empty.md"); 536 let path_whitespace = PathBuf::from("/tmp/whitespace.md"); 537 538 // Zero-byte or whitespace-only files 539 assert!(extract_discovery_from_markdown(&path_empty, "").is_none()); 540 assert!(extract_discovery_from_markdown(&path_whitespace, " \n\t \n ").is_none()); 541 542 // File extensions filter validation in scanner 543 assert_ne!(path_txt.extension().and_then(|e| e.to_str()), Some("md")); 544 assert_ne!(path_png.extension().and_then(|e| e.to_str()), Some("md")); 545 } 546 547 #[test] 548 fn test_idle_cycle_detection_gpu_and_operator_thresholds() { 549 let idle_threshold = 900; // 15 minutes 550 551 // 1. GPU busy (> 5%) -> not idle 552 assert!(!is_idle(6, 1200, idle_threshold)); 553 assert!(!is_idle(99, 1200, idle_threshold)); 554 555 // 2. GPU idle (0%), operator recently active (< 900s) -> not idle 556 assert!(!is_idle(0, 300, idle_threshold)); 557 assert!(!is_idle(2, 899, idle_threshold)); 558 559 // 3. GPU idle (<= 5%) and operator idle (>= 900s) -> idle trigger! 560 assert!(is_idle(0, 900, idle_threshold)); 561 assert!(is_idle(3, 1500, idle_threshold)); 562 assert!(is_idle(5, 3600, idle_threshold)); 563 } 564 565 #[test] 566 fn test_last_session_activity_detection() { 567 let temp_dir = 568 std::env::temp_dir().join(format!("spark_dream_test_sessions_{}", Uuid::new_v4())); 569 let sessions_dir = temp_dir.join("sessions"); 570 fs::create_dir_all(&sessions_dir).unwrap(); 571 572 let engine = DreamEngine::new(temp_dir.clone()); 573 574 // Empty directory 575 assert!(engine.get_last_session_activity().is_none()); 576 577 // Write a session file 578 let sess_file = sessions_dir.join("session-alpha.json"); 579 fs::write(&sess_file, "{\"active\": true}").unwrap(); 580 581 let last_act = engine.get_last_session_activity(); 582 assert!(last_act.is_some()); 583 584 let _ = fs::remove_dir_all(&temp_dir); 585 } 586 587 #[tokio::test] 588 async fn test_deduplication_and_simulated_dream_consolidation_cycle() { 589 // Spin up mock Cortex server to verify deduplication and entity upserts 590 let write_count = Arc::new(AtomicUsize::new(0)); 591 let last_canonical_name = Arc::new(std::sync::Mutex::new(String::new())); 592 593 let wc = Arc::clone(&write_count); 594 let lcn = Arc::clone(&last_canonical_name); 595 596 let app = Router::new().route( 597 "/api/cortex/write", 598 post(move |Json(payload): Json| { 599 let wc = Arc::clone(&wc); 600 let lcn = Arc::clone(&lcn); 601 async move { 602 wc.fetch_add(1, Ordering::SeqCst); 603 if let Some(val) = payload.get("value") { 604 if let Some(name) = val.get("canonicalName").and_then(|n| n.as_str()) { 605 *lcn.lock().unwrap() = name.to_string(); 606 } 607 } 608 Json(json!({ 609 "recorded": true, 610 "receipt": { 611 "id": "mock-receipt-id", 612 "operation": "entity.upsert", 613 "targetType": "entity", 614 "targetId": "entity-uuid-1", 615 "committedAt": Utc::now().to_rfc3339() 616 } 617 })) 618 } 619 }), 620 ); 621 622 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 623 let port = listener.local_addr().unwrap().port(); 624 let server_handle = tokio::spawn(async move { 625 axum::serve(listener, app).await.unwrap(); 626 }); 627 628 // Set up test directories 629 let temp_dir = 630 std::env::temp_dir().join(format!("spark_dream_cycle_test_{}", Uuid::new_v4())); 631 let park_dir = temp_dir.join("park"); 632 fs::create_dir_all(&park_dir).unwrap(); 633 634 let test_note = park_dir.join("note-dedup.md"); 635 fs::write( 636 &test_note, 637 "---\ntitle: Deduplication Fact\ntype: discovery\n---\nImportant consolidated insight.", 638 ) 639 .unwrap(); 640 641 // Also add non-markdown and empty file to verify scanner resilience 642 fs::write(park_dir.join("ignore.txt"), "non-markdown content").unwrap(); 643 fs::write(park_dir.join("empty.md"), "").unwrap(); 644 645 std::env::set_var("CORTEX_TOKEN", "mock_token"); 646 647 let engine = DreamEngine::new(temp_dir.clone()) 648 .with_cortex_url(format!("http://127.0.0.1:{}", port)) 649 .with_park_dir(park_dir.clone()); 650 651 // Execute dream cycle 652 let state = engine 653 .execute_dream_cycle() 654 .await 655 .expect("dream cycle executed"); 656 657 assert_eq!(state.facts_committed, 1); 658 assert_eq!(state.facts_rejected, 0); 659 assert_eq!(write_count.load(Ordering::SeqCst), 1); 660 assert_eq!(*last_canonical_name.lock().unwrap(), "Deduplication Fact"); 661 662 // Verify note was archived to .consolidated 663 assert!(!test_note.exists()); 664 assert!(park_dir.join("note-dedup.md.consolidated").exists()); 665 666 // Verify non-markdown file was NOT touched or moved 667 assert!(park_dir.join("ignore.txt").exists()); 668 669 // Clean up 670 server_handle.abort(); 671 std::env::remove_var("CORTEX_TOKEN"); 672 let _ = fs::remove_dir_all(&temp_dir); 673 } 674 675 use aien_localhttp::test_server::{closed_port, response, serve_once}; 676 677 /// Never reads the operator's real token file: tests must not put a real 678 /// token on the wire or into a failure message. 679 fn engine_at(cortex_url: String) -> DreamEngine { 680 let mut engine = DreamEngine::new(std::env::temp_dir()).with_cortex_url(cortex_url); 681 engine.cortex_token_path = PathBuf::from("/nonexistent/spark-dream-test-token"); 682 engine 683 } 684 685 #[tokio::test] 686 async fn commit_to_cortex_sends_the_same_request_and_returns_the_receipt() { 687 let (base, server) = serve_once(response( 688 "200 OK", 689 "application/json", 690 "{\"recorded\":true}", 691 )) 692 .await; 693 let got = engine_at(base) 694 .commit_to_cortex("discovery", "Fact", "body", &json!({"k": 1})) 695 .await 696 .unwrap(); 697 assert_eq!(got, json!({"recorded": true})); 698 let request = server.await.unwrap(); 699 assert!( 700 request.starts_with("POST /api/cortex/write HTTP/1.1\r\n"), 701 "{request}" 702 ); 703 // The token is empty here, or "mock_token" when the cycle test runs at the 704 // same time. Header values are sent trimmed, as HTTP field values are 705 // defined without surrounding whitespace, so an empty token is "Bearer". 706 assert!(request.contains("\r\nAuthorization: Bearer"), "{request}"); 707 // Content-Type is set once: the explicit header wins over json(). 708 assert_eq!(request.matches("Content-Type: application/json").count(), 1); 709 let body: Value = serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap(); 710 assert_eq!(body["kind"], "entity"); 711 assert_eq!(body["value"]["canonicalName"], "Fact"); 712 assert_eq!(body["value"]["entityType"], "discovery"); 713 assert_eq!(body["value"]["space"], "atlas-memory"); 714 assert_eq!(body["value"]["metadata"], json!({"k": 1})); 715 } 716 717 #[tokio::test] 718 async fn commit_to_cortex_non_json_success_falls_back_to_ok() { 719 let (base, _server) = serve_once(response("201 Created", "text/plain", "done")).await; 720 let got = engine_at(base) 721 .commit_to_cortex("t", "n", "c", &json!({})) 722 .await 723 .unwrap(); 724 assert_eq!(got, json!({"status": "ok"})); 725 } 726 727 #[tokio::test] 728 async fn commit_to_cortex_reports_error_status_refused_port_and_https() { 729 let (base, _server) = 730 serve_once(response("500 Internal Server Error", "text/plain", "x")).await; 731 let err = engine_at(base) 732 .commit_to_cortex("t", "n", "c", &json!({})) 733 .await 734 .unwrap_err(); 735 assert_eq!(err, "Cortex returned status 500 Internal Server Error"); 736 737 let err = engine_at(closed_port().await) 738 .commit_to_cortex("t", "n", "c", &json!({})) 739 .await 740 .unwrap_err(); 741 assert!(err.starts_with("Cortex request failed: "), "{err}"); 742 743 let err = engine_at("https://127.0.0.1:1".to_string()) 744 .commit_to_cortex("t", "n", "c", &json!({})) 745 .await 746 .unwrap_err(); 747 assert!(err.contains("https is refused"), "{err}"); 748 } 749 }