//! brain_local.rs — In-process Brain singleton (stoneshell-brain) //! Copyright 2026 Joseph Stone - All Rights Reserved //! //! Replaces ALL run_brain() subprocess calls with direct Candle+LMDB calls. //! Zero subprocesses. Zero API tokens. Self-contained on device. //! //! Collections: //! "default" — general knowledge + RAG indexed content //! "flint_episodic" — FLINT conversation Q+A pairs (runtime memory) //! "flint_training" — gate training signals indexed for FLINT learning //! "flint_knowledge"— curated knowledge FLINT can reference //! "spf_source" — SPF src/*.rs indexed at startup (FLINT reads its own code) use std::path::PathBuf; use std::sync::{LazyLock, Mutex}; use stoneshell_brain::{Brain, BrainConfig}; use crate::paths::spf_root; // ── Global singleton ───────────────────────────────────────────────────────── static BRAIN: LazyLock>> = LazyLock::new(|| Mutex::new(None)); // ── Config ─────────────────────────────────────────────────────────────────── fn brain_config() -> BrainConfig { let base = spf_root().join("LIVE/TMP/stoneshell-brain"); BrainConfig { model_path: base.join("models/all-MiniLM-L6-v2").to_string_lossy().to_string(), storage_path: base.join("storage").to_string_lossy().to_string(), docs_path: spf_root().join("LIVE/BRAIN/DOCS").to_string_lossy().to_string(), embedding_dim: 384, chunk_size: 512, chunk_overlap: 64, top_k: 20, // generous — handlers truncate to requested limit threshold: 0.3, } } // ── Init ───────────────────────────────────────────────────────────────────── /// Initialize the brain singleton. Call once at startup (run/run_worker). /// Non-fatal — if model fails to load, brain returns error strings but SPF keeps running. /// RC-1: Retries up to 3 times with 2s delay to handle transient failures /// (model file locked, LMDB contention during startup race). pub fn init_brain() { const MAX_RETRIES: u32 = 3; const RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(2); for attempt in 1..=MAX_RETRIES { let config = brain_config(); match Brain::new(config) { Ok(mut brain) => { match brain.load_model() { Ok(()) => log::info!("Brain: MiniLM-L6-v2 loaded — stoneshell-brain active"), Err(e) => log::error!("Brain: model load failed (search disabled): {}", e), } *BRAIN.lock().unwrap() = Some(brain); return; } Err(e) => { if attempt < MAX_RETRIES { log::warn!("Brain: init attempt {}/{} failed: {} — retrying", attempt, MAX_RETRIES, e); std::thread::sleep(RETRY_DELAY); } else { log::error!("Brain: init failed after {} attempts: {}", MAX_RETRIES, e); } } } } } /// Index knowledge/ directory into "flint_knowledge" collection. /// Drop any .md or .txt file there — FLINT reads it on next startup. /// Skipped if collection already has content (idempotent on restart). pub fn index_knowledge_docs() { let knowledge_dir = spf_root().join("LIVE/TMP/stoneshell-brain/knowledge"); if !knowledge_dir.exists() { return; // no knowledge dir yet — silent skip } let mut lock = BRAIN.lock().unwrap(); let Some(ref mut brain) = *lock else { return; }; // Skip if already indexed if let Ok(stats) = brain.collection_stats("flint_knowledge") { if stats.document_count > 0 { log::info!("Brain: flint_knowledge already has {} chunks — skipping re-index", stats.document_count); return; } } match brain.index_directory(&knowledge_dir, "flint_knowledge", &["md", "txt"]) { Ok(stats) => log::info!( "Brain: indexed {} knowledge docs ({} chunks) → flint_knowledge", stats.files_indexed, stats.chunks_created ), Err(e) => log::warn!("Brain: flint_knowledge index failed: {}", e), } } /// Index SPF source code into "spf_source" collection. /// Skipped if collection already has content (idempotent on restart). pub fn index_spf_sources() { let src_dir = spf_root().join("src"); if !src_dir.exists() { log::warn!("Brain: src/ not found at {:?} — spf_source skipped", src_dir); return; } let mut lock = BRAIN.lock().unwrap(); let Some(ref mut brain) = *lock else { return; }; // Skip if already indexed if let Ok(stats) = brain.collection_stats("spf_source") { if stats.document_count > 0 { log::info!("Brain: spf_source already has {} chunks — skipping re-index", stats.document_count); return; } } match brain.index_directory(&src_dir, "spf_source", &["rs"]) { Ok(stats) => log::info!( "Brain: indexed {} src files ({} chunks) → spf_source", stats.files_indexed, stats.chunks_created ), Err(e) => log::warn!("Brain: spf_source index failed: {}", e), } } // ── Public wrappers — one per MCP handler ─────────────────────────────────── /// spf_brain_search — vector similarity search, returns formatted results pub fn brain_search(query: &str, collection: &str, limit: usize) -> String { let lock = BRAIN.lock().unwrap(); let Some(ref brain) = *lock else { return "Brain not initialized".to_string(); }; match brain.search(query, collection) { Ok(results) => { if results.is_empty() { return format!("No results for '{}' in '{}'", query, collection); } let take = limit.min(results.len()); let mut out = format!("Brain search '{}' — {} result(s):\n\n", query, take); for r in results.iter().take(take) { out.push_str(&format!( "Score: {:.3} | {}\n{}\n\n", r.score, r.source, r.text )); } out } Err(e) => format!("Brain search error: {}", e), } } /// spf_brain_store — chunk + embed + store arbitrary text pub fn brain_store(text: &str, title: &str, collection: &str) -> String { let mut lock = BRAIN.lock().unwrap(); let Some(ref mut brain) = *lock else { return "Brain not initialized".to_string(); }; match brain.store_document(text, title, collection) { Ok(count) => format!("Stored '{}' → {} chunk(s) in '{}'", title, count, collection), Err(e) => format!("Brain store error: {}", e), } } /// spf_brain_context — hybrid search, returns formatted context for prompt injection pub fn brain_context(query: &str, collection: &str, max_tokens: usize) -> String { let lock = BRAIN.lock().unwrap(); let Some(ref brain) = *lock else { return "Brain not initialized".to_string(); }; match brain.get_context(query, collection, max_tokens) { Ok(ctx) if ctx.is_empty() => format!("No context found for '{}'", query), Ok(ctx) => ctx, Err(e) => format!("Brain context error: {}", e), } } /// spf_brain_index — index a file or directory into a collection pub fn brain_index_path(path: &str, collection: &str) -> String { let mut lock = BRAIN.lock().unwrap(); let Some(ref mut brain) = *lock else { return "Brain not initialized".to_string(); }; let p = PathBuf::from(path); if p.is_dir() { match brain.index_directory(&p, collection, &[]) { Ok(stats) => format!( "Indexed directory '{}': {} files, {} chunks ({} failed)", path, stats.files_indexed, stats.chunks_created, stats.files_failed ), Err(e) => format!("Brain index error: {}", e), } } else { match brain.index_file(&p, collection) { Ok(count) => format!("Indexed '{}': {} chunks", path, count), Err(e) => format!("Brain index error: {}", e), } } } /// spf_brain_list — list all collections with doc counts pub fn brain_list_collections() -> String { let lock = BRAIN.lock().unwrap(); let Some(ref brain) = *lock else { return "Brain not initialized".to_string(); }; match brain.list_collections() { Ok(cols) if cols.is_empty() => "No collections found".to_string(), Ok(cols) => { let mut out = format!("{} collection(s):\n\n", cols.len()); for col in &cols { match brain.collection_stats(col) { Ok(s) => out.push_str(&format!(" {} — {} docs, {}d\n", col, s.document_count, s.embedding_dim)), Err(_) => out.push_str(&format!(" {}\n", col)), } } out } Err(e) => format!("Brain list error: {}", e), } } /// spf_brain_status — model state, storage size, collections summary pub fn brain_status() -> String { let base = spf_root().join("LIVE/TMP/stoneshell-brain"); let lock = BRAIN.lock().unwrap(); let mut parts = Vec::new(); match &*lock { Some(brain) => { parts.push(format!("Status: active")); parts.push(format!("Model: {}", if brain.is_model_loaded() { "loaded ✓" } else { "not loaded ✗" })); parts.push(format!("Model path: {}", base.join("models/all-MiniLM-L6-v2").display())); parts.push(format!("Storage: {}", base.join("storage").display())); let storage = base.join("storage"); if storage.exists() { if let Ok(entries) = std::fs::read_dir(&storage) { let size: u64 = entries .filter_map(|e| e.ok()) .filter_map(|e| e.metadata().ok()) .map(|m| m.len()) .sum(); parts.push(format!("Storage size: {:.2} MB", size as f64 / 1_048_576.0)); } } match brain.list_collections() { Ok(cols) if cols.is_empty() => parts.push("Collections: (none)".to_string()), Ok(cols) => { let col_lines: Vec = cols.iter().map(|c| { brain.collection_stats(c) .map(|s| format!(" {} ({} docs)", c, s.document_count)) .unwrap_or_else(|_| format!(" {}", c)) }).collect(); parts.push(format!("Collections:\n{}", col_lines.join("\n"))); } Err(e) => parts.push(format!("Collections: error — {}", e)), } } None => { parts.push("Status: NOT INITIALIZED".to_string()); parts.push(format!("Expected model at: {}", base.join("models/all-MiniLM-L6-v2").display())); } } parts.join("\n") } /// spf_brain_recall — search + return grouped full text by source pub fn brain_recall(query: &str, collection: &str) -> String { let lock = BRAIN.lock().unwrap(); let Some(ref brain) = *lock else { return "Brain not initialized".to_string(); }; match brain.search(query, collection) { Ok(results) if results.is_empty() => { format!("No documents found for '{}'", query) } Ok(results) => { let mut out = format!("Recall '{}' ({} chunks):\n", query, results.len()); let mut current_source = String::new(); for r in &results { if r.source != current_source { out.push_str(&format!("\n══ {} ══\n", r.source)); current_source = r.source.clone(); } out.push_str(&r.text); out.push('\n'); } out } Err(e) => format!("Brain recall error: {}", e), } } /// spf_brain_list_docs — doc count + summary for a collection pub fn brain_list_docs(collection: &str) -> String { let lock = BRAIN.lock().unwrap(); let Some(ref brain) = *lock else { return "Brain not initialized".to_string(); }; match brain.collection_stats(collection) { Ok(stats) => format!( "Collection '{}': {} document chunk(s), {}d embeddings", collection, stats.document_count, stats.embedding_dim ), Err(e) => format!("Brain list-docs error: {}", e), } } /// spf_brain_get_doc — find chunk by ID or source name match pub fn brain_get_doc(doc_id: &str, collection: &str) -> String { let lock = BRAIN.lock().unwrap(); let Some(ref brain) = *lock else { return "Brain not initialized".to_string(); }; // Search using the doc_id as a query, then find exact or partial match match brain.search(doc_id, collection) { Ok(results) => { if let Some(r) = results .into_iter() .find(|r| r.id == doc_id || r.source.contains(doc_id)) { format!( "ID: {}\nSource: {}\nScore: {:.3}\n\n{}", r.id, r.source, r.score, r.text ) } else { format!("Doc '{}' not found in '{}'", doc_id, collection) } } Err(e) => format!("Brain get-doc error: {}", e), } }