/** * RESTORE AUDIT 2 (coordinator, 27 Nov 2026): what each token and device row held at its last LOGGED write, so the * restore audit can tell a row a restore laid or rewrote (which logs nothing) from one only touched by the object's * own silent stamps (a token's last use, a device's pass). * * The change log cannot say it: a create or update keeps the NAMES of what it wrote, never the values * (changes.ts `Journal.record`), so no change row's `after` can be compared with a row. Here, every write the engine * logs (`engine.journal` set) on a watched table keeps the row's data less its silent stamps (`row_witness`); a restore * runs with no journal and keeps none. The audit then holds each row to its witness: * - no witness: no logged create laid it (a restore did, or a write that should have logged): suspect; * - the witness differs in any field but the silent stamps: suspect, and it stays so (a later logged write on a row * that no longer matches its witness marks it broken, never launders it); * - else explained. A stamp named "only earlier" (a token's `expires_at`, ended early by the object) explains a * value earlier than the witness, never a later one. * Every row standing when witnesses began is adopted as it stood then (`adopted`): counted as not judged. */ type Data = Record; /** The tables the restore audit watches. */ export const WITNESSED = ["mcp_token", "device"] as const; /** * The fields the object writes on these tables with no change row (an `engine().update(..., new Outcome_())` with no * journal), by table: the one list the audit leaves out and the writes take their keys from * (business.ts `stampUsed`, `renewLegacy`; sync_status.ts `refreshDevice`, `recordPage`). */ export const SILENT_STAMPS = { mcp_token: ["last_used_at", "expires_at"], device: ["name", "platform", "app_version", "synced_at", "sync_version", "sync_rows_total", "sync_rows_done", "caught_up"], } as const satisfies Record<(typeof WITNESSED)[number], readonly string[]>; /** Silent stamps that may only move a value earlier: kept in the witness, and a later value is not explained. */ export const ONLY_EARLIER: Record = { mcp_token: ["expires_at"] }; export const SCHEMA = "CREATE TABLE IF NOT EXISTS row_witness (table_id TEXT NOT NULL, record_id TEXT NOT NULL, data TEXT NOT NULL, broken INTEGER NOT NULL DEFAULT 0, adopted INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (table_id, record_id))"; /** When witnesses began on this object (meta): every row standing then was adopted. */ export const FROM_META = "row_witness_from"; export function isWitnessed(table: string): boolean { return (WITNESSED as readonly string[]).includes(table); } function canonical(v: unknown): string { if (v && typeof v === "object" && !Array.isArray(v)) { const o = v as Record; return `{${Object.keys(o).filter((k) => o[k] !== undefined).sort().map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`).join(",")}}`; } return JSON.stringify(v ?? null); } /** A row's data as its witness keeps it: less the silent stamps, but for the "only earlier" ones. */ export function witnessOf(table: string, data: Data): string { const stamps = (SILENT_STAMPS as Record)[table] ?? []; const kept = ONLY_EARLIER[table] ?? []; const out: Data = {}; for (const [k, v] of Object.entries(data)) if (!stamps.includes(k) || kept.includes(k)) out[k] = v ?? null; return canonical(out); } /** Whether `data` is what the witness kept, but for silent stamps (an "only earlier" one no later than kept). */ export function explains(table: string, witness: string, data: Data): boolean { const kept = ONLY_EARLIER[table] ?? []; const held = JSON.parse(witness) as Data; const now = JSON.parse(witnessOf(table, data)) as Data; for (const k of kept) { const was = held[k]; const is = now[k]; if (is !== was) { // An end made earlier by the object (or set where there was none) is a stamp; a later one is not. const earlier = typeof is === "string" && (was === null || was === undefined || (typeof was === "string" && Date.parse(is) <= Date.parse(was))); if (!earlier) return false; } delete held[k]; delete now[k]; } return canonical(held) === canonical(now); } /** A logged write on a watched table: a create keeps its witness; a write over a row keeps the new one only if the row still matched. */ export function noteLogged(sql: SqlStorage, table: string, id: string, before: Data | null, after: Data): void { if (!isWitnessed(table)) return; const held = sql.exec<{ data: string; broken: number }>("SELECT data, broken FROM row_witness WHERE table_id = ? AND record_id = ?", table, id).toArray()[0]; if (before === null) { // A create. One over a held witness (an id used again) is a write over that row. if (!held) { sql.exec("INSERT INTO row_witness (table_id, record_id, data) VALUES (?, ?, ?)", table, id, witnessOf(table, after)); return; } } // A write over a row with no witness (a restored one) keeps none: it stays unexplained. if (!held) return; const matched = held.broken === 0 && (before === null || explains(table, held.data, before)); sql.exec("UPDATE row_witness SET data = ?, broken = ?, adopted = 0 WHERE table_id = ? AND record_id = ?", witnessOf(table, after), matched ? 0 : 1, table, id); } /** Once per object: every watched row standing now is adopted as it stands. */ export function adopt(sql: SqlStorage, now: string, meta: { get(key: string): string | null; set(key: string, value: string): void }): void { sql.exec(SCHEMA); if (meta.get(FROM_META)) return; for (const table of WITNESSED) { for (const r of sql.exec<{ id: string; data: string }>("SELECT id, data FROM rows WHERE table_id = ?", table)) { let data: Data = {}; try { data = JSON.parse(r.data) as Data; } catch { // an unreadable row is adopted as empty: it will differ, and be said } sql.exec("INSERT OR IGNORE INTO row_witness (table_id, record_id, data, adopted) VALUES (?, ?, ?, 1)", table, r.id, witnessOf(table, data)); } } meta.set(FROM_META, now); } export interface Judged { /** Rows a restore may have laid or rewritten: ids, times and why, never data. */ unexplained: { table: string; id: string; version: number; created_at: string; deleted: boolean; why: "no_logged_create" | "differs" }[]; /** Rows adopted as they stood when witnesses began, and untouched by a logged write since. */ notJudged: number; rows: number; } export function judge(sql: SqlStorage): Judged { const out: Judged = { unexplained: [], notJudged: 0, rows: 0 }; for (const table of WITNESSED) { for (const r of sql.exec<{ id: string; version: number; created_at: string; deleted: number; data: string }>("SELECT id, version, created_at, deleted, data FROM rows WHERE table_id = ?", table)) { out.rows++; const w = sql.exec<{ data: string; broken: number; adopted: number }>("SELECT data, broken, adopted FROM row_witness WHERE table_id = ? AND record_id = ?", table, r.id).toArray()[0]; let data: Data = {}; try { data = JSON.parse(r.data) as Data; } catch { data = {}; } const row = { table, id: r.id, version: Number(r.version), created_at: r.created_at, deleted: r.deleted === 1 }; if (!w) out.unexplained.push({ ...row, why: "no_logged_create" }); else if (w.broken === 1 || !explains(table, w.data, data)) out.unexplained.push({ ...row, why: "differs" }); else if (w.adopted === 1) out.notJudged++; } } return out; }