//! 記憶庫: every memory a bot has, in the SQLite file beside the audit trail (store.rs). //! //! Three kinds of rows: //! - `fact`: 記得的事 — what the person asked to keep (「記住…」), or a bot kept with remember. //! - `event`: 做過的事 — one line per finished turn, written without anyone asking. //! - `rollup`: older 做過的事, folded by `tidy`: a week per line after 30 days, a month per line //! after half a year. Done here with words and counts — no model, nothing leaves the machine. //! //! Nothing is deleted at once: forgetting, merging and folding put a row in the trash //! (`deleted` = when) for 30 days, where it can be put back; `tidy` empties what is older. //! //! Search is two kinds of evidence, each a 0–1 score: //! - words: the query cut into words (jieba, on the Simplified form so Traditional text cuts as //! well as the dictionary's own), each weighted by how rare it is on this bot's shelf; the //! score is the share of that weight a memory contains. Rows are found through an FTS5 table //! of the same words plus every two-character pair (so a word jieba cut wrongly still meets). //! - meaning: cosine of the local model's vectors (embed.rs), stretched so that the static //! model's "related" (~0.45) and "same thing" (~0.7) land at the middle and the top. //! //! The larger counts, the smaller adds a little: a memory both kinds like comes first. use rusqlite::{params, Connection}; use serde_json::{json, Value}; use std::collections::{HashMap, HashSet}; use std::sync::OnceLock; /// How long the trash keeps what was forgotten, merged or folded. pub const TRASH_DAYS: i64 = 30; /// 做過的事 older than this are folded into one line a week. pub const EVENT_DAYS: i64 = 30; /// Weekly lines older than this are folded into one line a month. pub const WEEK_DAYS: i64 = 180; /// A fact nobody has used (or touched) in this long is offered for cleaning up. pub const STALE_DAYS: i64 = 180; const DAY: i64 = 86_400_000; #[derive(Clone, Debug, PartialEq)] pub struct Mem { pub id: i64, pub bot: u64, pub text: String, pub kind: String, pub created: i64, pub pinned: bool, pub uses: i64, pub last_used: i64, pub deleted: i64, pub superseded_by: i64, pub span: String, } impl Mem { pub fn json(&self) -> Value { json!({"id": self.id, "text": self.text, "kind": self.kind, "created": self.created, "pinned": self.pinned, "uses": self.uses, "last_used": self.last_used, "deleted": self.deleted, "superseded_by": self.superseded_by, "span": self.span}) } } #[derive(Clone, Debug)] pub struct Hit { pub m: Mem, pub score: f32, } const COLS: &str = "id, bot, text, kind, created, pinned, uses, last_used, deleted, superseded_by, span"; fn row(r: &rusqlite::Row) -> rusqlite::Result { Ok(Mem { id: r.get(0)?, bot: r.get::<_, i64>(1)? as u64, text: r.get(2)?, kind: r.get(3)?, created: r.get(4)?, pinned: r.get::<_, i64>(5)? != 0, uses: r.get(6)?, last_used: r.get(7)?, deleted: r.get(8)?, superseded_by: r.get(9)?, span: r.get(10)?, }) } fn many(c: &Connection, sql: &str, p: impl rusqlite::Params) -> Vec { let mut out = vec![]; if let Ok(mut st) = c.prepare(sql) { if let Ok(it) = st.query_map(p, row) { out.extend(it.flatten()); } } out } // ---------- schema ---------- /// New columns and tables on top of store.rs's `memories` (older files just gain them). pub(crate) fn migrate(c: &Connection) { for col in [ "pinned INTEGER NOT NULL DEFAULT 0", "uses INTEGER NOT NULL DEFAULT 0", "last_used INTEGER NOT NULL DEFAULT 0", "deleted INTEGER NOT NULL DEFAULT 0", "superseded_by INTEGER NOT NULL DEFAULT 0", "span TEXT NOT NULL DEFAULT ''", ] { let _ = c.execute_batch(&format!("ALTER TABLE memories ADD COLUMN {col};")); } let _ = c.execute_batch( "CREATE VIRTUAL TABLE IF NOT EXISTS memories_words USING fts5(words, tokenize='unicode61 remove_diacritics 0'); CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE INDEX IF NOT EXISTS memories_alive ON memories(bot, deleted, kind); CREATE TRIGGER IF NOT EXISTS memories_words_ad AFTER DELETE ON memories BEGIN DELETE FROM memories_words WHERE rowid = old.id; END; CREATE TRIGGER IF NOT EXISTS memories_au_text AFTER UPDATE OF text ON memories BEGIN INSERT INTO memories_fts(memories_fts, rowid, text) VALUES ('delete', old.id, old.text); INSERT INTO memories_fts(rowid, text) VALUES (new.id, new.text); END;", ); // Rows from before the word index (or written by an older version): cut them now. let missing: Vec<(i64, String)> = { let mut v = vec![]; if let Ok(mut st) = c.prepare("SELECT id, text FROM memories WHERE id NOT IN (SELECT rowid FROM memories_words)") { if let Ok(it) = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?))) { v.extend(it.flatten()); } } v }; for (id, text) in missing { set_words(c, id, &text); } } fn set_words(c: &Connection, id: i64, text: &str) { let _ = c.execute("DELETE FROM memories_words WHERE rowid=?1", params![id]); let _ = c.execute("INSERT INTO memories_words(rowid, words) VALUES(?1, ?2)", params![id, words_of(text).join(" ")]); } pub fn meta_get(key: &str) -> Option { crate::store::with_conn(|c| c.query_row("SELECT value FROM meta WHERE key=?1", params![key], |r| r.get::<_, String>(0)).ok()).flatten() } pub fn meta_set(key: &str, value: &str) { crate::store::with_conn(|c| c.execute("INSERT INTO meta(key,value) VALUES(?1,?2) ON CONFLICT(key) DO UPDATE SET value=excluded.value", params![key, value])); } // ---------- words ---------- fn jieba() -> &'static jieba_rs::Jieba { static J: OnceLock = OnceLock::new(); J.get_or_init(jieba_rs::Jieba::new) } /// One form for matching: Simplified (the dictionary's own), lower case. fn simple(s: &str) -> String { zhconv::zhconv(s, zhconv::Variant::ZhHans).to_lowercase() } fn is_cjk(c: char) -> bool { matches!(c as u32, 0x3040..=0x30FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xAC00..=0xD7AF | 0xF900..=0xFAFF | 0x20000..=0x2FA1F) } /// Words that say nothing about which memory is meant (in the Simplified form they are matched in). const STOP: &[&str] = &[ "没有", "有没有", "帮我", "一下", "可以", "什么", "怎么", "怎么样", "这个", "那个", "一个", "我们", "你们", "他们", "现在", "还是", "然后", "因为", "所以", "如果", "但是", "已经", "应该", "需要", "知道", "觉得", "是不是", "不是", "就是", "还有", "这样", "那样", "一些", "请问", "谢谢", "好的", "帮忙", "麻烦", "哪里", "为什么", "多少", "记得", "记住", "告诉", "看看", "一样", "东西", "时候", "的话", "不要", "不会", "能不能", "可不可以", "要不要", "有点", "一点", "我的", "你的", "自己", "the", "a", "an", "is", "are", "was", "to", "of", "and", "or", "for", "in", "on", "it", "my", "me", "you", "what", "how", "can", "do", "please", "this", "that", "with", ]; fn tokens(simplified: &str) -> Vec { jieba() .cut_for_search(simplified, true) .into_iter() .map(|t| t.word.trim().to_string()) .filter(|w| w.chars().any(|c| c.is_alphanumeric())) .collect() } /// What a memory is indexed under: its words, and every two-character pair of its CJK runs. pub fn words_of(text: &str) -> Vec { let s = simple(text); let mut out: Vec = tokens(&s); let chars: Vec = s.chars().collect(); for w in chars.windows(2) { if is_cjk(w[0]) && is_cjk(w[1]) { out.push(w.iter().collect()); } } let mut seen = HashSet::new(); out.retain(|w| seen.insert(w.clone())); out } /// What a query looks for: its meaningful words (two characters or more, not in STOP), each with /// a weight factor — 1 for the words themselves, less for the two-character pieces of a longer /// word (高鐵票 also looks for 高鐵, a little). pub fn terms_of(query: &str) -> Vec<(String, f32)> { let s = simple(query); let mut words: Vec = tokens(&s) .into_iter() .filter(|w| { let n = w.chars().count(); let cjk = w.chars().any(is_cjk); (if cjk { n >= 2 } else { n >= 2 && w.chars().any(|c| c.is_alphanumeric()) }) && !STOP.contains(&w.as_str()) }) .collect(); // A pronoun glued to a verb (帮我订 → 我订, 我想, 你查): jieba's cut, not a word anyone means. words.retain(|w| { let c: Vec = w.chars().collect(); !(c.len() == 2 && "我你他她".contains(c[0]) && "订买查找想要看问说做写改加开关用把给让帮去来跟".contains(c[1])) }); let mut seen = HashSet::new(); words.retain(|w| seen.insert(w.clone())); // jieba's search mode gives 有没有 and 没有 both: a shorter word inside a longer one goes, // and comes back below as a lighter piece. let all = words.clone(); words.retain(|w| !all.iter().any(|o| o != w && o.contains(w.as_str()))); words.truncate(12); let mut out: Vec<(String, f32)> = words.iter().map(|w| (w.clone(), 1.0)).collect(); for w in &words { let ch: Vec = w.chars().collect(); if ch.len() >= 3 && ch.iter().all(|c| is_cjk(*c)) { for p in ch.windows(2) { let piece: String = p.iter().collect(); if !STOP.contains(&piece.as_str()) && !out.iter().any(|(t, _)| *t == piece) { out.push((piece, 0.4)); } } } } out } fn fts_quote(term: &str) -> String { format!("\"{}\"", term.replace('"', "")) } // ---------- reading ---------- pub fn get(id: i64) -> Option { crate::store::with_conn(|c| c.query_row(&format!("SELECT {COLS} FROM memories WHERE id=?1"), params![id], row).ok()).flatten() } /// A row by its words (alive or in the trash). pub fn find(bot: u64, text: &str) -> Option { crate::store::with_conn(|c| c.query_row(&format!("SELECT {COLS} FROM memories WHERE bot=?1 AND text=?2"), params![bot as i64, text], row).ok()).flatten() } /// 釘選: the memories carried in every chat (the bot's own and the person's shared ones, bot 0). pub fn pinned(bot: u64) -> Vec { crate::store::with_conn(|c| many(c, &format!("SELECT {COLS} FROM memories WHERE bot IN (?1, 0) AND deleted=0 AND pinned=1 ORDER BY created"), params![bot as i64])).unwrap_or_default() } fn kinds_sql(kinds: &[&str]) -> String { let ok: Vec = kinds.iter().filter(|k| matches!(**k, "fact" | "event" | "rollup")).map(|k| format!("'{k}'")).collect(); if ok.is_empty() { "('fact','event','rollup')".into() } else { format!("({})", ok.join(",")) } } /// Stretch the static model's cosine: ~0.35 is noise, ~0.45 related, 0.70 and up the same thing. fn meaning_score(cos: f32) -> f32 { ((cos - 0.35) / 0.35).clamp(0.0, 1.0) } /// The memories that answer `query`, best first, each with its 0–1 score. pub fn search(bot: u64, query: &str, kinds: &[&str], limit: usize) -> Vec { let q = query.trim(); if q.is_empty() { return vec![]; } let terms = terms_of(q); let qs = simple(q); let qv = if crate::embed::enabled() { crate::embed::embed(&[q.to_string()]).and_then(|mut v| v.pop()) } else { None }; let ks = kinds_sql(kinds); let Some(scored) = crate::store::with_conn(|c| { let bot = bot as i64; let mut words: HashMap = HashMap::new(); if !terms.is_empty() { // How rare each word is here: a word on every line says little. let n: i64 = c.query_row(&format!("SELECT COUNT(*) FROM memories WHERE bot IN (?1,0) AND deleted=0 AND kind IN {ks}"), params![bot], |r| r.get(0)).unwrap_or(0); let df = |t: &str| -> i64 { c.query_row( &format!("SELECT COUNT(*) FROM memories_words w JOIN memories m ON m.id=w.rowid WHERE memories_words MATCH ?1 AND m.bot IN (?2,0) AND m.deleted=0 AND m.kind IN {ks}"), params![fts_quote(t), bot], |r| r.get(0), ) .unwrap_or(0) }; let weight: Vec<(String, f32)> = terms .iter() .map(|(t, f)| { let idf = (1.0 + n.max(1) as f32 / df(t).max(1) as f32).ln(); let long = 1.0 + 0.15 * (t.chars().count() as f32 - 2.0).clamp(0.0, 4.0); (t.clone(), idf * long * f) }) .collect(); // A missing light piece shouldn't sink a line that has the whole word. let total: f32 = weight.iter().zip(&terms).filter(|(_, (_, f))| *f >= 1.0).map(|(w, _)| w.1).sum::().max(1e-6); let expr = terms.iter().map(|(t, _)| fts_quote(t)).collect::>().join(" OR "); if let Ok(mut st) = c.prepare(&format!( "SELECT m.id, w.words, m.text FROM memories_words w JOIN memories m ON m.id=w.rowid WHERE memories_words MATCH ?1 AND m.bot IN (?2,0) AND m.deleted=0 AND m.kind IN {ks} ORDER BY bm25(memories_words) LIMIT 300" )) { if let Ok(it) = st.query_map(params![expr, bot], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?))) { for (id, ws, text) in it.flatten() { let have: HashSet<&str> = ws.split(' ').collect(); // Whole words count fully; a piece only where its word is missing. let mut got = 0f32; for ((t, w), (_, f)) in weight.iter().zip(&terms) { if !have.contains(t.as_str()) { continue; } if *f >= 1.0 { got += w; } else if !terms.iter().any(|(big, bf)| *bf >= 1.0 && big.contains(t.as_str()) && have.contains(big.as_str())) { got += w; } } let mut s = (got / total).min(1.0); if qs.chars().count() >= 2 && simple(&text).contains(&qs) { s = 1.0; } words.insert(id, s); } } } } // The whole query inside a line (a short or oddly cut query). if qs.chars().count() >= 2 { if let Ok(mut st) = c.prepare(&format!("SELECT id FROM memories WHERE bot IN (?1,0) AND deleted=0 AND kind IN {ks} AND (text LIKE '%'||?2||'%' OR text LIKE '%'||?3||'%') LIMIT 100")) { if let Ok(it) = st.query_map(params![bot, q, qs], |r| r.get::<_, i64>(0)) { for id in it.flatten() { words.insert(id, 1.0); } } } } let mut meaning: HashMap = HashMap::new(); if let Some(v) = &qv { if let Ok(mut st) = c.prepare(&format!("SELECT id, vec FROM memories WHERE bot IN (?1,0) AND deleted=0 AND kind IN {ks} AND vec IS NOT NULL")) { if let Ok(it) = st.query_map(params![bot], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Vec>(1)?))) { for (id, b) in it.flatten() { let w = crate::embed::blob_to_f32s(&b); if w.len() == v.len() { let s = meaning_score(crate::embed::cosine(v, &w)); if s > 0.0 { meaning.insert(id, s); } } } } } } let ids: HashSet = words.keys().chain(meaning.keys()).copied().collect(); let mut out: Vec = vec![]; for id in ids { let (a, b) = (words.get(&id).copied().unwrap_or(0.0), meaning.get(&id).copied().unwrap_or(0.0)); let mut s = a.max(b) + 0.15 * a.min(b); if let Ok(m) = c.query_row(&format!("SELECT {COLS} FROM memories WHERE id=?1"), params![id], row) { // What the person said to keep counts a little more than what happened once. if m.kind != "fact" { s *= 0.9; } out.push(Hit { m, score: s.min(1.0) }); } } out.sort_by(|x, y| y.score.partial_cmp(&x.score).unwrap_or(std::cmp::Ordering::Equal).then(y.m.created.cmp(&x.m.created))); out.truncate(limit); out }) else { return vec![]; }; scored } pub struct Page { pub items: Vec, pub total: usize, } /// The memory page's list. `filter`: all, fact, event (with the folded weeks and months), /// pinned, trash. With words in `q`, best matches first; otherwise pinned first, newest next. pub fn list(bot: u64, filter: &str, q: &str, offset: usize, limit: usize) -> Page { let q = q.trim(); let b = bot as i64; if filter == "trash" { let like = format!("%{q}%"); let all = crate::store::with_conn(|c| many(c, &format!("SELECT {COLS} FROM memories WHERE bot=?1 AND deleted>0 AND (?2='' OR text LIKE ?3) ORDER BY deleted DESC"), params![b, q, like])).unwrap_or_default(); let total = all.len(); return Page { items: all.into_iter().skip(offset).take(limit).collect(), total }; } let (kinds, pinned_only): (&[&str], bool) = match filter { "fact" => (&["fact"], false), "event" => (&["event", "rollup"], false), "pinned" => (&["fact", "event", "rollup"], true), _ => (&["fact", "event", "rollup"], false), }; if !q.is_empty() { let mut hits: Vec = search(bot, q, kinds, 400).into_iter().filter(|h| h.score >= 0.15 && h.m.bot == bot).map(|h| h.m).collect(); if pinned_only { hits.retain(|m| m.pinned); } let total = hits.len(); return Page { items: hits.into_iter().skip(offset).take(limit).collect(), total }; } let ks = kinds_sql(kinds); let pin = if pinned_only { "AND pinned=1" } else { "" }; crate::store::with_conn(|c| { let total: i64 = c.query_row(&format!("SELECT COUNT(*) FROM memories WHERE bot=?1 AND deleted=0 AND kind IN {ks} {pin}"), params![b], |r| r.get(0)).unwrap_or(0); let items = many(c, &format!("SELECT {COLS} FROM memories WHERE bot=?1 AND deleted=0 AND kind IN {ks} {pin} ORDER BY pinned DESC, created DESC LIMIT ?2 OFFSET ?3"), params![b, limit as i64, offset as i64]); Page { items, total: total as usize } }) .unwrap_or(Page { items: vec![], total: 0 }) } /// Counts for the page's header. pub fn stats(bot: u64) -> Value { // (Before taking the connection: pinned() takes it too, and it isn't re-entrant.) let pinned_tokens = crate::agent::estimate_tokens(&pinned(bot).iter().map(|m| m.text.as_str()).collect::>().join("\n")); crate::store::with_conn(|c| { let b = bot as i64; let count = |sql: &str| -> i64 { c.query_row(sql, params![b], |r| r.get(0)).unwrap_or(0) }; let bytes: i64 = c.query_row("SELECT COALESCE(SUM(LENGTH(CAST(text AS BLOB)) + COALESCE(LENGTH(vec),0)),0) FROM memories WHERE bot=?1", params![b], |r| r.get(0)).unwrap_or(0); json!({ "facts": count("SELECT COUNT(*) FROM memories WHERE bot=?1 AND deleted=0 AND kind='fact'"), "events": count("SELECT COUNT(*) FROM memories WHERE bot=?1 AND deleted=0 AND kind='event'"), "rollups": count("SELECT COUNT(*) FROM memories WHERE bot=?1 AND deleted=0 AND kind='rollup'"), "pinned": count("SELECT COUNT(*) FROM memories WHERE bot=?1 AND deleted=0 AND pinned=1"), "trash": count("SELECT COUNT(*) FROM memories WHERE bot=?1 AND deleted>0"), "vectors": count("SELECT COUNT(*) FROM memories WHERE bot=?1 AND deleted=0 AND vec IS NOT NULL"), "bytes": bytes, "pinned_tokens": pinned_tokens, }) }) .unwrap_or(json!({})) } // ---------- writing ---------- /// Add a memory, or put back the same words from the trash. The row's id. pub fn add(bot: u64, text: &str, kind: &str) -> Option { let text = text.trim(); if text.is_empty() { return None; } crate::store::with_conn(|c| { let id: i64 = c .query_row( "INSERT INTO memories(bot,text,kind,created) VALUES(?1,?2,?3,?4) ON CONFLICT(bot,text) DO UPDATE SET deleted=0, superseded_by=0 RETURNING id", params![bot as i64, text, kind, crate::model::now_ms()], |r| r.get(0), ) .ok()?; set_words(c, id, text); Some(id) }) .flatten() } /// Make sure a fact from the settings list is on the shelf, without bringing back one the person /// put in the trash (the list on a screen may be a moment behind). pub fn ensure(bot: u64, text: &str) { let text = text.trim(); if text.is_empty() { return; } crate::store::with_conn(|c| { if 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()]).unwrap_or(0) == 1 { set_words(c, c.last_insert_rowid(), text); } }); } pub fn set_pinned(id: i64, on: bool) -> Option { crate::store::with_conn(|c| c.execute("UPDATE memories SET pinned=?1 WHERE id=?2", params![on as i64, id])); get(id) } /// New words for a memory. Words another memory of the bot already has: that one stays, this one /// goes to the trash (the same thing twice is a merge). pub fn edit(id: i64, text: &str) -> Result<(Mem, Mem), String> { let text = text.trim(); if text.is_empty() { return Err("內容是空的".into()); } let old = get(id).ok_or("找不到這一條")?; if old.text == text { return Ok((old.clone(), old)); } if let Some(other) = find(old.bot, text) { if other.deleted == 0 { trash(id, other.id); return Ok((old, other)); } crate::store::with_conn(|c| c.execute("DELETE FROM memories WHERE id=?1", params![other.id])); } crate::store::with_conn(|c| { let _ = c.execute("UPDATE memories SET text=?1, vec=NULL WHERE id=?2", params![text, id]); set_words(c, id, text); }); let new = get(id).ok_or("找不到這一條")?; Ok((old, new)) } /// Into the trash (restorable for TRASH_DAYS). `by`: the memory that took its place, or 0. pub fn trash(id: i64, by: i64) -> Option { crate::store::with_conn(|c| c.execute("UPDATE memories SET deleted=?1, superseded_by=?2 WHERE id=?3 AND deleted=0", params![crate::model::now_ms(), by, id])); get(id) } pub fn restore(id: i64) -> Option { crate::store::with_conn(|c| c.execute("UPDATE memories SET deleted=0, superseded_by=0 WHERE id=?1", params![id])); get(id) } /// Carried into a chat: counted, so the page can say what is used and what never is. pub fn used(ids: &[i64]) { let now = crate::model::now_ms(); crate::store::with_conn(|c| { for id in ids { let _ = c.execute("UPDATE memories SET uses=uses+1, last_used=?1 WHERE id=?2", params![now, id]); } }); } /// Empty the trash for good: everything older than TRASH_DAYS (or all of it, for one bot). pub fn purge(bot: Option, older_than: i64) -> usize { crate::store::with_conn(|c| match bot { Some(b) => c.execute("DELETE FROM memories WHERE bot=?1 AND deleted>0 AND deleted c.execute("DELETE FROM memories WHERE deleted>0 AND deleted Vec<(i64, String)> { crate::store::with_conn(|c| { let mut out = vec![]; if let Ok(mut st) = c.prepare("SELECT id, text FROM memories WHERE vec IS NULL AND deleted=0 ORDER BY created DESC LIMIT ?1") { if let Ok(it) = st.query_map(params![limit as i64], |r| Ok((r.get(0)?, r.get(1)?))) { out.extend(it.flatten()); } } out }) .unwrap_or_default() } pub fn set_vecs(rows: &[(i64, Vec)]) { crate::store::with_conn(|c| { let _ = c.execute_batch("BEGIN"); for (id, v) in rows { let _ = c.execute("UPDATE memories SET vec=?1 WHERE id=?2", params![crate::embed::f32s_to_blob(v), id]); } let _ = c.execute_batch("COMMIT"); }); } fn vec_of(c: &Connection, id: i64) -> Option> { c.query_row("SELECT vec FROM memories WHERE id=?1 AND vec IS NOT NULL", params![id], |r| r.get::<_, Vec>(0)).ok().map(|b| crate::embed::blob_to_f32s(&b)) } // ---------- cleaning up ---------- fn word_set(c: &Connection, id: i64) -> HashSet { c.query_row("SELECT words FROM memories_words WHERE rowid=?1", params![id], |r| r.get::<_, String>(0)).map(|w| w.split(' ').filter(|x| !x.is_empty()).map(String::from).collect()).unwrap_or_default() } fn jaccard(a: &HashSet, b: &HashSet) -> f32 { if a.is_empty() || b.is_empty() { return 0.0; } a.intersection(b).count() as f32 / a.union(b).count() as f32 } /// What the page offers to clean up: facts that say the same thing, facts nobody has used in /// half a year, and how many lines the next fold will take in. pub fn suggestions(bot: u64, now: i64) -> Value { crate::store::with_conn(|c| { let b = bot as i64; let facts = many(c, &format!("SELECT {COLS} FROM memories WHERE bot=?1 AND deleted=0 AND kind='fact' ORDER BY created DESC LIMIT 400"), params![b]); let sets: Vec> = facts.iter().map(|m| word_set(c, m.id)).collect(); let vecs: Vec>> = facts.iter().map(|m| vec_of(c, m.id)).collect(); let mut dupes = vec![]; let mut paired: HashSet = HashSet::new(); 'outer: for i in 0..facts.len() { for j in i + 1..facts.len() { if paired.contains(&facts[i].id) || paired.contains(&facts[j].id) { continue; } let jac = jaccard(&sets[i], &sets[j]); let cos = match (&vecs[i], &vecs[j]) { (Some(x), Some(y)) if x.len() == y.len() => crate::embed::cosine(x, y), _ => 0.0, }; // Or one says all the other says, and more (the newer usually adds a detail). let (small, big) = if sets[i].len() <= sets[j].len() { (&sets[i], &sets[j]) } else { (&sets[j], &sets[i]) }; let inside = small.len() >= 3 && small.intersection(big).count() as f32 >= 0.9 * small.len() as f32; if jac >= 0.7 || cos > 0.9 || inside { paired.insert(facts[i].id); paired.insert(facts[j].id); // The newer words first: they are the ones to keep, usually. dupes.push(json!([facts[i].json(), facts[j].json()])); if dupes.len() >= 10 { break 'outer; } } } } let stale: Vec = facts.iter().filter(|m| !m.pinned && m.created.max(m.last_used) < now - STALE_DAYS * DAY).take(30).map(|m| m.json()).collect(); let old_events: i64 = c.query_row("SELECT COUNT(*) FROM memories WHERE bot=?1 AND deleted=0 AND kind='event' AND created String { let t = event.split_once(':').map(|x| x.1).unwrap_or(event); let t = t.split(" → ").next().unwrap_or(t).trim(); t.chars().take(28).collect::().trim().to_string() } /// A folded line's items back: 「…(14 件):整理照片 ×3、修 Docker」 → [(整理照片, 3), (修 Docker, 1)] /// and its total. fn items_of(rollup: &str) -> (Vec<(String, u32)>, u32) { let total = rollup.split_once('(').and_then(|x| x.1.split_once(" 件)")).and_then(|x| x.0.trim().parse().ok()).unwrap_or(0); let body = rollup.split_once("件):").map(|x| x.1).unwrap_or(""); let body = body.split('…').next().unwrap_or(""); let mut items = vec![]; for it in body.split('、') { let it = it.trim().trim_end_matches('…'); if it.is_empty() || it.starts_with("還有") { continue; } match it.rsplit_once(" ×") { Some((a, n)) if n.parse::().is_ok() => items.push((a.to_string(), n.parse().unwrap_or(1))), _ => items.push((it.to_string(), 1)), } } (items, total) } /// Most a folded line says (characters). const FOLD_CHARS: usize = 400; /// Group like with like — words that mostly match, or (with the local model) the same meaning — /// most frequent first: one folded line. fn fold_line(label: &str, items: &[(String, u32)], total: u32) -> String { let asks: Vec = items.iter().map(|(a, _)| a.replace('、', ",")).collect(); let vecs: Option>> = if crate::embed::enabled() { crate::embed::embed(&asks) } else { None }; let mut groups: Vec<(String, HashSet, Option>, u32)> = vec![]; for (i, ask) in asks.iter().enumerate() { if ask.is_empty() { continue; } let n = items[i].1; let ws: HashSet = words_of(ask).into_iter().collect(); let v = vecs.as_ref().and_then(|vs| vs.get(i).cloned()); let same = |g: &(String, HashSet, Option>, u32)| { g.0 == *ask || jaccard(&g.1, &ws) >= 0.5 || matches!((&g.2, &v), (Some(a), Some(b)) if crate::embed::cosine(a, b) >= 0.8) }; match groups.iter_mut().find(|g| same(g)) { Some(g) => g.3 += n, None => groups.push((ask.clone(), ws, v, n)), } } groups.sort_by(|a, b| b.3.cmp(&a.3)); let mut s = format!("{label}({total} 件):"); let mut shown = 0u32; for (i, (ask, _, _, n)) in groups.iter().enumerate() { let piece = if *n > 1 { format!("{ask} ×{n}") } else { ask.clone() }; if s.chars().count() + piece.chars().count() + 12 > FOLD_CHARS { break; } if i > 0 { s.push('、'); } s.push_str(&piece); shown += n; } if shown < total { s.push_str(&format!("…還有 {} 件", total - shown)); } s } #[derive(Default, Debug, PartialEq)] pub struct Tidy { pub events: usize, pub weeks: usize, pub purged: usize, } /// 整理: 做過的事 older than EVENT_DAYS become a line a week (whole weeks only, so a week is folded /// once), weekly lines older than WEEK_DAYS a line a month, and the trash forgets what is older /// than TRASH_DAYS. What was folded goes to the trash itself (restorable), pointing at its line. pub fn tidy(bot: Option, timezone: &str, now: i64) -> Tidy { use chrono::{Datelike, TimeZone}; let tz: chrono_tz::Tz = timezone.parse().unwrap_or(chrono_tz::Tz::UTC); let day_of = |ms: i64| tz.timestamp_millis_opt(ms).single().map(|t| t.date_naive()).unwrap_or_default(); let start_ms = |d: chrono::NaiveDate| tz.from_local_datetime(&d.and_hms_opt(0, 0, 0).unwrap_or_default()).earliest().map(|t| t.timestamp_millis()).unwrap_or(0); let mut out = Tidy::default(); let bots: Vec = match bot { Some(b) => vec![b as i64], None => crate::store::with_conn(|c| { let mut v = vec![]; if let Ok(mut st) = c.prepare("SELECT DISTINCT bot FROM memories WHERE deleted=0 AND kind IN ('event','rollup')") { if let Ok(it) = st.query_map([], |r| r.get::<_, i64>(0)) { v.extend(it.flatten()); } } v }) .unwrap_or_default(), }; for b in bots { // Weeks (Monday first) whose last day is past the line. let events = crate::store::with_conn(|c| many(c, &format!("SELECT {COLS} FROM memories WHERE bot=?1 AND deleted=0 AND kind='event' AND created)> = vec![]; for m in events { let d = day_of(m.created); let monday = d - chrono::Duration::days(d.weekday().num_days_from_monday() as i64); match weeks.iter_mut().find(|w| w.0 == monday) { Some(w) => w.1.push(m), None => weeks.push((monday, vec![m])), } } for (monday, ms) in weeks { let sunday = monday + chrono::Duration::days(6); if start_ms(sunday + chrono::Duration::days(1)) > now - EVENT_DAYS * DAY { continue; } let items: Vec<(String, u32)> = ms.iter().map(|m| (ask_of(&m.text), 1)).collect(); let label = format!("{}/{}–{}/{} 做過的事", monday.month(), monday.day(), sunday.month(), sunday.day()); let line = fold_line(&label, &items, ms.len() as u32); let Some(id) = add(b as u64, &line, "rollup") else { continue }; crate::store::with_conn(|c| { let _ = c.execute("UPDATE memories SET created=?1, span=?2 WHERE id=?3", params![start_ms(monday), format!("week:{monday}"), id]); }); for m in &ms { trash(m.id, id); } out.events += ms.len(); } // Months, from weekly lines old enough. let wk = crate::store::with_conn(|c| many(c, &format!("SELECT {COLS} FROM memories WHERE bot=?1 AND deleted=0 AND kind='rollup' AND span LIKE 'week:%' AND created)> = vec![]; for m in wk { let d = day_of(m.created); match months.iter_mut().find(|x| x.0 == (d.year(), d.month())) { Some(x) => x.1.push(m), None => months.push(((d.year(), d.month()), vec![m])), } } for ((y, mo), ms) in months { let first = chrono::NaiveDate::from_ymd_opt(y, mo, 1).unwrap_or_default(); let next = if mo == 12 { chrono::NaiveDate::from_ymd_opt(y + 1, 1, 1) } else { chrono::NaiveDate::from_ymd_opt(y, mo + 1, 1) }.unwrap_or_default(); if start_ms(next) > now - WEEK_DAYS * DAY { continue; } let mut items = vec![]; let mut total = 0; for m in &ms { let (it, n) = items_of(&m.text); items.extend(it); total += n; } let line = fold_line(&format!("{y} 年 {mo} 月做過的事"), &items, total); let Some(id) = add(b as u64, &line, "rollup") else { continue }; crate::store::with_conn(|c| { let _ = c.execute("UPDATE memories SET created=?1, span=?2 WHERE id=?3", params![start_ms(first), format!("month:{y}-{mo:02}"), id]); }); for m in &ms { trash(m.id, id); } out.weeks += ms.len(); } } out.purged = purge(bot, now - TRASH_DAYS * DAY); out } /// A shelf to look at (screenshot mode): facts — two pinned, two saying the same thing, one /// untouched for half a year — recent 做過的事, old ones waiting to be folded, and a folded week. pub fn seed_demo(bot: u64, now: i64) { let set = |id: Option, created: i64, uses: i64, last: i64, pinned: bool| { if let Some(id) = id { crate::store::with_conn(|c| c.execute("UPDATE memories SET created=?1, uses=?2, last_used=?3, pinned=?4 WHERE id=?5", params![created, uses, last, pinned as i64, id])); } }; let d = |n: i64| now - n * DAY; set(add(bot, "回報時先講結論,最多三段;程式碼範例用 Rust", "fact"), d(40), 31, d(0), true); set(add(bot, "咖啡不加糖,要熱的", "fact"), d(25), 6, d(2), true); set(add(bot, "我喜歡靠窗的座位,長途航班也是", "fact"), d(60), 4, d(3), false); set(add(bot, "我住在台南,常搭高鐵去台北開會", "fact"), d(90), 9, d(1), false); set(add(bot, "週五下午不要排會議", "fact"), d(30), 2, d(8), false); set(add(bot, "週五下午不要排會議喔,那是讀書時間", "fact"), d(6), 0, 0, false); set(add(bot, "公司的 VPN 用 Tailscale,伺服器在 10.0.0.25", "fact"), d(14), 3, d(5), false); set(add(bot, "以前用 Windows 7 的筆電(已經換掉了)", "fact"), d(220), 0, 0, false); set(add(bot, "11-10:幫我追蹤台灣 FSD 狀況 → 交通部希望年底前完成審查,頁面已更新", "event"), d(1), 1, d(0), false); set(add(bot, "11-08:訂週五去台北的高鐵 → 訂好 9:00 靠窗", "event"), d(3), 0, 0, false); set(add(bot, "11-05:整理下載資料夾的照片 → 依月份分好 3 個資料夾", "event"), d(6), 0, 0, false); for (i, t) in ["整理照片", "查高鐵時刻", "整理照片資料夾", "修伺服器的 Docker", "寫週報"].iter().enumerate() { set(add(bot, &format!("09-{:02}:{t} → 好了", 20 + i), "event"), d(45 + i as i64), 0, 0, false); } let id = add(bot, "9/1–9/7 做過的事(6 件):整理照片 ×2、寫週報 ×2、查高鐵時刻、修 Docker", "rollup"); set(id, d(70), 0, 0, false); if let Some(id) = id { crate::store::with_conn(|c| c.execute("UPDATE memories SET span='week:2026-09-01' WHERE id=?1", params![id])); } if let Some(id) = add(bot, "使用者想先用台中當大腦(後來改成伺服器)", "fact") { trash(id, 0); } } #[cfg(test)] mod tests { use super::*; #[test] fn traditional_text_cuts_into_words_that_meet() { let w = words_of("我喜歡靠窗的座位,長途航班也是"); for x in ["靠窗", "座位", "长途", "航班"] { assert!(w.contains(&x.to_string()), "{x} in {w:?}"); } // A query's filler words don't count; the meaningful ones do. let t: Vec = terms_of("有沒有靠窗的位子?").into_iter().map(|x| x.0).collect(); assert!(t.contains(&"靠窗".to_string()) && !t.iter().any(|x| x == "没有" || x == "有没有"), "{t:?}"); assert_eq!(terms_of("Docker 壞掉了"), vec![("docker".to_string(), 1.0), ("坏掉".to_string(), 1.0)]); // A longer word also looks for its pieces, lightly. let t = terms_of("高鐵票"); assert!(t.contains(&("高铁票".to_string(), 1.0)) || t.contains(&("高铁".to_string(), 1.0)), "{t:?}"); } #[test] fn the_shelf_answers_with_scores() { let bot = 7101; add(bot, "我喜歡靠窗的座位,長途航班也是", "fact"); add(bot, "週五下午不開會", "fact"); add(bot, "咖啡不加糖", "fact"); add(bot, "伺服器的 Docker 容器用 sudo 會失敗", "fact"); add(7102, "別的 Bot:咖啡要加奶", "fact"); let top = |q: &str| search(bot, q, &["fact"], 5); let h = top("有沒有靠窗的位子"); assert!(h[0].m.text.contains("靠窗") && h[0].score >= 0.5, "{h:?}"); let h = top("咖啡"); assert_eq!(h[0].m.text, "咖啡不加糖"); assert!(h[0].score > 0.9 && !h.iter().any(|x| x.m.text.contains("加奶")), "another bot's memory stays its own: {h:?}"); let h = top("Docker 壞掉了"); assert!(h[0].m.text.contains("Docker") && h[0].score >= 0.5, "{h:?}"); // Nothing in common: nothing, rather than the newest line. assert!(top("寫一首關於海的詩").iter().all(|x| x.score < 0.2), "{:?}", top("寫一首關於海的詩")); } #[test] fn forgetting_is_a_trash_you_can_take_back() { let bot = 7103; let id = add(bot, "我住在台南", "fact").unwrap(); trash(id, 0); assert!(search(bot, "台南", &["fact"], 5).is_empty(), "the trash isn't searched"); assert_eq!(list(bot, "trash", "", 0, 10).total, 1); // The settings list a moment behind doesn't bring it back… ensure(bot, "我住在台南"); assert!(get(id).unwrap().deleted > 0); // …but saying it again (or 還原) does. restore(id); assert_eq!(search(bot, "台南", &["fact"], 5)[0].m.id, id); // An edit to words another memory has is a merge. let other = add(bot, "我搬到台北了", "fact").unwrap(); let (_, kept) = edit(id, "我搬到台北了").unwrap(); assert_eq!(kept.id, other); assert_eq!(get(id).unwrap().superseded_by, other); } #[test] fn old_events_fold_into_weeks_then_months() { let bot = 7104; let tz = "Asia/Taipei"; let now = chrono::DateTime::parse_from_rfc3339("2026-11-11T12:00:00+08:00").unwrap().timestamp_millis(); let at = |s: &str| chrono::DateTime::parse_from_rfc3339(s).unwrap().timestamp_millis(); let ev = |t: &str, when: &str| { let id = add(bot, t, "event").unwrap(); crate::store::with_conn(|c| c.execute("UPDATE memories SET created=?1 WHERE id=?2", params![at(when), id])); id }; // A week in early April (Mon 4/6 – Sun 4/12), long past both lines. ev("04-06:幫我整理照片 → 好了", "2026-04-06T10:00:00+08:00"); ev("04-07:幫我整理照片資料夾 → 整理好了", "2026-04-07T10:00:00+08:00"); ev("04-08:修伺服器的 Docker → 修好了", "2026-04-08T10:00:00+08:00"); // Last week of September: past 30 days, not past half a year. ev("09-29:查高鐵時刻 → 給了三班", "2026-09-29T10:00:00+08:00"); // Yesterday: stays as it is. let fresh = ev("11-10:寫週報 → 寫好了", "2026-11-10T10:00:00+08:00"); let r = tidy(Some(bot), tz, now); assert_eq!(r.events, 4, "{r:?}"); let page = list(bot, "event", "", 0, 20); let texts: Vec<&str> = page.items.iter().map(|m| m.text.as_str()).collect(); assert!(texts.iter().any(|t| t.starts_with("9/28–10/4 做過的事(1 件):查高鐵時刻")), "{texts:?}"); // April's week went one step further: into its month (weeks older than half a year). assert!(texts.iter().any(|t| t.starts_with("2026 年 4 月做過的事(3 件):") && t.contains("整理照片 ×2") && t.contains("Docker")), "{texts:?}"); assert!(texts.contains(&"11-10:寫週報 → 寫好了")); assert_eq!(get(fresh).unwrap().deleted, 0); // Folded lines wait in the trash, pointing at their line. let trashed = list(bot, "trash", "", 0, 20); assert!(trashed.items.iter().all(|m| m.superseded_by > 0), "{:?}", trashed.items); // A second run finds nothing more to do. assert_eq!(tidy(Some(bot), tz, now).events, 0); } #[test] fn folded_lines_read_back() { let (items, total) = items_of("2026 年 4 月做過的事(14 件):整理照片 ×3、修 Docker…還有 10 件"); assert_eq!(total, 14); assert_eq!(items, vec![("整理照片".to_string(), 3), ("修 Docker".to_string(), 1)]); assert_eq!(ask_of("04-06:幫我整理照片 → 好了"), "幫我整理照片"); } #[test] fn duplicates_and_forgotten_facts_are_offered() { let bot = 7105; add(bot, "週五下午不要排會議", "fact"); add(bot, "週五下午不要排會議喔", "fact"); let old = add(bot, "以前用 Windows 7", "fact").unwrap(); crate::store::with_conn(|c| c.execute("UPDATE memories SET created=1 WHERE id=?1", params![old])); let s = suggestions(bot, crate::model::now_ms()); assert_eq!(s["dupes"].as_array().unwrap().len(), 1, "{s}"); assert!(s["stale"].as_array().unwrap().iter().any(|m| m["id"] == old), "{s}"); } }