interplane.Get Omega
Read in your language

spark-dream

Idle-cycle neural memory consolidator and vectorizer

Brought by drakestapleton

branch main Branches Tags History

spark-dream / src / lib.rs

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