331 lines · 22.0 KB · TypeScriptRaw
/** * RULE (owner, 22 Nov 2026): `POST /v1/admin/erase` erases rows for good, on * the owner's word, on a personal database: every row of tables no kept app * lists, the photos and videos nothing else names, and session prompts older * than their 30 days. Without `confirm: "erase"` nothing that is a record * changes and the answer says what would go. A call works a bounded while and * says `more` until done. Phones are told: an erased whole table is named in * `dropped` on a pass from before it; a filtered row comes as a tombstone. * Every other row stays as it was. A table a kept app's kit lists, a system * table, and anyone but the owner are refused. */import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import { keptTables, type EraseAnswer } from "../src/erase.ts";import type { SyncAnswer } from "../src/protocol.ts";import { GONE_TABLES, KIT_RETIRED } from "../src/retired.ts";import type { Business } from "../src/business.ts";import { runStepJob } from "../src/jobs/step_job.ts";import { ADMIN, DATABASE_ID, http, personalObject } from "./personal.ts";import THOUGHT from "./fixtures/thought.json"; // the retired definition as it shipped (TABLE DROP 1)const ROUTE = "/v1/admin/erase";const AT = "2026-10-01T06:00:00.000Z";const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const KEY = (rest: string): string => `${DATABASE_ID}/${rest}`;type Row = [table: string, id: string, data: Record<string, unknown>, deleted?: number];async function seed(slug: string, rows: Row[], links: [string, string, string, string][] = []): Promise<void> { await runInDurableObject(stub(slug), (_i, state) => { const sql = state.storage.sql; let v = Number(sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'version'").toArray()[0]?.value ?? "0"); for (const [table, id, data, deleted = 0] of rows) { v += 1; sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES (?, ?, ?, NULL, ?, ?, ?, ?)", table, id, JSON.stringify(data), v, deleted, AT, AT); } for (const [table, id, column, target] of links) sql.exec("INSERT INTO links (table_id, id, column, target) VALUES (?, ?, ?, ?)", table, id, column, target); sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('version', ?)", String(v)); });}/** Every row outside `tables`, as stored: what must not change. */async function others(slug: string, tables: string[]): Promise<string[]> { return runInDurableObject(stub(slug), (_i, state) => state.storage.sql .exec<{ r: string }>(`SELECT table_id || '/' || id || '/' || version || '/' || deleted || '/' || data AS r FROM rows WHERE table_id NOT IN (${tables.map((t) => `'${t}'`).join(", ")}) ORDER BY table_id, id`) .toArray() .map((x) => x.r), );}async function version(slug: string): Promise<number> { return runInDurableObject(stub(slug), (_i, state) => Number(state.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'version'").one().value));}/** Calls until done: every answer, the last one last. */async function untilDone(slug: string, body: Record<string, unknown>, auth: Record<string, string>): Promise<EraseAnswer[]> { const out: EraseAnswer[] = []; for (let i = 0; i < 200; i++) { const res = await http<EraseAnswer>(slug, "POST", ROUTE, body, auth); expect(res.status, JSON.stringify(res.body)).toBe(200); out.push(res.body); if (res.body.done) return out; } throw new Error("the erase never finished");}describe("erasing whole tables", () => { // TABLE DROP 1 (27 Nov 2026): a retired table is erased whole by the later commit, so neither a parked app's kit // (Money's transaction, Music's song) nor the system list (decision, location, meeting) keeps it. it("keeps no table held as retired", () => { const kept = keptTables(); expect(GONE_TABLES.filter((t) => kept.has(t))).toEqual([]); expect(kept.get("note")).toBeTruthy(); expect(kept.get("session_task")).toBe("a system table"); }); it("refuses kept and system tables, a bad body, a business and anyone but the owner", async () => { const slug = "erase-refusals"; const { owner, credential } = await personalObject(slug); const auth = ADMIN; for (const [body, code] of [ [{ set: "tables", tables: ["note"] }, "kept_table"], [{ set: "tables", tables: ["message"] }, "kept_table"], [{ set: "tables", tables: ["prompt"] }, "kept_table"], [{ set: "tables", tables: ["media"] }, "kept_table"], [{ set: "tables", tables: ["device"] }, "kept_table"], [{ set: "tables", tables: [] }, "bad_erase"], [{ set: "tables", tables: ["Robert'); DROP"] }, "bad_erase"], [{ set: "everything" }, "bad_erase"], [{ set: "old_prompts", days: 0 }, "bad_erase"], ] as const) { const res = await http<{ code: string }>(slug, "POST", ROUTE, body, auth); expect(res.body.code, JSON.stringify(body)).toBe(code); } expect((await http(slug, "POST", ROUTE, { set: "tables", tables: ["mood"], confirm: "erase" }, { authorization: `Bearer ${credential}` })).status).toBe(403); // The owner's own token too (SERVER 27 H2): erasing for good takes the admin token alone, token scopes on or off. expect(await http(slug, "POST", ROUTE, { set: "tables", tables: ["mood"] }, { authorization: `Bearer ${owner}` })).toMatchObject({ status: 403, body: { code: "admin_only" } }); expect((await http(slug, "POST", ROUTE, { set: "tables", tables: ["mood"] })).status).toBe(403); const shop = "erase-a-shop"; expect((await http(shop, "PUT", "/v1/admin/business", { name: "A Shop", kind: "business" }, ADMIN)).status).toBe(200); expect(await http(shop, "POST", ROUTE, { set: "tables", tables: ["mood"] }, ADMIN)).toMatchObject({ status: 404, body: { code: "not_personal" } }); }); it("counts on a dry run, erases with the confirmation in bounded calls, keeps a shared file, and tells a phone behind it", async () => { const slug = "erase-tables"; const { credential } = await personalObject(slug, { open: ["note"] }); // The tables erased here are retired (TABLE DROP 1): an object that held them keeps their definitions aside as // the keep retired them (src/retired.ts KIT_RETIRED), which is where the erase reads a thought's file column from. await runInDurableObject(stub(slug), (_i, state) => { state.storage.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", KIT_RETIRED, JSON.stringify({ table: { thought: THOUGHT }, tool: {} })); }); const auth = ADMIN; const rows: Row[] = []; for (let i = 0; i < 1_234; i++) rows.push(["news_story", `ns-${i}`, { title: `An invented story ${i}` }, i % 10 === 0 ? 1 : 0]); for (let i = 0; i < 40; i++) rows.push(["mood", `mood-${i}`, { feeling: "calm" }]); rows.push(["thought", "th-1", { text: "an invented thought", audio_url: KEY("thoughts/one.m4a") }]); rows.push(["thought", "th-2", { text: "another", audio_url: KEY("thoughts/shared.m4a") }]); rows.push(["note", "keep-1", { title: "a neighbour that names a shared file", cover: KEY("thoughts/shared.m4a") }]); rows.push(["note", "keep-2", { title: "a neighbour", about: "ns-1" }]); await seed(slug, rows, [["note", "keep-2", "about", "ns-1"], ["news_story", "ns-2", "topic", "t1"]]); await runInDurableObject(stub(slug), (_i, state) => { const sql = state.storage.sql; sql.exec("INSERT INTO change (at, table_id, record_id, kind, version) VALUES (?, 'news_story', 'ns-3', 'update', 1), (?, 'news_story', 'gone-long-ago', 'update', 1), (?, 'note', 'keep-2', 'update', 1)", AT, AT, AT); sql.exec("INSERT INTO acts (id, at, act, args, outcome) VALUES ('a1', ?, 'create', ?, 'ok'), ('a2', ?, 'create', ?, 'ok')", AT, JSON.stringify({ table: "mood", data: { feeling: "calm" } }), AT, JSON.stringify({ table: "note", data: {} })); }); for (const k of ["thoughts/one.m4a", "thoughts/shared.m4a"]) await env.MEDIA.put(`${slug}/${k}`, "invented sound"); const tables = ["mood", "news_story", "thought"]; const before = await others(slug, tables); const phoneAt = await version(slug); const dry = await http<EraseAnswer>(slug, "POST", ROUTE, { set: "tables", tables: ["thought", "news_story", "mood"] }, auth); expect(dry.body).toMatchObject({ erased: false, done: true, going: { news_story: 1_234, mood: 40, thought: 2 }, media: { named: 2, shared: 1 } }); expect(dry.body.before.news_story).toEqual({ live: 1_110, tombstones: 124 }); expect(await others(slug, tables)).toEqual(before); expect((await http<EraseAnswer>(slug, "POST", ROUTE, { set: "tables", tables: ["mood"] }, auth)).body.after.mood).toEqual({ live: 40, tombstones: 0 }); const runs = await untilDone(slug, { set: "tables", tables: ["mood", "news_story", "thought"], confirm: "erase" }, auth); const last = runs[runs.length - 1]!; expect(last).toMatchObject({ erased: true, done: true, gone: { news_story: 1_234, mood: 40, thought: 2 }, media: { named: 2, shared: 1, dropped: 1 } }); for (const t of tables) expect(last.after[t]).toEqual({ live: 0, tombstones: 0 }); expect(last.also.change).toBe(2); expect(last.also.acts).toBe(1); expect(await env.MEDIA.head(`${slug}/thoughts/one.m4a`)).toBeNull(); expect(await env.MEDIA.head(`${slug}/thoughts/shared.m4a`), "a file a note names stays").not.toBeNull(); await runInDurableObject(stub(slug), (_i, state) => { const sql = state.storage.sql; const n = (q: string) => Number(sql.exec<{ n: number }>(`SELECT count(*) AS n FROM ${q}`).one().n); expect(n("links WHERE table_id IN ('news_story', 'mood', 'thought')")).toBe(0); expect(n("change WHERE table_id IN ('news_story', 'mood', 'thought')")).toBe(0); expect(n("change WHERE table_id = 'note'")).toBe(1); expect(n("links WHERE table_id = 'note'"), "a neighbour's link to an erased row stays as the neighbour's").toBe(1); expect(n("acts WHERE id = 'a2'")).toBe(1); expect(n("erase_queue") + n("erase_media") + n("erase_names") + n("erase_kept")).toBe(0); }); expect(await others(slug, tables), "every other row as it was").toEqual(before); const phone = { authorization: `Bearer ${credential}` }; const behind = await http<SyncAnswer>(slug, "GET", `/v1/sync?since=${phoneAt}`, undefined, phone); expect(Object.keys(behind.body.dropped ?? {}).sort()).toEqual(tables); expect(behind.body.rows.some((r) => tables.includes(r.table))).toBe(false); const caught = await http<SyncAnswer>(slug, "GET", `/v1/sync?since=${behind.body.version}`, undefined, phone); expect(caught.body.dropped, "a phone past the erase is told nothing").toBeUndefined(); // A second run finds nothing. const again = await untilDone(slug, { set: "tables", tables, confirm: "erase" }, auth); expect(again[again.length - 1]!.going).toEqual({}); }); /** * RULE (OPEN TABLES, owner, 24 Nov 2026: the AI accounts are retired; assets/design/shared/OPEN-TABLES.md §4): the four * AI-account tables erase whole, counted first, and every other row stays; project and session stay system tables. */ it("erases the retired AI-account tables whole, counted first, and keeps the session tables", async () => { const slug = "erase-ai-accounts"; await personalObject(slug); const auth = ADMIN; const counts = { agent_account: 4, quota: 6, quota_reading: 1_475, account_usage_sample: 481 }; const rows: Row[] = []; for (const [table, n] of Object.entries(counts)) for (let i = 0; i < n; i++) rows.push([table, `${table}-${i}`, { email: `invented-${i}@example.test`, week_pct: i % 100 }]); rows.push(["session", "s-1", { tool: "claude-code", title: "an invented session" }], ["prompt", "p-1", { session: "s-1", text: "an invented turn" }]); await seed(slug, rows); const tables = Object.keys(counts).sort(); const before = await others(slug, tables); const dry = await http<EraseAnswer>(slug, "POST", ROUTE, { set: "tables", tables }, auth); expect(dry.status, JSON.stringify(dry.body)).toBe(200); expect(dry.body).toMatchObject({ erased: false, going: counts }); const runs = await untilDone(slug, { set: "tables", tables, confirm: "erase" }, auth); expect(runs[runs.length - 1]).toMatchObject({ erased: true, done: true, gone: counts }); expect(await others(slug, tables), "every other row as it was").toEqual(before); for (const kept of ["session", "prompt", "project", "session_message"]) { const refused = await http<{ code: string }>(slug, "POST", ROUTE, { set: "tables", tables: [kept] }, auth); expect(refused.body.code, kept).toBe("kept_table"); } }); it("a job under way is refused another ask until it is done, and goes on where it stood", async () => { const slug = "erase-one-job"; await personalObject(slug); const auth = ADMIN; const rows: Row[] = []; for (let i = 0; i < 3_000; i++) rows.push(["goal", `g-${String(i).padStart(5, "0")}`, { title: `goal ${i}` }]); await seed(slug, rows); // A job stood after its first chunk, as one a call's time ran out on. await runInDurableObject(stub(slug), async (instance) => { const { runErase } = await import("../src/erase.ts"); const self = instance as unknown as { store: import("../src/store.ts").Store; definitions(): import("../src/definitions.ts").Definitions; ctx: DurableObjectState }; const host = { sql: self.ctx.storage.sql, store: self.store, defs: self.definitions(), databaseId: DATABASE_ID, bucketKey: () => null, held: () => false, drop: async () => null, counted: () => {}, transaction: <T,>(fn: () => T) => self.ctx.storage.transactionSync(fn), now: () => new Date() }; const first = await runErase(host, { set: "tables", tables: ["goal"], confirm: "erase" }, 0); expect(first.more).toBe(true); }); expect((await http<{ code: string }>(slug, "POST", ROUTE, { set: "tables", tables: ["mood"], confirm: "erase" }, auth)).body.code).toBe("erase_running"); const runs = await untilDone(slug, { set: "tables", tables: ["goal"], confirm: "erase" }, auth); expect(runs[runs.length - 1]!.gone.goal).toBe(3_000); expect(runs[runs.length - 1]!.after.goal).toEqual({ live: 0, tombstones: 0 }); });});describe("erasing the photos nothing names", () => { it("says what stays and why, takes the rest with their faces, sightings and duplicates as tombstones, and their files", async () => { const slug = "erase-photos"; const { credential } = await personalObject(slug, { open: ["photo", "video", "face", "sighting", "book", "person", "media"] }); const auth = ADMIN; const photo = (id: string, sha: string): Row => ["photo", id, { key: KEY(`photos/${sha}.jpg`), sha256: sha, size_bytes: 1000 }]; await seed( slug, [ photo("p-lone", "aaa"), photo("p-cover", "bbb"), photo("p-avatar", "ccc"), photo("p-chat", "ddd"), photo("p-media", "eee"), ["video", "v-lone", { key: KEY("videos/fff.mov"), poster_key: KEY("videos/fff.poster.jpg"), size_bytes: 5000 }], ["face", "f-1", { photo_id: "p-lone", record_kind: "photo", record_id: "p-lone", crop: KEY("faces/f1.jpg") }], ["face", "f-2", { photo_id: "p-cover", record_kind: "photo", record_id: "p-cover" }], ["sighting", "s-1", { photo_id: "p-lone", key: KEY("photos/aaa.jpg") }], ["sighting", "s-2", { photo_id: "p-chat", thread_id: "thread-1" }], ["duplicate", "d-1", { keep_id: "p-cover", copy_id: "p-lone" }], ["book", "b-1", { title: "An invented book", cover: KEY("photos/bbb.jpg") }], ["person", "pe-1", { name: "An invented person", avatar_photo_id: "p-avatar" }], ["media", "m-1", { kind: "photo", key: KEY("photos/eee.jpg") }], ["message", "msg-1", { thread_id: "thread-1", sealed_enc: "s1:00", dek_enc: "d1:x", seal_v: 1 }], ], [["person", "pe-1", "avatar_photo_id", "p-avatar"], ["face", "f-2", "photo_id", "p-cover"]], ); for (const k of ["photos/aaa.jpg", "photos/aaa.t256.jpg", "photos/bbb.jpg", "photos/eee.jpg", "videos/fff.mov", "videos/fff.poster.jpg", "faces/f1.jpg"]) await env.MEDIA.put(`${slug}/${k}`, "invented bytes"); const goes = ["photo", "video", "face", "sighting", "duplicate"]; const before = await others(slug, goes); const phoneAt = await version(slug); const dry = await untilDone(slug, { set: "unlinked_photos" }, auth); const said = dry[dry.length - 1]!; expect(said.erased).toBe(false); expect(said.going).toEqual({ photo: 1, video: 1, face: 1, sighting: 1, duplicate: 1 }); expect(said.kept).toMatchObject({ "book.cover": 1, "person.avatar_photo_id": 1, "sighting.thread_id": 1, "media.key": 1, "(photos and videos kept)": 4 }); expect(said.unseen?.["message.media"], "a sealed table's files the object cannot read").toBe(1); expect(await others(slug, goes)).toEqual(before); // The coordinator reads the dry run and lets the media library's own key go too, by the admin token (the route's alone). const runs = await untilDone(slug, { set: "unlinked_photos", ignore: ["media.key"], confirm: "erase" }, ADMIN); const done = runs[runs.length - 1]!; expect(done.gone).toEqual({ photo: 2, video: 1, face: 1, sighting: 1, duplicate: 1 }); expect(done.after.photo).toEqual({ live: 3, tombstones: 2 }); expect(await env.MEDIA.head(`${slug}/photos/aaa.jpg`)).toBeNull(); expect(await env.MEDIA.head(`${slug}/photos/aaa.t256.jpg`), "its rendition goes with it").toBeNull(); expect(await env.MEDIA.head(`${slug}/videos/fff.mov`)).toBeNull(); expect(await env.MEDIA.head(`${slug}/videos/fff.poster.jpg`)).toBeNull(); expect(await env.MEDIA.head(`${slug}/faces/f1.jpg`)).toBeNull(); expect(await env.MEDIA.head(`${slug}/photos/bbb.jpg`), "a book's cover stays").not.toBeNull(); expect(await env.MEDIA.head(`${slug}/photos/eee.jpg`), "the media row still names its file").not.toBeNull(); expect(await others(slug, goes)).toEqual(before); const pass = await http<SyncAnswer>(slug, "GET", `/v1/sync?since=${phoneAt}`, undefined, { authorization: `Bearer ${credential}` }); const dead = pass.body.rows.filter((r) => r.deleted).map((r) => `${r.table}/${r.id}`).sort(); expect(dead).toEqual(["duplicate/d-1", "face/f-1", "photo/p-lone", "photo/p-media", "sighting/s-1", "video/v-lone"]); expect(pass.body.rows.filter((r) => r.deleted).every((r) => JSON.stringify(r.data ?? {}) === "{}")).toBe(true); });});describe("keeping the prompts to 30 days", () => { it("erases the older ones on the owner's word, and the alarm keeps them so each day", async () => { const slug = "erase-prompts"; const { credential } = await personalObject(slug); const auth = ADMIN; const day = (n: number): string => new Date(Date.now() - n * 86_400_000).toISOString(); const rows: Row[] = []; for (let i = 0; i < 50; i++) rows.push(["prompt", `old-${i}`, { ts: day(31 + i), text: "an invented prompt" }]); for (let i = 0; i < 20; i++) rows.push(["prompt", `new-${i}`, { ts: day(i), text: "an invented prompt" }]); rows.push(["session", "sess-1", { title: "an invented session" }]); await seed(slug, rows); const before = await others(slug, ["prompt"]); const phoneAt = await version(slug); const dry = await http<EraseAnswer>(slug, "POST", ROUTE, { set: "old_prompts" }, auth); expect(dry.body.going).toEqual({ prompt: 50 }); const runs = await untilDone(slug, { set: "old_prompts", confirm: "erase" }, auth); expect(runs[runs.length - 1]!.after.prompt).toEqual({ live: 20, tombstones: 50 }); expect(await others(slug, ["prompt"])).toEqual(before); const pass = await http<SyncAnswer>(slug, "GET", `/v1/sync?since=${phoneAt}`, undefined, { authorization: `Bearer ${credential}` }); expect(pass.body.rows.filter((r) => r.table === "prompt" && r.deleted).length).toBe(50); // From then on the alarm keeps them: a prompt that ages past 30 days goes on the next day's pass, not before. await seed(slug, [["prompt", "aged", { ts: day(40), text: "an invented prompt" }]]); await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('prompts_kept_at', ?)", new Date().toISOString())); await runDurableObjectAlarm(stub(slug)); const live = async () => runInDurableObject(stub(slug), (_i, state) => Number(state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE table_id = 'prompt' AND deleted = 0").one().n)); expect(await live(), "kept today already").toBe(21); await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('prompts_kept_at', ?)", day(2))); await runDurableObjectAlarm(stub(slug)); expect(await live()).toBe(20); });});// JOBS OUT W3 (assets/design/shared/JOBS-OUT.md): the prompts' 30 days as a step job beside the account object.describe("JOBS OUT W3: keeping the prompts to 30 days by a step job", { timeout: 120_000 }, () => { it("on: the alarm erases nothing; the run lets the older prompts go, then rests", async () => { const slug = "step-w3-prompts"; await personalObject(slug); expect((await http(slug, "PUT", "/v1/admin/business", { jobs: { prompts: "on" } }, ADMIN)).status).toBe(200); const day = (n: number): string => new Date(Date.now() - n * 86_400_000).toISOString(); await seed(slug, [...Array.from({ length: 12 }, (_, i): Row => ["prompt", `old-${i}`, { ts: day(31 + i), text: "an invented prompt" }]), ["prompt", "new-0", { ts: day(1), text: "an invented prompt" }]]); const live = () => runInDurableObject(stub(slug), (_i, state) => Number(state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE table_id = 'prompt' AND deleted = 0").one().n)); await runInDurableObject(stub(slug), (instance: Business) => instance.alarm()); expect(await live(), "the alarm left them to the job").toBe(13); const message = await runInDurableObject(stub(slug), (instance: Business) => instance.stepJobMessage("prompts")); const door = (s: string, path: string, init: RequestInit) => SELF.fetch(`https://jobs.internal/b/${s}${path}`, init); expect(await runStepJob({ door }, message)).toBe("ran"); expect(await live()).toBe(1); });});