131 lines · 9.8 KB · TypeScriptRaw
/** * Who the change log is for (owner, 23 Nov 2026): a person taking back what a person or their assistant wrote. A * machine's write (src/changes.ts MACHINE_WRITERS) keeps only that it happened. His log after the shrink was 430 MB of * a 500 MB budget in 468 `fetch_progress` entries: each tick on a sealed download kept, as its `before`, every sealed * title patch the ticks before it had left. Every link, title and id is invented. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { ACTS } from "../src/acts.ts";import { MACHINE_WRITERS } from "../src/changes.ts";import catalogue from "../src/mcp/catalogue.json";import { ADMIN, answer, FILMS_OPEN, http, NOTES_OPEN, personalObject, tool } from "./personal.ts";const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const act = (slug: string, auth: string, name: string, args: Record<string, unknown> = {}) => http<Record<string, unknown>>(slug, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${auth}` });type Logged = { id: number; via: string; kind: string; before: string | null; after: string | null;};const logOf = (slug: string, table: string, id: string): Promise<Logged[]> => runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<Logged>("SELECT id, via, kind, before, after FROM change WHERE table_id = ? AND record_id = ? ORDER BY id", table, id).toArray());/** The writers that log through a Journal of their own (src/business.ts `new Journal(this.store, null, "<via>", "act")`). */const INTERNAL = ["alarm", "calendar", "artwork", "book_file", "owner", "feedback", "send", "unlock", "mail", "google", "spotify"];describe("a machine's write keeps only that it happened", () => { it("names only real writers: an act, a Cotton MCP tool or one of the object's own", () => { const tools = (catalogue as unknown as { tools: { name: string }[] }).tools.map((t) => t.name); const known = new Set([...Object.keys(ACTS), ...tools, ...INTERNAL]); expect(Object.keys(MACHINE_WRITERS).filter((via) => !known.has(via))).toEqual([]); // What a person or their assistant writes by hand keeps its undo. for (const by of ["create", "update", "delete", "create_record", "update_record", "delete_record", "create_todo", "update_todo", "remember", "memory_update", "story_line_write", "story_scene_write", "merge_people", "restore_from_bin", "make_todo_recurring", "book_statement", "find_book", "read_statement", "submit_statement_reading"]) { expect(MACHINE_WRITERS[by], by).toBeUndefined(); } }); it("logs a sealed download's progress ticks bare, however many patches the row holds", async () => { const slug = "machine-ticks"; const { credential, owner } = await personalObject(slug, { arrival: true }); const added = await act(slug, credential, "fetch_add", { source: "https://video.example/watch?v=invented01", wants: "audio" }); expect(added.status, JSON.stringify(added.body)).toBe(200); const id = String(added.body.fetch); expect((await act(slug, owner, "fetch_claim", { id, machine: "m-invented" })).status).toBe(200); for (let i = 1; i <= 5; i++) { const tick = await act(slug, owner, "fetch_progress", { id, progress: i / 10, bytes: i * 1000, of_bytes: 10_000, title: `An Invented Short, part ${i}` }); expect(tick.status, JSON.stringify(tick.body)).toBe(200); expect(tick.body.undoable, "a tick is not a person's to take back").toBe(false); } const log = await logOf(slug, "fetch", id); expect(log.map((c) => [c.via, c.kind, c.before, c.after])).toEqual([ ["fetch_add", "machine", null, null], ["fetch_claim", "machine", null, null], ...Array.from({ length: 5 }, () => ["fetch_progress", "machine", null, null]), ]); const undone = await tool(slug, owner, "undo", { change_id: log.at(-1)!.id }); expect([undone.isError, undone.structuredContent?.code]).toEqual([true, "machine_not_undone"]); }); it("keeps a person's own write whole, and refuses to restore it across a machine's", async () => { const slug = "machine-person"; const { owner } = await personalObject(slug, { open: [...NOTES_OPEN.open, ...FILMS_OPEN.open] }); const made = await answer<{ record: { id: string }; change_id: number; undoable: boolean }>(slug, owner, "create_record", { table: "note", data: { title: "Groceries", body: "milk" } }); expect(made.undoable).toBe(true); const edited = await answer<{ change_id: number; undoable: boolean }>(slug, owner, "update_record", { table: "note", id: made.record.id, patch: { body: "milk, eggs" } }); expect(edited.undoable).toBe(true); const log = await logOf(slug, "note", made.record.id); expect(log.map((c) => [c.via, c.kind])).toEqual([["create_record", "create"], ["update_record", "update"]]); expect(JSON.parse(log[1]!.before!)).toEqual({ body: "milk" }); const back = await answer<{ record: { data: Record<string, unknown> } }>(slug, owner, "undo", { change_id: edited.change_id }); expect(back.record.data.body).toBe("milk"); }); it("thins what machines logged with bodies before, counting first, and leaves a person's entries whole (ERASES)", async () => { const slug = "machine-thin"; const { owner } = await personalObject(slug, { open: [...NOTES_OPEN.open, ...FILMS_OPEN.open] }); const note = await answer<{ record: { id: string } }>(slug, owner, "create_record", { table: "note", data: { title: "Groceries", body: "milk" } }); const edit = await answer<{ change_id: number }>(slug, owner, "update_record", { table: "note", id: note.record.id, patch: { body: "milk, eggs" } }); // Old-shape ticks, as the owner's log holds them: an act's kind and a sealed body before. await runInDurableObject(stub(slug), (_i, state) => { for (let i = 0; i < 3; i++) state.storage.sql.exec("INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) VALUES (?, NULL, 'fetch_progress', 'fetch', 'f-old', 'act', ?, ?, 1)", new Date().toISOString(), JSON.stringify({ arrival_patches: "x".repeat(10_000 * (i + 1)) }), JSON.stringify({ $keys: ["progress"] })); }); const thin = (body: Record<string, unknown>) => http<{ by: { via: string; entries: number; chars: number }[]; thinned: number; more: boolean }>(slug, "POST", "/v1/admin/change-log/thin-machine", body, ADMIN); const counted = await thin({}); expect(counted.status, JSON.stringify(counted.body)).toBe(200); expect(counted.body.thinned, "without confirm it only counts").toBe(0); expect(counted.body.by).toEqual([{ via: "fetch_progress", entries: 3, chars: expect.any(Number) }]); expect(counted.body.by[0]!.chars).toBeGreaterThan(60_000); expect((await thin({ confirm: "thin", most: 2 })).body).toMatchObject({ thinned: 2, more: true }); expect((await thin({ confirm: "thin" })).body).toMatchObject({ thinned: 1, more: false }); expect((await thin({})).body.by).toEqual([]); const ticks = await logOf(slug, "fetch", "f-old"); expect(ticks.map((c) => [c.kind, c.before, c.after])).toEqual(Array.from({ length: 3 }, () => ["machine", null, null])); // The person's own edit is whole, and still taken back. const back = await answer<{ record: { data: Record<string, unknown> } }>(slug, owner, "undo", { change_id: edit.change_id }); expect(back.record.data.body).toBe("milk"); }); it("counts and erases only with the admin token and confirm thin (ERASES); an owner token is refused (NEXT-ADMIN-KEYS 1)", async () => { const slug = "machine-thin-owner"; const { owner, credential } = await personalObject(slug, { open: [...NOTES_OPEN.open] }); await runInDurableObject(stub(slug), (_i, state) => { for (let i = 0; i < 2; i++) state.storage.sql.exec("INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) VALUES (?, NULL, 'fetch_progress', 'fetch', 'f-old', 'act', ?, ?, 1)", new Date().toISOString(), JSON.stringify({ arrival_patches: "x".repeat(5_000) }), JSON.stringify({ $keys: ["progress"] })); }); const asOwner = { authorization: `Bearer ${owner}` }; expect((await http<{ code: string }>(slug, "POST", "/v1/admin/change-log/thin-machine", { confirm: "thin" }, asOwner)).body.code, "an assistant's owner token never thins").toBe("admin_only"); const thin = (body: Record<string, unknown>, headers: Record<string, string> = ADMIN) => http<{ by: { via: string; entries: number }[]; thinned: number; more: boolean }>(slug, "POST", "/v1/admin/change-log/thin-machine", body, headers); const counted = await thin({}); expect(counted.status, JSON.stringify(counted.body)).toBe(200); expect(counted.body).toMatchObject({ thinned: 0, by: [{ via: "fetch_progress", entries: 2 }] }); expect((await thin({ confirm: "yes" })).body.thinned, "only the words confirm thin erase").toBe(0); expect((await logOf(slug, "fetch", "f-old")).every((c) => c.before !== null), "nothing erased yet").toBe(true); expect((await thin({ confirm: "thin" })).body).toMatchObject({ thinned: 2, more: false }); expect((await logOf(slug, "fetch", "f-old")).map((c) => [c.kind, c.before, c.after])).toEqual([["machine", null, null], ["machine", null, null]]); // A phone's credential is not the admin token, and no other caller reaches it. expect((await thin({}, { authorization: `Bearer ${credential}` })).status).toBe(403); expect((await thin({}, {})).status).toBe(403); }); it("keeps a business object's thinning the admin's", async () => { const shop = "machine-thin-shop"; expect((await http(shop, "PUT", "/v1/admin/business", { name: "A Shop", kind: "business" }, ADMIN)).status).toBe(200); expect((await http(shop, "POST", "/v1/admin/change-log/thin-machine", {}, ADMIN)).status).toBe(200); expect((await http(shop, "POST", "/v1/admin/change-log/thin-machine", {})).status).toBe(403); });});