2026-11-09 10:00:56 +00:00
//! The SQLite layer: a queryable audit trail beside the JSON files.
//!
//! `state.json` stays the app's truth (one struct, written atomically; every layer of
//! the app reads it as a struct, not as rows). What JSON files cannot do is *ask
//! questions*: "what has this bot done in the last week?" The audit trail therefore
//! lives in SQLite (bundled, WAL, one file in the data folder) and keeps what the
//! per-turn oplog drops — turns finished days ago, answerable from the phone. The
//! memory/RAG layer lands here too.
//!
//! It is deliberately side-car: every write is best-effort, an audit that never
//! breaks a turn. If the database cannot be opened, the log of the turn in flight
//! (oplog) still works and the timeline page just shows less.
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 < Connection > ,
}
static STORE : OnceLock < Option < Store > > = OnceLock ::new ( ) ;
fn path ( ) -> PathBuf {
crate ::oplog ::dir ( ) . join ( " audit.db " )
}
/// Open (create if needed) the data folder's audit database. Failure means "no
/// history", never "no bot".
fn open ( ) -> Option < Store > {
2026-11-09 10:02:56 +00:00
let p = path ( ) ;
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 ( ) ? ;
2026-11-09 10:00:56 +00:00
c . pragma_update ( None , " journal_mode " , " WAL " ) . ok ( ) ? ;
c . pragma_update ( None , " synchronous " , " NORMAL " ) . ok ( ) ? ;
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 ) ;
2026-11-09 10:15:24 +00:00
CREATE INDEX IF NOT EXISTS audit_call ON audit ( bot , op , call_id ) ;
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 ,
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 ) ;
Meaning beside the words: local embeddings + a document shelf (P6, step 2)
- embed.rs: vectors from the person's own Ollama (/api/embed), model
auto-found among installed ones (bge-m3, nomic-embed-text…), off by
absence — no Ollama is a normal state: every search still answers
with words, the toggle lives in 設定 › 一般
- memories grow a vec column; recall() is now hybrid: trigram FTS,
two-character windows for Chinese, cosine over the shelf, merged by
reciprocal rank — 「那篇講語法的筆記」 finds text that never says 筆記
- docindex.rs: the person's folders (their 文件 by default, add more in
設定 › 一般), text-shaped files chunked into SQLite + FTS, refreshed
by mtime, gone files leave; one background thread does it all — the
turn never waits on embeddings
- one tool for it: search_documents {query, limit} — reads, no approval
- 251 tests: a real temp folder swept, answered, and swept again after
deletion; offline Ollama tested as the normal state it is
2026-11-09 12:23:35 +00:00
END ;
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 ) ;
2026-11-09 10:15:24 +00:00
END ; " ,
2026-11-09 10:00:56 +00:00
)
. ok ( ) ? ;
Meaning beside the words: local embeddings + a document shelf (P6, step 2)
- embed.rs: vectors from the person's own Ollama (/api/embed), model
auto-found among installed ones (bge-m3, nomic-embed-text…), off by
absence — no Ollama is a normal state: every search still answers
with words, the toggle lives in 設定 › 一般
- memories grow a vec column; recall() is now hybrid: trigram FTS,
two-character windows for Chinese, cosine over the shelf, merged by
reciprocal rank — 「那篇講語法的筆記」 finds text that never says 筆記
- docindex.rs: the person's folders (their 文件 by default, add more in
設定 › 一般), text-shaped files chunked into SQLite + FTS, refreshed
by mtime, gone files leave; one background thread does it all — the
turn never waits on embeddings
- one tool for it: search_documents {query, limit} — reads, no approval
- 251 tests: a real temp folder swept, answered, and swept again after
deletion; offline Ollama tested as the normal state it is
2026-11-09 12:23:35 +00:00
// Memories gained a vector beside the words (P6 step 2); older bases just get the column.
let _ = c . execute_batch ( " ALTER TABLE memories ADD COLUMN vec BLOB; " ) ;
2026-11-09 10:00:56 +00:00
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 store ( ) -> Option < & 'static Store > {
STORE . get_or_init ( open ) . as_ref ( )
}
/// 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 {
2026-11-09 10:02:56 +00:00
let bot = bot as i64 ;
2026-11-09 10:00:56 +00:00
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 < i64 > > ( 2 ) ? ,
r . get ::< _ , String > ( 3 ) ? ,
r . get ::< _ , Option < String > > ( 4 ) ? ,
r . get ::< _ , Option < String > > ( 5 ) ? ,
r . get ::< _ , Option < String > > ( 6 ) ? ,
) )
} )
. map ( | it | it . filter_map ( Result ::ok ) . collect ::< Vec < _ > > ( ) )
. unwrap_or_default ( ) ;
drop ( st ) ;
#[ derive(Default) ]
struct Turn {
op : String ,
at : i64 ,
prompt : String ,
outcome : Option < String > ,
steps : Vec < serde_json ::Value > ,
}
let mut turns : Vec < Turn > = Vec ::new ( ) ;
let pos = | turns : & mut Vec < Turn > , 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 < serde_json ::Value > = 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 } )
}
#[ cfg(test) ]
mod tests {
use super ::* ;
use crate ::oplog ::{ Prompt , Replay } ;
2026-11-09 10:15:24 +00:00
#[ test ]
fn the_memory_index_answers_in_chinese ( ) {
// (One database per test process, one bot id: 4243 is ours here.)
let bot = 4243 u64 ;
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 ( ) ) ) ;
}
2026-11-09 10:00:56 +00:00
#[ test ]
fn the_trail_keeps_the_story_after_the_turn_log_cleans_up ( ) {
2026-11-09 10:02:56 +00:00
// (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.)
2026-11-09 10:00:56 +00:00
let bot = 4242 ;
2026-11-09 10:02:56 +00:00
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 ( ) } ) } ) ;
2026-11-09 10:00:56 +00:00
record ( bot , & Record ::StepAttempt { op : " op1 " . into ( ) , step : " assistant " . into ( ) , attempt : 1 } ) ;
record ( bot , & Record ::StepAttempt { op : " op1 " . into ( ) , step : " assistant " . into ( ) , attempt : 2 } ) ;
2026-11-09 10:02:56 +00:00
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 ) } ) ;
2026-11-09 10:00:56 +00:00
record ( bot , & Record ::QueueConsumed { id : " q1 " . into ( ) } ) ;
record ( bot , & Record ::OperationFinished { op : " op1 " . into ( ) , outcome : Outcome ::Completed } ) ;
2026-11-09 10:02:56 +00:00
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 ) } ) ;
2026-11-09 10:00:56 +00:00
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 " ) ;
}
}
2026-11-09 10:15:24 +00:00
// ---------- 記憶的索引( P6) ----------
// `state.json`'s bot.memories stays the source that mirrors sync between devices, and the
// list the person manages in 設定 › 記得的事. The index is its searchable side: a superset
// (the JSON caps at 200, the index does not) plus *events* — one line per finished turn,
// nobody's asked to write them — so "我上個月說的那個…" answers across months.
// Best-effort in, best-effort out: with no index the caller falls back to the JSON list.
/// Index what a bot already remembers (startup / first use; INSERT OR IGNORE, cheap).
pub fn memory_index ( bot : u64 , texts : & [ String ] ) {
let Some ( s ) = store ( ) else { return } ;
let Ok ( c ) = s . conn . lock ( ) else { return } ;
let now = crate ::model ::now_ms ( ) ;
for t in texts {
let _ = c . execute ( " INSERT OR IGNORE INTO memories(bot,text,kind,created) VALUES(?1,?2,'fact',?3) " , params! [ bot as i64 , t , now ] ) ;
}
}
/// One new memory (the model's `remember`, or the person's 記住…).
pub fn memory_add ( bot : u64 , text : & str ) {
let Some ( s ) = store ( ) else { return } ;
let Ok ( c ) = s . conn . lock ( ) else { return } ;
let _ = c . execute ( " INSERT OR IGNORE INTO memories(bot,text,kind,created) VALUES(?1,?2,'fact',?3) " , params! [ bot as i64 , text , crate ::model ::now_ms ( ) ] ) ;
}
/// A forgotten memory leaves the index with the list.
pub fn memory_del ( bot : u64 , text : & str ) {
let Some ( s ) = store ( ) else { return } ;
let Ok ( c ) = s . conn . lock ( ) else { return } ;
let _ = c . execute ( " DELETE FROM memories WHERE bot=?1 AND text=?2 " , params! [ bot as i64 , text ] ) ;
}
/// One finished turn as a line of the event log: 「3-8: 幫我發一篇 Threads… → 發好了…」.
pub fn memory_event ( bot : u64 , text : & str ) {
if text . trim ( ) . is_empty ( ) {
return ;
}
let Some ( s ) = store ( ) else { return } ;
let Ok ( c ) = s . conn . lock ( ) else { return } ;
let _ = c . execute ( " INSERT INTO memories(bot,text,kind,created) VALUES(?1,?2,'event',?3) " , params! [ bot as i64 , text , crate ::model ::now_ms ( ) ] ) ;
}
/// The memories that answer a request: phrase hits first (FTS trigram, good with Chinese),
/// words inside lines next (LIKE, for short queries), newest facts last. The person's own
/// shared preferences ride along (bot 0). Empty means "no index" — the caller decides.
pub fn recall ( bot : u64 , query : & str , limit : usize ) -> Vec < String > {
let mut out : Vec < String > = vec! [ ] ;
let Some ( s ) = store ( ) else { return out } ;
let Ok ( c ) = s . conn . lock ( ) else { return out } ;
let q : String = query . chars ( ) . filter ( | ch | * ch ! = '"' ) . collect ::< String > ( ) . split_whitespace ( ) . collect ::< Vec < _ > > ( ) . join ( " " ) ;
let bot = bot as i64 ;
if q . chars ( ) . count ( ) > = 3 {
// Trigram wants at least three characters; a quoted phrase keeps it literal.
let phrase = format! ( " \" {q} \" " ) ;
if let Ok ( rows ) = c . prepare ( " SELECT m.text FROM memories m JOIN memories_fts f ON f.rowid=m.id WHERE memories_fts MATCH ?1 AND m.bot IN (?2, 0) ORDER BY bm25(memories_fts) LIMIT ?3 " ) . and_then ( | mut st | {
let it = st . query_map ( params! [ phrase , bot , limit as i64 ] , | r | r . get ::< _ , String > ( 0 ) ) ? ;
let mut v = vec! [ ] ;
for x in it . flatten ( ) {
v . push ( x ) ;
}
Ok ( v )
} ) {
out . extend ( rows ) ;
}
}
// Words inside lines next. Chinese queries are cut into two-character windows
// ("有没有靠窗" → 有没/没有/有靠/靠窗) and lines score by how many windows they
// contain: a shelf line answering the question outranks a fresh one.
let mut segs : Vec < String > = vec! [ ] ;
for w in q . split_whitespace ( ) {
let ch : Vec < char > = 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 , i64 , String ) > = vec! [ ] ; // (windows hit, freshness, text)
for seg in & segs {
let _ = c . prepare ( " SELECT id, created, text FROM memories WHERE bot IN (?1, 0) AND text LIKE '%'||?2||'%' LIMIT 60 " ) . and_then ( | mut st | {
let it = st . query_map ( params! [ bot , seg ] , | r | Ok ( ( r . get ::< _ , i64 > ( 0 ) ? , r . get ::< _ , i64 > ( 1 ) ? , r . get ::< _ , String > ( 2 ) ? ) ) ) ? ;
for x in it . flatten ( ) {
Meaning beside the words: local embeddings + a document shelf (P6, step 2)
- embed.rs: vectors from the person's own Ollama (/api/embed), model
auto-found among installed ones (bge-m3, nomic-embed-text…), off by
absence — no Ollama is a normal state: every search still answers
with words, the toggle lives in 設定 › 一般
- memories grow a vec column; recall() is now hybrid: trigram FTS,
two-character windows for Chinese, cosine over the shelf, merged by
reciprocal rank — 「那篇講語法的筆記」 finds text that never says 筆記
- docindex.rs: the person's folders (their 文件 by default, add more in
設定 › 一般), text-shaped files chunked into SQLite + FTS, refreshed
by mtime, gone files leave; one background thread does it all — the
turn never waits on embeddings
- one tool for it: search_documents {query, limit} — reads, no approval
- 251 tests: a real temp folder swept, answered, and swept again after
deletion; offline Ollama tested as the normal state it is
2026-11-09 12:23:35 +00:00
let ( _id , created , text ) = x ;
2026-11-09 10:15:24 +00:00
match scored . iter_mut ( ) . find ( | ( _ , _ , t ) | t = = & text ) {
Some ( e ) = > e . 0 + = 1 ,
None = > scored . push ( ( 1 , created , text ) ) ,
}
}
Ok ( ( ) )
} ) ;
}
scored . sort_by ( | a , b | b . 0. cmp ( & a . 0 ) . then ( b . 1. cmp ( & a . 1 ) ) ) ;
for ( _ , _ , text ) in scored {
if ! out . contains ( & text ) {
out . push ( text ) ;
}
}
}
Meaning beside the words: local embeddings + a document shelf (P6, step 2)
- embed.rs: vectors from the person's own Ollama (/api/embed), model
auto-found among installed ones (bge-m3, nomic-embed-text…), off by
absence — no Ollama is a normal state: every search still answers
with words, the toggle lives in 設定 › 一般
- memories grow a vec column; recall() is now hybrid: trigram FTS,
two-character windows for Chinese, cosine over the shelf, merged by
reciprocal rank — 「那篇講語法的筆記」 finds text that never says 筆記
- docindex.rs: the person's folders (their 文件 by default, add more in
設定 › 一般), text-shaped files chunked into SQLite + FTS, refreshed
by mtime, gone files leave; one background thread does it all — the
turn never waits on embeddings
- one tool for it: search_documents {query, limit} — reads, no approval
- 251 tests: a real temp folder swept, answered, and swept again after
deletion; offline Ollama tested as the normal state it is
2026-11-09 12:23:35 +00:00
// The semantic side (P6 step 2): vectors of the same shelf, when the person's Ollama
// has an embedding model. Reciprocal-rank merge: a line both words and meaning rank
// high goes first; with no Ollama this whole arm is simply absent.
if crate ::embed ::enabled ( ) {
if let Some ( v ) = crate ::embed ::embed ( & [ query . to_string ( ) ] ) . and_then ( | mut v | v . pop ( ) ) {
let mut ranked : Vec < ( f32 , String ) > = memory_vecs_of ( bot ) . into_iter ( ) . map ( | ( t , w ) | ( crate ::embed ::cosine ( & v , & w ) , t ) ) . filter ( | ( sc , _ ) | * sc > 0.30 ) . collect ( ) ;
ranked . sort_by ( | a , b | b . 0. partial_cmp ( & a . 0 ) . unwrap_or ( std ::cmp ::Ordering ::Equal ) ) ;
let vr : Vec < String > = ranked . into_iter ( ) . map ( | ( _ , t ) | t ) . take ( limit * 2 ) . collect ( ) ;
out = rrf ( & [ vr , out ] , limit * 2 ) ;
}
}
2026-11-09 10:15:24 +00:00
if out . is_empty ( ) {
// Nothing matched: the freshest facts, so "記住…" works in the very next chat even
// with no words to match.
let want = limit ;
let _ = c . prepare ( " SELECT text FROM memories WHERE bot IN (?1, 0) AND kind='fact' ORDER BY created DESC LIMIT ?2 " ) . and_then ( | mut st | {
let it = st . query_map ( params! [ bot , want as i64 ] , | r | r . get ::< _ , String > ( 0 ) ) ? ;
for x in it . flatten ( ) {
if ! out . contains ( & x ) {
out . push ( x ) ;
}
}
Ok ( ( ) )
} ) ;
}
out . truncate ( limit ) ;
out
}
Meaning beside the words: local embeddings + a document shelf (P6, step 2)
- embed.rs: vectors from the person's own Ollama (/api/embed), model
auto-found among installed ones (bge-m3, nomic-embed-text…), off by
absence — no Ollama is a normal state: every search still answers
with words, the toggle lives in 設定 › 一般
- memories grow a vec column; recall() is now hybrid: trigram FTS,
two-character windows for Chinese, cosine over the shelf, merged by
reciprocal rank — 「那篇講語法的筆記」 finds text that never says 筆記
- docindex.rs: the person's folders (their 文件 by default, add more in
設定 › 一般), text-shaped files chunked into SQLite + FTS, refreshed
by mtime, gone files leave; one background thread does it all — the
turn never waits on embeddings
- one tool for it: search_documents {query, limit} — reads, no approval
- 251 tests: a real temp folder swept, answered, and swept again after
deletion; offline Ollama tested as the normal state it is
2026-11-09 12:23:35 +00:00
/// 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 < String > ] , limit : usize ) -> Vec < String > {
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 ( )
}
// ---------- 向量與文件 (P6 step 2) ----------
/// Memory rows the background thread has not embedded yet.
pub fn memory_pending ( limit : usize ) -> Vec < ( i64 , String ) > {
let Some ( s ) = store ( ) else { return vec! [ ] } ;
let Ok ( c ) = s . conn . lock ( ) else { return vec! [ ] } ;
let mut out = vec! [ ] ;
let _ = c . prepare ( " SELECT id, text FROM memories WHERE vec IS NULL ORDER BY created DESC 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
}
pub fn memory_set_vec ( id : i64 , v : & [ f32 ] ) {
let Some ( s ) = store ( ) else { return } ;
let Ok ( c ) = s . conn . lock ( ) else { return } ;
let _ = c . execute ( " UPDATE memories SET vec=?1 WHERE id=?2 " , params! [ crate ::embed ::f32s_to_blob ( v ) , id ] ) ;
}
fn memory_vecs_of ( bot : i64 ) -> Vec < ( String , Vec < f32 > ) > {
let Some ( s ) = store ( ) else { return vec! [ ] } ;
let Ok ( c ) = s . conn . lock ( ) else { return vec! [ ] } ;
let mut out = vec! [ ] ;
let _ = c . prepare ( " SELECT text, vec FROM memories WHERE bot IN (?1, 0) AND vec IS NOT NULL LIMIT 5000 " ) . and_then ( | mut st | {
for x in st . query_map ( params! [ bot ] , | r | Ok ( ( r . get ::< _ , String > ( 0 ) ? , r . get ::< _ , Vec < u8 > > ( 1 ) ? ) ) ) ? . flatten ( ) {
out . push ( ( x . 0 , crate ::embed ::blob_to_f32s ( & x . 1 ) ) ) ;
}
Ok ( ( ) )
} ) ;
out
}
/// The sweep's cheap change check: the file is indexed and unmodified.
pub fn doc_mtime_is ( path : & str , mtime : i64 ) -> bool {
let Some ( s ) = store ( ) else { return false } ;
let Ok ( c ) = s . conn . lock ( ) else { return false } ;
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 )
}
/// 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 ] ) {
let Some ( s ) = store ( ) else { return } ;
let Ok ( c ) = s . conn . lock ( ) else { return } ;
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 ] ) ;
}
}
pub fn doc_remove ( path : & str ) {
let Some ( s ) = store ( ) else { return } ;
let Ok ( c ) = s . conn . lock ( ) else { return } ;
let _ = c . execute ( " DELETE FROM docs WHERE path=?1 " , params! [ path ] ) ;
}
pub fn doc_mtimes ( ) -> Vec < ( String , i64 ) > {
let Some ( s ) = store ( ) else { return vec! [ ] } ;
let Ok ( c ) = s . conn . lock ( ) else { return vec! [ ] } ;
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
}
/// Chunks the background thread has not embedded yet.
pub fn doc_pending ( limit : usize ) -> Vec < ( i64 , String ) > {
let Some ( s ) = store ( ) else { return vec! [ ] } ;
let Ok ( c ) = s . conn . lock ( ) else { return vec! [ ] } ;
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
}
pub fn doc_set_vec ( rowid : i64 , v : & [ f32 ] ) {
let Some ( s ) = store ( ) else { return } ;
let Ok ( c ) = s . conn . lock ( ) else { return } ;
let _ = c . execute ( " UPDATE docs SET vec=?1 WHERE rowid=?2 " , params! [ crate ::embed ::f32s_to_blob ( v ) , rowid ] ) ;
}
/// 「我上個月那份報表」: chunks of the person's indexed files, words first (FTS, then
/// two-character windows for Chinese), meaning when the local model is there.
pub fn docs_search ( query : & str , limit : usize ) -> Vec < ( String , String ) > {
let mut words : Vec < ( String , String ) > = vec! [ ] ; // (path, chunk), best first, no doubles
let Some ( s ) = store ( ) else { return words } ;
let Ok ( c ) = s . conn . lock ( ) else { return words } ;
let q : String = query . chars ( ) . filter ( | ch | * ch ! = '"' ) . collect ::< String > ( ) . split_whitespace ( ) . collect ::< Vec < _ > > ( ) . join ( " " ) ;
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 like the memory shelf.
let mut segs : Vec < String > = vec! [ ] ;
for w in q . split_whitespace ( ) {
let ch : Vec < char > = 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 ) ) ;
}
}
}
if crate ::embed ::enabled ( ) {
if let Some ( v ) = crate ::embed ::embed ( & [ query . to_string ( ) ] ) . and_then ( | mut v | v . pop ( ) ) {
let mut ranked : Vec < ( f32 , String , String ) > = vec! [ ] ;
let _ = c . prepare ( " SELECT path, text, vec FROM docs WHERE vec IS NOT NULL LIMIT 8000 " ) . and_then ( | mut st | {
for x in st . query_map ( [ ] , | r | Ok ( ( r . get ::< _ , String > ( 0 ) ? , r . get ::< _ , String > ( 1 ) ? , r . get ::< _ , Vec < u8 > > ( 2 ) ? ) ) ) ? . flatten ( ) {
let sc = crate ::embed ::cosine ( & v , & crate ::embed ::blob_to_f32s ( & x . 2 ) ) ;
if sc > 0.30 {
ranked . push ( ( sc , x . 0 , x . 1 ) ) ;
}
}
Ok ( ( ) )
} ) ;
ranked . sort_by ( | a , b | b . 0. partial_cmp ( & a . 0 ) . unwrap_or ( std ::cmp ::Ordering ::Equal ) ) ;
let keys : Vec < String > = words . iter ( ) . map ( | ( p , t ) | format! ( " {p} \u{1} {t} " ) ) . collect ( ) ;
let vr : Vec < String > = ranked . into_iter ( ) . map ( | ( _ , p , t ) | format! ( " {p} \u{1} {t} " ) ) . take ( limit * 2 ) . 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 ( ) ;
}
}
words . truncate ( limit ) ;
words
}