//! The SQLite layer: three files beside the JSON ones, each with its own connection, so a slow //! write in one (the document sweep embedding thousands of chunks) never holds up another (a //! memory search while the person types). //! //! - `memory.db` (data folder): every memory of every bot — the one to back up (memstore.rs; //! the nightly tidy keeps a week of copies in `backups/`). //! - `docs.db` (data folder): the index of the person's document folders. A cache: delete it //! and the sweep builds it again. //! - `oplog/audit.db`: the audit trail — what each turn did, kept KEEP_DAYS. //! //! `state.json` stays the app's truth for everything else (one struct, written atomically). What //! JSON files cannot do is *ask questions*: "what has this bot done in the last week?", "which of //! 500 memories answer this?". Every write here is best-effort: a database that can't be opened //! means less history or plainer search, never "no bot". //! //! Before the split, memories and documents lived in audit.db: the first start moves them over //! (`split_audit`) and drops them there. use crate::oplog::{Outcome, Record}; use rusqlite::{params, Connection}; use std::path::PathBuf; use std::sync::{Mutex, OnceLock}; /// How far back the timeline answers. Rows older than this are deleted on open. const KEEP_DAYS: i64 = 30; pub struct Store { conn: Mutex, } static AUDIT: OnceLock> = OnceLock::new(); static MEMORY: OnceLock> = OnceLock::new(); static DOCS: OnceLock> = OnceLock::new(); static SPLIT: std::sync::Once = std::sync::Once::new(); fn audit_path() -> PathBuf { crate::oplog::dir().join("audit.db") } /// The data folder (tests: their own temporary one). fn data_dir() -> PathBuf { if cfg!(test) { return crate::oplog::dir(); } crate::model::State::path().parent().map(PathBuf::from).unwrap_or_else(std::env::temp_dir) } pub fn memory_path() -> PathBuf { data_dir().join("memory.db") } pub fn docs_path() -> PathBuf { data_dir().join("docs.db") } fn connect(p: &std::path::Path) -> Option { if let Some(d) = p.parent() { let _ = std::fs::create_dir_all(d); // (the data folder may not exist yet on first run) } let c = Connection::open(p).ok()?; c.pragma_update(None, "journal_mode", "WAL").ok()?; c.pragma_update(None, "synchronous", "NORMAL").ok()?; let _ = c.busy_timeout(std::time::Duration::from_secs(5)); Some(c) } fn audit_schema(c: &Connection) -> Option<()> { c.execute_batch( "CREATE TABLE IF NOT EXISTS audit( id INTEGER PRIMARY KEY, bot INTEGER NOT NULL, op TEXT NOT NULL, at INTEGER NOT NULL, end_at INTEGER, kind TEXT NOT NULL, name TEXT, detail TEXT, status TEXT, call_id TEXT ); CREATE INDEX IF NOT EXISTS audit_bot_at ON audit(bot, at DESC); CREATE INDEX IF NOT EXISTS audit_call ON audit(bot, op, call_id);", ) .ok() } fn memory_schema(c: &Connection) -> Option<()> { c.execute_batch( "CREATE TABLE IF NOT EXISTS memories( id INTEGER PRIMARY KEY, bot INTEGER NOT NULL, text TEXT NOT NULL, kind TEXT NOT NULL DEFAULT 'fact', created INTEGER NOT NULL, vec BLOB, UNIQUE(bot, text) ); CREATE INDEX IF NOT EXISTS memories_bot ON memories(bot, created DESC); CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(text, content='memories', content_rowid='id', tokenize='trigram'); CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN INSERT INTO memories_fts(rowid, text) VALUES (new.id, new.text); END; CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN INSERT INTO memories_fts(memories_fts, rowid, text) VALUES ('delete', old.id, old.text); END;", ) .ok()?; crate::memstore::migrate(c); Some(()) } fn docs_schema(c: &Connection) -> Option<()> { c.execute_batch( "CREATE TABLE IF NOT EXISTS docs( path TEXT NOT NULL, mtime INTEGER NOT NULL, idx INTEGER NOT NULL, text TEXT NOT NULL, vec BLOB, PRIMARY KEY(path, idx) ); CREATE VIRTUAL TABLE IF NOT EXISTS docs_fts USING fts5(text, content='docs', content_rowid='rowid', tokenize='trigram'); CREATE TRIGGER IF NOT EXISTS docs_ai AFTER INSERT ON docs BEGIN INSERT INTO docs_fts(rowid, text) VALUES (new.rowid, new.text); END; CREATE TRIGGER IF NOT EXISTS docs_ad AFTER DELETE ON docs BEGIN INSERT INTO docs_fts(docs_fts, rowid, text) VALUES ('delete', old.rowid, old.text); END; CREATE TRIGGER IF NOT EXISTS docs_au AFTER UPDATE ON docs BEGIN INSERT INTO docs_fts(docs_fts, rowid, text) VALUES ('delete', old.rowid, old.text); INSERT INTO docs_fts(rowid, text) VALUES (new.rowid, new.text); END; CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);", ) .ok() } /// Once: memories and documents that an older version kept in audit.db move to their own files. fn split_audit() { SPLIT.call_once(|| split_files(&audit_path(), &memory_path(), &docs_path())); } /// The move itself (by ATTACH, one transaction per table), then the tables leave the old file, /// which is compacted. A copy that fails leaves the old table where it was (tried next start). fn split_files(old: &std::path::Path, mem_to: &std::path::Path, docs_to: &std::path::Path) { if !old.is_file() { return; } let Some(a) = connect(old) else { return }; let has = |t: &str| a.query_row("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?1", params![t], |r| r.get::<_, i64>(0)).map(|n| n > 0).unwrap_or(false); let (mem, docs) = (has("memories"), has("docs")); if !mem && !docs { return; } let path = old.display().to_string(); let moved = |target: &std::path::Path, schema: fn(&Connection) -> Option<()>, is_mem: bool, copy: &str| -> bool { let Some(c) = connect(target) else { return false }; if schema(&c).is_none() || c.execute("ATTACH DATABASE ?1 AS old", params![path]).is_err() { return false; } let ok = c.execute_batch(&format!("BEGIN; {copy} COMMIT;")).is_ok(); if !ok { let _ = c.execute_batch("ROLLBACK;"); } let _ = c.execute_batch("DETACH DATABASE old;"); if ok && is_mem { // The word index for what just arrived. crate::memstore::migrate(&c); } ok }; if mem { let cols: Vec = a.prepare("SELECT name FROM pragma_table_info('memories')").and_then(|mut st| st.query_map([], |r| r.get::<_, String>(0))?.collect()).unwrap_or_default(); let vec = if cols.iter().any(|c| c == "vec") { "vec" } else { "NULL" }; let copy = format!("INSERT OR IGNORE INTO memories(id,bot,text,kind,created,vec) SELECT id,bot,text,kind,created,{vec} FROM old.memories;"); if moved(mem_to, memory_schema, true, ©) { let _ = a.execute_batch("DROP TRIGGER IF EXISTS memories_ai; DROP TRIGGER IF EXISTS memories_ad; DROP TABLE IF EXISTS memories_fts; DROP TABLE IF EXISTS memories;"); } } if docs { let copy = "INSERT OR IGNORE INTO docs(path,mtime,idx,text,vec) SELECT path,mtime,idx,text,vec FROM old.docs;"; if moved(docs_to, docs_schema, false, copy) { let _ = a.execute_batch("DROP TRIGGER IF EXISTS docs_ai; DROP TRIGGER IF EXISTS docs_ad; DROP TRIGGER IF EXISTS docs_au; DROP TABLE IF EXISTS docs_fts; DROP TABLE IF EXISTS docs;"); } } // Give the space back (documents were most of the file). let _ = a.execute_batch("VACUUM;"); } fn open_audit() -> Option { split_audit(); let c = connect(&audit_path())?; audit_schema(&c)?; let cutoff = crate::model::now_ms() - KEEP_DAYS * 86_400_000; let _ = c.execute("DELETE FROM audit WHERE at < ?1", params![cutoff]); Some(Store { conn: Mutex::new(c) }) } fn open_memory() -> Option { split_audit(); let c = connect(&memory_path())?; memory_schema(&c)?; Some(Store { conn: Mutex::new(c) }) } fn open_docs() -> Option { split_audit(); let c = connect(&docs_path())?; docs_schema(&c)?; Some(Store { conn: Mutex::new(c) }) } fn store() -> Option<&'static Store> { AUDIT.get_or_init(open_audit).as_ref() } fn docs() -> Option<&'static Store> { DOCS.get_or_init(open_docs).as_ref() } /// memory.db, for the memory shelf (memstore.rs). None: no database (still a working app). pub(crate) fn with_conn(f: impl FnOnce(&Connection) -> T) -> Option { let s = MEMORY.get_or_init(open_memory).as_ref()?; let c = s.conn.lock().ok()?; Some(f(&c)) } /// The engine that makes vectors is `id` now: vectors another engine made (other dimensions, /// other meanings) are cleared, in each file, and made again by the background thread. pub fn ensure_engine(id: &str) { if id.is_empty() { return; } let check = |c: &Connection, table: &str| { let had: Option = c.query_row("SELECT value FROM meta WHERE key='embed_engine'", [], |r| r.get(0)).ok(); if had.as_deref() != Some(id) { let _ = c.execute_batch(&format!("UPDATE {table} SET vec=NULL;")); let _ = c.execute("INSERT INTO meta(key,value) VALUES('embed_engine',?1) ON CONFLICT(key) DO UPDATE SET value=excluded.value", params![id]); if table == "docs" { *DOC_VECS.lock().unwrap_or_else(|e| e.into_inner()) = None; } } }; with_conn(|c| check(c, "memories")); if let Some(s) = docs() { if let Ok(c) = s.conn.lock() { check(&c, "docs"); } } } /// Copy memory.db aside (a consistent copy, even while it is written): backups/memory-YYYYMMDD.db, /// the newest `keep` of them. pub fn backup_memory(keep: usize) -> Option { let dir = data_dir().join("backups"); std::fs::create_dir_all(&dir).ok()?; let to = dir.join(format!("memory-{}.db", chrono::Local::now().format("%Y%m%d"))); if !to.exists() { with_conn(|c| c.execute("VACUUM INTO ?1", params![to.display().to_string()]))?.ok()?; } let mut old: Vec = std::fs::read_dir(&dir).ok()?.flatten().map(|e| e.path()).filter(|p| p.file_name().map(|n| n.to_string_lossy().starts_with("memory-")).unwrap_or(false)).collect(); old.sort(); while old.len() > keep { let _ = std::fs::remove_file(old.remove(0)); } Some(to) } /// Keep the files small: the word indexes keep a tombstone for every deleted row until they are /// merged (a document folder that lost 2,000 files left docs.db at 260 MB for 31 MB of index), /// and freed pages stay in the file until VACUUM. Once a day, on its own thread; a search that /// arrives meanwhile waits a few seconds. pub fn compact() { with_docs(|c| { let _ = c.execute_batch("INSERT INTO docs_fts(docs_fts) VALUES('optimize');"); let free: i64 = c.query_row("SELECT freelist_count * page_size FROM pragma_freelist_count, pragma_page_size", [], |r| r.get(0)).unwrap_or(0); if free > 16 << 20 { let _ = c.execute_batch("VACUUM;"); } let _ = c.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);"); }); with_conn(|c| { let _ = c.execute_batch("INSERT INTO memories_fts(memories_fts) VALUES('optimize'); INSERT INTO memories_words(memories_words) VALUES('optimize'); PRAGMA wal_checkpoint(TRUNCATE);"); }); } /// The size of each file (with its write-ahead log), for the memory page and `make doctor`. pub fn sizes() -> [(String, u64); 3] { let size = |p: PathBuf| -> u64 { let wal = PathBuf::from(format!("{}-wal", p.display())); std::fs::metadata(&p).map(|m| m.len()).unwrap_or(0) + std::fs::metadata(wal).map(|m| m.len()).unwrap_or(0) }; [("memory.db".into(), size(memory_path())), ("docs.db".into(), size(docs_path())), ("audit.db".into(), size(audit_path()))] } /// One record of the oplog, mirrored into the trail. Best-effort by contract. pub fn record(bot: u64, r: &Record) { let bot = bot as i64; // (rusqlite speaks i64; ids stay far below 2^63.) let Some(s) = store() else { return }; let Ok(c) = s.conn.lock() else { return }; let now = crate::model::now_ms(); match r { Record::OperationStarted { op, at, prompt, .. } => { let _ = c.execute( "INSERT INTO audit(bot,op,at,kind,detail) VALUES(?1,?2,?3,'turn',?4)", params![bot, op, at, prompt.as_ref().map(|p| p.text.clone())], ); } Record::StepAttempt { op, step, .. } => { let _ = c.execute("INSERT INTO audit(bot,op,at,kind,name) VALUES(?1,?2,?3,'model',?4)", params![bot, op, now, step]); } Record::ToolStarted { op, call_id, name, args, at, .. } => { let _ = c.execute( "INSERT INTO audit(bot,op,at,kind,name,detail,status,call_id) VALUES(?1,?2,?3,'tool',?4,?5,'running',?6)", params![bot, op, at, name, args, call_id], ); } Record::ToolFinished { op, call_id, status, at } => { let _ = c.execute( "UPDATE audit SET status=?1, end_at=?2 WHERE id=(SELECT id FROM audit WHERE bot=?3 AND op=?4 AND call_id=?5 AND kind='tool' ORDER BY id DESC LIMIT 1)", params![status, at, bot, op, call_id], ); } Record::QueueEnqueued { op, id, text, at } => { let _ = c.execute( "INSERT INTO audit(bot,op,at,kind,detail,status,call_id) VALUES(?1,?2,?3,'queue',?4,'waiting',?5)", params![bot, op.as_deref().unwrap_or(""), at, text, id], ); } Record::QueueConsumed { id } | Record::QueueCancelled { id } => { let state = if matches!(r, Record::QueueConsumed { .. }) { "consumed" } else { "cancelled" }; let _ = c.execute( "UPDATE audit SET status=?1 WHERE id=(SELECT id FROM audit WHERE bot=?2 AND call_id=?3 AND kind='queue' ORDER BY id DESC LIMIT 1)", params![state, bot, id], ); } Record::AbortRequested { op } => { let _ = c.execute("INSERT INTO audit(bot,op,at,kind) VALUES(?1,?2,?3,'abort')", params![bot, op, now]); } Record::OperationFinished { op, outcome } => { let name = match outcome { Outcome::Completed => "completed", Outcome::Aborted => "aborted", Outcome::Failed => "failed", }; let _ = c.execute( "UPDATE audit SET status=?1 WHERE id=(SELECT id FROM audit WHERE bot=?2 AND op=?3 AND kind='turn' ORDER BY id DESC LIMIT 1)", params![name, bot, op], ); } } } /// The phone's 稽核時間軸: finished turns stay here, so the page answers for /// KEEP_DAYS, not just for the turn running now. Newest turn first; the last 20 turns. pub fn turns(bot: u64) -> serde_json::Value { let bot = bot as i64; let Some(s) = store() else { return serde_json::json!({"turns": []}) }; let Ok(c) = s.conn.lock() else { return serde_json::json!({"turns": []}) }; let cutoff = crate::model::now_ms() - KEEP_DAYS * 86_400_000; let Ok(mut st) = c.prepare( "SELECT op,at,end_at,kind,name,detail,status,call_id FROM audit WHERE bot=?1 AND at>?2 ORDER BY id ASC", ) else { return serde_json::json!({"turns": []}) }; let rows = st .query_map(params![bot, cutoff], |r| { Ok(( r.get::<_, String>(0)?, r.get::<_, i64>(1)?, r.get::<_, Option>(2)?, r.get::<_, String>(3)?, r.get::<_, Option>(4)?, r.get::<_, Option>(5)?, r.get::<_, Option>(6)?, )) }) .map(|it| it.filter_map(Result::ok).collect::>()) .unwrap_or_default(); drop(st); #[derive(Default)] struct Turn { op: String, at: i64, prompt: String, outcome: Option, steps: Vec, } let mut turns: Vec = Vec::new(); let pos = |turns: &mut Vec, op: &str| -> usize { turns.iter().rposition(|t| t.op == op).unwrap_or_else(|| { turns.push(Turn { op: op.to_string(), at: 0, prompt: String::new(), outcome: None, steps: Vec::new() }); turns.len() - 1 }) }; for (op, at, end_at, kind, name, detail, status) in rows { let i = pos(&mut turns, &op); match kind.as_str() { "turn" => { turns[i].at = at; turns[i].prompt = detail.unwrap_or_default(); turns[i].outcome = status; } "model" => { // Consecutive attempts at the same step read as one line, counted. match turns[i].steps.last_mut().filter(|s| s["type"] == "model" && s["step"] == *name.as_deref().unwrap_or("")) { Some(last) => last["attempts"] = serde_json::json!(last["attempts"].as_u64().unwrap_or(1) + 1), None => turns[i].steps.push(serde_json::json!({"type": "model", "step": name.unwrap_or_default(), "attempts": 1})), } } "tool" => { // The row carries its end status; args stay as they ran. let at_tool = at; match turns[i].steps.iter_mut().rev().find(|s| s["type"] == "tool" && s["name"] == *name.as_deref().unwrap_or("") && s["status"] == "running") { Some(s) => { s["status"] = serde_json::json!(status.as_deref().unwrap_or("running")); s["end_at"] = serde_json::json!(end_at); } None => turns[i].steps.push(serde_json::json!({"type": "tool", "name": name.unwrap_or_default(), "args": detail.unwrap_or_default(), "status": status.unwrap_or_else(|| "running".into()), "at": at_tool})), } } "queue" => turns[i].steps.push(serde_json::json!({"type": "queue", "text": detail.unwrap_or_default(), "at": at, "state": status.unwrap_or_else(|| "waiting".into())})), "abort" => turns[i].steps.push(serde_json::json!({"type": "abort"})), _ => {} } } let keep = turns.len().min(20); let out: Vec = turns[turns.len() - keep..] .iter() .rev() .map(|t| serde_json::json!({"op": t.op, "at": t.at, "prompt": t.prompt, "outcome": t.outcome, "steps": t.steps})) .collect(); serde_json::json!({"turns": out}) } // ---------- 記憶(memory.db, memstore.rs) ---------- // `state.json`'s bot.memories stays the copy that mirrors sync between devices; the shelf here is // the whole of it (the JSON caps at 200) plus 做過的事, and what the memory page shows. /// Index what a bot already remembers (startup / first use; INSERT OR IGNORE, cheap). A fact the /// person put in the trash stays there (the settings list may be a moment behind). pub fn memory_index(bot: u64, texts: &[String]) { for t in texts { crate::memstore::ensure(bot, t); } } /// One new memory (the model's `remember`, or the person's 記住…); one forgotten earlier comes back. #[cfg(test)] pub fn memory_add(bot: u64, text: &str) { crate::memstore::add(bot, text, "fact"); } /// A forgotten memory goes to the trash (30 days, restorable) with the list. #[cfg(test)] pub fn memory_del(bot: u64, text: &str) { if let Some(m) = crate::memstore::find(bot, text) { crate::memstore::trash(m.id, 0); } } /// One finished turn as a line of 做過的事: 「3-8:幫我發一篇 Threads… → 發好了…」. pub fn memory_event(bot: u64, text: &str) { if text.trim().is_empty() { return; } crate::memstore::add(bot, text, "event"); } /// The memories that answer a request, best first (memstore::search: words and meaning, each /// scored), those worth showing at all. Empty means nothing answers. #[cfg(test)] pub fn recall(bot: u64, query: &str, limit: usize) -> Vec { crate::memstore::search(bot, query, &["fact", "event", "rollup"], limit).into_iter().filter(|h| h.score >= crate::memory::SHOW_SCORE).map(|h| h.m.text).collect() } /// Memory rows the background thread has not embedded yet. pub fn memory_pending(limit: usize) -> Vec<(i64, String)> { crate::memstore::pending(limit) } // ---------- 文件(docs.db) ---------- fn with_docs(f: impl FnOnce(&Connection) -> T) -> Option { let s = docs()?; let c = s.conn.lock().ok()?; Some(f(&c)) } /// Every chunk's vector, in memory: a search reads 60,000 of them in milliseconds, where reading /// them out of the file each time took longer than the question. Rebuilt after the files change. struct DocVecs { rows: Vec<(i64, Vec)>, } static DOC_VECS: Mutex> = Mutex::new(None); fn doc_vecs_stale() { *DOC_VECS.lock().unwrap_or_else(|e| e.into_inner()) = None; } /// The sweep's cheap change check: the file is indexed and unmodified. pub fn doc_mtime_is(path: &str, mtime: i64) -> bool { with_docs(|c| c.query_row("SELECT COUNT(*) FROM docs WHERE path=?1 AND mtime=?2", params![path, mtime], |r| r.get::<_, i64>(0)).map(|n| n > 0).unwrap_or(false)).unwrap_or(false) } /// A file's chunks, replacing the old ones (the index of a file is exactly its current self). pub fn doc_replace(path: &str, mtime: i64, chunks: &[String]) { with_docs(|c| { let _ = c.execute_batch("BEGIN"); let _ = c.execute("DELETE FROM docs WHERE path=?1", params![path]); for (i, ch) in chunks.iter().enumerate() { let _ = c.execute("INSERT INTO docs(path,mtime,idx,text) VALUES(?1,?2,?3,?4)", params![path, mtime, i as i64, ch]); } let _ = c.execute_batch("COMMIT"); }); doc_vecs_stale(); } pub fn doc_remove(path: &str) { with_docs(|c| c.execute("DELETE FROM docs WHERE path=?1", params![path])); doc_vecs_stale(); } pub fn doc_mtimes() -> Vec<(String, i64)> { with_docs(|c| { let mut out = vec![]; let _ = c.prepare("SELECT DISTINCT path, mtime FROM docs").and_then(|mut st| { for x in st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?.flatten() { out.push(x); } Ok(()) }); out }) .unwrap_or_default() } /// Chunks the background thread has not embedded yet. pub fn doc_pending(limit: usize) -> Vec<(i64, String)> { with_docs(|c| { let mut out = vec![]; let _ = c.prepare("SELECT rowid, text FROM docs WHERE vec IS NULL LIMIT ?1").and_then(|mut st| { for x in st.query_map(params![limit as i64], |r| Ok((r.get(0)?, r.get(1)?)))?.flatten() { out.push(x); } Ok(()) }); out }) .unwrap_or_default() } pub fn doc_set_vecs(rows: &[(i64, Vec)]) { with_docs(|c| { let _ = c.execute_batch("BEGIN"); for (rowid, v) in rows { let _ = c.execute("UPDATE docs SET vec=?1 WHERE rowid=?2", params![crate::embed::f32s_to_blob(v), rowid]); } let _ = c.execute_batch("COMMIT"); }); // New vectors join the copy in memory as they come (no reload for each batch). if let Some(cache) = DOC_VECS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { cache.rows.extend(rows.iter().cloned()); } } /// The chunks closest in meaning to `v` (cosine above `floor`), best first: (rowid, cosine). fn doc_nearest(v: &[f32], floor: f32, limit: usize) -> Vec<(i64, f32)> { let mut g = DOC_VECS.lock().unwrap_or_else(|e| e.into_inner()); if g.is_none() { let rows = with_docs(|c| { let mut out = vec![]; let _ = c.prepare("SELECT rowid, vec FROM docs WHERE vec IS NOT NULL").and_then(|mut st| { for x in st.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Vec>(1)?)))?.flatten() { out.push((x.0, crate::embed::blob_to_f32s(&x.1))); } Ok(()) }); out }) .unwrap_or_default(); *g = Some(DocVecs { rows }); } let mut ranked: Vec<(i64, f32)> = g.as_ref().map(|d| d.rows.iter().filter(|(_, w)| w.len() == v.len()).map(|(id, w)| (*id, crate::embed::cosine(v, w))).filter(|(_, s)| *s > floor).collect()).unwrap_or_default(); ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); ranked.truncate(limit); ranked } /// Reciprocal-rank fusion of ranked lists (words, meaning): a line two lists like beats a /// line one list loves. k=60 is the usual calm setting. fn rrf(lists: &[Vec], limit: usize) -> Vec { let mut scored: Vec<(f64, String)> = vec![]; for list in lists { for (rank, item) in list.iter().enumerate() { let add = 1.0 / (60.0 + rank as f64); match scored.iter_mut().find(|(_, t)| t == item) { Some(e) => e.0 += add, None => scored.push((add, item.clone())), } } } scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)); scored.into_iter().take(limit).map(|(_, t)| t).collect() } /// 「我上個月那份報表」: chunks of the person's indexed files, words first (FTS, then /// two-character windows for Chinese), meaning when the local model is there — over every /// chunk (the vectors are kept in memory), not the first few thousand. pub fn docs_search(query: &str, limit: usize) -> Vec<(String, String)> { let q: String = query.chars().filter(|ch| *ch != '"').collect::().split_whitespace().collect::>().join(" "); let words: Vec<(String, String)> = with_docs(|c| { let mut words: Vec<(String, String)> = vec![]; // (path, chunk), best first, no doubles if q.chars().count() >= 3 { let phrase = format!("\"{q}\""); let _ = c.prepare("SELECT d.path, d.text FROM docs d JOIN docs_fts f ON f.rowid=d.rowid WHERE docs_fts MATCH ?1 ORDER BY bm25(docs_fts) LIMIT ?2").and_then(|mut st| { for x in st.query_map(params![phrase, limit as i64 * 2], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?.flatten() { if !words.contains(&x) { words.push(x); } } Ok(()) }); } // Two-character windows, scored by how many a chunk has. let mut segs: Vec = vec![]; for w in q.split_whitespace() { let ch: Vec = w.chars().collect(); if w.is_ascii() { if ch.len() >= 2 { segs.push(w.to_lowercase()); } } else if ch.len() >= 2 { for i in 0..ch.len() - 1 { segs.push(format!("{}{}", ch[i], ch[i + 1])); } } } segs.sort(); segs.dedup(); segs.truncate(12); if !segs.is_empty() { let mut scored: Vec<(usize, String, String)> = vec![]; for seg in &segs { let _ = c.prepare("SELECT path, text FROM docs WHERE text LIKE '%'||?1||'%' LIMIT 80").and_then(|mut st| { for x in st.query_map(params![seg], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?.flatten() { match scored.iter_mut().find(|(_, p, t)| p == &x.0 && t == &x.1) { Some(e) => e.0 += 1, None => scored.push((1, x.0, x.1)), } } Ok(()) }); } scored.sort_by(|a, b| b.0.cmp(&a.0)); for (_, path, text) in scored { if !words.iter().any(|(p, t)| p == &path && t == &text) { words.push((path, text)); } } } words }) .unwrap_or_default(); if crate::embed::enabled() { if let Some(v) = crate::embed::embed(&[query.to_string()]).and_then(|mut v| v.pop()) { let near = doc_nearest(&v, 0.30, limit * 2); let found: Vec<(String, String)> = with_docs(|c| near.iter().filter_map(|(id, _)| c.query_row("SELECT path, text FROM docs WHERE rowid=?1", params![id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).ok()).collect()).unwrap_or_default(); let keys: Vec = words.iter().map(|(p, t)| format!("{p}\u{1}{t}")).collect(); let vr: Vec = found.into_iter().map(|(p, t)| format!("{p}\u{1}{t}")).collect(); let merged = rrf(&[vr, keys], limit * 2); let mut out: Vec<(String, String)> = vec![]; for k in merged { let mut sp = k.splitn(2, '\u{1}'); if let (Some(p), Some(t)) = (sp.next(), sp.next()) { out.push((p.to_string(), t.to_string())); } } return out.into_iter().take(limit).collect(); } } let mut words = words; words.truncate(limit); words } #[cfg(test)] mod tests { use super::*; use crate::oplog::{Prompt, Replay}; #[test] fn the_memory_index_answers_in_chinese() { // (One database per test process, one bot id: 4243 is ours here.) let bot = 4243u64; memory_add(bot, "我喜歡靠窗的座位,長途航班也是"); memory_add(bot, "週五下午不開會"); memory_add(9999, "別的 Bot 的事:預算 42 萬"); memory_event(bot, "3-8:幫我排週五的會 → 已排在 15:00"); let hits = recall(bot, "靠窗的座位", 10); assert!(hits.iter().any(|m| m.contains("靠窗")), "{hits:?}"); // A two-word query finds lines that merely contain the words (LIKE path). let hits = recall(bot, "週五", 10); assert!(hits.iter().any(|m| m.contains("週五下午")), "{hits:?}"); // Other bots' memories stay theirs. assert!(!recall(bot, "預算 42 萬", 10).iter().any(|m| m.contains("預算")), "leaked another bot's memory"); // Events answer the "上個月說過的那個" questions. let hits = recall(bot, "排週五的會", 10); assert!(hits.iter().any(|m| m.contains("已排在 15:00")), "{hits:?}"); // Forgetting leaves the index with the list. memory_del(bot, "週五下午不開會"); assert!(!recall(bot, "週五下午不開會", 3).contains(&"週五下午不開會".to_string())); } #[test] fn the_trail_keeps_the_story_after_the_turn_log_cleans_up() { // (Tests share the temp dir of this process; one database, one bot id. // Times ride on "now" — the trail prunes anything older than a month.) let bot = 4242; let t0 = crate::model::now_ms() - 60_000; let at = |d| t0 + d; record(bot, &Record::OperationStarted { op: "op1".into(), at: at(0), source_leaf: 0, prompt: Some(Prompt { at: at(0), text: "幫我叫車".into() }) }); record(bot, &Record::StepAttempt { op: "op1".into(), step: "assistant".into(), attempt: 1 }); record(bot, &Record::StepAttempt { op: "op1".into(), step: "assistant".into(), attempt: 2 }); record(bot, &Record::ToolStarted { op: "op1".into(), call_id: "c1".into(), name: "computer".into(), args: "{\"action\":\"click\"}".into(), replay: Replay::Never, at: at(10) }); record(bot, &Record::ToolFinished { op: "op1".into(), call_id: "c1".into(), status: "done".into(), at: at(20) }); record(bot, &Record::QueueEnqueued { op: Some("op1".into()), id: "q1".into(), text: "快一點".into(), at: at(11) }); record(bot, &Record::QueueConsumed { id: "q1".into() }); record(bot, &Record::OperationFinished { op: "op1".into(), outcome: Outcome::Completed }); record(bot, &Record::OperationStarted { op: "op2".into(), at: at(100), source_leaf: 100, prompt: None }); record(bot, &Record::ToolStarted { op: "op2".into(), call_id: "c9".into(), name: "run_cmd".into(), args: "{}".into(), replay: Replay::Safe, at: at(110) }); let v = turns(bot); let ts = v["turns"].as_array().unwrap(); assert_eq!(ts.len(), 2, "both turns are in the trail"); // (Newest first: the phone puts the running turn at the top.) assert_eq!(ts[0]["op"], "op2"); assert_eq!(ts[0]["outcome"], serde_json::Value::Null); assert_eq!(ts[0]["steps"][0]["status"], "running"); assert_eq!(ts[1]["prompt"], "幫我叫車"); assert_eq!(ts[1]["outcome"], "completed"); assert_eq!(ts[1]["steps"][0], serde_json::json!({"type": "model", "step": "assistant", "attempts": 2})); assert_eq!(ts[1]["steps"][1]["name"], "computer"); assert_eq!(ts[1]["steps"][1]["status"], "done", "the finished tool answers with its end status"); assert_eq!(ts[1]["steps"][2]["state"], "consumed"); } #[test] fn documents_stay_findable_after_compaction() { let chunks: Vec = (0..200).map(|i| format!("第 {i} 段:語法筆記,的得地的用法 {i}")).collect(); doc_replace("/test/compact/a.md", 1, &chunks); doc_replace("/test/compact/b.md", 1, &["咖啡豆的烘焙度筆記".to_string()]); doc_remove("/test/compact/a.md"); compact(); let hits = docs_search("烘焙度", 5); assert!(hits.iter().any(|(p, _)| p == "/test/compact/b.md"), "{hits:?}"); assert!(!docs_search("的得地的用法", 5).iter().any(|(p, _)| p == "/test/compact/a.md"), "a removed file stays removed"); } #[test] fn an_old_audit_db_moves_into_its_own_files() { // An audit.db from before the split: audit rows, memories (with vectors) and documents. let dir = std::env::temp_dir().join(format!("anybot-split-test-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let (old, mem, docs) = (dir.join("audit.db"), dir.join("memory.db"), dir.join("docs.db")); { let c = connect(&old).unwrap(); audit_schema(&c).unwrap(); c.execute_batch( "CREATE TABLE memories(id INTEGER PRIMARY KEY, bot INTEGER NOT NULL, text TEXT NOT NULL, kind TEXT NOT NULL DEFAULT 'fact', created INTEGER NOT NULL, UNIQUE(bot, text)); ALTER TABLE memories ADD COLUMN vec BLOB; CREATE VIRTUAL TABLE memories_fts USING fts5(text, content='memories', content_rowid='id', tokenize='trigram'); INSERT INTO memories(bot,text,kind,created,vec) VALUES (5,'我喜歡靠窗的座位','fact',1,x'0000803f'), (5,'11-03:整理照片 → 好了','event',2,NULL); INSERT INTO audit(bot,op,at,kind) VALUES (5,'op',1,'turn');", ) .unwrap(); docs_schema(&c).unwrap(); c.execute("INSERT INTO docs(path,mtime,idx,text) VALUES('/n/a.md',1,0,'語法筆記:的得地')", []).unwrap(); } split_files(&old, &mem, &docs); let m = connect(&mem).unwrap(); let n: i64 = m.query_row("SELECT COUNT(*) FROM memories WHERE bot=5", [], |r| r.get(0)).unwrap(); assert_eq!(n, 2); let v: Vec = m.query_row("SELECT vec FROM memories WHERE kind='fact'", [], |r| r.get(0)).unwrap(); assert_eq!(v.len(), 4, "vectors come along"); let words: String = m.query_row("SELECT words FROM memories_words w JOIN memories x ON x.id=w.rowid WHERE x.kind='fact'", [], |r| r.get(0)).unwrap(); assert!(words.contains("靠窗"), "the word index is built for what moved: {words}"); let d = connect(&docs).unwrap(); let hit: String = d.query_row("SELECT d.text FROM docs d JOIN docs_fts f ON f.rowid=d.rowid WHERE docs_fts MATCH '\"語法筆\"'", [], |r| r.get(0)).unwrap(); assert!(hit.contains("語法")); // audit.db keeps only the trail. let a = connect(&old).unwrap(); let tables: Vec = a.prepare("SELECT name FROM sqlite_master WHERE type='table'").unwrap().query_map([], |r| r.get(0)).unwrap().flatten().collect(); assert!(tables.contains(&"audit".to_string()) && !tables.iter().any(|t| t.starts_with("memories") || t.starts_with("docs")), "{tables:?}"); // A second start has nothing to move (and loses nothing). split_files(&old, &mem, &docs); assert_eq!(connect(&mem).unwrap().query_row("SELECT COUNT(*) FROM memories", [], |r| r.get::<_, i64>(0)).unwrap(), 2); let _ = std::fs::remove_dir_all(&dir); } }