//! Recall path (PRD section 2): query-side retrieval over stored text using //! BM25 - NEVER the ingestion embedder. Optional student hidden-state //! projection plugs in later behind the same trait. use std::collections::HashMap; use crate::memory::TriMemory; #[derive(Default)] pub struct Bm25Index { df: HashMap, doc_len: HashMap, terms: HashMap>, // doc_id -> unique terms total_docs: usize, avgdl: f32, } const K1: f32 = 1.4; const B: f32 = 0.75; const TOP_K: usize = 3; fn tokenize(t: &str) -> Vec { t.to_lowercase() .split(|c: char| !c.is_alphanumeric()) .filter(|s| s.len() > 1) .map(|s| s.to_string()) .collect() } impl Bm25Index { /// Rebuild from current episodic diary (idempotent, cheap at serving scale). pub fn rebuild(memory: &TriMemory) -> Self { let mut ix = Bm25Index::default(); let mut total_len = 0usize; for e in &memory.episodic.entries { let toks = tokenize(&e.text); if toks.is_empty() { continue; } let mut uniq: Vec = Vec::new(); let mut seen = std::collections::HashSet::new(); for t in &toks { *ix.df.entry(t.clone()).or_insert(0) += 1; if seen.insert(t.clone()) { uniq.push(t.clone()); } } total_len += toks.len(); ix.doc_len.insert(e.id.clone(), toks.len()); ix.terms.insert(e.id.clone(), uniq); ix.total_docs += 1; } if ix.total_docs > 0 { ix.avgdl = total_len as f32 / ix.total_docs as f32; } ix } pub fn len(&self) -> usize { self.total_docs } /// Top-k episode ids matching the query. pub fn search(&self, query: &str) -> Vec<(String, f32)> { if self.total_docs == 0 { return Vec::new(); } let n = self.total_docs as f32; let mut scores: HashMap<&str, f32> = HashMap::new(); for q in tokenize(query) { let df = match self.df.get(&q) { Some(d) => *d as f32, None => continue, }; let idf = ((n - df + 0.5) / (df + 0.5)).max(1e-6).ln(); for (doc_id, terms) in &self.terms { let tf = terms.iter().filter(|t| **t == q).count() as f32; if tf == 0.0 { continue; } let dl = *self.doc_len.get(doc_id).unwrap_or(&1) as f32; let denom = tf + K1 * (1.0 - B + B * dl / self.avgdl.max(1.0)); *scores.entry(doc_id.as_str()).or_default() += idf * (tf * (K1 + 1.0)) / denom; } } let mut v: Vec<(String, f32)> = scores.into_iter().map(|(k, s)| (k.to_string(), s)).collect(); v.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); v.truncate(TOP_K); v } /// Retrieved context strings for prompt assembly / telemetry. pub fn recall_context(&self, memory: &TriMemory, query: &str) -> Vec { self.search(query) .into_iter() .filter_map(|(id, _)| { memory .episodic .entries .iter() .find(|e| e.id == id) .map(|e| e.text.clone()) }) .collect() } } #[cfg(test)] mod tests { use super::*; use crate::memory::Experience; #[test] fn bm25_finds_relevant_episode() { let mut m = TriMemory::new(16); let mut a = Experience::with_text(vec![], vec![], vec![], "rust borrow checker rules".to_string(), "t"); a.id = "a".into(); let mut b = Experience::with_text(vec![], vec![], vec![], "cake recipe sugar butter".to_string(), "t"); b.id = "b".into(); m.episodic.record(a); m.episodic.record(b); let ix = Bm25Index::rebuild(&m); assert_eq!(ix.len(), 2); let hits = ix.search("how does the borrow checker work"); assert_eq!(hits[0].0, "a", "relevant episode must rank first"); let ctx = ix.recall_context(&m, "borrow checker"); assert!(ctx[0].contains("borrow")); } }