File size: 13,933 Bytes
1269259 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | //! 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<Mutex<Option<Brain>>> =
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<String> = 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),
}
}
|