Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Truth Ledger C1: mirror bot memory into facts in shadow mode

Lin (kwant bot)90bdc7dc143a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a2d1f861..2fd6424e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
### Added
+- **Truth Ledger, shadow mode (Mission Control Phase C1).** A new `truth_ledger` setting (off by
+ default; `shadow`, or `on`, which behaves like shadow for now) lets you see every bot note as a fact
+ with where it came from. Notes a bot wrote after reading a web page, a file or another tool, and
+ imported notes, show as proposed until you accept or reject them; your own and the bot's other notes
+ are accepted. Nothing the bots see changes yet. Only you can read or decide facts; bots get a 403.
- **Routines can say what a good run is.** A routine can carry a Flight School class, a description
of a good result and checks. Each run's board task gets them, with the checks already approved, so a
run that passes its checks is verified on its own. Only the person sets the class and the checks; a
diff --git a/docs/mission-control.md b/docs/mission-control.md
index 04235e9a..7acc2f76 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -1012,3 +1012,62 @@ never applied (the person approves checks), and the preview says so.
offer), `suggestion_id`, `task_class`, `acceptance` and `checks` (JSON). `routine_suggestions` holds
offers, with one live offer per `(space_id, cluster_key)`. `routine_suggestion_events` is their
append-only history, enforced by triggers. Older binaries ignore all of it.
+
+## 21. Truth Ledger (Phase C1, shadow mode)
+
+Contract: `phase-c/contract.md`. **C1 ships the ledger in shadow mode only: it records, the person can
+read and decide, and nothing the bots see changes.** Memory stays the write path; C2 makes it a view of
+the ledger.
+
+**Setting.** `truth_ledger`: `off` (default), `shadow` or `on`, set by the person in `POST /api/settings`
+(a bot's token gets a 403, and the bots' own settings tool refuses it). **In C1 `on` behaves exactly like
+`shadow`.** The mirror below runs in every mode, so turning the ledger on later shows the whole history;
+the setting only gates the routes.
+
+**What it covers (D1).** Bot memory (`kwant_memories`), the person's notes on a bot and imported notes.
+Team and space facts, evidence, citations and disputes have tables but nothing writes them in C1.
+
+**The mirror (D2).** SQL triggers on `kwant_memories` mirror every insert, text change, pin and delete
+into `knowledge_facts`, so any writer (an older binary included) is seen; no row is moved. A fact has a
+`trust` and a `status`:
+- the person's note: `person`/`accepted`, decided by the person;
+- a bot's note: `bot`/`accepted`;
+- a bot's note from a turn that read outside text, or an imported note: `outside`/`proposed`
+ (`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.
+
+**Taint.** A turn is tainted once it calls a tool that brings outside text in: web fetch or search, a
+shell, a sub-agent, any MCP server other than kwant's own, the browser, `read_attachment`, `mcp_search`
+or `page_source`, or when every call needs approval (the turn is assumed to). A bot note written later in
+that turn is `outside`. The bit lives in memory for the turn and is cleared at its end.
+
+**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`).
+
+**Routes, all person only** (a bot's token gets a 403 on every one, reads included; bots get facts
+through tools in C2):
+- `GET /api/facts?space=&scope=&scope_id=&status=&q=`: `{setting, facts}`, newest first, at most 500;
+ with the ledger off `{setting: "off", facts: []}`.
+- `GET /api/facts/:id?space=`: `{fact, events, evidence: [], citations: [], disputes: []}`; 404 when off.
+- `POST /api/facts/:id/accept` and `/reject` (`Idempotency-Key` optional; the same key replays): a
+ `proposed` fact becomes `accepted`, or `superseded` with no successor, decided by the person. 409
+ `{error, status}` when it isn't proposed, so of racing clicks exactly one changes it; 409 when off. In
+ C1 a rejected note stays in the bot's memory.
+
+**Storage** (add-only, idempotent): `knowledge_facts`, `fact_evidence`, `fact_citations`,
+`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.
+
+**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
+ledger can't say whether their turn read outside text, so they are `bot`/`accepted`. An edited or
+deleted note keeps its old text as history in the ledger until the bot is deleted.
diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs
index 651cc90a..1fc16037 100644
--- a/src/db/bot_actions.rs
+++ b/src/db/bot_actions.rs
@@ -273,6 +273,9 @@ impl Database {
] {
sqlx::query(sql).bind(id).execute(&mut *tx).await?;
}
+ for sql in super::truth_ledger::PURGE_BOT_FACTS {
+ sqlx::query(sql).bind(id).execute(&mut *tx).await?;
+ }
for table in ["channels", "teams"] {
let rows: Vec<(String, String)> =
sqlx::query_as(&format!("SELECT id, member_kwants FROM {table} WHERE member_kwants LIKE '%' || ? || '%'"))
@@ -352,6 +355,9 @@ impl Database {
] {
sqlx::query(sql).bind(id).execute(&mut *tx).await?;
}
+ for sql in super::truth_ledger::PURGE_BOT_FACTS {
+ sqlx::query(sql).bind(id).execute(&mut *tx).await?;
+ }
// Memberships; a channel or team it led goes to its next member, else `new_lead`
for table in ["channels", "teams"] {
let rows: Vec<(String, String, String)> = sqlx::query_as(&format!(
diff --git a/src/db/continuity.rs b/src/db/continuity.rs
index 143822ec..ece669a5 100644
--- a/src/db/continuity.rs
+++ b/src/db/continuity.rs
@@ -484,6 +484,19 @@ impl Database {
text: &str,
source: &str,
pinned: bool,
+ ) -> Result<Memory, MemoryError> {
+ self.add_memory_from(kwant_id, text, source, pinned, None).await
+ }
+
+ /// [`Self::add_memory_pinned`] by a bot in turn `outside_turn`, which read outside text: the
+ /// Truth Ledger mirrors the note as `outside`/`proposed` (contract §2.4).
+ pub async fn add_memory_from(
+ &self,
+ kwant_id: &str,
+ text: &str,
+ source: &str,
+ pinned: bool,
+ outside_turn: Option<&str>,
) -> Result<Memory, MemoryError> {
let text = clean_memory_text(text)?;
let id = Uuid::new_v4().to_string();
@@ -501,6 +514,9 @@ impl Database {
if pinned && pinned_count(&mut tx, kwant_id).await? >= MAX_PINNED_PER_KWANT {
return Err(MemoryError::TooManyPinned);
}
+ if let Some(turn_id) = outside_turn {
+ super::truth_ledger::note_provenance(&mut tx, &id, super::truth_ledger::Provenance::Outside { turn_id }).await?;
+ }
sqlx::query("INSERT INTO kwant_memories (id, kwant_id, text, source, pinned_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
.bind(&id)
.bind(kwant_id)
@@ -555,8 +571,24 @@ impl Database {
kwant_id: &str,
id: &str,
text: &str,
+ ) -> Result<Memory, MemoryError> {
+ self.agent_update_memory_from(kwant_id, id, text, None).await
+ }
+
+ /// [`Self::agent_update_memory`] in turn `outside_turn`, which read outside text (see
+ /// [`Self::add_memory_from`]).
+ pub async fn agent_update_memory_from(
+ &self,
+ kwant_id: &str,
+ id: &str,
+ text: &str,
+ outside_turn: Option<&str>,
) -> Result<Memory, MemoryError> {
let text = clean_memory_text(text)?;
+ let mut tx = self.pool.begin().await?;
+ if let Some(turn_id) = outside_turn {
+ super::truth_ledger::note_provenance(&mut tx, id, super::truth_ledger::Provenance::Outside { turn_id }).await?;
+ }
let res = sqlx::query(
"UPDATE kwant_memories SET text = ?, updated_at = ? \
WHERE id = ? AND kwant_id = ? AND source <> 'user'",
@@ -565,11 +597,16 @@ impl Database {
.bind(Utc::now())
.bind(id)
.bind(kwant_id)
- .execute(&self.pool)
+ .execute(&mut *tx)
.await?;
if res.rows_affected() == 0 {
+ // Rolls the provenance row back with it
+ drop(tx);
return Err(self.why_agent_cannot_touch(kwant_id, id).await);
}
+ // Unchanged text fires no mirror; the marker must not outlive this write
+ sqlx::query("DELETE FROM fact_provenance WHERE memory_id = ?").bind(id).execute(&mut *tx).await?;
+ tx.commit().await?;
self.get_memory(id).await
}
diff --git a/src/db/imports.rs b/src/db/imports.rs
index fec33fed..a4530292 100644
--- a/src/db/imports.rs
+++ b/src/db/imports.rs
@@ -179,6 +179,8 @@ impl Database {
let now = Utc::now();
let mut tx = self.pool.begin().await?;
let mut ids: HashMap<&str, String> = HashMap::new();
+ // Known up front so the ledger can say which import each memory came from
+ let import_id = Uuid::new_v4().to_string();
for bot in &bundle.bots {
let (taken,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM kwants WHERE space_id = ? AND name = ? COLLATE NOCASE")
@@ -211,8 +213,10 @@ impl Database {
.execute(&mut *tx)
.await?;
for text in &bot.memories {
+ let memory_id = Uuid::new_v4().to_string();
+ super::truth_ledger::note_provenance(&mut tx, &memory_id, super::truth_ledger::Provenance::Import { import_id: &import_id }).await?;
sqlx::query("INSERT INTO kwant_memories (id, kwant_id, text, source, imported, created_at, updated_at) VALUES (?, ?, ?, 'user', 1, ?, ?)")
- .bind(Uuid::new_v4().to_string())
+ .bind(&memory_id)
.bind(&id)
.bind(text)
.bind(now)
@@ -276,7 +280,7 @@ impl Database {
}
}
- let id = Uuid::new_v4().to_string();
+ let id = import_id;
sqlx::query("INSERT INTO imports (id, space_id, source_kind, created, status, created_at) VALUES (?, ?, ?, ?, 'applied', ?)")
.bind(&id)
.bind(space.as_str())
@@ -356,6 +360,9 @@ impl Database {
] {
sqlx::query(sql).bind(&k.id).execute(&mut *tx).await?;
}
+ for sql in super::truth_ledger::PURGE_BOT_FACTS {
+ sqlx::query(sql).bind(&k.id).execute(&mut *tx).await?;
+ }
// Memberships the person added since (another team or channel) go with it.
for table in ["channels", "teams"] {
let rows: Vec<(String, String)> = sqlx::query_as(&format!("SELECT id, member_kwants FROM {table} WHERE member_kwants LIKE '%' || ? || '%'"))
diff --git a/src/db/mod.rs b/src/db/mod.rs
index d990a641..04a88c53 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -33,6 +33,7 @@ pub mod performance;
pub mod auditor;
pub mod foundry;
pub mod automation;
+pub mod truth_ledger;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -197,6 +198,9 @@ impl Database {
db.migrate_foundry().await?;
// Phase D4: routines carry class, acceptance and checks; suggestion storage (add-only)
db.migrate_automation_discovery().await?;
+ // Phase C1: the Truth Ledger mirrors memory (add-only). Last, so no later step rebuilds
+ // a table its triggers or lookups depend on
+ db.migrate_truth_ledger().await?;
db.pool.close().await;
let pool = SqlitePoolOptions::new()
diff --git a/src/db/truth_ledger.rs b/src/db/truth_ledger.rs
new file mode 100644
index 00000000..0a1bf1ae
--- /dev/null
+++ b/src/db/truth_ledger.rs
@@ -0,0 +1,437 @@
+//! Mission Control Phase C1: the Truth Ledger in shadow mode. Every bot memory (`kwant_memories`)
+//! is mirrored into `knowledge_facts` by SQL triggers, so nothing can write memory without the
+//! ledger seeing it; `kwant_memories` stays the write path and nothing is moved or deleted.
+//! Add-only: older binaries keep writing memory and the triggers still mirror it, and running it
+//! twice changes nothing. See docs/mission-control.md §21.
+
+use super::{Database, DbError};
+use chrono::Utc;
+use serde::Serialize;
+use sqlx::{FromRow, SqliteConnection};
+
+/// A fact still in force (not superseded).
+pub const LIVE: &str = "('proposed', 'accepted', 'disputed')";
+
+const TABLES: &[&str] = &[
+ "CREATE TABLE IF NOT EXISTS knowledge_facts (
+ id TEXT PRIMARY KEY,
+ space_id TEXT NOT NULL,
+ scope TEXT NOT NULL CHECK (scope IN ('bot', 'team', 'space')),
+ scope_id TEXT NOT NULL,
+ statement TEXT NOT NULL,
+ subject TEXT,
+ source_kind TEXT NOT NULL CHECK (source_kind IN ('person', 'bot', 'import', 'check', 'task')),
+ source_ref TEXT,
+ author_kwant_id TEXT,
+ trust TEXT NOT NULL CHECK (trust IN ('person', 'bot', 'outside')),
+ status TEXT NOT NULL CHECK (status IN ('proposed', 'accepted', 'superseded', 'disputed')),
+ superseded_by TEXT REFERENCES knowledge_facts(id),
+ valid_from TEXT NOT NULL,
+ valid_until TEXT,
+ memory_id TEXT,
+ pinned INTEGER NOT NULL DEFAULT 0,
+ decided_by TEXT CHECK (decided_by IN ('person', 'evidence')),
+ decided_at TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ )",
+ // One fact in force per memory; superseded ones stay as its history
+ "CREATE UNIQUE INDEX IF NOT EXISTS knowledge_facts_live_memory ON knowledge_facts (memory_id) \
+ WHERE memory_id IS NOT NULL AND status IN ('proposed', 'accepted', 'disputed')",
+ "CREATE INDEX IF NOT EXISTS knowledge_facts_memory ON knowledge_facts (memory_id)",
+ "CREATE INDEX IF NOT EXISTS knowledge_facts_scope ON knowledge_facts (space_id, scope, scope_id, status)",
+ "CREATE TABLE IF NOT EXISTS fact_evidence (
+ fact_id TEXT NOT NULL REFERENCES knowledge_facts(id),
+ evidence_id TEXT REFERENCES evidence(id),
+ check_id TEXT REFERENCES outcome_checks(id),
+ message_id TEXT,
+ added_by TEXT NOT NULL,
+ added_at TEXT NOT NULL
+ )",
+ "CREATE INDEX IF NOT EXISTS fact_evidence_fact ON fact_evidence (fact_id)",
+ "CREATE TABLE IF NOT EXISTS fact_citations (
+ fact_id TEXT NOT NULL REFERENCES knowledge_facts(id),
+ cited_by_kind TEXT NOT NULL CHECK (cited_by_kind IN ('task', 'fact')),
+ cited_by_id TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ PRIMARY KEY (fact_id, cited_by_kind, cited_by_id)
+ )",
+ "CREATE TABLE IF NOT EXISTS fact_disputes (
+ id TEXT PRIMARY KEY,
+ fact_a TEXT NOT NULL,
+ fact_b TEXT NOT NULL,
+ cause TEXT NOT NULL CHECK (cause IN ('same_subject', 'numbers_differ', 'negation', 'person', 'bot')),
+ status TEXT NOT NULL CHECK (status IN ('open', 'resolved', 'dismissed')),
+ winner TEXT,
+ resolved_by TEXT CHECK (resolved_by IN ('person', 'evidence')),
+ created_at TEXT NOT NULL,
+ resolved_at TEXT,
+ UNIQUE (fact_a, fact_b),
+ CHECK (fact_a < fact_b)
+ )",
+ "CREATE TABLE IF NOT EXISTS fact_events (
+ id INTEGER PRIMARY KEY,
+ fact_id TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ actor TEXT NOT NULL,
+ detail TEXT,
+ created_at TEXT NOT NULL
+ )",
+ "CREATE INDEX IF NOT EXISTS fact_events_fact ON fact_events (fact_id, id)",
+ // Where the next write of a memory came from, when the row alone can't say (a tainted turn,
+ // an import). Written in the memory write's transaction; the mirror trigger reads and deletes it.
+ "CREATE TABLE IF NOT EXISTS fact_provenance (
+ memory_id TEXT PRIMARY KEY,
+ trust TEXT NOT NULL CHECK (trust IN ('person', 'bot', 'outside')),
+ source_kind TEXT NOT NULL CHECK (source_kind IN ('person', 'bot', 'import', 'check', 'task')),
+ source_ref TEXT
+ )",
+];
+
+/// The new fact of a memory row `new`: trust and source from its provenance row, else from the
+/// row itself (the person's note, an import, the bot's own). Outside facts land `proposed`.
+const MIRROR_INSERT: &str = "INSERT INTO knowledge_facts (id, space_id, scope, scope_id, statement, source_kind, source_ref, \
+ author_kwant_id, trust, status, valid_from, memory_id, pinned, decided_by, decided_at, created_at, updated_at) \
+ SELECT 'f_' || lower(hex(randomblob(12))), COALESCE((SELECT space_id FROM kwants WHERE id = new.kwant_id), 'spc_default'), \
+ 'bot', new.kwant_id, new.text, d.kind, d.ref, CASE WHEN new.source = 'agent' THEN new.kwant_id END, d.trust, \
+ CASE WHEN d.trust = 'outside' THEN 'proposed' ELSE 'accepted' END, \
+ {valid_from}, new.id, new.pinned_by IS NOT NULL, \
+ CASE WHEN d.trust = 'person' THEN 'person' END, CASE WHEN d.trust = 'person' THEN strftime('%Y-%m-%dT%H:%M:%fZ', 'now') END, \
+ strftime('%Y-%m-%dT%H:%M:%fZ', 'now'), strftime('%Y-%m-%dT%H:%M:%fZ', 'now') \
+ FROM (SELECT COALESCE(p.trust, CASE WHEN new.imported = 1 THEN 'outside' WHEN new.source = 'user' THEN 'person' ELSE 'bot' END) AS trust, \
+ COALESCE(p.source_kind, CASE WHEN new.imported = 1 THEN 'import' WHEN new.source = 'user' THEN 'person' ELSE 'bot' END) AS kind, \
+ p.source_ref AS ref \
+ FROM (SELECT 1) LEFT JOIN fact_provenance p ON p.memory_id = new.id) d;";
+
+fn triggers() -> Vec<String> {
+ let now = "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
+ let live = LIVE;
+ vec![
+ format!(
+ "CREATE TRIGGER IF NOT EXISTS kwant_memories_ledger_ai AFTER INSERT ON kwant_memories BEGIN \
+ {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} \
+ FROM knowledge_facts WHERE memory_id = new.id AND status IN {live}; \
+ DELETE FROM fact_provenance WHERE memory_id = new.id; END",
+ 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.
+ 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); \
+ 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}; \
+ UPDATE knowledge_facts SET status = 'superseded', updated_at = {now} WHERE memory_id = new.id AND status IN {live}; \
+ {insert} \
+ UPDATE knowledge_facts SET superseded_by = (SELECT id FROM knowledge_facts WHERE memory_id = new.id AND status IN {live}) \
+ WHERE memory_id = new.id AND status = 'superseded' AND superseded_by IS NULL AND decided_by IS NULL; \
+ INSERT INTO fact_events (fact_id, kind, actor, created_at) \
+ SELECT id, 'created', 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}; \
+ DELETE FROM fact_provenance WHERE memory_id = new.id; END",
+ insert = MIRROR_INSERT.replace("{valid_from}", now),
+ ),
+ format!(
+ "CREATE TRIGGER IF NOT EXISTS kwant_memories_ledger_pin AFTER UPDATE OF pinned_by ON kwant_memories \
+ WHEN (old.pinned_by IS NULL) <> (new.pinned_by IS NULL) BEGIN \
+ UPDATE knowledge_facts SET pinned = new.pinned_by IS NOT NULL, updated_at = {now} WHERE memory_id = new.id AND status IN {live}; \
+ INSERT INTO fact_events (fact_id, kind, actor, created_at) \
+ SELECT id, CASE WHEN new.pinned_by IS NULL THEN 'unpinned' ELSE 'pinned' END, \
+ CASE COALESCE(new.pinned_by, old.pinned_by) WHEN 'user' THEN 'person' ELSE new.kwant_id END, {now} \
+ FROM knowledge_facts WHERE memory_id = new.id AND status IN {live}; END"
+ ),
+ // A removed note: its fact goes `superseded` with no successor; the row stays as history.
+ format!(
+ "CREATE TRIGGER IF NOT EXISTS kwant_memories_ledger_ad AFTER DELETE ON kwant_memories BEGIN \
+ INSERT INTO fact_events (fact_id, kind, actor, created_at) \
+ SELECT id, 'removed', 'system', {now} FROM knowledge_facts WHERE memory_id = old.id AND status IN {live}; \
+ UPDATE knowledge_facts SET status = 'superseded', superseded_by = NULL, updated_at = {now} \
+ WHERE memory_id = old.id AND status IN {live}; \
+ DELETE FROM fact_provenance WHERE memory_id = old.id; END"
+ ),
+ // Status rules (contract §2.2, §5 rules 1–2)
+ "CREATE TRIGGER IF NOT EXISTS knowledge_facts_terminal BEFORE UPDATE ON knowledge_facts \
+ WHEN old.status = 'superseded' AND (new.status IS NOT 'superseded' OR new.statement IS NOT old.statement \
+ OR new.trust IS NOT old.trust OR new.scope IS NOT old.scope OR new.decided_by IS NOT old.decided_by \
+ OR (old.superseded_by IS NOT NULL AND new.superseded_by IS NOT old.superseded_by)) BEGIN \
+ SELECT RAISE(ABORT, 'superseded facts are final'); END"
+ .into(),
+ "CREATE TRIGGER IF NOT EXISTS knowledge_facts_decided BEFORE UPDATE OF status ON knowledge_facts \
+ WHEN new.status = 'accepted' AND old.status IN ('proposed', 'disputed') AND (new.decided_by IS NULL OR new.decided_at IS NULL) BEGIN \
+ SELECT RAISE(ABORT, 'accepting a proposed or disputed fact needs decided_by'); END"
+ .into(),
+ "CREATE TRIGGER IF NOT EXISTS knowledge_facts_rules_insert BEFORE INSERT ON knowledge_facts \
+ WHEN (new.trust = 'outside' AND new.status = 'accepted' AND new.decided_by IS NOT 'person') \
+ 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(),
+ "CREATE TRIGGER IF NOT EXISTS knowledge_facts_rules_update BEFORE UPDATE ON knowledge_facts \
+ WHEN (new.trust = 'outside' AND new.status = 'accepted' AND new.decided_by IS NOT 'person') \
+ 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(),
+ "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
+ "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 \
+ SELECT RAISE(ABORT, 'fact_events is append-only'); END"
+ .into(),
+ ]
+}
+
+/// Undoes [`Database::migrate_truth_ledger`]: memory itself is untouched. For tests and a manual
+/// rollback.
+#[doc(hidden)]
+pub const TRUTH_LEDGER_DOWN: &[&str] = &[
+ "DROP TRIGGER IF EXISTS kwant_memories_ledger_ai",
+ "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_provenance",
+ "DROP TABLE IF EXISTS fact_events",
+ "DROP TABLE IF EXISTS fact_disputes",
+ "DROP TABLE IF EXISTS fact_citations",
+ "DROP TABLE IF EXISTS fact_evidence",
+ "DROP TABLE IF EXISTS knowledge_facts",
+];
+
+/// 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.
+pub const PURGE_BOT_FACTS: &[&str] = &[
+ "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)",
+];
+
+/// 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> {
+ /// A bot write in a turn that read outside text (`source_ref` is the turn id).
+ Outside { turn_id: &'a str },
+ /// An import (`source_ref` is the import id).
+ Import { import_id: &'a str },
+}
+
+/// Records where the next write of memory `memory_id` came from; call it in the write's
+/// transaction, before the INSERT or UPDATE. The mirror trigger consumes it.
+pub async fn note_provenance(conn: &mut SqliteConnection, memory_id: &str, p: Provenance<'_>) -> Result<(), sqlx::Error> {
+ let (kind, reference) = match p {
+ Provenance::Outside { turn_id } => ("bot", turn_id),
+ Provenance::Import { import_id } => ("import", import_id),
+ };
+ sqlx::query("INSERT OR REPLACE INTO fact_provenance (memory_id, trust, source_kind, source_ref) VALUES (?, 'outside', ?, ?)")
+ .bind(memory_id)
+ .bind(kind)
+ .bind(reference)
+ .execute(conn)
+ .await?;
+ Ok(())
+}
+
+#[derive(Debug, Clone, Serialize, FromRow)]
+pub struct Fact {
+ pub id: String,
+ pub space_id: String,
+ pub scope: String,
+ pub scope_id: String,
+ pub statement: String,
+ pub subject: Option<String>,
+ pub source_kind: String,
+ pub source_ref: Option<String>,
+ pub author_kwant_id: Option<String>,
+ pub trust: String,
+ pub status: String,
+ pub superseded_by: Option<String>,
+ pub valid_from: String,
+ pub valid_until: Option<String>,
+ pub memory_id: Option<String>,
+ pub pinned: bool,
+ pub decided_by: Option<String>,
+ pub decided_at: Option<String>,
+ pub created_at: String,
+ pub updated_at: String,
+}
+
+#[derive(Debug, Clone, Serialize, FromRow)]
+pub struct FactEvent {
+ pub id: i64,
+ pub kind: String,
+ pub actor: String,
+ pub detail: Option<String>,
+ pub created_at: String,
+}
+
+#[derive(Debug, Default)]
+pub struct FactFilter<'a> {
+ pub scope: Option<&'a str>,
+ pub scope_id: Option<&'a str>,
+ pub status: Option<&'a str>,
+ pub q: Option<&'a str>,
+}
+
+/// What a person's accept or reject did.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Decision {
+ /// This call changed the fact.
+ Done,
+ /// The fact isn't `proposed` (any more): someone decided it first, or it was superseded.
+ NotProposed(String),
+ NotFound,
+}
+
+pub const MAX_FACTS: i64 = 500;
+
+impl Database {
+ pub(super) async fn migrate_truth_ledger(&self) -> Result<(), DbError> {
+ for stmt in TABLES {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ // The mirror needs memory's `imported`/`pinned_by` and the bots' spaces; a database from
+ // before spaces (migration tests) gets them on its next start.
+ let cols: Vec<(String,)> = sqlx::query_as(
+ "SELECT name FROM pragma_table_info('kwants') WHERE name = 'space_id' \
+ UNION ALL SELECT name FROM pragma_table_info('kwant_memories') WHERE name IN ('imported', 'pinned_by')",
+ )
+ .fetch_all(&self.pool)
+ .await?;
+ if cols.len() < 3 {
+ return Ok(());
+ }
+ for t in triggers() {
+ sqlx::query(&t).execute(&self.pool).await?;
+ }
+ self.backfill_truth_ledger().await?;
+ Ok(())
+ }
+
+ /// Mirrors every memory that has no fact at all (so a rejected or removed one isn't brought
+ /// back). Idempotent. Notes from before the ledger can't say whether the bot had read outside
+ /// text, so a bot's own note is `bot`/`accepted` and an imported one `outside`/`proposed`.
+ pub async fn backfill_truth_ledger(&self) -> Result<u64, DbError> {
+ let imports: Option<(String,)> = sqlx::query_as("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'imports'")
+ .fetch_optional(&self.pool)
+ .await?;
+ let import_ref = if imports.is_some() {
+ "(SELECT i.id FROM imports i, json_each(i.created, '$.kwants') k \
+ WHERE json_extract(k.value, '$.id') = m.kwant_id ORDER BY i.created_at DESC LIMIT 1)"
+ } else {
+ "NULL"
+ };
+ let now = "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
+ let mut tx = self.pool.begin().await?;
+ let res = sqlx::query(&format!(
+ "INSERT INTO knowledge_facts (id, space_id, scope, scope_id, statement, source_kind, source_ref, author_kwant_id, \
+ trust, status, valid_from, memory_id, pinned, decided_by, decided_at, created_at, updated_at) \
+ SELECT 'f_' || lower(hex(randomblob(12))), COALESCE(k.space_id, 'spc_default'), 'bot', m.kwant_id, m.text, \
+ CASE WHEN m.imported = 1 THEN 'import' WHEN m.source = 'user' THEN 'person' ELSE 'bot' END, \
+ CASE WHEN m.imported = 1 THEN {import_ref} END, \
+ CASE WHEN m.source = 'agent' THEN m.kwant_id END, \
+ CASE WHEN m.imported = 1 THEN 'outside' WHEN m.source = 'user' THEN 'person' ELSE 'bot' END, \
+ CASE WHEN m.imported = 1 THEN 'proposed' ELSE 'accepted' END, \
+ COALESCE(m.created_at, {now}), m.id, m.pinned_by IS NOT NULL, \
+ CASE WHEN m.imported = 0 AND m.source = 'user' THEN 'person' END, \
+ CASE WHEN m.imported = 0 AND m.source = 'user' THEN {now} END, {now}, {now} \
+ FROM kwant_memories m LEFT JOIN kwants k ON k.id = m.kwant_id \
+ WHERE NOT EXISTS (SELECT 1 FROM knowledge_facts f WHERE f.memory_id = m.id) \
+ ORDER BY m.created_at, m.rowid"
+ ))
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query(&format!(
+ "INSERT INTO fact_events (fact_id, kind, actor, created_at) \
+ SELECT f.id, 'backfilled', 'system', {now} FROM knowledge_facts f \
+ WHERE NOT EXISTS (SELECT 1 FROM fact_events e WHERE e.fact_id = f.id)"
+ ))
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(res.rows_affected())
+ }
+
+ /// Facts in `space`, newest first, at most [`MAX_FACTS`].
+ pub async fn list_facts(&self, space: &str, f: &FactFilter<'_>) -> Result<Vec<Fact>, DbError> {
+ let mut sql = String::from("SELECT * FROM knowledge_facts WHERE space_id = ?");
+ if f.scope.is_some() {
+ sql.push_str(" AND scope = ?");
+ }
+ if f.scope_id.is_some() {
+ sql.push_str(" AND scope_id = ?");
+ }
+ if f.status.is_some() {
+ sql.push_str(" AND status = ?");
+ }
+ if f.q.is_some() {
+ sql.push_str(" AND statement LIKE '%' || ? || '%' ESCAPE '\\'");
+ }
+ sql.push_str(" ORDER BY created_at DESC, rowid DESC LIMIT ?");
+ let mut q = sqlx::query_as::<_, Fact>(&sql).bind(space);
+ for v in [f.scope, f.scope_id, f.status].into_iter().flatten() {
+ q = q.bind(v);
+ }
+ if let Some(text) = f.q {
+ q = q.bind(text.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"));
+ }
+ Ok(q.bind(MAX_FACTS).fetch_all(&self.pool).await?)
+ }
+
+ pub async fn get_fact(&self, space: &str, id: &str) -> Result<Option<Fact>, DbError> {
+ Ok(sqlx::query_as::<_, Fact>("SELECT * FROM knowledge_facts WHERE id = ? AND space_id = ?")
+ .bind(id)
+ .bind(space)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// A fact's history, oldest first.
+ pub async fn fact_events(&self, id: &str) -> Result<Vec<FactEvent>, DbError> {
+ Ok(sqlx::query_as::<_, FactEvent>("SELECT id, kind, actor, detail, created_at FROM fact_events WHERE fact_id = ? ORDER BY id")
+ .bind(id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// The person accepting (`accept`) or rejecting a `proposed` fact: claim-first, so of racing
+ /// calls exactly one changes it. Rejecting supersedes it with no successor; in shadow mode the
+ /// memory row itself is not touched.
+ pub async fn decide_fact(&self, space: &str, id: &str, accept: bool) -> Result<Decision, DbError> {
+ let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
+ let mut tx = self.pool.begin().await?;
+ let res = sqlx::query(
+ "UPDATE knowledge_facts SET status = ?, decided_by = 'person', decided_at = ?, updated_at = ? \
+ WHERE id = ? AND space_id = ? AND status = 'proposed'",
+ )
+ .bind(if accept { "accepted" } else { "superseded" })
+ .bind(&now)
+ .bind(&now)
+ .bind(id)
+ .bind(space)
+ .execute(&mut *tx)
+ .await?;
+ if res.rows_affected() == 0 {
+ let status: Option<(String,)> = sqlx::query_as("SELECT status FROM knowledge_facts WHERE id = ? AND space_id = ?")
+ .bind(id)
+ .bind(space)
+ .fetch_optional(&mut *tx)
+ .await?;
+ return Ok(status.map_or(Decision::NotFound, |(s,)| Decision::NotProposed(s)));
+ }
+ sqlx::query("INSERT INTO fact_events (fact_id, kind, actor, created_at) VALUES (?, ?, 'person', ?)")
+ .bind(id)
+ .bind(if accept { "accepted" } else { "rejected" })
+ .bind(&now)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(Decision::Done)
+ }
+}
diff --git a/src/server/auth.rs b/src/server/auth.rs
index aaff020c..0fda1a8f 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -373,6 +373,9 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "skills", "foundry", ..] | ["", "api", "skills", _, "foundry"] => true,
// Automation Discovery reads every board task the person made in the space
["", "api", "automation-discovery", ..] => true,
+ // Truth Ledger (C1): the person reads facts here and accepts or rejects them; bots get fact
+ // tools in C2
+ ["", "api", "facts", ..] => true,
["", "api", "skills", ..] => *method != Method::GET && *method != Method::HEAD,
["", "api", "bot-actions" | "imports", _, "undo"] => *method == Method::POST,
_ => false,
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 9b9915d6..a6b43352 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -413,6 +413,11 @@ impl ToolApprover for SelfToolsApprover {
}
}
+/// The turn's id when it read outside text: its notes land `outside`/`proposed` in the Truth Ledger.
+fn outside_turn(scope: &SelfScope) -> Option<&str> {
+ scope.turn_id.as_deref().filter(|t| super::missions::truth_ledger::is_tainted(t))
+}
+
/// The address the turn's browser shows now, without starting a browser.
async fn page_url(state: &AppState, target: &str) -> Option<String> {
let ctrl = state.browser_controllers.lock().await.get(target).cloned()?;
@@ -896,7 +901,7 @@ async fn call_tool(
let text = str_arg("text").unwrap_or("");
let before = db.list_memories(&scope.kwant_id).await.unwrap_or_default();
let pinned = args["pinned"].as_bool().unwrap_or(false);
- match db.add_memory_pinned(&scope.kwant_id, text, "agent", pinned).await {
+ match db.add_memory_from(&scope.kwant_id, text, "agent", pinned, outside_turn(scope)).await {
Ok(m) => {
memory_changed();
let mut reply = format!("Saved as [{}].", m.id);
@@ -923,7 +928,7 @@ async fn call_tool(
}
let mut updated = None;
if let Some(text) = text {
- match db.agent_update_memory(&scope.kwant_id, id, text).await {
+ match db.agent_update_memory_from(&scope.kwant_id, id, text, outside_turn(scope)).await {
Ok(m) => updated = Some(m),
Err(e) => return (e.to_string(), true),
}
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 42c4fcb8..02930e8f 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -170,6 +170,10 @@ impl ToolApprover for BrokerApprover {
}
async fn note(&self, req: &ToolApprovalRequest, decision: &'static str, approval_id: Option<&str>) {
+ // Truth Ledger: a turn that ran a tool reading outside text writes `outside` notes from now on
+ if decision != "denied" && super::missions::truth_ledger::request_reads_outside(req) {
+ super::missions::truth_ledger::taint(&req.turn_id);
+ }
super::missions::checkpoints::log_call(&self.db, &self.data_dir, req, decision, approval_id).await;
}
@@ -558,7 +562,7 @@ pub async fn prepare_turn_with_opts(
kwant: &Kwant,
turn_id: Option<String>,
cwd: Option<PathBuf>,
- self_scope: Option<super::continuity::SelfScope>,
+ mut self_scope: Option<super::continuity::SelfScope>,
opts: TurnApprovalOpts,
) -> Option<(McpTurnContext, String)> {
let mut servers = match state.db.list_active_mcp_servers_for_kwant(&kwant.id).await {
@@ -583,6 +587,14 @@ pub async fn prepare_turn_with_opts(
}
let setting = state.db.get_setting("mcp_max_tool_iterations").await.ok().flatten();
let turn_id = turn_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
+ // The memory tools look the turn's taint up by this id
+ if let Some(scope) = self_scope.as_mut() {
+ scope.turn_id.get_or_insert_with(|| turn_id.clone());
+ }
+ // A turn that always asks reads outside text from the start (contract §2.4)
+ if opts.always_ask {
+ super::missions::truth_ledger::taint(&turn_id);
+ }
let mut chat = turn_chat(state, &turn_id).await;
if let Some((agent, effort)) = &opts.routed {
let chat = chat.get_or_insert_with(|| json!({"direct_kwant_id": kwant.id}));
@@ -627,6 +639,7 @@ pub async fn finish_turn(state: &AppState, token: &str) {
state.self_tools.lock().await.remove(token);
let session = state.mcp_sessions.lock().await.remove(token);
if let Some(session) = session {
+ super::missions::truth_ledger::end_turn(&session.turn_id);
session.close().await;
}
}
diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rs
index 93b24964..15caae85 100644
--- a/src/server/missions/mod.rs
+++ b/src/server/missions/mod.rs
@@ -25,6 +25,7 @@ pub mod performance;
pub mod routes;
pub mod runner;
pub mod tools;
+pub mod truth_ledger;
use super::AppState;
use crate::db::missions::{Mission, NewCheck, NewTask, OutcomeCheck, Task, TaskChange};
diff --git a/src/server/missions/truth_ledger.rs b/src/server/missions/truth_ledger.rs
new file mode 100644
index 00000000..3ab321e4
--- /dev/null
+++ b/src/server/missions/truth_ledger.rs
@@ -0,0 +1,236 @@
+//! Mission Control Phase C1: the Truth Ledger in shadow mode. Memory stays the write path and SQL
+//! triggers mirror it into facts (`crate::db::truth_ledger`); this module holds the setting, the
+//! per-turn taint bit (a turn that read outside text: its notes land `outside`/`proposed`) and
+//! the routes: read the facts, and the person's accept/reject. The bot's memory block is the same
+//! in every mode in C1. See docs/mission-control.md §21.
+
+// Handler helpers return the ready-made error `Response`
+#![allow(clippy::result_large_err)]
+
+use super::routes::{bad, err, internal, not_found};
+use crate::db::truth_ledger::{Decision, FactFilter};
+use crate::server::spaces::{space_param, Scope};
+use crate::server::AppState;
+use axum::{
+ extract::{Path, Query, RawQuery, State},
+ http::{HeaderMap, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::Deserialize;
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+pub const SETTING: &str = "truth_ledger";
+/// `on` reads the same as `shadow` until C2 makes memory a view of the ledger.
+pub const MODES: [&str; 3] = ["off", "shadow", "on"];
+const STATUSES: [&str; 4] = ["proposed", "accepted", "superseded", "disputed"];
+const SCOPES: [&str; 3] = ["bot", "team", "space"];
+
+/// The saved mode; anything unreadable is `off`.
+pub async fn mode(state: &AppState) -> &'static str {
+ match state.db.get_setting(SETTING).await.ok().flatten().as_deref().map(str::trim) {
+ Some("shadow") => "shadow",
+ Some("on") => "on",
+ _ => "off",
+ }
+}
+
+pub fn settings_error(mode: Option<&str>) -> Option<String> {
+ mode.filter(|m| !MODES.contains(m)).map(|m| format!("{SETTING} must be off, shadow or on (got {m})"))
+}
+
+// Taint: a turn that read outside text (contract §2.4)
+
+/// Turns that read outside text, with when they were marked. Never cleared within a turn; the
+/// turn's end removes it, and anything older than a day goes (a turn that never ended cleanly).
+static TAINTED: Mutex<Option<HashMap<String, Instant>>> = Mutex::new(None);
+const TAINT_TTL: Duration = Duration::from_secs(24 * 3600);
+
+pub fn taint(turn_id: &str) {
+ if turn_id.is_empty() {
+ return;
+ }
+ let mut guard = TAINTED.lock().unwrap_or_else(|e| e.into_inner());
+ let map = guard.get_or_insert_with(HashMap::new);
+ if map.len() > 1000 {
+ map.retain(|_, at| at.elapsed() < TAINT_TTL);
+ }
+ map.entry(turn_id.to_string()).or_insert_with(Instant::now);
+}
+
+pub fn is_tainted(turn_id: &str) -> bool {
+ let guard = TAINTED.lock().unwrap_or_else(|e| e.into_inner());
+ guard.as_ref().is_some_and(|m| m.contains_key(turn_id))
+}
+
+/// The turn ended: its id isn't used again.
+pub fn end_turn(turn_id: &str) {
+ let mut guard = TAINTED.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(map) = guard.as_mut() {
+ map.remove(turn_id);
+ }
+}
+
+/// Built-in tools (claude's, Codex's, the API driver's) that bring text from outside into the turn.
+const OUTSIDE_TOOLS: &[&str] = &[
+ "WebFetch",
+ "WebSearch",
+ "Bash",
+ "Task",
+ "Agent",
+ "web_search",
+ "web_fetch",
+ "command_execution",
+ "execute_shell",
+];
+
+/// kwant's own tools that read outside text: a page, an attachment, another server's tools.
+const OUTSIDE_SELF_TOOLS: &[&str] = &["read_attachment", "mcp_search", crate::server::page_source::TOOL];
+
+fn outside_self_tool(tool: &str) -> bool {
+ tool.starts_with("browser_") || OUTSIDE_SELF_TOOLS.contains(&tool)
+}
+
+/// Whether calling tool `name` (as an engine reports it: `WebFetch`, `mcp__github__get_issue`,
+/// `mcp__kwnt_tools__browser_open`, the API driver's bare `browser_open`) reads outside text.
+/// Any MCP server but kwant's own counts.
+pub fn reads_outside(name: &str) -> bool {
+ if let Some(rest) = name.strip_prefix("mcp__") {
+ let self_prefix = format!("{}__", crate::mcp::SELF_SERVER_NAME);
+ return match rest.strip_prefix(&self_prefix) {
+ Some(tool) => outside_self_tool(tool),
+ None => true,
+ };
+ }
+ OUTSIDE_TOOLS.contains(&name) || outside_self_tool(name)
+}
+
+/// [`reads_outside`] for an approval request (server and tool split).
+pub fn request_reads_outside(req: &crate::mcp::ToolApprovalRequest) -> bool {
+ if req.builtin.is_some() {
+ return OUTSIDE_TOOLS.contains(&req.tool.as_str()) || OUTSIDE_TOOLS.contains(&req.tool_name.as_str());
+ }
+ if req.server == crate::mcp::SELF_SERVER_NAME {
+ return outside_self_tool(&req.tool);
+ }
+ !req.server.is_empty() || reads_outside(&req.tool_name)
+}
+
+// Routes (all person only, see `auth::person_only`)
+
+#[derive(Deserialize, Default)]
+pub struct ListQuery {
+ scope: Option<String>,
+ scope_id: Option<String>,
+ status: Option<String>,
+ q: Option<String>,
+}
+
+fn opt(v: &Option<String>) -> Option<&str> {
+ v.as_deref().map(str::trim).filter(|s| !s.is_empty())
+}
+
+/// `GET /api/facts?space=&scope=&scope_id=&status=&q=`: the setting and the space's facts, newest
+/// first (at most 500). With the ledger off: `{setting: "off", facts: []}`.
+pub async fn list(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<ListQuery>) -> Response {
+ let setting = mode(&state).await;
+ if setting == "off" {
+ return Json(json!({ "setting": setting, "facts": [] })).into_response();
+ }
+ let filter = FactFilter { scope: opt(&q.scope), scope_id: opt(&q.scope_id), status: opt(&q.status), q: opt(&q.q) };
+ if filter.scope.is_some_and(|s| !SCOPES.contains(&s)) {
+ return bad("scope must be bot, team or space");
+ }
+ if filter.status.is_some_and(|s| !STATUSES.contains(&s)) {
+ return bad("status must be proposed, accepted, superseded or disputed");
+ }
+ if filter.q.is_some_and(|t| t.chars().count() > 200) {
+ return bad("q is at most 200 characters");
+ }
+ match state.db.list_facts(space.as_str(), &filter).await {
+ Ok(facts) => Json(json!({ "setting": setting, "facts": facts })).into_response(),
+ Err(e) => internal(e),
+ }
+}
+
+async fn space_of(state: &AppState, query: Option<&str>) -> Result<String, Response> {
+ match space_param(query) {
+ None => Ok(crate::db::spaces::SpaceId::default_space().as_str().to_string()),
+ Some(id) => crate::server::spaces::active_space(state, &id).await.map(|s| s.as_str().to_string()),
+ }
+}
+
+/// `GET /api/facts/:id?space=`: the fact with its events (evidence, citations and disputes come
+/// in C2 and are empty). 404 with the ledger off.
+pub async fn get(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {
+ if mode(&state).await == "off" {
+ return not_found("fact");
+ }
+ let space = match space_of(&state, q.as_deref()).await {
+ Ok(s) => s,
+ Err(r) => return r,
+ };
+ match fact_json(&state, &space, &id).await {
+ Ok(Some(v)) => Json(v).into_response(),
+ Ok(None) => not_found("fact"),
+ Err(e) => internal(e),
+ }
+}
+
+async fn fact_json(state: &AppState, space: &str, id: &str) -> Result<Option<Value>, crate::db::DbError> {
+ let Some(fact) = state.db.get_fact(space, id).await? else {
+ return Ok(None);
+ };
+ let events = state.db.fact_events(id).await?;
+ Ok(Some(json!({
+ "fact": fact,
+ "events": events,
+ "evidence": [],
+ "citations": [],
+ "disputes": [],
+ })))
+}
+
+/// `POST /api/facts/:id/accept?space=` (person only; `Idempotency-Key` optional, the same key
+/// replays): a `proposed` fact becomes `accepted`, decided by the person. 409 when it isn't
+/// proposed (any more), so of racing clicks exactly one changes it; 409 with the ledger off.
+pub async fn accept(state: State<AppState>, q: RawQuery, headers: HeaderMap, id: Path<String>) -> Response {
+ decide(state, q, headers, id, true).await
+}
+
+/// `POST /api/facts/:id/reject?space=`: like accept; the fact is superseded with no successor.
+/// In C1 the bot's note itself stays as it is.
+pub async fn reject(state: State<AppState>, q: RawQuery, headers: HeaderMap, id: Path<String>) -> Response {
+ decide(state, q, headers, id, false).await
+}
+
+async fn decide(State(state): State<AppState>, RawQuery(q): RawQuery, headers: HeaderMap, Path(id): Path<String>, accept: bool) -> Response {
+ if mode(&state).await == "off" {
+ return err(StatusCode::CONFLICT, "the Truth Ledger is off");
+ }
+ let space = match space_of(&state, q.as_deref()).await {
+ Ok(s) => s,
+ Err(r) => return r,
+ };
+ let route = format!("POST /api/facts/{id}/{}", if accept { "accept" } else { "reject" });
+ super::graph::idempotent(&state, &headers, route, || async {
+ match state.db.decide_fact(&space, &id, accept).await {
+ Ok(Decision::Done) => match fact_json(&state, &space, &id).await {
+ Ok(Some(v)) => Ok(v),
+ Ok(None) => Err(not_found("fact")),
+ Err(e) => Err(internal(e)),
+ },
+ Ok(Decision::NotProposed(status)) => Err((
+ StatusCode::CONFLICT,
+ Json(json!({ "error": format!("this fact is already {status}"), "status": status })),
+ )
+ .into_response()),
+ Ok(Decision::NotFound) => Err(not_found("fact")),
+ Err(e) => Err(internal(e)),
+ }
+ })
+ .await
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 1f98743b..9917e759 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -408,6 +408,10 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/automation-discovery/scan", post(missions::discovery::scan))
.route("/api/automation-discovery/:id/accept", post(missions::discovery::accept))
.route("/api/automation-discovery/:id/dismiss", post(missions::discovery::dismiss))
+ .route("/api/facts", get(missions::truth_ledger::list))
+ .route("/api/facts/:id", get(missions::truth_ledger::get))
+ .route("/api/facts/:id/accept", post(missions::truth_ledger::accept))
+ .route("/api/facts/:id/reject", post(missions::truth_ledger::reject))
.route("/api/skills/foundry", get(missions::foundry::overview))
.route("/api/skills/foundry/:cluster/draft", post(missions::foundry::draft_now))
.route("/api/skills/:id/foundry", get(missions::foundry::detail))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index f109ecef..715020f0 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2416,6 +2416,10 @@ async fn run_kwant_turn_inner(
Some(RuntimeEvent::UsageSoFar { fresh }) => state.turns.saw_usage(&tag.turn_id, fresh),
Some(event) => {
if let RuntimeEvent::ToolCallPending { name, args, .. } = &event {
+ // Engines' own tools that no approver sees (Codex's web search)
+ if super::missions::truth_ledger::reads_outside(name) {
+ super::missions::truth_ledger::taint(&tag.turn_id);
+ }
if name == super::questions::NATIVE_ASK_TOOL {
let place = crate::db::questions::QuestionPlace {
kwant_id: target_kwant.id.clone(),
@@ -3489,6 +3493,9 @@ pub struct SettingsResponse {
pub automation_discovery: String,
/// Routines suggested per space per 24 hours (0–10).
pub automation_discovery_daily_cap: i64,
+ /// Truth Ledger: `off` (default), `shadow` or `on` (`on` reads like `shadow` until C2; see
+ /// `super::missions::truth_ledger`).
+ pub truth_ledger: String,
}
/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of
@@ -3542,6 +3549,7 @@ pub struct SaveSettingsPayload {
pub skill_foundry_replay_tokens: Option<i64>,
pub automation_discovery: Option<String>,
pub automation_discovery_daily_cap: Option<i64>,
+ pub truth_ledger: Option<String>,
}
pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {
@@ -3604,6 +3612,7 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settings
skill_foundry_replay_tokens: super::missions::foundry::replay_tokens(&state).await,
automation_discovery: if super::missions::discovery::enabled(&state).await { "on" } else { "off" }.into(),
automation_discovery_daily_cap: super::missions::discovery::daily_cap(&state).await,
+ truth_ledger: super::missions::truth_ledger::mode(&state).await.into(),
}))
}
@@ -3677,6 +3686,9 @@ pub async fn save_settings(
if let Some(e) = super::missions::discovery::settings_error(payload.automation_discovery.as_deref(), payload.automation_discovery_daily_cap) {
return bad(e);
}
+ if let Some(e) = super::missions::truth_ledger::settings_error(payload.truth_ledger.as_deref()) {
+ return bad(e);
+ }
if payload.chain_token_budget.is_some_and(|n| n > super::budget::MAX) {
return bad(format!("chain_token_budget must be 0–{}", super::budget::MAX));
}
@@ -3828,6 +3840,9 @@ pub async fn save_settings(
if let Some(n) = payload.automation_discovery_daily_cap {
let _ = state.db.set_setting(super::missions::discovery::CAP_SETTING, &n.to_string()).await;
}
+ if let Some(m) = &payload.truth_ledger {
+ let _ = state.db.set_setting(super::missions::truth_ledger::SETTING, m).await;
+ }
if let Some(on) = payload.agent_tools {
let _ = state.db.set_setting("agent_tools", if on { "on" } else { "off" }).await;
}
diff --git a/tests/truth_ledger_test.rs b/tests/truth_ledger_test.rs
new file mode 100644
index 00000000..d0717052
--- /dev/null
+++ b/tests/truth_ledger_test.rs
@@ -0,0 +1,499 @@
+//! Truth Ledger C1, shadow mode (Mission Control Phase C1). Triggers mirror every bot memory into
+//! `knowledge_facts`; a note from a turn that read outside text, or an import, lands
+//! `outside`/`proposed`; only the person reads facts or decides them, and of racing accepts
+//! exactly one changes the fact; the bot's memory block is the same with the ledger off or on.
+//! Contract: docs/mission-control.md §21.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{
+ continuity::PinChange,
+ models::{Kwant, NewKwant},
+ spaces::SpaceId,
+ truth_ledger::TRUTH_LEDGER_DOWN,
+ Database,
+ },
+ router::LayaRouter,
+ server::{
+ continuity::{memory_block, SelfScope, TurnOrigin},
+ create_router, mcp_runtime,
+ missions::truth_ledger,
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use sqlx::{sqlite::SqlitePoolOptions, SqlitePool};
+use std::path::{Path, PathBuf};
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+struct Env {
+ app: Router,
+ state: AppState,
+ general: String,
+ pool: SqlitePool,
+ data: PathBuf,
+ _tmp: TempDir,
+}
+
+async fn open(data: &Path) -> (Router, AppState, SqlitePool) {
+ let db = Database::init(data).await.unwrap();
+ let config = Config { data_dir: data.to_path_buf(), laya_url: "http://127.0.0.1:9".into(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };
+ let state = AppState::new(config.clone(), db, ToolRunner::new(data.join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
+ let pool = SqlitePoolOptions::new().max_connections(1).connect(&format!("sqlite://{}", data.join("kwnt.db").display())).await.unwrap();
+ (create_router(state.clone()), state, pool)
+}
+
+async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let (app, state, pool) = open(&data).await;
+ let general = state.db.list_channels(&SpaceId::default_space()).await.unwrap().into_iter().find(|c| c.name == "general").unwrap().id;
+ Env { app, state, general, pool, data, _tmp: tmp }
+}
+
+async fn call(app: &Router, method: &str, uri: &str, auth: Option<&str>, key: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ if let Some(token) = auth {
+ req = req.header("authorization", format!("Bearer {token}"));
+ }
+ if let Some(key) = key {
+ req = req.header("idempotency-key", key);
+ }
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+async fn person(e: &Env, method: &str, uri: &str, body: Option<Value>) -> Value {
+ let (status, v) = call(&e.app, method, uri, None, None, body).await;
+ assert!(status.is_success(), "{method} {uri}: {status} {v}");
+ v
+}
+
+async fn ledger(e: &Env, mode: &str) {
+ person(e, "POST", "/api/settings", Some(json!({"truth_ledger": mode}))).await;
+}
+
+async fn bot(e: &Env, name: &str) -> Kwant {
+ let input = NewKwant {
+ name: name.into(),
+ title: "Tester".into(),
+ persona_prompt: String::new(),
+ soul: String::new(),
+ avatar_sprite: "s".into(),
+ driver_type: "cli".into(),
+ preferred_model: "codex".into(),
+ };
+ e.state.db.create_kwant(&SpaceId::default_space(), &input).await.unwrap()
+}
+
+/// A turn for `bot`: its id and the bot's token.
+async fn turn(e: &Env, bot: &Kwant) -> (String, String) {
+ let turn_id = format!("t-{}", uuid::Uuid::new_v4());
+ let origin = TurnOrigin { channel_id: Some(e.general.clone()), ..Default::default() };
+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), origin: Some(origin), turn_id: Some(turn_id.clone()), ..Default::default() };
+ let token = mcp_runtime::prepare_turn_with_self(&e.state, bot, Some(turn_id.clone()), None, Some(scope)).await.unwrap().1;
+ (turn_id, token)
+}
+
+async fn tool(e: &Env, token: &str, name: &str, args: Value) -> String {
+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});
+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), None, Some(rpc)).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_ne!(v["result"]["isError"], json!(true), "{name}: {v}");
+ v["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string()
+}
+
+/// `Saved as [id].` → id
+fn saved_id(reply: &str) -> String {
+ reply.split('[').nth(1).and_then(|s| s.split(']').next()).unwrap().to_string()
+}
+
+/// (statement, trust, status, source_kind, source_ref, pinned, decided_by) of a memory's facts, oldest first.
+type Row = (String, String, String, String, Option<String>, bool, Option<String>);
+
+async fn facts_of(e: &Env, memory_id: &str) -> Vec<Row> {
+ sqlx::query_as("SELECT statement, trust, status, source_kind, source_ref, pinned, decided_by FROM knowledge_facts WHERE memory_id = ? ORDER BY rowid")
+ .bind(memory_id)
+ .fetch_all(&e.pool)
+ .await
+ .unwrap()
+}
+
+async fn live_fact(e: &Env, memory_id: &str) -> (String, String, String) {
+ sqlx::query_as("SELECT id, trust, status FROM knowledge_facts WHERE memory_id = ? AND status <> 'superseded'")
+ .bind(memory_id)
+ .fetch_one(&e.pool)
+ .await
+ .unwrap()
+}
+
+async fn events(e: &Env, memory_id: &str) -> Vec<String> {
+ sqlx::query_as::<_, (String,)>(
+ "SELECT ev.kind FROM fact_events ev JOIN knowledge_facts f ON f.id = ev.fact_id WHERE f.memory_id = ? ORDER BY ev.id",
+ )
+ .bind(memory_id)
+ .fetch_all(&e.pool)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|r| r.0)
+ .collect()
+}
+
+async fn count(pool: &SqlitePool, sql: &str) -> i64 {
+ sqlx::query_as::<_, (i64,)>(sql).fetch_one(pool).await.unwrap().0
+}
+
+/// A memory the bot itself wrote, mirrored as a fact a person can decide: outside, so proposed.
+async fn proposed_fact(e: &Env) -> String {
+ let a = bot(e, "Ana").await;
+ let (turn_id, token) = turn(e, &a).await;
+ truth_ledger::taint(&turn_id);
+ let id = saved_id(&tool(e, &token, "memory_add", json!({"text": "The vendor's SLA is 99.9%"})).await);
+ live_fact(e, &id).await.0
+}
+
+#[tokio::test]
+async fn the_setting_is_off_by_default_person_only_and_validated() {
+ let e = setup().await;
+ let s = person(&e, "GET", "/api/settings", None).await;
+ assert_eq!(s["truth_ledger"], "off");
+ let (status, _) = call(&e.app, "POST", "/api/settings", None, None, Some(json!({"truth_ledger": "loud"}))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ for m in ["shadow", "on", "off"] {
+ ledger(&e, m).await;
+ assert_eq!(person(&e, "GET", "/api/settings", None).await["truth_ledger"], m);
+ }
+ // Off: nothing to read and nothing to decide, though the mirror keeps the facts
+ let a = bot(&e, "Ana").await;
+ e.state.db.add_memory(&a.id, "Likes tea", "agent").await.unwrap();
+ assert_eq!(person(&e, "GET", "/api/facts", None).await, json!({"setting": "off", "facts": []}));
+ assert_eq!(count(&e.pool, "SELECT COUNT(*) FROM knowledge_facts").await, 1);
+}
+
+#[tokio::test]
+async fn mirror_follows_insert_update_pin_and_delete() {
+ let e = setup().await;
+ let a = bot(&e, "Ana").await;
+ let m = e.state.db.add_memory(&a.id, "Standup is at 10", "agent").await.unwrap();
+ assert_eq!(facts_of(&e, &m.id).await, vec![("Standup is at 10".into(), "bot".into(), "accepted".into(), "bot".into(), None, false, None)]);
+ let (scope, scope_id, author, space): (String, String, Option<String>, String) =
+ sqlx::query_as("SELECT scope, scope_id, author_kwant_id, space_id FROM knowledge_facts WHERE memory_id = ?").bind(&m.id).fetch_one(&e.pool).await.unwrap();
+ assert_eq!((scope.as_str(), scope_id.as_str(), author.as_deref(), space.as_str()), ("bot", a.id.as_str(), Some(a.id.as_str()), "spc_default"));
+
+ // Update: the old fact is superseded by the new one, history kept
+ e.state.db.agent_update_memory(&a.id, &m.id, "Standup is at 9:30").await.unwrap();
+ let rows = facts_of(&e, &m.id).await;
+ assert_eq!(rows.len(), 2);
+ assert_eq!((rows[0].0.as_str(), rows[0].2.as_str()), ("Standup is at 10", "superseded"));
+ assert_eq!((rows[1].0.as_str(), rows[1].2.as_str()), ("Standup is at 9:30", "accepted"));
+ let (old_next, new_id): (Option<String>, String) = sqlx::query_as(
+ "SELECT (SELECT superseded_by FROM knowledge_facts WHERE memory_id = ?1 AND status = 'superseded'), \
+ (SELECT id FROM knowledge_facts WHERE memory_id = ?1 AND status = 'accepted')",
+ )
+ .bind(&m.id)
+ .fetch_one(&e.pool)
+ .await
+ .unwrap();
+ assert_eq!(old_next.as_deref(), Some(new_id.as_str()));
+
+ // The person edits it: their words now
+ e.state.db.update_memory(&a.id, &m.id, "Standup is at 9").await.unwrap();
+ let rows = facts_of(&e, &m.id).await;
+ assert_eq!((rows[2].1.as_str(), rows[2].2.as_str(), rows[2].3.as_str(), rows[2].6.as_deref()), ("person", "accepted", "person", Some("person")));
+
+ // Pin and unpin
+ e.state.db.set_memory_pinned(&a.id, &m.id, PinChange { pinned: true, by_person: true }).await.unwrap();
+ assert!(facts_of(&e, &m.id).await[2].5);
+ e.state.db.set_memory_pinned(&a.id, &m.id, PinChange { pinned: false, by_person: true }).await.unwrap();
+ assert!(!facts_of(&e, &m.id).await[2].5);
+
+ // Delete: the fact is superseded with no successor, nothing live is left
+ assert!(e.state.db.delete_memory(&a.id, &m.id).await.unwrap());
+ assert!(facts_of(&e, &m.id).await.iter().all(|r| r.2 == "superseded"));
+ assert_eq!(events(&e, &m.id).await, ["created", "superseded", "created", "superseded", "created", "pinned", "unpinned", "removed"]);
+
+ // Events are append-only
+ let upd = sqlx::query("UPDATE fact_events SET kind = 'created'").execute(&e.pool).await;
+ assert!(upd.is_err(), "fact_events can't be rewritten");
+ let del = sqlx::query("DELETE FROM fact_events").execute(&e.pool).await;
+ assert!(del.is_err(), "fact_events of a fact that exists can't be deleted");
+}
+
+#[tokio::test]
+async fn status_rules_hold_in_the_database() {
+ let e = setup().await;
+ let a = bot(&e, "Ana").await;
+ let m = e.state.db.add_memory(&a.id, "Likes tea", "agent").await.unwrap();
+ let (fid, _, _) = live_fact(&e, &m.id).await;
+ // Outside can't be accepted except by the person
+ let r = sqlx::query("UPDATE knowledge_facts SET trust = 'outside', status = 'accepted', decided_by = 'evidence' WHERE id = ?").bind(&fid).execute(&e.pool).await;
+ assert!(r.is_err(), "outside+accepted needs the person");
+ // A superseded fact is final
+ sqlx::query("UPDATE knowledge_facts SET status = 'superseded' WHERE id = ?").bind(&fid).execute(&e.pool).await.unwrap();
+ let r = sqlx::query("UPDATE knowledge_facts SET status = 'accepted' WHERE id = ?").bind(&fid).execute(&e.pool).await;
+ assert!(r.is_err(), "superseded is terminal");
+ // A team-scope fact can't be accepted except by the person
+ let r = sqlx::query(
+ "INSERT INTO knowledge_facts (id, space_id, scope, scope_id, statement, source_kind, trust, status, valid_from, created_at, updated_at) \
+ VALUES ('f_x', 'spc_default', 'team', 't1', 's', 'bot', 'bot', 'accepted', 'now', 'now', 'now')",
+ )
+ .execute(&e.pool)
+ .await;
+ assert!(r.is_err(), "non-bot scope needs the person to accept");
+}
+
+#[tokio::test]
+async fn backfill_is_idempotent() {
+ let e = setup().await;
+ let a = bot(&e, "Ana").await;
+ for t in ["One", "Two", "Three"] {
+ 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");
+ sqlx::query("DELETE FROM knowledge_facts").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);
+ assert_eq!(count(&e.pool, "SELECT COUNT(*) FROM fact_events WHERE kind = 'backfilled'").await, 3);
+}
+
+#[tokio::test]
+async fn memory_add_in_a_tainted_turn_lands_outside_proposed_and_stays_visible() {
+ let e = setup().await;
+ ledger(&e, "shadow").await;
+ let a = bot(&e, "Ana").await;
+
+ // A clean turn: the bot's own note
+ let (_, clean) = turn(&e, &a).await;
+ let mine = saved_id(&tool(&e, &clean, "memory_add", json!({"text": "Oleks prefers short replies"})).await);
+ assert_eq!(live_fact(&e, &mine).await.1, "bot");
+ assert_eq!(live_fact(&e, &mine).await.2, "accepted");
+
+ // A turn that read a web page
+ let (turn_id, token) = turn(&e, &a).await;
+ assert!(truth_ledger::reads_outside("WebFetch") && truth_ledger::reads_outside("mcp__github__get_issue"));
+ assert!(!truth_ledger::reads_outside("mcp__kwnt_tools__memory_add"));
+ truth_ledger::taint(&turn_id);
+ let theirs = saved_id(&tool(&e, &token, "memory_add", json!({"text": "The API limit is 50 rps"})).await);
+ let rows = facts_of(&e, &theirs).await;
+ assert_eq!(rows, vec![("The API limit is 50 rps".into(), "outside".into(), "proposed".into(), "bot".into(), Some(turn_id.clone()), false, None)]);
+ assert_eq!(count(&e.pool, "SELECT COUNT(*) FROM fact_provenance").await, 0, "provenance is consumed");
+
+ // Still visible to the bot (D3)
+ let memories = e.state.db.list_memories(&a.id).await.unwrap();
+ assert!(memory_block(&memories, true).contains("The API limit is 50 rps"));
+
+ // Rewriting it in a later clean turn doesn't launder it
+ let (_, later) = turn(&e, &a).await;
+ tool(&e, &later, "memory_update", json!({"id": theirs, "text": "The API limit is 60 rps"})).await;
+ assert_eq!(live_fact(&e, &theirs).await.1, "outside");
+ assert_eq!(live_fact(&e, &theirs).await.2, "proposed");
+
+ // The turn's end clears the bit
+ truth_ledger::end_turn(&turn_id);
+ assert!(!truth_ledger::is_tainted(&turn_id));
+}
+
+#[tokio::test]
+async fn an_import_lands_outside_proposed_with_source_still_user() {
+ let e = setup().await;
+ let fixture = std::fs::read(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/import/kwant-bundle.json")).unwrap();
+ let req = Request::builder()
+ .method("POST")
+ .uri("/api/import/preview?space=spc_default&filename=kwant-bundle.json")
+ .header("content-type", "application/octet-stream")
+ .body(Body::from(fixture))
+ .unwrap();
+ let resp = e.app.clone().oneshot(req).await.unwrap();
+ let preview: Value = serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap();
+ let (status, applied) = call(&e.app, "POST", "/api/import/apply?space=spc_default", None, None, Some(json!({"bundle": preview["bundle"], "skip": []}))).await;
+ assert_eq!(status, StatusCode::CREATED, "{applied}");
+ let import_id = applied["import"]["id"].as_str().unwrap();
+ let bot_id = applied["import"]["created"]["kwants"][0]["id"].as_str().unwrap();
+ let memories = e.state.db.list_memories(bot_id).await.unwrap();
+ assert_eq!(memories.len(), 1);
+ assert_eq!((memories[0].source.as_str(), memories[0].imported), ("user", true), "the memory row is unchanged");
+ let rows = facts_of(&e, &memories[0].id).await;
+ assert_eq!(rows.len(), 1);
+ assert_eq!((rows[0].1.as_str(), rows[0].2.as_str(), rows[0].3.as_str(), rows[0].4.as_deref()), ("outside", "proposed", "import", Some(import_id)));
+
+ // Undoing the import takes its facts with it
+ let token = e.state.api_token.reveal().to_string();
+ let (status, v) = call(&e.app, "POST", &format!("/api/imports/{import_id}/undo"), Some(&token), None, None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_eq!(count(&e.pool, &format!("SELECT COUNT(*) FROM knowledge_facts WHERE scope_id = '{bot_id}'")).await, 0);
+}
+
+#[tokio::test]
+async fn memory_block_is_byte_identical_with_the_ledger_off_and_shadow() {
+ let e = setup().await;
+ let a = bot(&e, "Ana").await;
+ let (turn_id, token) = turn(&e, &a).await;
+ e.state.db.add_memory(&a.id, "Person wrote this", "user").await.unwrap();
+ tool(&e, &token, "memory_add", json!({"text": "Own note", "pinned": true})).await;
+ truth_ledger::taint(&turn_id);
+ tool(&e, &token, "memory_add", json!({"text": "Read on a web page"})).await;
+
+ let mut blocks = Vec::new();
+ for m in ["off", "shadow", "on"] {
+ ledger(&e, m).await;
+ let memories = e.state.db.list_memories(&a.id).await.unwrap();
+ blocks.push((memory_block(&memories, true), memory_block(&memories, false)));
+ }
+ assert_eq!(blocks[0], blocks[1]);
+ assert_eq!(blocks[0], blocks[2], "`on` is shadow in C1");
+}
+
+#[tokio::test]
+async fn a_bot_token_gets_403_on_every_facts_route() {
+ let e = setup().await;
+ ledger(&e, "shadow").await;
+ let fid = proposed_fact(&e).await;
+ let b = bot(&e, "Bea").await;
+ let (_, token) = turn(&e, &b).await;
+ for (method, uri) in [
+ ("GET", "/api/facts".to_string()),
+ ("GET", format!("/api/facts/{fid}")),
+ ("POST", format!("/api/facts/{fid}/accept")),
+ ("POST", format!("/api/facts/{fid}/reject")),
+ ] {
+ let (status, v) = call(&e.app, method, &uri, Some(&token), Some("k1"), None).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{method} {uri}: {v}");
+ }
+ // Nor can a bot turn the ledger on or off
+ let (status, _) = call(&e.app, "POST", "/api/settings", Some(&token), None, Some(json!({"truth_ledger": "off"}))).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ 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.2, "proposed");
+}
+
+#[tokio::test]
+async fn the_person_reads_and_decides_facts() {
+ let e = setup().await;
+ let fid = proposed_fact(&e).await;
+ let (status, _) = call(&e.app, "POST", &format!("/api/facts/{fid}/accept"), None, None, None).await;
+ assert_eq!(status, StatusCode::CONFLICT, "nothing to decide with the ledger off");
+ ledger(&e, "shadow").await;
+
+ let list = person(&e, "GET", "/api/facts?status=proposed", None).await;
+ assert_eq!(list["setting"], "shadow");
+ assert_eq!(list["facts"].as_array().unwrap().len(), 1);
+ assert_eq!(person(&e, "GET", "/api/facts?q=SLA", None).await["facts"].as_array().unwrap().len(), 1);
+ assert_eq!(person(&e, "GET", "/api/facts?q=nothing%25", None).await["facts"].as_array().unwrap().len(), 0);
+ let (status, _) = call(&e.app, "GET", "/api/facts?status=maybe", None, None, None).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+
+ let one = person(&e, "GET", &format!("/api/facts/{fid}"), None).await;
+ assert_eq!(one["fact"]["status"], "proposed");
+ assert_eq!(one["events"][0]["kind"], "created");
+ let (status, _) = call(&e.app, "GET", "/api/facts/f_nope", None, None, None).await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+
+ let v = person(&e, "POST", &format!("/api/facts/{fid}/accept"), None).await;
+ assert_eq!((v["fact"]["status"].as_str(), v["fact"]["decided_by"].as_str()), (Some("accepted"), Some("person")));
+ let (status, v) = call(&e.app, "POST", &format!("/api/facts/{fid}/reject"), None, None, None).await;
+ assert_eq!((status, v["status"].as_str()), (StatusCode::CONFLICT, Some("accepted")));
+
+ // Reject: superseded, the note itself untouched in C1
+ let a = bot(&e, "Cy").await;
+ let (turn_id, token) = turn(&e, &a).await;
+ truth_ledger::taint(&turn_id);
+ let mid = saved_id(&tool(&e, &token, "memory_add", json!({"text": "Prices rise in May"})).await);
+ let fid2 = live_fact(&e, &mid).await.0;
+ let v = person(&e, "POST", &format!("/api/facts/{fid2}/reject"), None).await;
+ assert_eq!(v["fact"]["status"], "superseded");
+ assert_eq!(v["events"].as_array().unwrap().last().unwrap()["kind"], "rejected");
+ assert_eq!(e.state.db.list_memories(&a.id).await.unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn ten_racing_accepts_make_one_change() {
+ let e = setup().await;
+ ledger(&e, "shadow").await;
+ let fid = proposed_fact(&e).await;
+ let mut handles = Vec::new();
+ for i in 0..10 {
+ let app = e.app.clone();
+ let uri = format!("/api/facts/{fid}/accept");
+ handles.push(tokio::spawn(async move { call(&app, "POST", &uri, None, Some(&format!("race-{i}")), None).await.0 }));
+ }
+ let mut statuses = Vec::new();
+ for h in handles {
+ statuses.push(h.await.unwrap());
+ }
+ assert_eq!(statuses.iter().filter(|s| **s == StatusCode::OK).count(), 1, "{statuses:?}");
+ assert_eq!(statuses.iter().filter(|s| **s == StatusCode::CONFLICT).count(), 9, "{statuses:?}");
+ assert_eq!(count(&e.pool, &format!("SELECT COUNT(*) FROM fact_events WHERE fact_id = '{fid}' AND kind = 'accepted'")).await, 1);
+
+ // The same key replays rather than conflicting
+ let (s1, v1) = call(&e.app, "POST", &format!("/api/facts/{fid}/accept"), None, Some("race-again"), None).await;
+ let (s2, v2) = call(&e.app, "POST", &format!("/api/facts/{fid}/accept"), None, Some("race-again"), None).await;
+ assert_eq!((s1, s2), (StatusCode::CONFLICT, StatusCode::CONFLICT));
+ assert_eq!(v1, v2);
+}
+
+#[tokio::test]
+async fn deleting_a_bot_removes_its_facts() {
+ let e = setup().await;
+ let a = bot(&e, "Ana").await;
+ e.state.db.add_memory(&a.id, "Secret-ish preference", "agent").await.unwrap();
+ assert_eq!(count(&e.pool, "SELECT COUNT(*) FROM knowledge_facts").await, 1);
+ 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, "SELECT COUNT(*) FROM knowledge_facts").await, 0);
+ assert_eq!(count(&e.pool, "SELECT COUNT(*) FROM fact_events").await, 0);
+}
+
+#[tokio::test]
+async fn migrating_a_copy_of_an_existing_database_keeps_every_memory() {
+ // An existing install: memories written before the ledger existed
+ let e = setup().await;
+ let a = bot(&e, "Ana").await;
+ let b = bot(&e, "Bea").await;
+ for i in 0..5 {
+ e.state.db.add_memory(&a.id, &format!("Ana note {i}"), "agent").await.unwrap();
+ }
+ e.state.db.add_memory(&b.id, "Bea's person note", "user").await.unwrap();
+ for stmt in TRUTH_LEDGER_DOWN {
+ sqlx::query(stmt).execute(&e.pool).await.unwrap();
+ }
+ sqlx::query("UPDATE kwant_memories SET imported = 1 WHERE kwant_id = ?").bind(&b.id).execute(&e.pool).await.unwrap();
+ let memories_before = count(&e.pool, "SELECT COUNT(*) FROM kwant_memories").await;
+ let before: Vec<(String, String, String)> =
+ sqlx::query_as("SELECT id, text, source FROM kwant_memories ORDER BY id").fetch_all(&e.pool).await.unwrap();
+ e.pool.close().await;
+
+ // Copy it and start the new binary on the copy
+ let copy = tempdir().unwrap();
+ let data = copy.path().join("data");
+ std::fs::create_dir_all(&data).unwrap();
+ for f in ["kwnt.db", "kwnt.db-wal", "kwnt.db-shm"] {
+ if e.data.join(f).exists() {
+ std::fs::copy(e.data.join(f), data.join(f)).unwrap();
+ }
+ }
+ let (_, state, pool) = open(&data).await;
+ let after: Vec<(String, String, String)> = sqlx::query_as("SELECT id, text, source FROM kwant_memories ORDER BY id").fetch_all(&pool).await.unwrap();
+ assert_eq!(after, before, "no memory moved or changed");
+ assert_eq!(count(&pool, "SELECT COUNT(*) FROM knowledge_facts").await, memories_before);
+ assert_eq!(count(&pool, "SELECT COUNT(*) FROM knowledge_facts f JOIN kwant_memories m ON m.id = f.memory_id AND m.text = f.statement").await, memories_before);
+ assert_eq!(count(&pool, "SELECT COUNT(*) FROM knowledge_facts WHERE trust = 'outside' AND status = 'proposed'").await, 1, "the imported note");
+ assert_eq!(count(&pool, "SELECT COUNT(*) FROM fact_events WHERE kind = 'backfilled'").await, memories_before);
+ // Starting again changes nothing
+ pool.close().await;
+ drop(state);
+ let (_, _state, pool) = open(&data).await;
+ assert_eq!(count(&pool, "SELECT COUNT(*) FROM knowledge_facts").await, memories_before);
+ assert_eq!(count(&pool, "SELECT COUNT(*) FROM fact_events").await, memories_before);
+}