From 4b5d290f1a03fec60ea084655bf45e40cdccb32e Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:48 +0100 Subject: [PATCH] capri-memory: add index module --- crates/capri-memory/src/index.rs | 714 +++++++++++++++++++++++++++++++ 1 file changed, 714 insertions(+) create mode 100644 crates/capri-memory/src/index.rs diff --git a/crates/capri-memory/src/index.rs b/crates/capri-memory/src/index.rs new file mode 100644 index 0000000..5001234 --- /dev/null +++ b/crates/capri-memory/src/index.rs @@ -0,0 +1,714 @@ +//! Memory index: Markdown memory files and conversation sessions, chunked, stored in +//! SQLite with FTS5 and embeddings, searched with OpenClaw's hybrid ranking. +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::LazyLock; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use parking_lot::Mutex; +use regex::Regex; +use rusqlite::{params, Connection, OpenFlags, OptionalExtension}; + +use crate::embed::{self, Embedder, EMBED_MODEL}; +use crate::{sha256_hex, truncate_utf16}; + +const CHUNK_CHARS: usize = 1600; +const OVERLAP_CHARS: usize = 320; +const CACHE_MAX: i64 = 50_000; +const SNIPPET_CHARS: usize = 700; +const MAX_FILE: u64 = 2 * 1024 * 1024; +const EMBED_BATCH: usize = 16; +const EMBED_RETRY: Duration = Duration::from_secs(60); +pub const DEFAULT_MAX_RESULTS: usize = 6; +pub const DEFAULT_MIN_SCORE: f64 = 0.35; +const VECTOR_WEIGHT: f64 = 0.7; +const TEXT_WEIGHT: f64 = 0.3; +const CANDIDATES: usize = 4; +const MMR_LAMBDA: f64 = 0.7; +const HALF_LIFE_DAYS: f64 = 30.0; + +/// Per-turn context the engine appends to the user text; never indexed. +const ENVELOPE_MARKERS: [&str; 4] = + ["\n\nDESKTOP STATE FOR THIS TURN", "\n\n[Read-only screen observation", "\n\n[Local Brain excerpts", "\n\nCURRENT WEB SEARCH"]; +static AVATAR: LazyLock = LazyLock::new(|| Regex::new(r"\[avatar:[^\]\n]*\][ \t]*\n?").expect("regex")); +static DATED: LazyLock = + LazyLock::new(|| Regex::new(r"(?:^|/)memory/(?:[^/]+/)*([0-9]{4})-([0-9]{2})-([0-9]{2})(?:-[^/]+)?\.md$").expect("regex")); +static WORD: LazyLock = LazyLock::new(|| Regex::new(r"[\p{L}\p{N}_][\p{L}\p{M}\p{N}_]*").expect("regex")); + +#[derive(Clone, Debug, PartialEq)] +pub struct Chunk { + pub start_line: usize, + pub end_line: usize, + pub text: String, +} + +/// ~400 tokens per chunk with ~80 tokens of overlap, on line boundaries. +pub fn chunk_markdown(content: &str) -> Vec { + let mut chunks = Vec::new(); + let mut current: Vec<(String, usize)> = Vec::new(); + let mut current_chars = 0; + let flush = |current: &[(String, usize)], chunks: &mut Vec| { + if let (Some(first), Some(last)) = (current.first(), current.last()) { + let text = current.iter().map(|(l, _)| l.as_str()).collect::>().join("\n"); + chunks.push(Chunk { start_line: first.1, end_line: last.1, text }); + } + }; + let append = |segment: String, line_no: usize, current: &mut Vec<(String, usize)>, current_chars: &mut usize, chunks: &mut Vec| { + let size = segment.chars().count() + 1; + if *current_chars + size > CHUNK_CHARS && !current.is_empty() { + flush(current, chunks); + let window = OVERLAP_CHARS.min(CHUNK_CHARS.saturating_sub(size)); + let mut kept: Vec<(String, usize)> = Vec::new(); + let mut acc = 0; + for (line, no) in current.iter().rev() { + let entry = line.chars().count() + 1; + if window == 0 { + break; + } + if entry > window - acc { + if kept.is_empty() { + let take = (window - acc).saturating_sub(1); + let tail: String = line.chars().skip(line.chars().count() - take.min(line.chars().count())).collect(); + if !tail.is_empty() { + acc += tail.chars().count() + 1; + kept.insert(0, (tail, *no)); + } + } + break; + } + acc += entry; + kept.insert(0, (line.clone(), *no)); + if acc >= window { + break; + } + } + *current = kept; + *current_chars = acc; + } + current.push((segment, line_no)); + *current_chars += size; + }; + for (i, line) in content.split('\n').enumerate() { + let chars: Vec = line.chars().collect(); + if chars.is_empty() { + append(String::new(), i + 1, &mut current, &mut current_chars, &mut chunks); + } + for piece in chars.chunks(CHUNK_CHARS) { + append(piece.iter().collect(), i + 1, &mut current, &mut current_chars, &mut chunks); + } + } + flush(¤t, &mut chunks); + chunks +} + +/// User or assistant text of a session entry without the per-turn envelope and avatar markers. +pub fn session_text(content: &str) -> String { + let end = ENVELOPE_MARKERS.iter().filter_map(|m| content.find(m)).min().unwrap_or(content.len()); + AVATAR.replace_all(&content[..end], "").trim().to_string() +} + +pub fn bm25_rank_to_score(rank: f64) -> f64 { + if !rank.is_finite() { + 0.001 + } else if rank < 0.0 { + -rank / (1.0 - rank) + } else { + 1.0 / (1.0 + rank) + } +} + +fn fts_query(raw: &str) -> Option { + let mut seen = HashSet::new(); + let terms: Vec = + WORD.find_iter(raw).map(|m| m.as_str().to_string()).filter(|t| seen.insert(t.clone())).map(|t| format!("\"{}\"", t.replace('"', ""))).collect(); + (!terms.is_empty()).then(|| terms.join(" AND ")) +} + +fn tokens(text: &str) -> HashSet { + WORD.find_iter(&text.to_lowercase()).map(|m| m.as_str().to_string()).collect() +} + +fn jaccard(a: &HashSet, b: &HashSet) -> f64 { + if a.is_empty() && b.is_empty() { + return 1.0; + } + let inter = a.intersection(b).count(); + inter as f64 / (a.len() + b.len() - inter) as f64 +} + +#[derive(Clone, Debug)] +pub struct Hit { + pub path: String, + pub source: String, + pub start_line: usize, + pub end_line: usize, + pub score: f64, + pub snippet: String, +} + +#[derive(Clone, Debug)] +struct Candidate { + hit: Hit, + vector: f64, + text: f64, + mtime: i64, +} + +/// Maximal marginal relevance over snippet tokens; reorders without changing scores. +fn mmr(items: Vec, lambda: f64) -> Vec { + if items.len() < 2 { + return items; + } + let max = items.iter().map(|h| h.score).fold(f64::MIN, f64::max); + let min = items.iter().map(|h| h.score).fold(f64::MAX, f64::min); + let mut remaining: Vec<(Hit, HashSet, f64, f64)> = items + .into_iter() + .map(|h| { + let relevance = if max == min { 1.0 } else { (h.score - min) / (max - min) }; + let t = tokens(&h.snippet); + (h, t, relevance, 0.0) + }) + .collect(); + let mut selected = Vec::new(); + while !remaining.is_empty() { + let mut best = 0; + let mut best_score = f64::NEG_INFINITY; + for (i, (h, _, relevance, similarity)) in remaining.iter().enumerate() { + let s = lambda * relevance - (1.0 - lambda) * similarity; + if s > best_score || (s == best_score && h.score > remaining[best].0.score) { + best = i; + best_score = s; + } + } + let (hit, best_tokens, _, _) = remaining.remove(best); + for candidate in remaining.iter_mut() { + let sim = if candidate.1.is_empty() && best_tokens.is_empty() { + f64::from(candidate.0.snippet.to_lowercase() == hit.snippet.to_lowercase()) + } else { + jaccard(&candidate.1, &best_tokens) + }; + candidate.3 = candidate.3.max(sim); + } + selected.push(hit); + } + selected +} + +fn timestamp_ms(c: &Candidate) -> Option { + if c.hit.source == "sessions" { + return (c.mtime > 0).then_some(c.mtime); + } + let m = DATED.captures(&c.hit.path)?; + let date = chrono::NaiveDate::from_ymd_opt(m[1].parse().ok()?, m[2].parse().ok()?, m[3].parse().ok()?)?; + Some(date.and_hms_opt(0, 0, 0)?.and_utc().timestamp_millis()) +} + +/// Hybrid ranking: 0.7 vector + 0.3 BM25 (keyword-only: BM25 alone), temporal decay, MMR, min score. +fn rank(candidates: Vec, keyword_only: bool, now_ms: i64, max_results: usize, min_score: f64) -> Vec { + let mut hits: Vec = candidates + .into_iter() + .map(|c| { + let mut score = if keyword_only { c.text } else { VECTOR_WEIGHT * c.vector + TEXT_WEIGHT * c.text }; + if let Some(ts) = timestamp_ms(&c) { + let age_days = ((now_ms - ts) as f64 / 86_400_000.0).max(0.0); + score *= (-(std::f64::consts::LN_2 / HALF_LIFE_DAYS) * age_days).exp(); + } + Hit { score, ..c.hit } + }) + .collect(); + hits.sort_by(|a, b| b.score.total_cmp(&a.score).then_with(|| a.path.cmp(&b.path)).then(a.start_line.cmp(&b.start_line))); + mmr(hits, MMR_LAMBDA).into_iter().filter(|h| h.score >= min_score).take(max_results).collect() +} + +#[derive(Clone, Debug, Default)] +pub struct SearchOutcome { + pub hits: Vec, + pub keyword_only: bool, + pub warning: Option, +} + +#[derive(Default)] +struct State { + dirty: bool, + embed_pending: bool, + fingerprint: String, + embed_error: Option, + embed_attempt: Option, +} + +pub struct MemoryIndex { + db: Mutex, + workspace: PathBuf, + session_db: PathBuf, + sync_lock: tokio::sync::Mutex<()>, + state: Mutex, +} + +struct Source { + path: String, + source: &'static str, + hash: String, + mtime: i64, +} + +impl MemoryIndex { + pub fn open(file: &Path, workspace: PathBuf, session_db: PathBuf) -> Result { + let db = Connection::open(file)?; + db.execute_batch( + "PRAGMA journal_mode=WAL; + CREATE TABLE IF NOT EXISTS files(path TEXT PRIMARY KEY, source TEXT NOT NULL, hash TEXT NOT NULL, mtime INTEGER NOT NULL); + CREATE TABLE IF NOT EXISTS chunks(id INTEGER PRIMARY KEY, path TEXT NOT NULL, source TEXT NOT NULL, + start_line INTEGER NOT NULL, end_line INTEGER NOT NULL, hash TEXT NOT NULL, text TEXT NOT NULL, embedding BLOB); + CREATE INDEX IF NOT EXISTS chunks_path ON chunks(path); + CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(text, tokenize='unicode61'); + CREATE TABLE IF NOT EXISTS embedding_cache(model TEXT NOT NULL, hash TEXT NOT NULL, embedding BLOB NOT NULL, + used_at INTEGER NOT NULL, PRIMARY KEY(model, hash));", + )?; + Ok(Self { db: Mutex::new(db), workspace, session_db, sync_lock: Default::default(), state: Mutex::new(State { dirty: true, ..Default::default() }) }) + } + + pub fn mark_dirty(&self) { + self.state.lock().dirty = true; + } + + /// Marked dirty or memory files changed: the text index is stale. + pub fn needs_reindex(&self) -> bool { + let fingerprint = self.fingerprint(); + let state = self.state.lock(); + state.dirty || state.fingerprint != fingerprint + } + + /// Background sync is due: stale text index, or chunks still waiting for embeddings (retried + /// at most once a minute after a failure). + pub fn needs_sync(&self) -> bool { + if self.needs_reindex() { + return true; + } + let state = self.state.lock(); + (state.embed_pending || state.embed_error.is_some()) && state.embed_attempt.is_none_or(|t| t.elapsed() >= EMBED_RETRY) + } + + /// Cheap stat-only fingerprint of the Markdown memory files. + pub fn fingerprint(&self) -> String { + let mut parts: Vec = self.memory_files().iter().map(|(rel, p)| { + let m = std::fs::symlink_metadata(p).ok(); + format!("{rel}:{}:{}", m.as_ref().map_or(0, |m| m.len()), m.and_then(|m| m.modified().ok()).map_or(0, |t| t.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()))) + }).collect(); + parts.sort(); + parts.join("|") + } + + /// `MEMORY.md`, `USER.md` and `memory/**/*.md` (regular files only, links skipped). + fn memory_files(&self) -> Vec<(String, PathBuf)> { + let mut out = Vec::new(); + for name in ["MEMORY.md", "USER.md"] { + let p = self.workspace.join(name); + if std::fs::symlink_metadata(&p).is_ok_and(|m| m.is_file()) { + out.push((name.to_string(), p)); + } + } + fn walk(dir: &Path, rel: &str, depth: usize, out: &mut Vec<(String, PathBuf)>) { + let Ok(list) = std::fs::read_dir(dir) else { return }; + for entry in list.flatten() { + let Ok(kind) = entry.file_type() else { continue }; + let name = entry.file_name().to_string_lossy().into_owned(); + let rel = format!("{rel}/{name}"); + if kind.is_dir() && depth < 16 { + walk(&entry.path(), &rel, depth + 1, out); + } else if kind.is_file() && name.ends_with(".md") { + out.push((rel, entry.path())); + } + } + } + if std::fs::symlink_metadata(self.workspace.join("memory")).is_ok_and(|m| m.is_dir()) { + walk(&self.workspace.join("memory"), "memory", 0, &mut out); + } + out + } + + /// Clears the derived index and embedding cache. + pub fn reset(&self) -> Result<()> { + self.db.lock().execute_batch("DELETE FROM chunks; DELETE FROM chunks_fts; DELETE FROM files; DELETE FROM embedding_cache;")?; + self.mark_dirty(); + Ok(()) + } + + fn replace(&self, db: &mut Connection, src: &Source, text: &str) -> Result<()> { + let tx = db.transaction()?; + tx.execute("DELETE FROM chunks_fts WHERE rowid IN (SELECT id FROM chunks WHERE path=?1)", [&src.path])?; + tx.execute("DELETE FROM chunks WHERE path=?1", [&src.path])?; + for chunk in chunk_markdown(text) { + if chunk.text.trim().is_empty() { + continue; + } + let hash = sha256_hex(chunk.text.as_bytes()); + let cached: Option> = + tx.query_row("SELECT embedding FROM embedding_cache WHERE model=?1 AND hash=?2", params![EMBED_MODEL, hash], |r| r.get(0)).optional()?; + tx.execute( + "INSERT INTO chunks(path, source, start_line, end_line, hash, text, embedding) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![src.path, src.source, chunk.start_line as i64, chunk.end_line as i64, hash, chunk.text, cached], + )?; + tx.execute("INSERT INTO chunks_fts(rowid, text) VALUES (?1, ?2)", params![tx.last_insert_rowid(), chunk.text])?; + } + tx.execute("INSERT OR REPLACE INTO files(path, source, hash, mtime) VALUES (?1, ?2, ?3, ?4)", params![src.path, src.source, src.hash, src.mtime])?; + tx.commit()?; + Ok(()) + } + + fn remove_missing(&self, db: &Connection, source: &str, keep: &HashSet) -> Result<()> { + let paths: Vec = + db.prepare("SELECT path FROM files WHERE source=?1")?.query_map([source], |r| r.get(0))?.collect::>()?; + for path in paths.iter().filter(|p| !keep.contains(*p)) { + db.execute("DELETE FROM chunks_fts WHERE rowid IN (SELECT id FROM chunks WHERE path=?1)", [path])?; + db.execute("DELETE FROM chunks WHERE path=?1", [path])?; + db.execute("DELETE FROM files WHERE path=?1", [path])?; + } + Ok(()) + } + + fn sync_files(&self, db: &mut Connection) -> Result<()> { + let mut keep = HashSet::new(); + for (rel, path) in self.memory_files() { + let Ok(Some(bytes)) = capri_core::fsutil::read_regular(&path, MAX_FILE) else { continue }; + let hash = sha256_hex(&bytes); + keep.insert(rel.clone()); + let known: Option = db.query_row("SELECT hash FROM files WHERE path=?1", [&rel], |r| r.get(0)).optional()?; + if known.as_deref() != Some(hash.as_str()) { + let src = Source { path: rel, source: "memory", hash, mtime: 0 }; + self.replace(db, &src, &String::from_utf8_lossy(&bytes))?; + } + } + self.remove_missing(db, "memory", &keep) + } + + /// Indexes user/assistant text of current and archived sessions of capri-agent's `session.sqlite`. + fn sync_sessions(&self, db: &mut Connection, enabled: bool) -> Result<()> { + let mut keep = HashSet::new(); + if enabled && self.session_db.exists() { + let sessions = Connection::open_with_flags(&self.session_db, OpenFlags::SQLITE_OPEN_READ_ONLY)?; + let list: Vec<(String, i64, String)> = sessions + .prepare("SELECT session_id, MAX(seq), MAX(created_at) FROM entries WHERE kind IN ('user','assistant') GROUP BY session_id")? + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))? + .collect::>()?; + for (id, seq, created) in list { + let path = format!("sessions/{id}"); + keep.insert(path.clone()); + let hash = format!("seq:{seq}"); + let known: Option = db.query_row("SELECT hash FROM files WHERE path=?1", [&path], |r| r.get(0)).optional()?; + if known.as_deref() == Some(hash.as_str()) { + continue; + } + let mut text = String::new(); + let mut stmt = sessions.prepare("SELECT kind, body FROM entries WHERE session_id=?1 AND kind IN ('user','assistant') ORDER BY seq")?; + let mut rows = stmt.query([&id])?; + while let Some(row) = rows.next()? { + let kind: String = row.get(0)?; + let body: String = row.get(1)?; + let Ok(message) = serde_json::from_str::(&body) else { continue }; + let content = session_text(&message.content); + if !content.is_empty() { + text.push_str(if kind == "user" { "User: " } else { "Assistant: " }); + text.push_str(&content); + text.push('\n'); + } + } + let mtime = chrono::DateTime::parse_from_rfc3339(&created).map_or(0, |d| d.timestamp_millis()); + self.replace(db, &Source { path, source: "sessions", hash, mtime }, &text)?; + } + } + self.remove_missing(db, "sessions", &keep) + } + + /// Brings the index up to date; `embed` also computes missing embeddings (slow on CPU, so the + /// search path leaves them to the background loop). Never fails because embeddings are unavailable. + pub async fn sync(&self, base_url: &str, sessions: bool, embed: bool) -> Result<()> { + let _guard = self.sync_lock.lock().await; + let fingerprint = self.fingerprint(); + self.state.lock().dirty = false; + { + let mut db = self.db.lock(); + self.sync_files(&mut db)?; + if let Err(e) = self.sync_sessions(&mut db, sessions) { + tracing::warn!("memory: session indexing failed: {e:#}"); + } + } + { + let mut state = self.state.lock(); + state.fingerprint = fingerprint; + state.embed_pending = !embed; + } + if embed && let Err(e) = self.embed_missing(&Embedder::new(base_url)).await { + tracing::warn!("memory: embeddings unavailable: {e:#}"); + let mut state = self.state.lock(); + state.embed_error = Some(format!("{e:#}")); + state.embed_attempt = Some(Instant::now()); + } + let db = self.db.lock(); + db.execute( + "DELETE FROM embedding_cache WHERE rowid IN (SELECT rowid FROM embedding_cache ORDER BY used_at ASC + LIMIT MAX(0, (SELECT COUNT(*) FROM embedding_cache) - ?1))", + [CACHE_MAX], + )?; + Ok(()) + } + + async fn embed_missing(&self, embedder: &Embedder) -> Result<()> { + let missing: Vec<(i64, String, String)> = { + let db = self.db.lock(); + db.prepare("SELECT id, hash, text FROM chunks WHERE embedding IS NULL")? + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))? + .collect::>()? + }; + if missing.is_empty() { + return Ok(()); + } + embedder.ensure_model().await?; + for batch in missing.chunks(EMBED_BATCH) { + let input: Vec = batch.iter().map(|(_, _, t)| t.clone()).collect(); + let vectors = embedder.embed(&input).await?; + let mut db = self.db.lock(); + let tx = db.transaction()?; + let now = chrono::Utc::now().timestamp_millis(); + for ((id, hash, _), v) in batch.iter().zip(vectors) { + let blob = embed::to_blob(&v); + tx.execute("UPDATE chunks SET embedding=?1 WHERE id=?2", params![blob, id])?; + tx.execute("INSERT OR REPLACE INTO embedding_cache(model, hash, embedding, used_at) VALUES (?1, ?2, ?3, ?4)", params![EMBED_MODEL, hash, blob, now])?; + } + tx.commit()?; + } + let mut state = self.state.lock(); + state.embed_error = None; + Ok(()) + } + + fn keyword(&self, query: &str, source: Option<&str>, limit: usize) -> Result> { + let Some(matcher) = fts_query(query) else { return Ok(vec![]) }; + let db = self.db.lock(); + let mut stmt = db.prepare( + "SELECT c.path, c.source, c.start_line, c.end_line, c.text, f.mtime, bm25(chunks_fts) FROM chunks_fts + JOIN chunks c ON c.id = chunks_fts.rowid JOIN files f ON f.path = c.path + WHERE chunks_fts MATCH ?1 AND (?2 IS NULL OR c.source = ?2) ORDER BY bm25(chunks_fts) LIMIT ?3", + )?; + let rows = stmt.query_map(params![matcher, source, limit as i64], |r| { + Ok(Candidate { hit: hit_from(r)?, vector: 0.0, text: bm25_rank_to_score(r.get(6)?), mtime: r.get(5)? }) + })?; + Ok(rows.collect::>()?) + } + + // TODO: brute-force cosine over every stored vector. Fine for a few thousand chunks; switch to + // sqlite-vec or an ANN index if search gets slower than ~100 ms. + fn vector(&self, query: &[f32], source: Option<&str>, limit: usize) -> Result> { + let db = self.db.lock(); + let mut stmt = db.prepare( + "SELECT c.path, c.source, c.start_line, c.end_line, c.text, f.mtime, c.embedding FROM chunks c JOIN files f ON f.path = c.path + WHERE c.embedding IS NOT NULL AND (?1 IS NULL OR c.source = ?1)", + )?; + let mut all: Vec = stmt + .query_map(params![source], |r| { + let v = embed::from_blob(&r.get::<_, Vec>(6)?); + Ok(Candidate { hit: hit_from(r)?, vector: f64::from(embed::dot(query, &v)), text: 0.0, mtime: r.get(5)? }) + })? + .collect::>()?; + all.sort_by(|a, b| b.vector.total_cmp(&a.vector)); + all.truncate(limit); + Ok(all) + } + + fn has_vectors(&self) -> bool { + self.db.lock().query_row("SELECT EXISTS(SELECT 1 FROM chunks WHERE embedding IS NOT NULL)", [], |r| r.get(0)).unwrap_or(false) + } + + /// Hybrid search. `source` restricts to `memory` or `sessions`. + pub async fn search(&self, base_url: &str, sessions: bool, query: &str, source: Option<&str>, max_results: usize, min_score: f64) -> Result { + if self.needs_reindex() { + self.sync(base_url, sessions, false).await?; + } + let pool = max_results.max(1) * CANDIDATES; + let embedded = if self.has_vectors() { + Embedder::new(base_url).embed(&[query.to_string()]).await.map(|mut v| v.remove(0)) + } else { + Err(anyhow::anyhow!(self.state.lock().embed_error.clone().unwrap_or_else(|| "no embeddings indexed".into()))) + }; + let mut by_key: HashMap<(String, usize), Candidate> = HashMap::new(); + let mut outcome = SearchOutcome::default(); + match embedded { + Ok(q) => { + for c in self.vector(&q, source, pool)? { + by_key.insert((c.hit.path.clone(), c.hit.start_line), c); + } + } + Err(e) => { + outcome.keyword_only = true; + outcome.warning = Some(format!("memory search: embeddings unavailable; using keyword-only results: {e:#}")); + } + } + for c in self.keyword(query, source, pool)? { + by_key.entry((c.hit.path.clone(), c.hit.start_line)).and_modify(|e| e.text = c.text).or_insert(c); + } + outcome.hits = rank(by_key.into_values().collect(), outcome.keyword_only, chrono::Utc::now().timestamp_millis(), max_results, min_score); + Ok(outcome) + } +} + +fn hit_from(r: &rusqlite::Row) -> rusqlite::Result { + let text: String = r.get(4)?; + Ok(Hit { + path: r.get(0)?, + source: r.get(1)?, + start_line: r.get::<_, i64>(2)? as usize, + end_line: r.get::<_, i64>(3)? as usize, + score: 0.0, + snippet: truncate_utf16(&text, SNIPPET_CHARS).to_string(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, Request, ResponseTemplate}; + + #[test] + fn chunks_follow_lines_with_overlap() { + let lines: Vec = (1..=100).map(|i| format!("line {i:03} {}", "x".repeat(40))).collect(); + let chunks = chunk_markdown(&lines.join("\n")); + assert!(chunks.len() > 2); + assert_eq!(chunks[0].start_line, 1); + assert!(chunks.iter().all(|c| c.text.chars().count() <= CHUNK_CHARS)); + assert!(chunks[1].start_line <= chunks[0].end_line, "consecutive chunks overlap"); + let overlap = chunks[0].end_line - chunks[1].start_line + 1; + assert!(overlap * 49 <= OVERLAP_CHARS + 49, "{overlap}"); + assert_eq!(chunks.last().unwrap().end_line, 100); + let long = chunk_markdown(&"y".repeat(4000)); + assert!(long.len() >= 3 && long.iter().all(|c| c.start_line == 1)); + } + + #[test] + fn envelope_and_avatar_are_stripped() { + assert_eq!(session_text("hello\n\nDESKTOP STATE FOR THIS TURN (data):\n{}"), "hello"); + assert_eq!(session_text("[avatar:happy;listen]\nHi there\n\n[Local Brain excerpts x]"), "Hi there"); + } + + #[test] + fn bm25_mapping() { + assert_eq!(bm25_rank_to_score(-1.0), 0.5); + assert_eq!(bm25_rank_to_score(1.0), 0.5); + assert_eq!(bm25_rank_to_score(f64::NAN), 0.001); + assert_eq!(fts_query("hi \"x\" hi"), Some("\"hi\" AND \"x\"".into())); + } + + fn cand(path: &str, source: &str, snippet: &str, vector: f64, text: f64, mtime: i64) -> Candidate { + Candidate { hit: Hit { path: path.into(), source: source.into(), start_line: 1, end_line: 1, score: 0.0, snippet: snippet.into() }, vector, text, mtime } + } + + #[test] + fn ranking_weights_decay_mmr_and_threshold() { + let now = chrono::NaiveDate::from_ymd_opt(2026, 3, 31).unwrap().and_hms_opt(0, 0, 0).unwrap().and_utc().timestamp_millis(); + let hits = rank( + vec![ + cand("MEMORY.md", "memory", "alpha beta", 0.75, 0.0, 0), + cand("memory/2026-03-01.md", "memory", "gamma delta", 1.0, 0.0, 0), + cand("USER.md", "memory", "alpha beta", 0.9, 0.5, 0), + cand("memory/x.md", "memory", "weak", 0.4, 0.0, 0), + ], + false, + now, + 6, + 0.3, + ); + let paths: Vec<_> = hits.iter().map(|h| h.path.as_str()).collect(); + // MEMORY.md (0.525) repeats USER.md (0.78), so MMR ranks the decayed dated note (0.35) before it. + assert_eq!(paths, ["USER.md", "memory/2026-03-01.md", "MEMORY.md"]); + assert!((hits[0].score - 0.78).abs() < 1e-9); + assert!((hits[1].score - 0.35).abs() < 1e-9, "30 days halve 0.7"); + let keyword = rank(vec![cand("MEMORY.md", "memory", "a", 0.0, 0.5, 0)], true, now, 6, 0.35); + assert_eq!(keyword.len(), 1); + } + + async fn ollama(dims_by_word: bool) -> MockServer { + let server = MockServer::start().await; + Mock::given(method("GET")).and(path("/api/tags")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": [{"name": EMBED_MODEL}]}))).mount(&server).await; + Mock::given(method("POST")).and(path("/api/embed")) + .respond_with(move |req: &Request| { + let body: serde_json::Value = serde_json::from_slice(&req.body).unwrap(); + let embeddings: Vec> = body["input"].as_array().unwrap().iter().map(|t| { + let t = t.as_str().unwrap().to_lowercase(); + if dims_by_word { vec![f32::from(u8::from(t.contains("tea"))), f32::from(u8::from(t.contains("car"))), 0.1] } else { vec![1.0, 0.0, 0.0] } + }).collect(); + ResponseTemplate::new(200).set_body_json(json!({"embeddings": embeddings})) + }) + .mount(&server).await; + server + } + + fn fixture() -> (tempfile::TempDir, MemoryIndex) { + let dir = tempfile::tempdir().unwrap(); + let ws = dir.path().join("ws"); + std::fs::create_dir_all(ws.join("memory")).unwrap(); + std::fs::write(ws.join("MEMORY.md"), "# Memory\n\nThe owner drinks green tea every morning.\n").unwrap(); + std::fs::write(ws.join("memory/cars.md"), "The owner drives a red car.\n").unwrap(); + let index = MemoryIndex::open(&dir.path().join("memory.sqlite"), ws, dir.path().join("session.sqlite")).unwrap(); + (dir, index) + } + + #[tokio::test] + async fn hybrid_search_and_resync_on_change() { + let server = ollama(true).await; + let (dir, index) = fixture(); + index.sync(&server.uri(), true, true).await.unwrap(); + assert!(!index.needs_sync()); + let out = index.search(&server.uri(), true, "tea", None, 6, 0.35).await.unwrap(); + assert!(!out.keyword_only, "{:?}", out.warning); + assert_eq!(out.hits[0].path, "MEMORY.md"); + assert_eq!((out.hits[0].start_line, out.hits[0].end_line), (1, 4)); + assert!(out.hits.iter().all(|h| h.path != "memory/cars.md")); + std::fs::remove_file(dir.path().join("ws/memory/cars.md")).unwrap(); + assert!(index.needs_sync()); + let out = index.search(&server.uri(), true, "car", None, 6, 0.0).await.unwrap(); + assert!(out.hits.iter().all(|h| h.path != "memory/cars.md")); + let cached: i64 = index.db.lock().query_row("SELECT COUNT(*) FROM embedding_cache", [], |r| r.get(0)).unwrap(); + assert!(cached >= 2); + index.reset().unwrap(); + assert!(index.needs_sync()); + } + + #[tokio::test] + async fn keyword_only_when_ollama_is_down() { + let (_dir, index) = fixture(); + index.sync("http://127.0.0.1:9", true, true).await.unwrap(); + assert!(!index.needs_sync(), "failed embeddings are retried after a delay"); + // BM25 idf is near zero in a two-file corpus, so the default 0.35 threshold would hide it. + let out = index.search("http://127.0.0.1:9", true, "green tea", None, 6, 0.0).await.unwrap(); + assert!(out.keyword_only); + assert!(out.warning.unwrap().contains("keyword-only")); + assert_eq!(out.hits.len(), 1); + assert_eq!(out.hits[0].path, "MEMORY.md"); + } + + #[tokio::test] + async fn sessions_are_indexed_without_envelope() { + let server = ollama(false).await; + let (dir, index) = fixture(); + let file = dir.path().join("session.sqlite"); + { + let mut s = capri_agent::session::Session::open(&file, "agent:capri:main").unwrap(); + s.append(Some("t"), &[ + ("user", capri_llm::Message::new("user", "I bought a violin\n\nDESKTOP STATE FOR THIS TURN (data, not a user request):\n{\"secretish\":1}")), + ("assistant", capri_llm::Message::new("assistant", "[avatar:happy]\nA violin, lovely!")), + ]).unwrap(); + s.reset().unwrap(); + } + index.sync(&server.uri(), true, true).await.unwrap(); + let out = index.search(&server.uri(), true, "violin", Some("sessions"), 6, 0.0).await.unwrap(); + assert_eq!(out.hits.len(), 1); + assert!(out.hits[0].path.starts_with("sessions/")); + assert_eq!(out.hits[0].snippet, "User: I bought a violin\nAssistant: A violin, lovely!\n"); + let leaked: i64 = index.db.lock().query_row("SELECT COUNT(*) FROM chunks WHERE text LIKE '%secretish%' OR text LIKE '%avatar%'", [], |r| r.get(0)).unwrap(); + assert_eq!(leaked, 0); + index.mark_dirty(); + assert!(index.search(&server.uri(), false, "violin", Some("sessions"), 6, 0.0).await.unwrap().hits.is_empty(), "disabled sessions are dropped"); + } +}