import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import { ADMIN, OWNER_PHONE, answer, changed, EVENTS_OPEN, changeKeys, http, mint, GROUPS_OPEN, personalObject, put, refusal, tool, TODOS_OPEN, FILMS_OPEN, PEOPLE_OPEN, PHOTOS_OPEN } from "./personal.ts"; import { Asks } from "../src/approval.ts"; import { marksProblem } from "../src/definition_writes.ts"; import { PERSONAL } from "../src/kits.ts"; /** Synthetic made tables in the Rust shared format (cotton-tools' fixtures), as an owner's import brings them: no tool names them. */ const MADE_TABLES = Object.values(import.meta.glob("../../../crates/cotton-tools/tests/fixtures/work/tables/*.json", { eager: true, import: "default" }) as Record>); async function withMadeTables(slug: string): Promise<{ credential: string; owner: string }> { const made = await personalObject(slug, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] }); const defs = await http(slug, "POST", "/v1/admin/definitions/tables", { tables: MADE_TABLES }, ADMIN); expect(defs.status, JSON.stringify(defs.body)).toBe(200); return made; } type Rec = { table: string; id: string; data: Record; created_at: string; updated_at: string; deleted_at: string | null; byline: string | null }; type Write = { change: Record & { before: Record | null; after: Record | null; receipt: { kind: string; said: string } }; record: Rec }; type Page = { table: string; records: Rec[]; next_page: number | null; total: number }; /** RULE (owner, 25 Oct 2026): the generic record tools serve every table the personal object holds — the package's and the owner's own made tables — with the Rust answers and refusals. */ describe("the generic record tools over a made table", () => { const SLUG = "records-made"; let owner = ""; it("creates a record and answers { change, record } in the Rust key order", async () => { ({ owner } = await withMadeTables(SLUG)); const made = await answer(SLUG, owner, "create_record", { table: "effort", data: { name: "Port the tools", percent: 10, state: "running" } }); expect(Object.keys(made)).toEqual(["change", "record", ...changeKeys()]); expect(Object.keys(made.record)).toEqual(["table", "id", "data", "created_at", "updated_at", "deleted_at", "byline"]); expect(Object.keys(made.change)).toEqual(["id", "table", "record_id", "verb", "byline", "before", "after", "created_at", "undone_by", "undoable", "reason", "receipt"]); expect(made.record).toMatchObject({ table: "effort", data: { name: "Port the tools", percent: 10, state: "running" }, deleted_at: null }); expect(Object.keys(made.record.data)).toEqual(["name", "percent", "state"]); expect(made.change).toMatchObject({ table: "effort", record_id: made.record.id, verb: "create", byline: "coordinator owner", before: null, after: { name: "Port the tools", percent: 10, state: "running" }, id: (made as unknown as { change_id: number }).change_id, undoable: true, reason: null }); expect(made.change.receipt).toEqual({ kind: "added", said: "Added Port the tools", words: [] }); }); it("refuses a wrong value, an unknown or missing column and a dangling link in the kit's words", async () => { expect(await refusal(SLUG, owner, "create_record", { table: "effort", data: { name: "x", percent: "ten" } })).toBe('"percent" takes a number; "ten" is not one'); expect(await refusal(SLUG, owner, "create_record", { table: "lane", data: { name: "x", state: "asleep" } })).toBe('"state" takes one of running, queued, silent, done, closed; "asleep" is not one'); expect(await refusal(SLUG, owner, "create_record", { table: "lane", data: { name: "x", started_at: "yesterday" } })).toBe('"started_at" takes a date written YYYY-MM-DD; "yesterday" is not one'); expect(await refusal(SLUG, owner, "create_record", { table: "lane", data: { name: "x", nope: 1 } })).toBe('Lanes have no column "nope"'); expect(await refusal(SLUG, owner, "create_record", { table: "lane", data: { machine: "mac-a" } })).toBe('"name" is required'); expect(await refusal(SLUG, owner, "create_record", { table: "lane", data: { name: "x", status_line: "hi" } })).toBe('"status_line" is read only'); expect(await refusal(SLUG, owner, "create_record", { table: "lane", data: { name: "x", effort: "00000000-0000-4000-8000-000000000000" } })).toBe('"effort" links to effort, and there is no effort "00000000-0000-4000-8000-000000000000"'); expect(await refusal(SLUG, owner, "create_record", { table: "lane" })).toBe("data is required: an object of column keys and values"); expect(await refusal(SLUG, owner, "list_records", {})).toBe('table is required: the table\'s id, e.g. "todo"'); // A date said against now takes an instant too. await answer(SLUG, owner, "create_record", { table: "lane", data: { name: "instant", started_at: "2026-10-25T09:00:00.000Z" } }); }); it("answers a table it does not hold, and an internal one, as no tool drawing it", async () => { for (const table of ["nope", "mcp_token"]) { const r = await tool(SLUG, owner, "list_records", { table }); expect(r).toEqual({ content: [{ type: "text", text: "No tool draws this table." }], isError: true, structuredContent: { code: "no_tool_draws_this_table", table } }); } expect(await refusal(SLUG, owner, "create_record", { table: "mcp_token", data: { name: "x" } })).toBe("No tool draws this table."); }); it("takes a brought row's data literally: a text that starts with @ is that text, not a seed reference", async () => { const id = "3c0b9f1e-2222-4111-8111-000000000002"; await put(SLUG, [{ verb: "put", table: "lane", id, data: { name: "@9$x", machine: "mac-d", state: "running", status_line: "@flow" } }]); const held = await answer(SLUG, owner, "get_record_by_table", { table: "lane", id }); expect(held.data).toMatchObject({ name: "@9$x", status_line: "@flow" }); }); it("updates only what moved, says the patch changes nothing, and drops an unchanged readonly echo", async () => { const ids = await put(SLUG, [{ verb: "put", table: "lane", id: "3c0b9f1e-1111-4111-8111-000000000001", data: { name: "mac-c", machine: "mac-c", state: "running", status_line: "folding" } }]); void ids; const id = "3c0b9f1e-1111-4111-8111-000000000001"; expect(await refusal(SLUG, owner, "update_record", { table: "lane", id, patch: { machine: "mac-c" } })).toBe("the patch changes nothing"); expect(await refusal(SLUG, owner, "update_record", { table: "lane", id, patch: {} })).toBe("the patch changes nothing"); expect(await refusal(SLUG, owner, "update_record", { table: "lane", id })).toBe("patch is required: an object of column keys and values"); expect(await refusal(SLUG, owner, "update_record", { table: "lane", id, patch: { name: null } })).toBe('"name" is required'); const held = await answer(SLUG, owner, "get_record_by_table", { table: "lane", id }); const moved = await answer(SLUG, owner, "update_record", { table: "lane", id, patch: { state: "done", status_line: "folding", model: "opus" } }); expect(moved.change.verb).toBe("update"); expect(moved.change.before).toEqual({ model: null, state: "running", updated_at: held.updated_at }); expect(moved.change.after).toEqual({ model: "opus", state: "done" }); expect(moved.record.data).toMatchObject({ name: "mac-c", state: "done", model: "opus", status_line: "folding" }); // A changed readonly value is still refused by name. expect(await refusal(SLUG, owner, "update_record", { table: "lane", id, patch: { status_line: "other" } })).toBe('"status_line" is read only'); }); it("reads one record by table and refuses one that is gone; delete answers the record as it went", async () => { const made = await answer(SLUG, owner, "create_record", { table: "landing", data: { name: "doomed", hour_at: "2026-10-25", hour: 3 } }); const one = await answer(SLUG, owner, "get_record_by_table", { table: "landing", id: made.record.id }); expect(one).toMatchObject({ table: "landing", id: made.record.id, data: { name: "doomed", hour_at: "2026-10-25", hour: 3 }, edited_by_person_id: null, edited_by_photo_key: null }); const gone = await answer(SLUG, owner, "delete_record", { table: "landing", id: made.record.id }); expect(gone.change).toMatchObject({ verb: "delete", after: null, before: { name: "doomed", hour_at: "2026-10-25", hour: 3 } }); expect(gone.change.receipt.said).toBe("Deleted doomed"); expect(gone.record.deleted_at).not.toBeNull(); expect(await refusal(SLUG, owner, "get_record_by_table", { table: "landing", id: made.record.id })).toBe("That landing hour is no longer here"); expect(await refusal(SLUG, owner, "delete_record", { table: "landing", id: made.record.id })).toBe("That landing hour is no longer here"); }); it("pages by offset to next_page null, in the definition's sort", async () => { const rows = [5, 1, 4, 2, 3].map((h) => ({ verb: "put", table: "landing", id: `5a5a5a5a-0000-4000-8000-00000000000${h}`, data: { name: `hour ${h}`, hour_at: `2026-10-2${h}`, hour: h } })); await put(SLUG, rows); const seen: string[] = []; let page: number | null = 0; const pages: (number | null)[] = []; while (page !== null) { const got: Page = await answer(SLUG, owner, "list_records", { table: "landing", limit: 2, page }); expect(got.total).toBe(5); seen.push(...got.records.map((r) => String(r.data.name))); page = got.next_page; pages.push(page); } expect(pages).toEqual([2, 4, null]); expect(seen).toEqual(["hour 1", "hour 2", "hour 3", "hour 4", "hour 5"]); expect(await refusal(SLUG, owner, "list_records", { table: "landing", page: -1 })).toBe("page is the number of records to skip, 0 or more"); expect(await refusal(SLUG, owner, "list_records", { table: "landing", limit: "2" })).toBe("limit must be a number — this tool pages, and the page size is how many rows come back in one call."); const counted = await answer(SLUG, owner, "list_records", { table: "landing", count_only: true }); expect(counted).toEqual({ table: "landing", total: 5 }); const byIds = await answer(SLUG, owner, "list_records", { table: "landing", ids: ["5a5a5a5a-0000-4000-8000-000000000003", "5a5a5a5a-0000-4000-8000-000000000001", "5a5a5a5a-0000-4000-8000-000000000003"] }); expect(byIds.records.map((r) => r.data.hour)).toEqual([3, 1]); expect(byIds.next_page).toBeNull(); }); it("narrows by where as the grammar says, and refuses what it cannot narrow by", async () => { const one = await answer(SLUG, owner, "list_records", { table: "landing", where: { hour: 2 } }); expect(one.records.map((r) => r.data.name)).toEqual(["hour 2"]); const some = await answer(SLUG, owner, "list_records", { table: "landing", where: { hour: { values: [1, 5] } } }); expect(some.records.map((r) => r.data.hour)).toEqual([1, 5]); const not = await answer(SLUG, owner, "list_records", { table: "landing", where: { hour: { not: [1, 2, 3] } } }); expect(not.records.map((r) => r.data.hour)).toEqual([4, 5]); const none = await answer(SLUG, owner, "list_records", { table: "landing", where: { lanes: { present: false } } }); expect(none.total).toBe(5); const month = await answer(SLUG, owner, "list_records", { table: "landing", where: { hour_at: { month: 10 } } }); expect(month.total).toBe(5); const words = await answer(SLUG, owner, "list_records", { table: "landing", query: "HOUR 4" }); expect(words.records.map((r) => r.data.hour)).toEqual([4]); expect(await refusal(SLUG, owner, "list_records", { table: "landing", where: { hour: null } })).toBe('where "hour": null matches nothing here; ask for {"present": false} to find records where it is empty'); expect(await refusal(SLUG, owner, "list_records", { table: "landing", where: { hour: { above: 1 } } })).toBe('where "hour": "above" is not a condition; say {"values": [...]}, {"not": [...]} or {"present": true | false}'); expect(await refusal(SLUG, owner, "list_records", { table: "landing", where: { hour: { month: 1 } } })).toBe('where "hour": month narrows only a date column'); expect(await refusal(SLUG, owner, "list_records", { table: "landing", where: { hour: "two" } })).toBe('"hour" takes a number; "two" is not one'); expect(await refusal(SLUG, owner, "list_records", { table: "landing", where: { colour: "red" } })).toBe('Landings have no column "colour"'); expect(await refusal(SLUG, owner, "list_records", { table: "landing", archived: true })).toBe("Landings are never archived"); expect(await refusal(SLUG, owner, "list_records", { table: "landing", view: "nope" })).toBe('Landings have no view "nope"'); }); it("lists the tools with their tables, never an internal one", async () => { const listed = await answer<{ tools: { signature: string; definition: { id: string }; pictures: unknown }[]; table_definitions: { definition: { id: string }; orphaned: boolean }[] }>(SLUG, owner, "list_tools"); expect(listed.tools.map((t) => t.definition.id)).toContain("personal"); expect(listed.tools[0]).toMatchObject({ signature: "unsigned", pictures: {} }); const tables = new Map(listed.table_definitions.map((t) => [t.definition.id, t.orphaned])); // A table kept by an engine (todo) is the build's, never one the owner defines. expect(tables.has("todo")).toBe(false); expect(tables.get("book")).toBe(false); expect(tables.has("mcp_token")).toBe(false); // A made table no tool names is orphaned. const made = await http(SLUG, "POST", "/v1/admin/definitions/tables", { tables: [{ format_version: 1, id: "invented_scrap", name: "Scrap", plural: "Scraps", visibility: "owner", columns: [{ key: "name", type: "text" }] }] }, ADMIN); expect(made.status, JSON.stringify(made.body)).toBe(200); const again = await answer<{ table_definitions: { definition: { id: string }; orphaned: boolean }[] }>(SLUG, owner, "list_tools"); expect(again.table_definitions.find((t) => t.definition.id === "invented_scrap")?.orphaned).toBe(true); }); it("reads a definition with the table alone and writes only its look", async () => { const read = await answer<{ table: string; definition: { columns: { key: string; readonly?: boolean }[]; id?: string; slip: unknown } }>(SLUG, owner, "update_definition", { table: "landing" }); expect(read.table).toBe("landing"); expect(read.definition.id).toBeUndefined(); // A column's readonly says who writes it (its producer): access, never a key's (ADMIN KEYS 4); its look is. const columns = read.definition.columns.map((c) => (c.key === "lanes" ? { ...c, readonly: true } : c)); const refused = await tool(SLUG, owner, "update_definition", { table: "landing", columns }); expect([refused.isError, refused.content[0]!.text]).toEqual([true, expect.stringMatching(/"lanes.readonly" says who may read or write the table/)]); const looked = read.definition.columns.map((c) => (c.key === "lanes" ? { ...c, name: "Lanes held" } : c)); const wrote = await answer<{ changed: string[]; before: Record; definition: { columns: { key: string; name?: string }[]; slip: unknown } }>(SLUG, owner, "update_definition", { table: "landing", slip: { title: "name" }, columns: looked }); expect(wrote.changed).toEqual(["columns", "slip"]); expect(wrote.before.slip).toEqual(read.definition.slip); expect(wrote.definition.columns.find((c) => c.key === "lanes")?.name).toBe("Lanes held"); expect(wrote.definition.slip).toEqual({ title: "name" }); // The refused readonly never landed: the column is written as before. expect((await tool(SLUG, owner, "create_record", { table: "landing", data: { name: "x", lanes: 2 } })).isError).toBe(false); const retyped = read.definition.columns.map((c) => (c.key === "hour" ? { ...c, type: "text" } : c)); expect(await refusal(SLUG, owner, "update_definition", { table: "landing", columns: retyped })).toBe('the definition is refused: "hour" is a column of "landing": it is never removed or retyped — its name, readonly, format, units, hidden and placeholder are look'); expect(await refusal(SLUG, owner, "update_definition", { table: "landing", columns: read.definition.columns.slice(1) })).toBe('the definition is refused: "name" is a shipped column of "landing": it is never removed — hide it instead'); expect(await refusal(SLUG, owner, "update_definition", { table: "landing", engine: "x" })).toBe('"engine" cannot be changed here: column types, engines, commands, connections and table identity stay as the table defines them'); expect(await refusal(SLUG, owner, "update_definition", { table: "mcp_token" })).toBe("No tool draws this table."); // Which act a mark drawn on its card runs is look too, held to the table's commands (owner, 3 Nov 2026: "marking a todo as done is just having a check mark"). expect(await refusal(SLUG, owner, "update_definition", { table: "landing", marks: { check: "done" } })).toBe('the definition is refused: marks.check names "done", which is not one of the definition\'s commands'); expect(await refusal(SLUG, owner, "update_definition", { table: "landing", marks: { circle: "done" } })).toBe('the definition is refused: marks names "circle", which is not one of "marks"\'s choices'); expect(await refusal(SLUG, owner, "update_definition", {})).toBe("table is required"); }); }); /** RULE (owner, 25 Oct 2026; the Work tool left Cotton, 27 Oct 2026): a lane's token reads every table, and writes only its session log. */ describe("a lane token on the generic record tools", () => { const SLUG = "records-lane"; let owner = ""; let lane = ""; it("reads every table and writes no record", async () => { let credential = ""; ({ credential, owner } = await withMadeTables(SLUG)); lane = await mint(SLUG, credential, "Lane mac-a", ["read", "lane:widgets"], 7); const prefix = "this is lane widgets's token: it reads, and writes only its session log — "; expect(await refusal(SLUG, lane, "create_record", { table: "lane", data: { name: "mac-a" } })).toBe(`${prefix}\`create_record\` is not log_session`); const other = await answer(SLUG, owner, "create_record", { table: "lane", data: { name: "mac-d", machine: "mac-d" } }); expect(await refusal(SLUG, lane, "update_record", { table: "lane", id: other.record.id, patch: { state: "done" } })).toBe(`${prefix}\`update_record\` is not log_session`); expect(await refusal(SLUG, lane, "delete_record", { table: "lane", id: other.record.id })).toBe(`${prefix}\`delete_record\` is not log_session`); // It reads every table. const lanes = await answer(SLUG, lane, "list_records", { table: "lane", limit: 200 }); expect(lanes.records.map((r) => r.data.name)).toEqual(["mac-d"]); expect(lanes.next_page).toBeNull(); }); }); /** RULE (owner, 25 Oct 2026): todos keep Rust's due words — a day in the database's zone, never UTC — and a list such as Agents is a group of todos. */ describe("todos", () => { const SLUG = "records-todos"; let owner = ""; it("creates a todo due on a day at a time in the database's zone", async () => { ({ owner } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, ...GROUPS_OPEN.open] })); const made = await answer>(SLUG, owner, "create_todo", { title: "Renew the domain", dueDate: "2026-11-02", dueTime: "09:30", notes: "before noon" }); expect(Object.keys(made)).toEqual(["id", "title", "due_at", "status", "dueDate", "dueTime", ...changeKeys()]); expect(made).toMatchObject({ title: "Renew the domain", due_at: "2026-11-02T04:00:00.000Z", status: "open", dueDate: "2026-11-02", dueTime: "09:30" }); const day = await answer>(SLUG, owner, "create_todo", { title: "Call the bank", dueDate: "2026-11-01" }); expect(day).toMatchObject({ due_at: "2026-10-31T18:30:00.000Z", dueDate: "2026-11-01", dueTime: null }); expect(await refusal(SLUG, owner, "create_todo", { title: "x", dueTime: "09:00" })).toBe("dueTime needs dueDate — a time is a time on a day"); expect(await refusal(SLUG, owner, "create_todo", { title: "x", dueAt: "2026-11-01T00:00:00Z", dueDate: "2026-11-01" })).toBe("pass dueAt OR dueDate/dueTime, not both — they name the same moment"); expect(await refusal(SLUG, owner, "create_todo", { title: "x", dueDate: "2026-11-01", timezone: "Mars/Olympus" })).toBe('unknown timezone "Mars/Olympus"'); expect(await refusal(SLUG, owner, "create_todo", {})).toBe("title is required"); expect(await refusal(SLUG, owner, "create_todo", { title: "x", label: "home" })).toContain("Todos have no label any more"); }); it("lists dated todos soonest first, then the undated newest first, paging by cursor to the end", async () => { await answer(SLUG, owner, "create_todo", { title: "Undated one" }); await answer(SLUG, owner, "create_todo", { title: "Undated two" }); const first = await answer<{ more: boolean; timezone: string; nextCursor?: string; todos: { title: string; projects: string[]; dueDate?: string }[] }>(SLUG, owner, "list_todos", { limit: 3 }); expect(Object.keys(first)).toEqual(["more", "timezone", "nextCursor", "todos"]); expect(first.more).toBe(true); expect(first.timezone).toBe("Asia/Kolkata"); expect(first.todos.map((t) => t.title)).toEqual(["Call the bank", "Renew the domain", "Undated two"]); expect(first.todos[0]!.projects).toEqual([]); const second = await answer<{ more: boolean; nextCursor?: string; todos: { title: string }[] }>(SLUG, owner, "list_todos", { limit: 3, cursor: first.nextCursor }); expect(second.more).toBe(false); expect(second.nextCursor).toBeUndefined(); expect(second.todos.map((t) => t.title)).toEqual(["Undated one"]); expect(await refusal(SLUG, owner, "list_todos", { cursor: "garbage!" })).toBe("cursor is not one list_todos handed out — pass nextCursor from the previous page exactly as it came, or drop it to start the list again"); expect(await refusal(SLUG, owner, "list_todos", { status: "late" })).toBe("status must be one of: open, done, dropped, missed, all"); }); it("updates a todo: done stamps completed_at, a new day keeps the hour", async () => { const list = await answer<{ todos: { id: string; title: string }[] }>(SLUG, owner, "list_todos", {}); const id = list.todos.find((t) => t.title === "Renew the domain")!.id; const moved = await answer>(SLUG, owner, "update_todo", { id, dueDate: "2026-11-05" }); expect(moved).toMatchObject({ id, due_at: "2026-11-05T04:00:00.000Z", dueDate: "2026-11-05", dueTime: "09:30" }); const done = await answer>(SLUG, owner, "update_todo", { id, status: "done", priority: "high" }); expect(Object.keys(done).slice(0, 8)).toEqual(["id", "title", "notes", "status", "due_at", "snoozed_until", "priority", "completed_at"]); expect(done).toMatchObject({ status: "done", priority: 1, notes: "before noon" }); expect(typeof done.completed_at).toBe("string"); const open = await answer<{ todos: { id: string }[] }>(SLUG, owner, "list_todos", {}); expect(open.todos.map((t) => t.id)).not.toContain(id); const all = await answer<{ todos: { id: string; status: string; completedAt?: string; priority?: string }[] }>(SLUG, owner, "list_todos", { status: "done" }); expect(all.todos.find((t) => t.id === id)).toMatchObject({ status: "done", priority: "high" }); expect(await refusal(SLUG, owner, "update_todo", { id })).toBe("nothing to change — pass a field to change"); expect(await refusal(SLUG, owner, "update_todo", { id: "nope", title: "x" })).toBe("id must be a uuid"); expect(await refusal(SLUG, owner, "update_todo", { id: "00000000-0000-4000-8000-000000000000", title: "x" })).toBe("no todo with id 00000000-0000-4000-8000-000000000000"); }); it("files todos under a project, and reads the Agents list as a group of todos", async () => { const todos = await answer<{ todos: { id: string; title: string }[] }>(SLUG, owner, "list_todos", {}); const bank = todos.todos.find((t) => t.title === "Call the bank")!.id; const one = todos.todos.find((t) => t.title === "Undated one")!.id; const two = todos.todos.find((t) => t.title === "Undated two")!.id; await put(SLUG, [ { ref: "p", table: "project", data: { slug: "cotton", name: "Cotton", status: "active" } }, { table: "project_link", data: { project: "@p", record_kind: "todo", record_id: bank } }, { ref: "agents", table: "record_group", data: { table_id: "todo", name: "Agents" } }, { table: "group_member", data: { group: "@agents", record_id: two, place: 2 } }, { table: "group_member", data: { group: "@agents", record_id: one, place: 1 } }, ]); const filed = await answer<{ todos: { id: string; projects: string[] }[] }>(SLUG, owner, "list_todos", { project: "cotton" }); expect(filed.todos).toEqual([expect.objectContaining({ id: bank, projects: ["cotton"] })]); const unfiled = await answer<{ todos: { id: string }[] }>(SLUG, owner, "list_todos", { unfiled: true }); expect(unfiled.todos.map((t) => t.id)).not.toContain(bank); expect(await refusal(SLUG, owner, "list_todos", { project: "nope" })).toBe('unknown project "nope" — projects are: cotton'); const groups = await answer(SLUG, owner, "list_records", { table: "record_group", where: { name: "Agents" } }); const agents = groups.records[0]!.id; const listed = await answer(SLUG, owner, "list_records", { table: "todo", where: { group: agents } }); expect(listed.records.map((r) => r.data.title)).toEqual(["Undated one", "Undated two"]); expect(listed).toMatchObject({ table: "todo", next_page: null, total: 2 }); expect(await refusal(SLUG, owner, "list_records", { table: "todo", where: { group: "00000000-0000-4000-8000-000000000000" } })).toBe("There is no such group. It may have been deleted."); expect(await refusal(SLUG, owner, "list_records", { table: "todo", where: { group: agents, status: "open" } })).toBe("group names the records itself; ask without another where"); }); }); /** RULE (owner, 4 Nov 2026): named lists on every table a person opens — an event goes in a list ("Bella": a friend's travel) made through the generic record tools, and the list reads its events in its own order. */ describe("a named list of events", () => { const SLUG = "records-event-group"; it("makes a group of events and lists its two members in the group's order", async () => { const { owner } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, ...EVENTS_OPEN.open, ...GROUPS_OPEN.open, ...FILMS_OPEN.open] }); const event = PERSONAL.tables.find((t) => t.id === "event")!; expect(event.groups, "the kit declares event's groups").toEqual({ stack: "slips" }); const flight = (await answer(SLUG, owner, "create_record", { table: "event", data: { title: "Bella's flight out", starts_at: "2026-12-01" } })).record.id; const stay = (await answer(SLUG, owner, "create_record", { table: "event", data: { title: "Bella's hotel", starts_at: "2026-11-20" } })).record.id; const bella = (await answer(SLUG, owner, "create_record", { table: "record_group", data: { table_id: "event", name: "Bella" } })).record.id; await answer(SLUG, owner, "create_record", { table: "group_member", data: { group: bella, record_id: flight, place: 1 } }); await answer(SLUG, owner, "create_record", { table: "group_member", data: { group: bella, record_id: stay, place: 2 } }); const listed = await answer(SLUG, owner, "list_records", { table: "event", where: { group: bella } }); expect(listed.records.map((r) => r.data.title)).toEqual(["Bella's flight out", "Bella's hotel"]); expect(listed).toMatchObject({ table: "event", next_page: null, total: 2 }); const all = await answer(SLUG, owner, "list_records", { table: "event" }); expect(all.records.map((r) => r.id), "a list never hides an event from the table").toEqual(expect.arrayContaining([flight, stay])); expect(await refusal(SLUG, owner, "list_records", { table: "film", where: { group: bella } })).toBe("That group is not a group of Films."); }); }); /** RULE (owner, 25 Oct 2026): a secret's value is sealed at rest under VAULT_KEY; no tool answers it but the owner's dev_reveal_secret. */ describe("the vault", () => { const SLUG = "records-vault"; const PASSWORD = "correct horse battery staple 4217"; let owner = ""; let credential = ""; let id = ""; it("seals a secret at rest: the stored row holds no plaintext", async () => { ({ credential, owner } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] })); const made = await answer>(SLUG, owner, "create_secret", { name: "Mail login", kind: "login", site: "mail.example.test", username: "someone@example.test", value: PASSWORD }); expect(made).toEqual({ id: made.id, kind: "login", name: "Mail login", site: "mail.example.test", username: "someone@example.test", ...changed() }); id = String(made.id); const exported = await http<{ rows: { table: string; id: string; data: Record }[] }>(SLUG, "GET", "/v1/admin/export", undefined, ADMIN); const row = exported.body.rows.find((r) => r.table === "secret" && r.id === id)!; expect(String(row.data.sealed)).toMatch(/^k1:/); expect(JSON.stringify(row.data)).not.toContain("battery"); expect(JSON.stringify(exported.body)).not.toContain(PASSWORD); }); it("lists names, never the value nor a hint of it (S2); a generic read never shows the sealed column", async () => { const listed = await answer<{ secrets: Record[] }>(SLUG, owner, "list_secrets", { q: "MAIL" }); expect(listed.secrets).toHaveLength(1); expect(listed.secrets[0]).toMatchObject({ id, kind: "login", name: "Mail login", site: "mail.example.test", isSet: true }); expect(listed.secrets[0]!.hint).toBeUndefined(); expect(JSON.stringify(listed)).not.toContain("4217"); expect(JSON.stringify(listed)).not.toContain("battery"); const generic = await answer(SLUG, owner, "list_records", { table: "secret" }); expect(generic.records[0]!.data.sealed).toBeUndefined(); expect(generic.records[0]!.data.hint).toBeUndefined(); expect((await answer<{ secrets: unknown[] }>(SLUG, owner, "list_secrets", { kind: "api_key" })).secrets).toEqual([]); expect(await refusal(SLUG, owner, "list_secrets", { kind: "pin" })).toBe("kind must be one of login, api_key, note, card, identity, document, code, wifi, address, file"); }); it("replaces a keyed secret by (service, name) and refuses what it cannot seal", async () => { const first = await answer<{ id: string; hint?: string }>(SLUG, owner, "create_secret", { name: "Model key", service: "anthropic", value: "sk-test-aaaa1111" }); // A row an earlier build wrote with a hint: saving it again takes the hint away (S2). await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(SLUG)), (_i, state) => state.storage.sql.exec("UPDATE rows SET data = json_set(data, '$.hint', '1111') WHERE table_id = 'secret' AND id = ?", first.id)); const again = await answer<{ id: string; hint?: string }>(SLUG, owner, "create_secret", { name: "Model key", service: "anthropic", value: "sk-test-bbbb2222" }); expect(again.id).toBe(first.id); expect(again.hint).toBeUndefined(); const hint = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(SLUG)), (_i, state) => state.storage.sql.exec<{ h: string | null }>("SELECT json_extract(data, '$.hint') AS h FROM rows WHERE table_id = 'secret' AND id = ?", first.id).one().h); expect(hint).toBeNull(); expect(await refusal(SLUG, owner, "create_secret", { name: "Model key", value: "x" })).toBe("service is required for an api key — it is how the key is found again ('anthropic', 'openai')"); expect(await refusal(SLUG, owner, "create_secret", { name: "k", service: "Bad Service", value: "x" })).toContain("service must be lowercase letters"); expect(await refusal(SLUG, owner, "create_secret", { name: "n", kind: "note" })).toBe("value is required — the body of a note"); expect(await refusal(SLUG, owner, "create_secret", { name: "n", kind: "note", value: "" })).toBe("value is empty — pass the credential itself, or delete_secret to bin one"); expect(await refusal(SLUG, owner, "create_secret", { name: "c", kind: "card", fields: { holder: "A" } })).toBe("fields is not a card payload: missing field `number`. The fields of a card are number, holder, expiry, cvv, notes."); expect(await refusal(SLUG, owner, "create_secret", { name: "c", kind: "card", value: "1", fields: { number: "1" } })).toBe("pass value OR fields, not both — value is the one primary field, fields is the whole typed payload"); expect(await refusal(SLUG, owner, "create_secret", {})).toBe("name is required"); }); it("opens a secret for the owner's token alone", async () => { const opened = await answer>(SLUG, owner, "dev_reveal_secret", { secretId: id }); expect(opened).toEqual({ id, kind: "login", name: "Mail login", service: null, site: "mail.example.test", username: "someone@example.test", binned: false, payload: { kind: "login", password: PASSWORD } }); const writer = await mint(SLUG, credential, "a writer", ["read", "write"]); expect(await refusal(SLUG, writer, "dev_reveal_secret", { secretId: id })).toBe("`dev_reveal_secret` is an owner-scope tool: the owner's app may call it; an assistant may not."); expect(await refusal(SLUG, owner, "dev_reveal_secret", { secretId: "x" })).toBe("secretId must be a uuid"); expect(await refusal(SLUG, owner, "dev_reveal_secret", { secretId: "00000000-0000-4000-8000-000000000000" })).toBe("no secret with id 00000000-0000-4000-8000-000000000000"); }); }); /** RULE (coordinator, 7 Nov 2026, option B): a passkey's private half is sealed v2 under the owner's devices; the Worker stores the sealed text and no tool, generic or the vault's, ever answers it. */ describe("a passkey's sealed private key", () => { const SLUG = "records-passkey"; const ID = "5e1f0000-0000-4000-8000-0000000000a1"; // Synthetic: no key seals to this, and nothing opens it. const SEALED = "v2:SYNTHETIC-not-a-sealed-scalar-0000000000"; let owner = ""; it("keeps private_key_enc out of every read, search, summary and reveal", async () => { ({ owner } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, "passkey"] })); await put(SLUG, [{ verb: "put", table: "passkey", id: ID, data: { rp_id: "example.com", user_name: "someone@example.test", user_handle: "dXNlci0x", credential_id: "q6urq6urq6urq6urq6urqw", algorithm: "ES256", public_key: "pQECAyYgASFYIA", private_key_enc: SEALED, vmk_version: 1, sign_count: 0 } }]); const listed = await answer(SLUG, owner, "list_records", { table: "passkey" }); expect(listed.records.map((r) => r.id)).toEqual([ID]); const held = await answer(SLUG, owner, "get_record_by_table", { table: "passkey", id: ID }); expect(held.data.rp_id).toBe("example.com"); const found = await answer(SLUG, owner, "search_records", { q: "example", table: "passkey" }); for (const read of [listed, held, found]) { expect(JSON.stringify(read)).not.toContain("SYNTHETIC"); expect(JSON.stringify(read)).not.toContain("private_key_enc"); } expect(await refusal(SLUG, owner, "summarize_records", { table: "passkey", measures: [{ column: "private_key_enc", op: "count" }] })).toBe('"private_key_enc" is never read'); expect(await refusal(SLUG, owner, "dev_reveal_secret", { secretId: ID })).toBe(`no secret with id ${ID}`); }); it("refuses an assistant writing a sealed key by hand", async () => { expect(await refusal(SLUG, owner, "update_record", { table: "passkey", id: ID, patch: { private_key_enc: "v2:other" } })).toBe('"private_key_enc" is read only'); expect(await refusal(SLUG, owner, "create_record", { table: "passkey", data: { rp_id: "example.org", credential_id: "AA", algorithm: "ES256", private_key_enc: "v2:other" } })).toBe('"private_key_enc" is read only'); }); }); /** RULE (owner, 11 Nov 2026): Cotton Keys is where passwords live, and a password's secret is sealed exactly as a passkey's private key is: v2 under the owner's devices into value_enc, its version in vmk_version. The object carries a device's row and no tool, generic or the vault's, ever answers the sealed value; rows the Worker sealed (k1 in sealed) are left as they are. */ describe("a password sealed on the owner's devices", () => { const SLUG = "records-password-v2"; const ID = "5e1f0000-0000-4000-8000-0000000000c1"; // Synthetic: no key seals to this, and nothing opens it. const SEALED = "v2:SYNTHETIC-not-a-sealed-password-0000"; let owner = ""; it("carries a device's row and keeps value_enc out of every read, search, summary and reveal", async () => { let credential = ""; ({ owner, credential } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] })); const auth = { authorization: `Bearer ${credential}` }; const made = await http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "secret", id: ID, data: { name: "Invented Mail", kind: "login", site: "mail.invented.test", username: "ada@invented.test", value_enc: SEALED, vmk_version: 1 } } }, auth); expect(made.status, JSON.stringify(made.body)).toBe(200); const exported = await http<{ rows: { table: string; id: string; data: Record }[] }>(SLUG, "GET", "/v1/admin/export", undefined, ADMIN); const row = exported.body.rows.find((r) => r.table === "secret" && r.id === ID)!; expect(row.data).toMatchObject({ value_enc: SEALED, vmk_version: 1, kind: "login" }); expect(row.data.sealed ?? null, "nothing sealed under the Worker's key").toBeNull(); const listed = await answer(SLUG, owner, "list_records", { table: "secret" }); expect(listed.records.map((r) => r.id)).toEqual([ID]); const held = await answer(SLUG, owner, "get_record_by_table", { table: "secret", id: ID }); expect(held.data.site).toBe("mail.invented.test"); const found = await answer(SLUG, owner, "search_records", { q: "invented", table: "secret" }); const secrets = await answer<{ secrets: Record[] }>(SLUG, owner, "list_secrets", {}); expect(secrets.secrets.map((s) => s.id)).toEqual([ID]); for (const read of [listed, held, found, secrets]) { expect(JSON.stringify(read)).not.toContain("SYNTHETIC"); expect(JSON.stringify(read)).not.toContain("value_enc"); } expect(await refusal(SLUG, owner, "summarize_records", { table: "secret", measures: [{ column: "value_enc", op: "count" }] })).toBe('"value_enc" is never read'); const revealed = await tool(SLUG, owner, "dev_reveal_secret", { secretId: ID }); expect(JSON.stringify(revealed)).not.toContain("SYNTHETIC"); }); it("refuses an assistant writing a sealed value by hand", async () => { expect(await refusal(SLUG, owner, "update_record", { table: "secret", id: ID, patch: { value_enc: "v2:other" } })).toBe('"value_enc" is read only'); }); }); /** RULE (coordinator, 7 Nov 2026, option B): a device publishes its key as a vault_key row through the object, an approving device writes the wrap onto it, and the waiting device reads it back; the object only carries them. */ /** The vault_key rows a device pulls, by id: the phone holds the wraps and public halves, which no MCP read answers (sealing plan §1). */ async function vaultRows(slug: string, auth: Record): Promise>> { const res = await http<{ rows: { table: string; id: string; data: Record; deleted?: boolean }[] }>(slug, "GET", "/v1/sync?since=0&tables=vault_key", undefined, auth); expect(res.status, JSON.stringify(res.body)).toBe(200); return new Map(res.body.rows.filter((r) => r.table === "vault_key" && !r.deleted).map((r) => [r.id, r.data])); } /** A synthetic key check value (`vmk_check`): the identity of the key a wrap holds, as a phone declares it (src/vault_identity.ts). */ const KEY_CHECK = "U1lOVEhFVElDLUtFWS1DSw"; /** An ask for `deviceId` with `vaultKey` that `approver` approved after the codes were compared, as the object holds one. */ async function admittedBy(slug: string, deviceId: string, vaultKey: string, approver: string): Promise { await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), async (_i, state) => { const t = Math.floor(Date.now() / 1000); const id = `cta_${deviceId}`; new Asks(state.storage.sql).add({ id, phone: OWNER_PHONE, deviceId, deviceName: null, vaultKey, commit: "c", createdAt: t, expiresAt: t + 180 }); state.storage.sql.exec("UPDATE approval_ask SET reveal = 'r', state = 'approved', decided_by = ?, decided_at = ? WHERE id = ?", approver, t, id); }); } describe("a device key row", () => { it("goes up as a device's create, takes the approver's wrap as an update, and comes back as written", async () => { const SLUG = "records-vault-key"; const { credential, owner } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] }); const auth = { authorization: `Bearer ${credential}` }; const id = "vault-key-mac-invented"; // Synthetic: a public half and a wrap nothing holds the private key to. const made = await http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "vault_key", id, data: { device_id: "mac-invented", name: "Invented Mac", public_key: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", wrapped_vmk: null, vmk_version: 0 } } }, auth); expect(made.status, JSON.stringify(made.body)).toBe(200); const waiting = await answer(SLUG, owner, "list_records", { table: "vault_key", where: { device_id: "mac-invented" } }); expect(waiting.records.map((r) => [r.id, r.data.name])).toEqual([[id, "Invented Mac"]]); expect((await vaultRows(SLUG, auth)).get(id)?.wrapped_vmk ?? null).toBeNull(); // The approver let it in after the codes were compared (src/approval.ts `Asks.admitted`). await admittedBy(SLUG, "mac-invented", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "coordinator"); const wrapped = await http(SLUG, "POST", "/v1/act", { act: "update", args: { table: "vault_key", id, data: { wrapped_vmk: "w1:SYNTHETIC-wrap", vmk_version: 1 } } }, auth); expect(wrapped.status, JSON.stringify(wrapped.body)).toBe(200); const open = await answer(SLUG, owner, "list_records", { table: "vault_key", where: { device_id: "mac-invented" } }); // The wrap and the public half are the device's to pull, never an assistant's to read. expect(open.records[0]!.data).toMatchObject({ vmk_version: 1 }); expect(open.records[0]!.data).not.toHaveProperty("wrapped_vmk"); expect(open.records[0]!.data).not.toHaveProperty("public_key"); expect((await vaultRows(SLUG, auth)).get(id)).toMatchObject({ wrapped_vmk: "w1:SYNTHETIC-wrap", vmk_version: 1 }); expect(await refusal(SLUG, owner, "update_record", { table: "vault_key", id, patch: { wrapped_vmk: "w1:by-hand" } })).toBe('"wrapped_vmk" is read only'); }); }); /** RULE (8 Nov 2026): the object is the arbiter of who founds the vault. A device writing the first wrap onto its own row founds it; a second device's founding is refused `vault_founded` and its row stays waiting; an approval onto another device's row passes. */ describe("a vault's founding", () => { // Synthetic public halves, one per device: a device is its key, so two devices never share one. const PUBLIC: Record = { "phone-first": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "phone-second": "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", "phone-local": "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC", "phone-before": "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD", }; async function device(slug: string, deviceId: string): Promise> { const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: deviceId }); const signed = await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: deviceId }); expect(signed.status, JSON.stringify(signed.body)).toBe(200); return { authorization: `Bearer ${signed.body.credential}` }; } const row = (deviceId: string) => ({ table: "vault_key", id: `vault-key-${deviceId}`, data: { device_id: deviceId, public_key: PUBLIC[deviceId]!, wrapped_vmk: null, vmk_version: 0 } }); const wrap = (deviceId: string, text: string) => ({ table: "vault_key", id: `vault-key-${deviceId}`, data: { wrapped_vmk: text, vmk_version: 1 } }); it("keeps the first founding, refuses a second with vault_founded, and lets an approval through", async () => { const SLUG = "records-vault-founding"; await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] }); const first = await device(SLUG, "phone-first"); const second = await device(SLUG, "phone-second"); for (const [auth, id] of [[first, "phone-first"], [second, "phone-second"]] as const) { const made = await http(SLUG, "POST", "/v1/act", { act: "create", args: row(id) }, auth); expect(made.status, JSON.stringify(made.body)).toBe(200); } const founded = await http(SLUG, "POST", "/v1/act", { act: "update", args: wrap("phone-first", "w1:SYNTHETIC-first") }, first); expect(founded.status, JSON.stringify(founded.body)).toBe(200); const raced = await http<{ code: string; message: string }>(SLUG, "POST", "/v1/act", { act: "update", args: wrap("phone-second", "w1:SYNTHETIC-second") }, second); expect([raced.status, raced.body.code]).toEqual([409, "vault_founded"]); expect(raced.body.message).toContain("waits for that one to let it in"); expect((await vaultRows(SLUG, second)).get("vault-key-phone-second")?.wrapped_vmk ?? null).toBeNull(); // The same founding handed over again is the row as it is: kept. const again = await http(SLUG, "POST", "/v1/act", { act: "update", args: wrap("phone-first", "w1:SYNTHETIC-first") }, first); expect(again.status, JSON.stringify(again.body)).toBe(200); // A wrap onto another device's row on a tap alone (an app from before the typed code) is refused update_app. const blind = await http<{ code: string }>(SLUG, "POST", "/v1/act", { act: "update", args: wrap("phone-second", "w1:SYNTHETIC-approved") }, first); expect([blind.status, blind.body.code]).toEqual([409, "update_app"]); // The founder approves the second device after the codes were compared (an ask it approved, naming that key). await admittedBy(SLUG, "phone-second", PUBLIC["phone-second"]!, "phone-first"); const approved = await http(SLUG, "POST", "/v1/act", { act: "update", args: wrap("phone-second", "w1:SYNTHETIC-approved") }, first); expect(approved.status, JSON.stringify(approved.body)).toBe(200); expect((await vaultRows(SLUG, second)).get("vault-key-phone-second")?.wrapped_vmk).toBe("w1:SYNTHETIC-approved"); }); it("refuses a founding create that arrives with its wrap once another device holds one", async () => { const SLUG = "records-vault-founding-create"; await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] }); const first = await device(SLUG, "phone-first"); const local = await device(SLUG, "phone-local"); const made = await http(SLUG, "POST", "/v1/act", { act: "create", args: { ...row("phone-first"), data: { ...row("phone-first").data, wrapped_vmk: "w1:SYNTHETIC-first", vmk_version: 1 } } }, first); expect(made.status, JSON.stringify(made.body)).toBe(200); // A phone that founded while it stood local brings its own wrap with its row at adoption. const adopted = await http<{ code: string }>(SLUG, "POST", "/v1/act", { act: "create", args: { ...row("phone-local"), data: { ...row("phone-local").data, wrapped_vmk: "w1:SYNTHETIC-local", vmk_version: 1 } } }, local); expect([adopted.status, adopted.body.code]).toEqual([409, "vault_founded"]); }); /** RULE (8 Nov 2026; KEPT FOUR 3 A, 27 Nov 2026): a device's vault key is its public key, not its row id: a wrapped row carrying the caller's own public key under an older id is the caller's own founding, so its wrap onto its signed-in row passes; the older row is retired only when both writes declare the same key identity (`vmk_check`, src/vault_identity.ts), one row per device key. */ it("takes a device's own older founding row as its own: the re-wrap passes and the older row is retired", async () => { const SLUG = "records-vault-own-key"; const { owner } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] }); const phone = await device(SLUG, "phone-before"); // The founding this phone made before it signed in, pushed at adoption under its founder id. const founder = { table: "vault_key", id: "founder:synthetic-device-key", data: { ...row("phone-before").data, wrapped_vmk: "w1:SYNTHETIC-before", vmk_version: 1 }, vmk_check: KEY_CHECK }; expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: founder }, phone)).status).toBe(200); // Its signed-in row, published unwrapped under a new id, then the wrap it took over from the founder row. expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: { ...row("phone-before"), id: "signed-in-row" } }, phone)).status).toBe(200); const taken = await http(SLUG, "POST", "/v1/act", { act: "update", args: { table: "vault_key", id: "signed-in-row", data: { wrapped_vmk: "w1:SYNTHETIC-before", vmk_version: 1 }, vmk_check: KEY_CHECK } }, phone); expect(taken.status, JSON.stringify(taken.body)).toBe(200); const rows = await answer(SLUG, owner, "list_records", { table: "vault_key", where: { device_id: "phone-before" } }); expect(rows.records.map((r) => r.id)).toEqual(["signed-in-row"]); expect((await vaultRows(SLUG, phone)).get("signed-in-row")?.wrapped_vmk).toBe("w1:SYNTHETIC-before"); // Another device's founding is still refused against it. const other = await device(SLUG, "phone-second"); expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: row("phone-second") }, other)).status).toBe(200); const raced = await http<{ code: string }>(SLUG, "POST", "/v1/act", { act: "update", args: wrap("phone-second", "w1:SYNTHETIC-second") }, other); expect([raced.status, raced.body.code]).toEqual([409, "vault_founded"]); }); /** RULE (VAULT GUARD 2, today's builds): the same walk with no `vmk_check` on either write, as every build today posts it: the re-wrap passes, and the older row is NOT retired (an undeclared post cannot be told same from different), so both rows stay. */ it("takes a device's own older founding row as its own with no declared identity: the re-wrap passes and both rows stay", async () => { const SLUG = "records-vault-own-key-undeclared"; const { owner } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] }); const phone = await device(SLUG, "phone-before"); const founder = { table: "vault_key", id: "founder:synthetic-device-key", data: { ...row("phone-before").data, wrapped_vmk: "w1:SYNTHETIC-before", vmk_version: 1 } }; expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: founder }, phone)).status).toBe(200); expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: { ...row("phone-before"), id: "signed-in-row" } }, phone)).status).toBe(200); const taken = await http(SLUG, "POST", "/v1/act", { act: "update", args: { table: "vault_key", id: "signed-in-row", data: { wrapped_vmk: "w1:SYNTHETIC-before", vmk_version: 1 } } }, phone); expect(taken.status, JSON.stringify(taken.body)).toBe(200); const rows = await answer(SLUG, owner, "list_records", { table: "vault_key", where: { device_id: "phone-before" } }); expect(rows.records.map((r) => r.id).sort()).toEqual(["founder:synthetic-device-key", "signed-in-row"]); expect((await vaultRows(SLUG, phone)).get("signed-in-row")?.wrapped_vmk).toBe("w1:SYNTHETIC-before"); const other = await device(SLUG, "phone-second"); expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: row("phone-second") }, other)).status).toBe(200); const raced = await http<{ code: string }>(SLUG, "POST", "/v1/act", { act: "update", args: wrap("phone-second", "w1:SYNTHETIC-second") }, other); expect([raced.status, raced.body.code]).toEqual([409, "vault_founded"]); }); }); /** RULE (owner at the Mac, 22 Nov 2026): a phone whose own key is wrapped on one row and published again, unwrapped, on a second row under its device id (another copy on the same phone) re-wraps the second row as its own, even while other devices hold wraps; the older row is retired. Refused `vault_founded`, the phone's copy (one row per device) never opened, and it could let no Mac in. */ describe("a vault's second row for one device key", () => { it("is re-wrapped as the device's own while other devices hold wraps, and the older row is retired", async () => { const SLUG = "records-vault-second-row"; const { owner } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] }); const KEY = "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"; const sign = async (deviceId: string) => { const code = await http<{ challenge_id: string }>(SLUG, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: deviceId }); const signed = await http<{ credential: string }>(SLUG, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: deviceId }); return { authorization: `Bearer ${signed.body.credential}` }; }; const phone = await sign("phone-twice"); const founded = { table: "vault_key", id: "vault-key-phone-twice", data: { device_id: "phone-twice", public_key: KEY, wrapped_vmk: "w1:SYNTHETIC-own", vmk_version: 1 }, vmk_check: KEY_CHECK }; expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: founded }, phone)).status).toBe(200); // Another device let in by this one: its row holds a wrap too. const other = await sign("galaxy-other"); expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "vault_key", id: "vault-key-galaxy-other", data: { device_id: "galaxy-other", public_key: "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", wrapped_vmk: null, vmk_version: 0 } } }, other)).status).toBe(200); await admittedBy(SLUG, "galaxy-other", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "phone-twice"); expect((await http(SLUG, "POST", "/v1/act", { act: "update", args: { table: "vault_key", id: "vault-key-galaxy-other", data: { wrapped_vmk: "w1:SYNTHETIC-galaxy", vmk_version: 1 } } }, phone)).status).toBe(200); // A second copy on the same phone publishes the same key again, unwrapped, then takes its own wrap over. expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "vault_key", id: "second-copy-row", data: { device_id: "phone-twice", public_key: KEY, wrapped_vmk: null, vmk_version: 0 } } }, phone)).status).toBe(200); const taken = await http(SLUG, "POST", "/v1/act", { act: "update", args: { table: "vault_key", id: "second-copy-row", data: { wrapped_vmk: "w1:SYNTHETIC-own", vmk_version: 1 }, vmk_check: KEY_CHECK } }, phone); expect(taken.status, JSON.stringify(taken.body)).toBe(200); const rows = await answer(SLUG, owner, "list_records", { table: "vault_key", where: { device_id: "phone-twice" } }); expect(rows.records.map((r) => r.id)).toEqual(["second-copy-row"]); // A different key on the device's row is still a founding, and still refused. const stranger = { table: "vault_key", id: "stranger-row", data: { device_id: "phone-twice", public_key: "GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG", wrapped_vmk: null, vmk_version: 0 } }; expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: stranger }, phone)).status).toBe(200); const raced = await http<{ code: string }>(SLUG, "POST", "/v1/act", { act: "update", args: { table: "vault_key", id: "stranger-row", data: { wrapped_vmk: "w1:SYNTHETIC-stranger", vmk_version: 1 } } }, phone); expect([raced.status, raced.body.code]).toEqual([409, "vault_founded"]); }); /** RULE (VAULT GUARD 2, today's builds): the same with no `vmk_check`, as every build today posts it: the second row is re-wrapped as the device's own, and both rows stay. */ it("is re-wrapped as the device's own with no declared identity, and both rows stay", async () => { const SLUG = "records-vault-second-row-undeclared"; const { owner } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] }); const KEY = "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"; const device = async (slug: string, deviceId: string) => { const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: deviceId }); const signed = await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: deviceId }); return { authorization: `Bearer ${signed.body.credential}` }; }; const phone = await device(SLUG, "phone-twice"); expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "vault_key", id: "vault-key-phone-twice", data: { device_id: "phone-twice", public_key: KEY, wrapped_vmk: "w1:SYNTHETIC-own", vmk_version: 1 } } }, phone)).status).toBe(200); const other = await device(SLUG, "galaxy-other"); expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "vault_key", id: "vault-key-galaxy-other", data: { device_id: "galaxy-other", public_key: "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", wrapped_vmk: null, vmk_version: 0 } } }, other)).status).toBe(200); await admittedBy(SLUG, "galaxy-other", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "phone-twice"); expect((await http(SLUG, "POST", "/v1/act", { act: "update", args: { table: "vault_key", id: "vault-key-galaxy-other", data: { wrapped_vmk: "w1:SYNTHETIC-galaxy", vmk_version: 1 } } }, phone)).status).toBe(200); expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "vault_key", id: "second-copy-row", data: { device_id: "phone-twice", public_key: KEY, wrapped_vmk: null, vmk_version: 0 } } }, phone)).status).toBe(200); const taken = await http(SLUG, "POST", "/v1/act", { act: "update", args: { table: "vault_key", id: "second-copy-row", data: { wrapped_vmk: "w1:SYNTHETIC-own", vmk_version: 1 } } }, phone); expect(taken.status, JSON.stringify(taken.body)).toBe(200); const rows = await answer(SLUG, owner, "list_records", { table: "vault_key", where: { device_id: "phone-twice" } }); expect(rows.records.map((r) => r.id).sort()).toEqual(["second-copy-row", "vault-key-phone-twice"]); }); }); /** RULE (owner at the Mac, 22 Nov 2026): a device's second, unwrapped row under its own key gets that key's wrap from its first row when the device next syncs, so a phone whose copy holds the unwrapped row opens again; a row under another key is left alone. */ describe("a device's unwrapped second row for its own key", () => { it("takes the wrap of the same key on the device's next sync", async () => { const SLUG = "records-vault-heal-on-sync"; await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] }); const KEY = "HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH"; const code = await http<{ challenge_id: string }>(SLUG, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: "phone-heal" }); const signed = await http<{ credential: string }>(SLUG, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "phone-heal" }); const phone = { authorization: `Bearer ${signed.body.credential}` }; const create = (id: string, data: Record, check?: string) => http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "vault_key", id, data: { device_id: "phone-heal", ...data }, ...(check ? { vmk_check: check } : {}) } }, phone); // Today's builds declare no identity (VAULT GUARD 2 item 1): with no identity pinned, the heal copies as it always did. expect((await create("first-row", { public_key: KEY, wrapped_vmk: "w1:SYNTHETIC-heal", vmk_version: 1 })).status).toBe(200); expect((await create("second-row", { public_key: KEY, wrapped_vmk: null, vmk_version: 0 })).status).toBe(200); expect((await create("other-key-row", { public_key: "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII", wrapped_vmk: null, vmk_version: 0 })).status).toBe(200); expect((await vaultRows(SLUG, phone)).get("second-row")?.wrapped_vmk ?? null).toBeNull(); // The sync that saw it heals it; the next pass pulls the wrap. const rows = await vaultRows(SLUG, phone); expect(rows.get("second-row")?.wrapped_vmk).toBe("w1:SYNTHETIC-heal"); expect(rows.get("second-row")?.vmk_version).toBe(1); expect(rows.get("other-key-row")?.wrapped_vmk ?? null).toBeNull(); }); }); describe("a person's related records", () => { it("counts and pages membership in a declared multiple link", async () => { const slug = "related-multiple-links"; const { owner } = await personalObject(slug, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open, ...PEOPLE_OPEN.open, ...PHOTOS_OPEN.open] }); await put(slug, [ { verb: "put", table: "photo", id: "photo-a", data: { people: ["aaaaaaaa-0000-4000-8000-000000000001", "bbbbbbbb-0000-4000-8000-000000000002"] } }, { verb: "put", table: "photo", id: "photo-b", data: { people: ["aaaaaaaa-0000-4000-8000-000000000001"] } }, { verb: "put", table: "photo", id: "photo-c", data: { people: ["bbbbbbbb-0000-4000-8000-000000000002"] } }, { verb: "put", table: "photo", id: "photo-empty", data: { people: [] } }, ]); const first = await answer(slug, owner, "list_records", { table: "photo", where: { people: "aaaaaaaa-0000-4000-8000-000000000001" }, limit: 1 }); expect(first.total).toBe(2); expect(first.records).toHaveLength(1); const all = await answer(slug, owner, "list_records", { table: "photo", where: { people: { values: ["aaaaaaaa-0000-4000-8000-000000000001", "bbbbbbbb-0000-4000-8000-000000000002"] } } }); expect(all.total).toBe(3); }); }); describe("a table's marks", () => { // RULE (owner, 3 Nov 2026: "marking a todo as done is just having a check mark"): the kit's todo binds the check to done, and a mark binds only a command that runs on the record at once, as the core holds it (`validate_marks`). it("bind a command that runs on the record at once", () => { const todo = PERSONAL.tables.find((t) => t.id === "todo")!; expect(todo.marks).toEqual({ check: "done" }); expect(marksProblem(todo)).toBeNull(); expect(marksProblem({ ...todo, marks: { check: "drop" } })).toBeNull(); expect(marksProblem({ ...todo, marks: { check: "delete" } })).toBe("marks.check needs an update command that does not ask first"); expect(marksProblem({ ...todo, marks: { check: "set-date" } })).toBe("marks.check needs an update command that does not ask first"); expect(marksProblem({ ...todo, marks: { check: "nowhere" } })).toBe('marks.check names "nowhere", which is not one of the definition\'s commands'); expect(marksProblem({ ...todo, marks: { circle: "done" } })).toBe('marks names "circle", which is not one of "marks"\'s choices'); }); });