/** * THE UNDO-HISTORY SHRINK, PROVEN ON THE DEV WORKER (coordinator for the owner, 23 Nov 2026). An invented account is * given the owner's undo history (about 82,000 old-style change-log entries, 2.4 GB, spread back over 90 days), then * the per-account switch of 9224954f16 is set (30 days, 500 MB) and the Worker's own alarms trim it. It says: * entries and bytes before and after, the file before and after, how long the trim ran and the slowest read during * it, that the switch was off until set, that every record and its latest version stand as they were, and that * recent changes are still undone. Invented data only; refuses any server but the dev Worker. * * pnpm -s exec tsx scripts/undo-shrink-proof.ts --number +1555… [--entries 82000] [--chars 29300] [--notes 2000] [--recent 300] * * The sign-in code is read from ~/.cotton-credentials/cotton/dev-otp and never printed. The planting route * (POST /v1/admin/dev/plant-history) answers only on the dev and test Workers. */ import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { signIn, type Session } from "./dev-seed/client.ts"; import { devBase } from "./dev-server"; const arg = (name: string, fallback?: string) => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1]! : fallback; }; // The dev Worker, or a local `wrangler dev` (http://127.0.0.1:) to try the script small first. Nothing else. const DEV = arg("base", devBase())!; if (DEV !== devBase() && !/^http:\/\/127\.0\.0\.1:\d+$/.test(DEV)) throw new Error("--base is the dev Worker or a local wrangler dev"); const NUMBER = arg("number"); const ENTRIES = Number(arg("entries", "82000")); const CHARS = Number(arg("chars", "29300")); const NOTES = Number(arg("notes", "2000")); const RECENT = Number(arg("recent", "0")); const BUDGET = Number(arg("budget", "500000000")); const STEP = 1_000; // Filler rows of a table of their own, so the account holds about as many rows as the owner's (about a million). const FILLER = Number(arg("rows", "0")); // Waits for this file before the off check and the switch: the time to sign phones in and let them sync. const WAIT_FOR = arg("wait-for"); // The session's owner token, written here (mode 600) for the undo and restore after; an invented account's. const SESSION_FILE = arg("session-file"); // An open table (no seal), so the account's own assistant token writes, reads and undoes with no grant from a phone; // the log and its trim are the same for every table. His history was mostly sealed notes: the planted entries are // shaped as theirs (a sealed body before and after). const TABLE = "decision"; if (!NUMBER || !/^\+1555\d{7}$/.test(NUMBER)) throw new Error("--number is an invented +1555 number"); const say = (line: string) => console.log(`[undo-shrink] ${new Date().toISOString().slice(11, 19)} ${line}`); async function call(s: Session, method: string, path: string, body?: unknown): Promise<{ status: number; body: T }> { for (let attempt = 0; ; attempt++) { try { const res = await fetch(`${DEV}${path}`, { method, headers: { "content-type": "application/json", authorization: `Bearer ${s.token}` }, body: body === undefined ? undefined : JSON.stringify(body) }); const text = await res.text(); if (res.status >= 500 && attempt < 4) throw new Error(`${res.status} ${text.slice(0, 200)}`); return { status: res.status, body: (text ? JSON.parse(text) : {}) as T }; } catch (error) { if (attempt >= 4) throw error; say(`retry ${path}: ${error instanceof Error ? error.message : String(error)}`); await new Promise((done) => setTimeout(done, 3_000 * (attempt + 1))); } } } async function tool(s: Session, name: string, args: Record): Promise { const r = await call<{ result?: { isError: boolean; content: { text: string }[] } }>(s, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }); const result = r.body.result; if (!result || result.isError) throw new Error(`${name}: ${JSON.stringify(r.body).slice(0, 400)}`); return JSON.parse(result.content[0]!.text) as T; } interface Summary { database: { bytes: number }; change_log: { rows: number; keeps: unknown; chars?: { counted: number; ready: boolean } } } const summary = (s: Session) => tool(s, "storage_summary", { parts: false }); /** Every live row as id, version and data, through the export's pages. */ async function snapshot(s: Session): Promise> { const out = new Map(); let after: string | null = null; for (;;) { const page: { body: { rows: { table: string; id: string; version: number; data: unknown }[]; next: string | null } } = await call(s, "GET", `/v1/admin/export?limit=5000${after ? `&after=${encodeURIComponent(after)}` : ""}`); // The script's own token row marks each use: it is the one row a read changes, so it is left out. for (const r of page.body.rows) if (r.table !== "mcp_token") out.set(`${r.table}/${r.id}`, `${r.version} ${JSON.stringify(r.data)}`); if (!page.body.next) return out; after = page.body.next; } } const mb = (n: number) => `${(n / 1e6).toFixed(0)} MB`; async function main() { // A local wrangler dev takes its own fixed code (--local-code); the dev Worker's is read from its file, never printed. const code = DEV.startsWith("http://127.0.0.1:") ? arg("local-code", "123456")! : readFileSync(`${homedir()}/.cotton-credentials/cotton/dev-otp`, "utf8").trim(); const s = await signIn(DEV, NUMBER!, code); say(`signed in as an invented account on the dev Worker`); if (SESSION_FILE) writeFileSync(SESSION_FILE, JSON.stringify({ base: DEV, token: s.token }), { mode: 0o600 }); const fresh = await summary(s); // --resume: the account was filled by an earlier run (its records and history stand); go on from the snapshot. const resume = process.argv.includes("--resume"); if (fresh.change_log.rows > 1_000 && !resume) throw new Error(`this account already holds ${fresh.change_log.rows} log entries: use a fresh invented number`); // 1. Invented notes, the records the history is about. const ids: string[] = []; for (let i = 0; i < (resume ? 0 : NOTES); i += 500) { const rows = Array.from({ length: Math.min(500, NOTES - i) }, (_x, k) => ({ table: TABLE, id: crypto.randomUUID(), data: { title: `Invented note ${i + k}: a line about the garden, the market and the walk home.` } })); const r = await call(s, "POST", "/v1/admin/import", { rows }); if (r.status !== 200) throw new Error(`import: ${r.status} ${JSON.stringify(r.body).slice(0, 300)}`); ids.push(...rows.map((x) => x.id)); } say(`${ids.length} invented notes`); for (let i = 0; i < (resume ? 0 : FILLER); i += 5_000) { const rows = Array.from({ length: Math.min(5_000, FILLER - i) }, (_x, k) => ({ table: "goal", id: crypto.randomUUID(), data: { title: `Invented goal ${i + k}`, why: "for the proof" } })); const r = await call(s, "POST", "/v1/admin/import", { rows }); if (r.status !== 200) throw new Error(`import filler: ${r.status} ${JSON.stringify(r.body).slice(0, 300)}`); if ((i / 5_000) % 20 === 0) say(`filler ${i + rows.length} of ${FILLER}`); } if (FILLER && !resume) say(`${FILLER} filler rows`); // 2. His undo history, planted old-style and spread back over 90 days. const t = Date.now(); for (let from = 0; from < (resume ? 0 : ENTRIES); from += STEP) { const r = await call(s, "POST", "/v1/admin/dev/plant-history", { table: TABLE, records: ids, entries: Math.min(STEP, ENTRIES - from), chars: CHARS, days: 90, from, of: ENTRIES }); if (r.status !== 200) throw new Error(`plant: ${r.status} ${JSON.stringify(r.body).slice(0, 300)}`); if ((from / STEP) % 10 === 0) say(`planted ${from + STEP} of ${ENTRIES}`); } say(`planted ${ENTRIES} entries in ${((Date.now() - t) / 1000).toFixed(0)} s`); // 3. Recent changes of the person's own, after the history. const recent: { id: string; change: number; was: string }[] = []; for (let i = 0; i < RECENT; i++) { const id = ids[i]!; // The owner's own write (the phone's act), as a person's recent edits are; it answers the change it logged. const res = await fetch(`${DEV}/v1/act`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${s.credential}` }, body: JSON.stringify({ act: "update", args: { table: TABLE, id, data: { title: `Invented note ${i}, rewritten today.` } } }) }); const answer = (await res.json()) as { change_id?: number; change?: number }; if (res.status !== 200) throw new Error(`update: ${res.status} ${JSON.stringify(answer).slice(0, 300)}`); recent.push({ id, change: Number(answer.change_id ?? answer.change), was: `Invented note ${i}: a line about the garden, the market and the walk home.` }); } say(`${RECENT} recent changes`); const before = await summary(s); const rowsBefore = await snapshot(s); say(`BEFORE: log ${before.change_log.rows} entries, file ${mb(before.database.bytes)}, ${rowsBefore.size} live rows; window ${JSON.stringify(before.change_log.keeps)}`); if (WAIT_FOR) { say(`waiting for ${WAIT_FOR}`); while (!existsSync(WAIT_FOR)) await new Promise((done) => setTimeout(done, 5_000)); } // 4. Off until set: the Worker's own alarms run for three minutes and take nothing. await new Promise((done) => setTimeout(done, Number(arg("idle", "180")) * 1000)); const idle = await summary(s); say(`OFF: after ${arg("idle", "180")} s unset, log ${idle.change_log.rows} entries (was ${before.change_log.rows})`); // New entries may come meanwhile (a signed-in phone's own writes); none may go. if (idle.change_log.rows < before.change_log.rows) throw new Error("the log shrank before the switch was set"); // 5. The switch, through the account's own route; then the alarms trim, a step each. const set = await call(s, "PUT", "/v1/admin/business", { change_days: 30, change_bytes: BUDGET }); if (set.status !== 200) throw new Error(`switch: ${set.status} ${JSON.stringify(set.body).slice(0, 300)}`); const t0 = Date.now(); let slowest = 0; let slowestSync = 0; let last = -1; let still = 0; for (;;) { await new Promise((done) => setTimeout(done, 10_000)); const r = Date.now(); const now = await summary(s); slowest = Math.max(slowest, Date.now() - r); const counted = now.change_log.chars; const p = Date.now(); const page = await call<{ rows?: unknown[] }>(s, "GET", "/v1/sync?tables=note&limit=100"); const pass = Date.now() - p; slowestSync = Math.max(slowestSync, pass); if (page.status !== 200) say(`sync page refused: ${page.status}`); still = now.change_log.rows === last ? still + 1 : 0; last = now.change_log.rows; say(`trimming: ${now.change_log.rows} entries, counted ${counted ? `${mb(counted.counted)}${counted.ready ? "" : " (counting)"}` : "not yet"}, summary ${slowest === 0 ? 0 : Date.now() - r - pass} ms, sync page ${pass} ms`); if (counted?.ready && counted.counted <= BUDGET && still >= 3) break; if (Date.now() - t0 > Number(arg("limit", "7200")) * 1000) throw new Error(`the trim did not finish in ${arg("limit", "7200")} s`); } const ran = (Date.now() - t0) / 1000; const after = await summary(s); const rowsAfter = await snapshot(s); // 6. Every record and its latest version as before. let same = 0; const differ: string[] = []; for (const [key, value] of rowsBefore) { if (rowsAfter.get(key) === value) same++; else differ.push(key); } say(`AFTER: log ${after.change_log.rows} entries, counted ${after.change_log.chars ? mb(after.change_log.chars.counted) : "?"}, file ${mb(after.database.bytes)}; trim ran ${ran.toFixed(0)} s, slowest read ${slowest} ms, slowest sync page ${slowestSync} ms`); say(`ROWS: ${same} of ${rowsBefore.size} identical with their versions; ${rowsAfter.size} live after; differing ${differ.length}${differ.length ? `: ${differ.slice(0, 5).join(", ")}` : ""}`); // 7. Recent changes kept: every one of them still stands in the log (undo reads them). Taking one back is an // assistant's tool, and a script's token reads nothing until the owner's phone signs the grant, so undo itself is // proven by the Worker's own test (test/plant-history.test.ts: after the trim, a recent change is undone). let undone = 0; if (recent.length) try { for (const r of recent.slice(-20)) { const listed = await tool<{ changes: { change_id: number }[] }>(s, "list_changes", { table: TABLE, id: r.id }); if (listed.changes.some((c) => c.change_id === r.change)) undone++; } } catch (error) { say(`list_changes refused the script's token (${error instanceof Error ? error.message.slice(0, 120) : String(error)})`); } if (recent.length) say(`RECENT: ${undone} of the newest 20 recent changes still in the log after the trim`); say(`RESULT entries ${before.change_log.rows} -> ${after.change_log.rows}; file ${mb(before.database.bytes)} -> ${mb(after.database.bytes)}; ${ran.toFixed(0)} s; slowest read ${slowest} ms; rows ${same}/${rowsBefore.size}; recent kept ${undone}/20`); } await main();