Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Truth Ledger: outside facts can't be laundered, relabelled or erased
Lin (kwant bot)7283c6862a84
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2fd6424e..41788402 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -57,6 +57,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).page; screen readers read it as "Made in Germany with love".### Fixed+- **Truth Ledger: outside facts can't be laundered or erased.** A bot editing a note that ever came+ from outside text, or re-adding its exact text after deleting it, lands it as proposed again, even+ after you accepted an earlier version. Only you can take a fact out of "outside", and your decision+ can't be overruled afterwards. Facts and their history can no longer be deleted except by deleting+ their bot or undoing their import.- **A CAPTCHA nobody solved is always reported as timed out.** When the time limit ran out, the botcould sometimes be told to keep waiting for a step that was already over, if the page watcher wasslow on a busy machine. The bot's own wait now closes the step as timed out once the limit hasdiff --git a/docs/mission-control.md b/docs/mission-control.mdindex 7acc2f76..de27e2f9 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -1036,10 +1036,13 @@ into `knowledge_facts`, so any writer (an older binary included) is seen; no row(`source_kind` `bot` with the turn id, or `import` with the import id). The memory row is unchanged:an import's note keeps `source = 'user'` and `imported = 1`, and the bot still sees the note (D3).-An edit supersedes the fact in force and adds a new one (`superseded_by` points to it); a bot rewriting-an `outside` note that the person hasn't accepted keeps it `outside`, so a later clean turn can't launder-it. A delete supersedes the fact with no successor. One fact per memory is in force at a time; the rest-are its history. Deleting a bot, or undoing an import, deletes its facts and their events.+An edit supersedes the fact in force and adds a new one (`superseded_by` points to it). A bot rewriting+a note whose history ever had an `outside` fact lands `outside`/`proposed` again, even in a clean turn+and even after the person accepted an earlier version; so does a bot re-adding the exact text of an+`outside` fact it had (delete, then add). A delete supersedes the fact with no successor. One fact per+memory is in force at a time; the rest are its history. Deleting a bot, or undoing an import, deletes+its facts and their events: those two paths hold a row in `fact_purge_permits` for the bot inside their+transaction, and any other `DELETE` of a fact or of a living fact's event is refused.**Taint.** A turn is tainted once it calls a tool that brings outside text in: web fetch or search, ashell, a sub-agent, any MCP server other than kwant's own, the browser, `read_attachment`, `mcp_search`@@ -1048,8 +1051,11 @@ that turn is `outside`. The bit lives in memory for the turn and is cleared at i**Rules in the database.** `superseded` is final; accepting a `proposed` or `disputed` fact needs`decided_by` and `decided_at`; an `outside` fact is accepted only by the person, and so is any team or-space fact that is accepted or `outside`. `fact_events` is append-only (`created`, `superseded`,-`pinned`, `unpinned`, `removed`, `backfilled`, `accepted`, `rejected`).+space fact that is accepted or `outside`. A fact's trust leaves `outside` only with `decided_by =+'person'`, and once the person decided a fact nothing changes `decided_by` again, so an ex-outside fact+never ends up `decided_by = 'evidence'`. `fact_events` is append-only (`created`, `superseded`,+`pinned`, `unpinned`, `removed`, `backfilled`, `accepted`, `rejected`). The triggers are recreated on+every start, in one transaction, so a database an earlier build migrated gets the current rules.**Routes, all person only** (a bot's token gets a 403 on every one, reads included; bots get factsthrough tools in C2):@@ -1065,9 +1071,13 @@ through tools in C2):`fact_disputes`, `fact_events` and `fact_provenance` (a write's pending trust, consumed by the mirror).The first start backfills every memory that has no fact (an `imported` note as `outside`/`proposed`,others by source) with a `backfilled` event; running it again adds nothing. Older binaries ignore the-tables and their memory writes are still mirrored.+tables and their memory writes are still mirrored. **Rollback:** releases before the ledger (2b936e4)+need nothing. A703732 deletes a bot's facts without a permit, so before rolling back to it run+`DELETE_GUARDS_DOWN` (drops `knowledge_facts_no_delete` and `fact_events_no_delete`), or deleting a bot+fails; the next start of a later build puts them back.**Known limits.** Taint is per turn and coarse: a tool call that was asked about and then denied still-taints, and a bot can save text it read in an earlier turn from a clean one. Notes from before the+taints, and a bot can save text it read in an earlier turn from a clean one, or re-add a removed+`outside` note in other words. Notes from before theledger can't say whether their turn read outside text, so they are `bot`/`accepted`. An edited ordeleted note keeps its old text as history in the ledger until the bot is deleted.diff --git a/src/db/truth_ledger.rs b/src/db/truth_ledger.rsindex 0a1bf1ae..3cbae87e 100644--- a/src/db/truth_ledger.rs+++ b/src/db/truth_ledger.rs@@ -86,6 +86,11 @@ const TABLES: &[&str] = &[source_kind TEXT NOT NULL CHECK (source_kind IN ('person', 'bot', 'import', 'check', 'task')),source_ref TEXT)",+ // Lets the privacy paths (a deleted bot, an undone import) delete that bot's facts and events;+ // written and cleared inside the deletion's transaction (see [`PURGE_BOT_FACTS`]).+ "CREATE TABLE IF NOT EXISTS fact_purge_permits (scope_id TEXT PRIMARY KEY)",+ // A bot re-adding a note it removed: finds the outside fact with the same text+ "CREATE INDEX IF NOT EXISTS knowledge_facts_outside_text ON knowledge_facts (scope_id, statement) WHERE trust = 'outside'",];/// The new fact of a memory row `new`: trust and source from its provenance row, else from the@@ -107,8 +112,13 @@ fn triggers() -> Vec<String> {let now = "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";let live = LIVE;vec![+ // A bot re-adding the exact text of an outside fact it had (delete, then add) keeps it outside.format!("CREATE TRIGGER IF NOT EXISTS kwant_memories_ledger_ai AFTER INSERT ON kwant_memories BEGIN \+ INSERT OR IGNORE INTO fact_provenance (memory_id, trust, source_kind, source_ref) \+ SELECT new.id, 'outside', f.source_kind, f.source_ref FROM knowledge_facts f \+ WHERE new.source = 'agent' AND f.trust = 'outside' AND f.scope = 'bot' AND f.scope_id = new.kwant_id \+ AND f.statement = new.text ORDER BY f.created_at DESC, f.rowid DESC LIMIT 1; \{insert} \INSERT INTO fact_events (fact_id, kind, actor, created_at) \SELECT id, 'created', CASE source_kind WHEN 'person' THEN 'person' WHEN 'import' THEN 'import' ELSE new.kwant_id END, {now} \@@ -117,14 +127,15 @@ fn triggers() -> Vec<String> {insert = MIRROR_INSERT.replace("{valid_from}", &format!("COALESCE(new.created_at, {now})")),),// A changed note: the fact in force goes `superseded`, a new one replaces it (history kept).- // A bot editing a note that came from outside text keeps it outside, even in a clean turn.+ // A bot editing a note that ever came from outside text keeps it outside, even in a clean+ // turn and even after the person accepted an earlier version.format!("CREATE TRIGGER IF NOT EXISTS kwant_memories_ledger_au AFTER UPDATE OF text, source, imported ON kwant_memories \WHEN old.text IS NOT new.text OR old.source IS NOT new.source OR old.imported IS NOT new.imported BEGIN \INSERT OR IGNORE INTO fact_provenance (memory_id, trust, source_kind, source_ref) \SELECT new.id, 'outside', f.source_kind, f.source_ref FROM knowledge_facts f \- WHERE new.source = 'agent' AND f.trust = 'outside' AND f.status <> 'accepted' \- AND f.id = (SELECT id FROM knowledge_facts WHERE memory_id = new.id ORDER BY created_at DESC, rowid DESC LIMIT 1); \+ WHERE new.source = 'agent' AND f.memory_id = new.id AND f.trust = 'outside' \+ ORDER BY f.created_at DESC, f.rowid DESC LIMIT 1; \INSERT INTO fact_events (fact_id, kind, actor, created_at) \SELECT id, 'superseded', CASE WHEN new.source = 'agent' THEN new.kwant_id ELSE 'person' END, {now} \FROM knowledge_facts WHERE memory_id = new.id AND status IN {live}; \@@ -177,12 +188,25 @@ fn triggers() -> Vec<String> {OR (new.scope <> 'bot' AND (new.trust = 'outside' OR new.status = 'accepted') AND new.decided_by IS NOT 'person') BEGIN \SELECT RAISE(ABORT, 'outside or shared facts are accepted only by the person'); END".into(),+ // Outside text stays outside unless the person decides; and nothing overrules the person+ // afterwards, so an ex-outside fact can't end up `decided_by = 'evidence'`.+ "CREATE TRIGGER IF NOT EXISTS knowledge_facts_trust BEFORE UPDATE ON knowledge_facts \+ WHEN (old.trust = 'outside' AND new.trust IS NOT 'outside' AND new.decided_by IS NOT 'person') \+ OR (old.decided_by = 'person' AND new.decided_by IS NOT 'person') BEGIN \+ SELECT RAISE(ABORT, 'only the person takes a fact out of outside, and their decision stands'); END"+ .into(),"CREATE TRIGGER IF NOT EXISTS fact_events_no_update BEFORE UPDATE ON fact_events BEGIN \SELECT RAISE(ABORT, 'fact_events is append-only'); END".into(),- // Only the events of a fact that no longer exists (a deleted bot's) may go+ // Facts and their events are deleted only by the privacy paths, which hold a permit for the+ // bot (PURGE_BOT_FACTS). Events of a fact that is already gone may go too.+ "CREATE TRIGGER IF NOT EXISTS knowledge_facts_no_delete BEFORE DELETE ON knowledge_facts \+ WHEN NOT (old.scope = 'bot' AND EXISTS (SELECT 1 FROM fact_purge_permits WHERE scope_id = old.scope_id)) BEGIN \+ SELECT RAISE(ABORT, 'facts are deleted only with their bot or import'); END"+ .into(),"CREATE TRIGGER IF NOT EXISTS fact_events_no_delete BEFORE DELETE ON fact_events \- WHEN EXISTS (SELECT 1 FROM knowledge_facts WHERE id = old.fact_id) BEGIN \+ WHEN EXISTS (SELECT 1 FROM knowledge_facts f WHERE f.id = old.fact_id \+ AND NOT (f.scope = 'bot' AND EXISTS (SELECT 1 FROM fact_purge_permits p WHERE p.scope_id = f.scope_id))) BEGIN \SELECT RAISE(ABORT, 'fact_events is append-only'); END".into(),]@@ -196,6 +220,7 @@ pub const TRUTH_LEDGER_DOWN: &[&str] = &["DROP TRIGGER IF EXISTS kwant_memories_ledger_au","DROP TRIGGER IF EXISTS kwant_memories_ledger_pin","DROP TRIGGER IF EXISTS kwant_memories_ledger_ad",+ "DROP TABLE IF EXISTS fact_purge_permits","DROP TABLE IF EXISTS fact_provenance","DROP TABLE IF EXISTS fact_events","DROP TABLE IF EXISTS fact_disputes",@@ -205,14 +230,24 @@ pub const TRUTH_LEDGER_DOWN: &[&str] = &[];/// Removes a deleted bot's facts and their events (run in the deletion's transaction, after its-/// memories): a bot that no longer exists keeps no history of what it remembered.+/// memories): a bot that no longer exists keeps no history of what it remembered. The only path+/// allowed to delete facts: it holds a permit for the bot while it runs.pub const PURGE_BOT_FACTS: &[&str] = &[+ "INSERT OR IGNORE INTO fact_purge_permits (scope_id) VALUES (?1)","DELETE FROM fact_evidence WHERE fact_id IN (SELECT id FROM knowledge_facts WHERE scope = 'bot' AND scope_id = ?1)","DELETE FROM fact_citations WHERE fact_id IN (SELECT id FROM knowledge_facts WHERE scope = 'bot' AND scope_id = ?1)",+ "DELETE FROM fact_events WHERE fact_id IN (SELECT id FROM knowledge_facts WHERE scope = 'bot' AND scope_id = ?1)","DELETE FROM knowledge_facts WHERE scope = 'bot' AND scope_id = ?1","DELETE FROM fact_events WHERE fact_id NOT IN (SELECT id FROM knowledge_facts)",+ "DELETE FROM fact_purge_permits WHERE scope_id = ?1",];+/// Takes the delete guards off again, for a rollback to a release whose bot deletion purges facts+/// without a permit (a703732). Older releases don't purge facts at all and need nothing.+#[doc(hidden)]+pub const DELETE_GUARDS_DOWN: &[&str] =+ &["DROP TRIGGER IF EXISTS knowledge_facts_no_delete", "DROP TRIGGER IF EXISTS fact_events_no_delete"];+/// How a memory write in the current turn should be trusted, when the row alone can't say.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Provenance<'a> {@@ -307,9 +342,15 @@ impl Database {if cols.len() < 3 {return Ok(());}+ // Recreated on every start, in one transaction, so a database an earlier build migrated+ // gets this build's rules and no memory write slips between drop and create.+ let mut tx = self.pool.begin().await?;for t in triggers() {- sqlx::query(&t).execute(&self.pool).await?;+ let name = t.split_whitespace().nth(5).unwrap_or_default();+ sqlx::query(&format!("DROP TRIGGER IF EXISTS {name}")).execute(&mut *tx).await?;+ sqlx::query(&t).execute(&mut *tx).await?;}+ tx.commit().await?;self.backfill_truth_ledger().await?;Ok(())}diff --git a/tests/truth_ledger_test.rs b/tests/truth_ledger_test.rsindex d0717052..a75a8a92 100644--- a/tests/truth_ledger_test.rs+++ b/tests/truth_ledger_test.rs@@ -16,7 +16,7 @@ use kwnt::{continuity::PinChange,models::{Kwant, NewKwant},spaces::SpaceId,- truth_ledger::TRUTH_LEDGER_DOWN,+ truth_ledger::{self as truth_ledger_db, DELETE_GUARDS_DOWN, TRUTH_LEDGER_DOWN},Database,},router::LayaRouter,@@ -262,7 +262,11 @@ async fn backfill_is_idempotent() {e.state.db.add_memory(&a.id, t, "agent").await.unwrap();}assert_eq!(e.state.db.backfill_truth_ledger().await.unwrap(), 0, "the mirror already has them");+ // Facts only go with a permit (the privacy paths hold one)+ sqlx::query("INSERT INTO fact_purge_permits (scope_id) VALUES (?)").bind(&a.id).execute(&e.pool).await.unwrap();+ sqlx::query("DELETE FROM fact_events").execute(&e.pool).await.unwrap();sqlx::query("DELETE FROM knowledge_facts").execute(&e.pool).await.unwrap();+ sqlx::query("DELETE FROM fact_purge_permits").execute(&e.pool).await.unwrap();assert_eq!(e.state.db.backfill_truth_ledger().await.unwrap(), 3);assert_eq!(e.state.db.backfill_truth_ledger().await.unwrap(), 0, "running it twice changes nothing");assert_eq!(count(&e.pool, "SELECT COUNT(*) FROM knowledge_facts").await, 3);@@ -497,3 +501,119 @@ async fn migrating_a_copy_of_an_existing_database_keeps_every_memory() {assert_eq!(count(&pool, "SELECT COUNT(*) FROM knowledge_facts").await, memories_before);assert_eq!(count(&pool, "SELECT COUNT(*) FROM fact_events").await, memories_before);}++#[tokio::test]+async fn an_edit_of_an_accepted_outside_fact_lands_outside_proposed() {+ let e = setup().await;+ let fid = proposed_fact(&e).await;+ let (a_id, m_id): (String, String) =+ sqlx::query_as("SELECT scope_id, memory_id FROM knowledge_facts WHERE id = ?").bind(&fid).fetch_one(&e.pool).await.unwrap();+ assert_eq!(e.state.db.decide_fact("spc_default", &fid, true).await.unwrap(), truth_ledger_db::Decision::Done);+ assert_eq!(live_fact(&e, &m_id).await, (fid.clone(), "outside".into(), "accepted".into()));++ // Rigel's case: the person accepted it, then a bot edit in a clean turn+ e.state.db.agent_update_memory(&a_id, &m_id, "limit is 5000").await.unwrap();+ let (_, trust, status) = live_fact(&e, &m_id).await;+ assert_eq!((trust.as_str(), status.as_str()), ("outside", "proposed"), "an accepted outside fact isn't laundered by a bot edit");+ let rows = facts_of(&e, &m_id).await;+ assert_eq!((rows[1].3.as_str(), rows[1].4.is_some()), ("bot", true), "it keeps where it came from");++ // Delete, then re-add the same text from a clean turn: still outside+ let (_, token) = turn(&e, &e.state.db.get_kwant(&a_id).await.unwrap().unwrap()).await;+ assert!(e.state.db.delete_memory(&a_id, &m_id).await.unwrap());+ let again = saved_id(&tool(&e, &token, "memory_add", json!({"text": "limit is 5000"})).await);+ let (_, trust, status) = live_fact(&e, &again).await;+ assert_eq!((trust.as_str(), status.as_str()), ("outside", "proposed"), "delete and re-add doesn't launder it");+ // Other text is the bot's own (exact text only: rewording is the known gap, docs §21)+ let other = saved_id(&tool(&e, &token, "memory_add", json!({"text": "standup is at 10"})).await);+ assert_eq!(live_fact(&e, &other).await.1, "bot");+}++#[tokio::test]+async fn only_the_person_takes_a_fact_out_of_outside() {+ let e = setup().await;+ let fid = proposed_fact(&e).await;+ let set = |sql: &'static str| {+ let (pool, fid) = (e.pool.clone(), fid.clone());+ async move { sqlx::query(sql).bind(fid).execute(&pool).await }+ };+ // Rigel's case: trust='bot' first, then an evidence accept+ assert!(set("UPDATE knowledge_facts SET trust = 'bot' WHERE id = ?").await.is_err(), "trust can't leave outside without the person");+ assert!(+ set("UPDATE knowledge_facts SET trust = 'bot', status = 'accepted', decided_by = 'evidence', decided_at = 'now' WHERE id = ?").await.is_err(),+ "nor in one go with evidence"+ );+ assert_eq!(live_fact(&e, &sqlx::query_as::<_, (String,)>("SELECT memory_id FROM knowledge_facts WHERE id = ?").bind(&fid).fetch_one(&e.pool).await.unwrap().0).await.1, "outside");++ // The person decides it; their decision then stands+ assert_eq!(e.state.db.decide_fact("spc_default", &fid, true).await.unwrap(), truth_ledger_db::Decision::Done);+ assert!(set("UPDATE knowledge_facts SET decided_by = 'evidence' WHERE id = ?").await.is_err(), "evidence can't overrule the person");+ assert!(set("UPDATE knowledge_facts SET trust = 'bot', decided_by = 'evidence' WHERE id = ?").await.is_err());+ set("UPDATE knowledge_facts SET trust = 'bot' WHERE id = ?").await.expect("with the person's decision, trust may change");+ assert!(set("UPDATE knowledge_facts SET decided_by = 'evidence' WHERE id = ?").await.is_err(), "an ex-outside fact never becomes evidence-accepted");+}++#[tokio::test]+async fn facts_and_their_events_are_deleted_only_with_their_bot() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ let b = bot(&e, "Ben").await;+ e.state.db.add_memory(&a.id, "Ana's note", "agent").await.unwrap();+ e.state.db.add_memory(&b.id, "Ben's note", "agent").await.unwrap();++ // Rigel's case: a plain DELETE, of facts or of their events, is refused+ assert!(sqlx::query("DELETE FROM knowledge_facts").execute(&e.pool).await.is_err(), "facts can't be deleted");+ assert!(sqlx::query("DELETE FROM fact_events").execute(&e.pool).await.is_err(), "events can't be deleted");+ assert_eq!(count(&e.pool, "SELECT COUNT(*) FROM knowledge_facts").await, 2);+ assert_eq!(count(&e.pool, "SELECT COUNT(*) FROM fact_events").await, 2);++ // Deleting Ana removes only hers, and leaves no permit behind+ let (status, v) = call(&e.app, "DELETE", &format!("/api/kwants/{}", a.id), None, None, None).await;+ assert!(status.is_success(), "{status} {v}");+ assert_eq!(count(&e.pool, &format!("SELECT COUNT(*) FROM knowledge_facts WHERE scope_id = '{}'", a.id)).await, 0);+ assert_eq!(count(&e.pool, "SELECT COUNT(*) FROM knowledge_facts").await, 1);+ assert_eq!(count(&e.pool, "SELECT COUNT(*) FROM fact_events").await, 1);+ assert_eq!(count(&e.pool, "SELECT COUNT(*) FROM fact_purge_permits").await, 0);+ assert!(sqlx::query("DELETE FROM knowledge_facts").execute(&e.pool).await.is_err(), "Ben's are still guarded");+}++#[tokio::test]+async fn a_restart_brings_this_builds_rules_to_a_database_an_earlier_build_migrated() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ e.state.db.add_memory(&a.id, "Ana's note", "agent").await.unwrap();++ // A rollback to a703732, whose bot deletion purges without a permit, takes the guards off first+ for sql in DELETE_GUARDS_DOWN {+ sqlx::query(sql).execute(&e.pool).await.unwrap();+ }+ let mut tx = e.pool.begin().await.unwrap();+ for sql in [+ "DELETE FROM fact_evidence WHERE fact_id IN (SELECT id FROM knowledge_facts WHERE scope = 'bot' AND scope_id = ?1)",+ "DELETE FROM fact_citations WHERE fact_id IN (SELECT id FROM knowledge_facts WHERE scope = 'bot' AND scope_id = ?1)",+ "DELETE FROM knowledge_facts WHERE scope = 'bot' AND scope_id = ?1",+ "DELETE FROM fact_events WHERE fact_id NOT IN (SELECT id FROM knowledge_facts)",+ ] {+ sqlx::query(sql).bind(&a.id).execute(&mut *tx).await.unwrap();+ }+ tx.rollback().await.unwrap();++ // An earlier build's laundering update trigger and missing guards: the next start replaces them+ sqlx::query("DROP TRIGGER kwant_memories_ledger_au").execute(&e.pool).await.unwrap();+ sqlx::query("CREATE TRIGGER kwant_memories_ledger_au AFTER UPDATE ON kwant_memories BEGIN SELECT 1; END").execute(&e.pool).await.unwrap();+ sqlx::query("DROP TRIGGER knowledge_facts_trust").execute(&e.pool).await.unwrap();+ drop(e.state);+ let (_, state, pool) = open(&e.data).await;+ let n = |name: &'static str| {+ let pool = pool.clone();+ async move { count(&pool, &format!("SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger' AND name = '{name}'")).await }+ };+ for name in ["knowledge_facts_no_delete", "fact_events_no_delete", "knowledge_facts_trust", "kwant_memories_ledger_au"] {+ assert_eq!(n(name).await, 1, "{name}");+ }+ assert!(sqlx::query("DELETE FROM knowledge_facts").execute(&pool).await.is_err(), "guards are back");+ let m = state.db.list_memories(&a.id).await.unwrap().remove(0);+ state.db.agent_update_memory(&a.id, &m.id, "Ana's note, edited").await.unwrap();+ assert_eq!(count(&pool, "SELECT COUNT(*) FROM knowledge_facts WHERE statement = 'Ana''s note, edited' AND status = 'accepted'").await, 1, "the mirror is this build's again");+ assert_eq!(count(&pool, "SELECT COUNT(*) FROM knowledge_facts").await, 2);+}