Cotton code
521 lines · 34.3 KB · TypeScriptRaw
import { describe, expect, it } from "vitest";import { FIRST } from "../src/first.ts";import { addDays, localDate, type SyncAnswer, type WireRow } from "../src/protocol.ts";import { ADMIN, http, mint, personalObject, put, refusal, TODOS_OPEN, PEOPLE_OPEN } from "./personal.ts";/** A dated table the test brings beside the package's: a window keeps it by `on`. */const DIARY = { format_version: 1, id: "diary", name: "Diary", plural: "Diaries", date: "on", columns: [{ key: "line", type: "text", required: true }, { key: "on", type: "date" }, { key: "about", type: "link", link_to: "diary" }] };const TODAY = localDate(new Date(), "Asia/Kolkata");async function page(slug: string, query: string, credential: string): Promise<SyncAnswer> {  const res = await http<SyncAnswer>(slug, "GET", `/v1/sync?${query}`, undefined, { authorization: `Bearer ${credential}` });  expect(res.status, JSON.stringify(res.body)).toBe(200);  return res.body;}/** Every page from `since`, as the phone pulls: the rows in order, the version it holds after, and how many pages it took. */async function pull(slug: string, credential: string, query: string): Promise<{ rows: WireRow[]; version: number; pages: SyncAnswer[] }> {  const pages: SyncAnswer[] = [await page(slug, query, credential)];  while (pages[pages.length - 1]!.next) pages.push(await page(slug, `cursor=${pages[pages.length - 1]!.next!}`, credential));  return { rows: pages.flatMap((p) => p.rows), version: pages[pages.length - 1]!.version, pages };}/** RULE (owner, 25 Oct 2026): every app's phone keeps a cache filled by snapshot sync since a cursor; Cotton keeps a window of the owner's data. */describe("snapshot sync on the personal object", () => {  const SLUG = "sync-personal";  let credential = "";  let base = 0;  it("pages one import's rows, all under one version, without a gap or a repeat, and holds the version only on the last page", async () => {    ({ credential } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open] }));    expect((await http(SLUG, "POST", "/v1/admin/definitions/tables", { tables: [DIARY] }, ADMIN)).status).toBe(200);    base = (await page(SLUG, "since=0", credential)).version;    const rows = Array.from({ length: 25 }, (_, i) => ({ verb: "put", table: "diary", id: `d-${String(i).padStart(2, "0")}`, data: { line: `day ${i}`, on: addDays(TODAY, -i * 5) } }));    await put(SLUG, rows);    const { rows: got, version, pages } = await pull(SLUG, credential, `since=${base}&limit=10`);    expect(pages.map((p) => p.rows.length)).toEqual([10, 10, 5]);    expect(new Set(got.map((r) => r.version)).size, "one import is one version").toBe(1);    expect(got.map((r) => r.id)).toEqual(rows.map((r) => r.id));    expect(pages.slice(0, -1).every((p) => p.version === base), "a page with more to come leaves the phone at since").toBe(true);    expect(version).toBe(got[0]!.version);    expect(pages.slice(0, -1).every((p) => p.people === undefined) && Array.isArray(pages[2]!.people), "people come with the last page").toBe(true);    expect((await page(SLUG, `since=${version}`, credential)).rows).toEqual([]);  });  it("says the object's clock on every page, the time the phone judges its writes' stamps by", async () => {    const before = Date.now();    const { pages } = await pull(SLUG, credential, `since=${base}&limit=10`);    const after = Date.now();    for (const p of pages) {      const at = Date.parse(p.server_time);      expect(at >= before - 1000 && at <= after + 1000, p.server_time).toBe(true);    }  });  it("reads up to the version its first page saw: a write between pages comes in the next sync, not the middle of this one", async () => {    const first = await page(SLUG, `since=${base}&limit=10`, credential);    await put(SLUG, [{ verb: "put", table: "diary", id: "d-00", data: { line: "rewritten", on: TODAY } }]);    let rest = first;    const later: WireRow[] = [];    while (rest.next) {      rest = await page(SLUG, `cursor=${rest.next}`, credential);      later.push(...rest.rows);    }    expect(first.rows.find((r) => r.id === "d-00")?.data.line, "the first page carried d-00 as it was").toBe("day 0");    expect(later.some((r) => r.id === "d-00"), "d-00 moved past this pass's upper bound, so no later page repeats it").toBe(false);    expect(later.length).toBe(15);    const next = await pull(SLUG, credential, `since=${rest.version}`);    expect(next.rows.map((r) => [r.id, r.data.line])).toEqual([["d-00", "rewritten"]]);  });  it("keeps a window: a dated table's rows before the window stay out of every page, a tombstone and an undated row come", async () => {    await put(SLUG, [      { verb: "put", table: "diary", id: "d-undated", data: { line: "no day" } },      { verb: "put", table: "memory", id: "mem-w", data: { slug: "keep-the-window", title: "Keep the window", origin_kind: "user" } },    ]);    const del = await http(SLUG, "POST", "/v1/act", { act: "delete", args: { table: "diary", id: "d-24" } }, { authorization: `Bearer ${credential}` });    expect(del.status, JSON.stringify(del.body)).toBe(200);    const windowed = await pull(SLUG, credential, `since=0&limit=3&window=diary:30`);    expect(windowed.pages[0]!.total, "the counted total is the live rows the pass carries").toBe(windowed.rows.filter((r) => !r.deleted).length);    const diary = windowed.rows.filter((r) => r.table === "diary");    // d-00 (today), d-01 … d-06 are within 30 days; d-24 is a tombstone; d-undated has no day.    expect(diary.filter((r) => !r.deleted).map((r) => r.id).sort()).toEqual(["d-00", "d-01", "d-02", "d-03", "d-04", "d-05", "d-06", "d-undated"]);    expect(diary.filter((r) => r.deleted).map((r) => r.id)).toEqual(["d-24"]);    const whole = await pull(SLUG, credential, "since=0");    expect(whole.version).toBe(windowed.version);    const others = (rows: WireRow[]) => rows.filter((r) => r.table !== "diary").map((r) => `${r.table}/${r.id}`).sort();    expect(others(whole.rows).length).toBeGreaterThan(0);    expect(others(windowed.rows), "the other tables come whole").toEqual(others(whole.rows));  });  /** RULE (coordinator, 5 Nov 2026): an app pulls only its kit's tables — Cotton Books signed in to the owner's object pulled his whole life. */  it("keeps a pass to the tables it names, on every page, and counts only those", async () => {    const scoped = await pull(SLUG, credential, "since=0&limit=3&tables=diary,memory");    expect(scoped.pages.length, "it pages").toBeGreaterThan(1);    expect([...new Set(scoped.rows.map((r) => r.table))].sort()).toEqual(["diary", "memory"]);    const whole = await pull(SLUG, credential, "since=0");    const of = (rows: WireRow[]) => rows.filter((r) => r.table === "diary" || r.table === "memory").map((r) => `${r.table}/${r.id}`).sort();    expect(of(scoped.rows), "those tables come whole").toEqual(of(whole.rows));    expect(whole.rows.some((r) => r.table !== "diary" && r.table !== "memory"), "and the object holds others").toBe(true);    expect(scoped.pages[0]!.total).toBe(scoped.rows.filter((r) => !r.deleted).length);    expect(scoped.version).toBe(whole.version);    expect((await pull(SLUG, credential, "since=0&tables=no_such_table")).rows, "a table the object lacks carries nothing").toEqual([]);  });  it("refuses a window on an undated or unknown table, a bad limit and a forged cursor", async () => {    const refused = async (query: string): Promise<string> => {      const res = await http<{ code: string }>(SLUG, "GET", `/v1/sync?${query}`, undefined, { authorization: `Bearer ${credential}` });      expect(res.status).toBeGreaterThanOrEqual(400);      return res.body.code;    };    expect(await refused("window=record_group:30")).toBe("bad_window");    expect(await refused("window=nope:30")).toBe("no_such_table");    expect(await refused("window=diary")).toBe("bad_window");    expect(await refused("tables=diary,Not-a-table")).toBe("bad_tables");    expect(await refused("tables=")).toBe("bad_tables");    expect(await refused("limit=0")).toBe("bad_request");    expect(await refused("limit=10001")).toBe("bad_request");    expect(await refused("cursor=bm90LWEtY3Vyc29y")).toBe("bad_cursor");  });  it("answers an import's puts by table, and pages the export with every count", async () => {    const again = await http<{ changed: number; puts: Record<string, { written: number; unchanged: number; deleted: number }> }>(      SLUG,      "POST",      "/v1/admin/import",      { rows: [        { verb: "put", table: "diary", id: "d-01", data: { line: "day 1", on: addDays(TODAY, -5) } },        { verb: "put", table: "diary", id: "d-02", data: { line: "day two", on: addDays(TODAY, -10) } },        { verb: "put", table: "diary", id: "d-24", data: { line: "day 24", on: addDays(TODAY, -120) } },        { verb: "put", table: "diary", id: "d-new", data: { line: "new", about: "d-01" } },      ] },      ADMIN,    );    expect(again.status, JSON.stringify(again.body)).toBe(200);    expect(again.body.puts).toEqual({ diary: { written: 2, unchanged: 1, deleted: 1 } });    type Export = { counts: Record<string, number>; rows: WireRow[]; next: string | null };    const first = await http<Export>(SLUG, "GET", "/v1/admin/export?limit=7", undefined, ADMIN);    expect(first.body.counts.diary).toBe(26);    const rows = [...first.body.rows];    for (let next = first.body.next; next; ) {      const p = await http<Export>(SLUG, "GET", `/v1/admin/export?limit=7&after=${encodeURIComponent(next)}`, undefined, ADMIN);      rows.push(...p.body.rows);      next = p.body.next;    }    const total = Object.values(first.body.counts).reduce((a, b) => a + b, 0);    expect(rows.length).toBe(total);    expect(new Set(rows.map((r) => `${r.table}/${r.id}`)).size).toBe(total);  });  it("keeps the owner's newest days of messages and every chat, by the message's sent_at", async () => {    const recent = new Date(Date.now() - 2 * 86_400_000).toISOString();    const old = new Date(Date.now() - 90 * 86_400_000).toISOString();    await put(SLUG, [      { verb: "put", table: "thread", id: "th-w", data: { kind: "dm", title: "Asha" } },      { verb: "put", table: "message", id: "mm-new", data: { thread_id: "th-w", direction: "in", channel: "whatsapp", origin: "imported", body: "new", sent_at: recent, media: [], reactions: [], meta: {}, mentions: [] } },      { verb: "put", table: "message", id: "mm-old", data: { thread_id: "th-w", direction: "in", channel: "whatsapp", origin: "imported", body: "old", sent_at: old, media: [], reactions: [], meta: {}, mentions: [] } },      { verb: "put", table: "memory", id: "mem-1", data: { slug: "ship-it", title: "Ship it", origin_kind: "user" }, created_at: old },    ]);    const kept = await pull(SLUG, credential, "since=0&window=message:30,memory:30");    expect(kept.rows.filter((r) => r.table === "message").map((r) => r.id)).toEqual(["mm-new"]);    expect(kept.rows.some((r) => r.table === "thread" && r.id === "th-w"), "every chat comes").toBe(true);    expect(kept.rows.some((r) => r.id === "mem-1"), "a table dated by created_at reads the row's own time").toBe(false);    expect(kept.pages[0]!.total, "a window is counted as it is read").toBe(kept.rows.filter((r) => !r.deleted).length);    expect(kept.pages[0]!.remaining).toBe(0);    const all = await pull(SLUG, credential, "since=0");    expect(all.rows.filter((r) => r.table === "message").map((r) => r.id).sort()).toEqual(["mm-new", "mm-old"]);    expect(all.pages[0]!.total).toBe(all.rows.filter((r) => !r.deleted).length);    const since = await pull(SLUG, credential, `since=${base}`);    expect(since.pages[0]!.total, "a pass from a later version says the same total").toBe(all.pages[0]!.total);  });  it("carries no row of the object's internal tables, token hashes and OAuth state, and counts none of them", async () => {    const INTERNAL = new Set(["mcp_token", "oauth_client", "oauth_code", "oauth_refresh"]);    await mint(SLUG, credential, "a token the object holds a row for", ["read"]);    const all = await pull(SLUG, credential, "since=0");    expect(all.rows.filter((r) => INTERNAL.has(r.table)), "no internal row on any page").toEqual([]);    expect(all.pages[0]!.total).toBe(all.rows.filter((r) => !r.deleted).length);    const since = await pull(SLUG, credential, `since=${base}`);    expect(since.rows.filter((r) => INTERNAL.has(r.table))).toEqual([]);    expect(since.pages[0]!.total).toBe(all.pages[0]!.total);  });});/** * RULE (owner, 2 Nov 2026): a fresh install holds the small tables whole in * its first minutes, then the big ones. Every table here is small (under * 10,000 rows), so a pass from nothing is one table after another, the fewest * rows first; the split and the big run are proved over a synthetic object in * test/sync-order.test.ts. */describe("a pass from nothing carries the small tables first", () => {  const SLUG = "sync-small-first";  let credential = "";  let base = 0;  const encode = (o: unknown): string => btoa(JSON.stringify(o)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");  const decode = (t: string): Record<string, unknown> => JSON.parse(atob(t.replace(/-/g, "+").replace(/_/g, "/"))) as Record<string, unknown>;  const at = (r: WireRow): string => `${r.table}/${r.id}`;  const changeOrder = (a: WireRow, b: WireRow): number => a.version - b.version || (a.table < b.table ? -1 : a.table > b.table ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0);  it("pages whole tables, the fewest rows first, across page edges; a later pass stays in change order", async () => {    ({ credential } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open] }));    base = (await page(SLUG, "since=0", credential)).version;    // Written interleaved, one import each, so change order mixes the tables.    for (let i = 0; i < 9; i++) {      const rows: Record<string, unknown>[] = [{ verb: "put", table: "person", id: `p-${i}`, data: { full_name: `Person ${i}` } }];      if (i < 5) rows.push({ verb: "put", table: "todo", id: `t-${i}`, data: { title: `Todo ${i}` } });      if (i < 2) rows.push({ verb: "put", table: "memory", id: `mem-${i}`, data: { slug: `memory-${i}`, title: `Memory ${i}`, origin_kind: "user" } });      await put(SLUG, rows);    }    const { rows, pages } = await pull(SLUG, credential, "since=0&limit=4");    expect(pages.length).toBeGreaterThan(3);    const counts = new Map<string, number>();    for (const r of rows) counts.set(r.table, (counts.get(r.table) ?? 0) + 1);    const runs = rows.map((r) => r.table).filter((t, i, ts) => i === 0 || ts[i - 1] !== t);    expect(new Set(runs).size, "each table comes whole, once").toBe(runs.length);    // A table a kit orders first (Days' todos, by due date around today: src/first.ts) comes in its own order,    // whole right after the small tables when it is small; every other small table the fewest rows first.    const plain = [...counts.keys()].filter((t) => !FIRST.has(t));    expect(runs.filter((t) => !FIRST.has(t))).toEqual(plain.sort((a, b) => counts.get(a)! - counts.get(b)! || (a < b ? -1 : 1)));    expect(runs.indexOf("memory")).toBeLessThan(runs.indexOf("person"));    expect(runs[runs.length - 1], "the todos, none due around today, come whole after").toBe("todo");    expect(new Set(rows.map(at)).size, "no row twice").toBe(rows.length);    expect(pages[0]!.total).toBe(rows.filter((r) => !r.deleted).length);    const later = await pull(SLUG, credential, `since=${base}&limit=4`);    expect(later.rows.map(at), "a pass from a version is in change order").toEqual([...later.rows].sort(changeOrder).map(at));  });  it("takes a cursor made before (version, table, id): the rows after it come once, small tables first, and the pass ends where it would have", async () => {    const whole = await pull(SLUG, credential, "since=0&limit=4");    const inOrder = [...whole.rows].sort(changeOrder);    // A copy mid-pull on an old cursor: it holds the first rows in change order.    const first = await page(SLUG, "since=0&limit=4", credential);    const made = decode(first.next!);    const held = inOrder.slice(0, 7);    const last = held[held.length - 1]!;    const old = encode({ since: made.since, upto: made.upto, limit: made.limit, windows: made.windows, after: { version: last.version, table: last.table, id: last.id }, figures: made.figures });    const pages: SyncAnswer[] = [await page(SLUG, `cursor=${old}`, credential)];    while (pages[pages.length - 1]!.next) pages.push(await page(SLUG, `cursor=${pages[pages.length - 1]!.next!}`, credential));    const rest = pages.flatMap((p) => p.rows);    const keys = [...held, ...rest].map(at);    expect(new Set(keys).size, "nothing twice").toBe(keys.length);    expect(new Set(keys), "nothing skipped").toEqual(new Set(whole.rows.map(at)));    expect(pages[pages.length - 1]!.version).toBe(whole.version);    expect(pages[pages.length - 1]!.done).toBe(whole.pages[0]!.total);    const next = decode(pages[0]!.next!);    expect(next.floor, "the old cursor's place is the floor of the rest").toEqual({ version: last.version, table: last.table, id: last.id });    expect(Array.isArray(next.small) && (next.small as string[]).includes("person"), "and its small tables are decided").toBe(true);    const runs = rest.map((r) => r.table).filter((t, i, ts) => i === 0 || ts[i - 1] !== t);    expect(new Set(runs).size, "the rest comes a table at a time").toBe(runs.length);  });});/** * RULE (owner, 2 Nov 2026): the deck's counter says while a tool's rows come * how far they have come ("347 of 950 todos arriving"). Every page says, for * each table the pass carries, its rows in the pass and how many have come * once that page has landed; the last page has every table whole. */describe("each page says how far each table's rows have come", () => {  const SLUG = "sync-tables";  let credential = "";  const encode = (o: unknown): string => btoa(JSON.stringify(o)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");  const decode = (t: string): Record<string, unknown> => JSON.parse(atob(t.replace(/-/g, "+").replace(/_/g, "/"))) as Record<string, unknown>;  it("counts each table's rows on the first page and what came of them page by page, whole on the last", async () => {    ({ credential } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open] }));    for (let i = 0; i < 9; i++) {      const rows: Record<string, unknown>[] = [{ verb: "put", table: "person", id: `p-${i}`, data: { full_name: `Person ${i}` } }];      if (i < 5) rows.push({ verb: "put", table: "todo", id: `t-${i}`, data: { title: `Todo ${i}` } });      await put(SLUG, rows);    }    const { rows, pages } = await pull(SLUG, credential, "since=0&limit=4");    const inPass = (table: string): number => rows.filter((r) => r.table === table).length;    expect(inPass("todo")).toBe(5);    expect(inPass("person")).toBeGreaterThanOrEqual(9);    const came = new Map<string, number>();    for (const p of pages) {      for (const r of p.rows) came.set(r.table, (came.get(r.table) ?? 0) + 1);      for (const table of ["todo", "person"]) {        expect(p.tables[table], `${table} on every page`).toEqual({ rows: inPass(table), done: came.get(table) ?? 0 });      }    }    const last = pages[pages.length - 1]!;    expect(Object.values(last.tables).every((t) => t.done === t.rows), "the last page has every table whole").toBe(true);    expect(Object.keys(last.tables).sort()).toEqual([...new Set(rows.map((r) => r.table))].sort());  });  it("answers a pass's first page short, so every table's figures come before its rows; later pages are the size asked", async () => {    await put(SLUG, Array.from({ length: 300 }, (_, i) => ({ verb: "put", table: "person", id: `pp-${String(i).padStart(3, "0")}`, data: { full_name: `Invented ${i}` } })));    const { rows, pages } = await pull(SLUG, credential, "since=0&limit=5000");    expect(rows.length).toBeGreaterThan(200);    expect(pages.map((p) => p.rows.length)).toEqual([200, rows.length - 200]);    const people = pages[0]!.tables.person!;    expect(people.rows).toBe(rows.filter((r) => r.table === "person").length);    expect(people.done, "the people are still to come after the first page").toBeLessThan(people.rows);    expect(pages[1]!.tables.person).toEqual({ rows: people.rows, done: people.rows });  });  it("a later pass counts only what changed, and a caught-up poll names no table", async () => {    const held = (await pull(SLUG, credential, "since=0")).version;    await put(SLUG, [{ verb: "put", table: "todo", id: "t-0", data: { title: "Todo 0, again" } }]);    const later = await page(SLUG, `since=${held}`, credential);    expect(later.tables).toEqual({ todo: { rows: 1, done: 1 } });    expect((await page(SLUG, `since=${later.version}`, credential)).tables).toEqual({});  });  it("takes a cursor whose figures name no tables and goes on, saying what came after it", async () => {    const first = await page(SLUG, "since=0&limit=4", credential);    const made = decode(first.next!);    const { tables: _counted, ...figures } = made.figures as Record<string, unknown>;    const old = encode({ ...made, figures });    const next = await page(SLUG, `cursor=${old}`, credential);    expect(next.rows.length).toBeGreaterThan(0);    for (const [table, t] of Object.entries(next.tables)) expect(t.done, table).toBe(t.rows);  });});/** RULE (owner, 26 Oct 2026): sync status is the phone's own device record — the object writes how far it has got on every page, the phone what only it knows. */describe("a signed-in device's sync status, on its own device row", () => {  const SLUG = "sync-status";  let credential = "";  let auth: Record<string, string> = {};  /** The device row as the object holds it now, read through the admin export. */  async function deviceRow(id: string): Promise<WireRow> {    const res = await http<{ rows: WireRow[] }>(SLUG, "GET", "/v1/admin/export?limit=10000", undefined, ADMIN);    const row = res.body.rows.find((r) => r.table === "device" && r.id === id);    expect(row, `device ${id}`).toBeDefined();    return row!;  }  it("names no row for a device the database holds none of, and writes nothing", async () => {    ({ credential } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open] }));    auth = { authorization: `Bearer ${credential}` };    const first = await page(SLUG, "since=0", credential);    expect(first.device).toBeNull();    const again = await page(SLUG, `since=${first.version}`, credential);    expect(again.rows, "a pull with no row writes no change").toEqual([]);    expect(again.total).toBe(first.total);    expect(again.remaining).toBe(0);  });  it("writes every page's standing on the row the device registered: rows done of total, the version, caught up on the last page", async () => {    const made = await http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "device", id: "dev-phone", data: { device_id: "coordinator", name: "Test phone", platform: "ios", approved_at: new Date().toISOString() } } }, auth);    expect(made.status, JSON.stringify(made.body)).toBe(200);    await put(SLUG, Array.from({ length: 12 }, (_, i) => ({ verb: "put", table: "todo", id: `st-${String(i).padStart(2, "0")}`, data: { title: `todo ${i}`, status: "open" } })));    const first = await page(SLUG, "since=0&limit=5", credential);    expect(first.device).toBe("dev-phone");    expect(first.next).toBeDefined();    expect(first.remaining).toBeGreaterThan(0);    const mid = await deviceRow("dev-phone");    expect(mid.data).toMatchObject({ caught_up: false, sync_version: 0, sync_rows_total: first.total });    expect(mid.data.sync_rows_done as number).toBeLessThan(first.total);    expect(mid.data.sync_rows_done, "the answer says what the row says").toBe(first.done);    expect(Date.parse(mid.data.synced_at as string)).toBeGreaterThan(Date.now() - 60_000);    const pages = [first];    while (pages[pages.length - 1]!.next) pages.push(await page(SLUG, `cursor=${pages[pages.length - 1]!.next!}`, credential));    const remaining = pages.map((p) => p.remaining);    expect(remaining, "what remains only falls, and is nothing on the last page").toEqual([...remaining].sort((a, b) => b - a));    expect(remaining[remaining.length - 1]).toBe(0);    expect(pages.every((p) => p.total === first.total), "a pass says one total").toBe(true);    const lastPage = pages[pages.length - 1]!;    const done = await deviceRow("dev-phone");    expect(done.data).toMatchObject({ caught_up: true, sync_version: lastPage.version, sync_rows_total: first.total, sync_rows_done: first.total });  });  it("does not write again for a caught-up pull that brought only its own row, so polling converges", async () => {    const held = (await deviceRow("dev-phone")).version;    const caughtUp = (await page(SLUG, `since=0`, credential)).version;    let since = caughtUp;    for (let i = 0; i < 3; i++) since = (await pull(SLUG, credential, `since=${since}`)).version;    const after = await page(SLUG, `since=${since}`, credential);    expect(after.rows, "nothing new after the row's own last write").toEqual([]);    expect((await deviceRow("dev-phone")).version).toBeGreaterThanOrEqual(held);  });  it("takes the phone's own figures through the general update: bytes received and the moment it stalled, and clears the stall", async () => {    const write = (data: Record<string, unknown>) => http<{ changed: WireRow[] }>(SLUG, "POST", "/v1/act", { act: "update", args: { table: "device", id: "dev-phone", data } }, auth);    const stalled = new Date().toISOString();    const a = await write({ sync_bytes: 1_234_567, stalled_at: stalled });    expect(a.status, JSON.stringify(a.body)).toBe(200);    expect(a.body.changed[0]?.data).toMatchObject({ sync_bytes: 1_234_567, stalled_at: stalled, caught_up: true });    const b = await write({ stalled_at: null });    expect(b.body.changed[0]?.data.stalled_at ?? null).toBeNull();  });  it("refuses an assistant writing the object's own sync columns", async () => {    const owner = await mint(SLUG, credential, "status test", ["owner"]);    const said = await refusal(SLUG, owner, "update_record", { table: "device", id: "dev-phone", patch: { caught_up: false } });    expect(said).toMatch(/read only/);  });});/** RULE (owner, 25 Oct 2026): the phone posts its writes to the database's object; a row keeps the id it was made with on the phone. */describe("the owner's phone writes through the general acts", () => {  const SLUG = "phone-writes";  it("creates a row under the id the phone named, refuses a second create of it, and updates and deletes it by that id", async () => {    const { credential } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open] });    const auth = { authorization: `Bearer ${credential}` };    const act = (name: string, args: Record<string, unknown>) => http<{ version: number; changed: WireRow[]; made?: { id: string } }>(SLUG, "POST", "/v1/act", { act: name, args }, auth);    const made = await act("create", { table: "todo", id: "phone-todo-1", data: { title: "Ring the bank", status: "open" } });    expect(made.status, JSON.stringify(made.body)).toBe(200);    expect(made.body.made?.id).toBe("phone-todo-1");    expect(made.body.changed.map((r) => [r.table, r.id])).toEqual([["todo", "phone-todo-1"]]);    const again = await act("create", { table: "todo", id: "phone-todo-1", data: { title: "Twice" } });    expect(again.status).toBe(409);    expect((again.body as unknown as { code: string }).code).toBe("duplicate_id");    const done = await act("update", { table: "todo", id: "phone-todo-1", data: { status: "done" } });    expect(done.body.changed[0]?.data).toMatchObject({ title: "Ring the bank", status: "done" });    const gone = await act("delete", { table: "todo", id: "phone-todo-1" });    expect(gone.body.changed[0]).toMatchObject({ id: "phone-todo-1", deleted: true });  });  // UNKNOWN FIELD (coordinator, 28 Nov 2026): refused under its own code, naming table and field, never trimmed. A phone  // on a newer kit than the Worker holds the change and sends it again once the definitions move (cotton-client).  it("refuses a create and an update carrying a key the table has no column for, naming the key, and writes nothing", async () => {    const { credential } = await personalObject(`${SLUG}-stray`, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open] });    const auth = { authorization: `Bearer ${credential}` };    const act = (name: string, args: Record<string, unknown>) => http<{ code: string; message: string }>(`${SLUG}-stray`, "POST", "/v1/act", { act: name, args }, auth);    expect((await act("create", { table: "todo", id: "kept", data: { title: "Ring the bank", status: "open" } })).status).toBe(200);    const before = (await page(`${SLUG}-stray`, "since=0", credential)).version;    const made = await act("create", { table: "todo", id: "stray", data: { title: "Pay rent", acount: "x" } });    expect(made.status).toBe(400);    expect(made.body.code).toBe("unknown_field");    expect(made.body.message).toBe('todo has no field "acount"');    const changed = await act("update", { table: "todo", id: "kept", data: { status: "done", acount: "x" } });    expect(changed.status).toBe(400);    expect(changed.body.code).toBe("unknown_field");    expect(changed.body.message).toBe('todo has no field "acount"');    const after = await page(`${SLUG}-stray`, `since=${before}`, credential);    expect(after.rows, "neither refusal wrote a row").toEqual([]);    expect(after.version).toBe(before);    const all = await page(`${SLUG}-stray`, "since=0", credential);    expect(all.rows.find((r) => r.id === "kept")?.data).toMatchObject({ status: "open" });  });});/** * RULE (owner, 21 Nov 2026): an app update never pulls the whole object again. * A phone whose new build keeps a table its copy's cursor went past asks * `again=<tables>` on a later pass: those tables come whole, first, the rest * since its cursor, nothing twice, and the answer says `again` so the phone * knows this Worker carried them. */describe("a later pass carries some tables again whole", () => {  const SLUG = "sync-again";  it("carries the named tables whole and every other table since the cursor, once each, and says so", async () => {    const { credential } = await personalObject(SLUG, { open: [...TODOS_OPEN, ...PEOPLE_OPEN.open] });    await put(SLUG, Array.from({ length: 6 }, (_, i) => ({ verb: "put", table: "todo", id: `ta-${i}`, data: { title: `Todo ${i}` } })));    await put(SLUG, Array.from({ length: 4 }, (_, i) => ({ verb: "put", table: "person", id: `pa-${i}`, data: { full_name: `Person ${i}` } })));    const held = (await pull(SLUG, credential, "since=0")).version;    await put(SLUG, [{ verb: "put", table: "person", id: "pa-new", data: { full_name: "A later person" } }, { verb: "put", table: "todo", id: "ta-0", data: { title: "Todo 0 again" } }]);    const { rows, pages } = await pull(SLUG, credential, `since=${held}&again=todo&limit=3`);    const keys = rows.map((r) => `${r.table}/${r.id}`);    expect(new Set(keys).size, "nothing twice").toBe(keys.length);    expect(rows.filter((r) => r.table === "todo").map((r) => r.id).sort(), "every todo, whole").toEqual(["ta-0", "ta-1", "ta-2", "ta-3", "ta-4", "ta-5"]);    expect(rows.filter((r) => r.table === "person").map((r) => r.id), "of the rest, only what changed").toEqual(["pa-new"]);    expect(rows.findIndex((r) => r.table === "person")).toBeGreaterThan(rows.map((r) => r.table).lastIndexOf("todo"));    expect(pages.every((p) => JSON.stringify(p.again) === JSON.stringify(["todo"])), "every page says it").toBe(true);    expect(pages[0]!.tables.todo?.rows, "the todos counted whole").toBe(6);    expect(pages[pages.length - 1]!.done).toBe(pages[0]!.total);    const plain = await pull(SLUG, credential, `since=${held}`);    expect(plain.pages[0]!.again, "a pass that asks nothing again says nothing").toBeUndefined();    expect(plain.rows.map((r) => r.id).sort()).toEqual(["pa-new", "ta-0"]);  });});/** * RULE (owner, 21 Nov 2026): a kit pulls only the rows of a table it needs. * Words keeps the documents that are web pages (an assistant's HTML), never * every document: `only=<table>.<column>:<value>|<value>` keeps the live rows * whose clear column holds one of the values, from nothing and in a later pass * alike; a tombstone still comes; a sealed column is refused, the object cannot * read it to choose. */describe("a kit's only keeps the rows it names", () => {  const SLUG = "sync-only";  it("keeps the live rows whose column holds a named value, counts them honestly, and lets tombstones through", async () => {    const { credential } = await personalObject(SLUG, { open: [...TODOS_OPEN, "document"] });    const doc = (id: string, mime: string) => ({ verb: "put", table: "document", id, data: { title: `Invented ${id}`, mime, byte_size: 10, sha256: id.padEnd(64, "0"), storage_path: `documents/${id}`, status: "ready" } });    await put(SLUG, [doc("d-h1", "text/html"), doc("d-h2", "text/html"), doc("d-p1", "application/pdf"), doc("d-p2", "application/pdf"), doc("d-p3", "image/png")]);    await put(SLUG, Array.from({ length: 3 }, (_, i) => ({ verb: "put", table: "todo", id: `to-${i}`, data: { title: `Todo ${i}` } })));    const first = await pull(SLUG, credential, "since=0&tables=document,todo&only=document.mime:text/html&limit=2");    const keys = first.rows.map((r) => `${r.table}/${r.id}`);    expect(new Set(keys).size, "nothing twice").toBe(keys.length);    expect(first.rows.filter((r) => r.table === "document").map((r) => r.id).sort(), "the web pages alone").toEqual(["d-h1", "d-h2"]);    expect(first.rows.filter((r) => r.table === "todo")).toHaveLength(3);    expect(first.pages[0]!.total, "counted as it carries").toBe(5);    expect(first.pages[first.pages.length - 1]!.done).toBe(5);    await put(SLUG, [doc("d-h3", "text/html"), doc("d-p4", "application/pdf")]);    const del = await http(SLUG, "POST", "/v1/act", { act: "delete", args: { table: "document", id: "d-p1" } }, { authorization: `Bearer ${credential}` });    expect(del.status, JSON.stringify(del.body)).toBe(200);    const later = await pull(SLUG, credential, `since=${first.version}&tables=document,todo&only=document.mime:text/html`);    expect(later.rows.map((r) => `${r.id}${r.deleted ? " gone" : ""}`).sort(), "a later pass: the new page, and a tombstone").toEqual(["d-h3", "d-p1 gone"]);    const sealed = await http(SLUG, "GET", "/v1/sync?since=0&only=project_link.record_kind:memory", undefined, { authorization: `Bearer ${credential}` });    expect(sealed.status).toBe(400);    expect(JSON.stringify(sealed.body)).toContain("sealed");    const unknown = await http(SLUG, "GET", "/v1/sync?since=0&only=document.nothing:x", undefined, { authorization: `Bearer ${credential}` });    expect(unknown.status).toBe(400);   }, 120_000);});