Cotton code
91 lines · 7.0 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { answer, mint, personalObject, put, refusal, TODOS_OPEN } from "./personal.ts";/** RULE (owner, 26 Oct 2026): a figure is worked out where the rows live — counted, summed, grouped — over the records a token sees, never a binned one. Synthetic rows only. */describe("computed reads", () => {  const slug = "summaries";  let reader = "";  it("sums, counts and averages by group, narrowed by where, never counting the bin", async () => {    const made = await personalObject(slug, { open: TODOS_OPEN });    reader = await mint(slug, made.credential, "a reader", ["read"]);    await put(slug, [      { table: "todo", data: { title: "Groceries", notes: "food", priority: 120000, status: "open", due_at: "2026-09-02" } },      { table: "todo", data: { title: "Dinner", notes: "food", priority: 80000, status: "open", due_at: "2026-09-12" } },      { table: "todo", data: { title: "Cab", notes: "travel", priority: 30000, status: "open", due_at: "2026-09-14" } },      { table: "todo", data: { title: "Salary", priority: 900000, status: "done", due_at: "2026-09-01" } },      { table: "todo", data: { title: "Binned lunch", notes: "food", priority: 99999, status: "open", due_at: "2026-09-20", trashed_at: "2026-09-21T00:00:00Z" } },    ]);    const spent = await answer(slug, reader, "summarize_records", { table: "todo", where: { status: "open" }, group_by: "notes", measures: [{ op: "count" }, { column: "priority", op: "sum" }, { column: "priority", op: "avg" }, { column: "due_at", op: "max" }] });    expect(spent).toEqual({      table: "todo",      groups: [        { notes: "food", count: 2, sum_priority: 200000, avg_priority: 100000, max_due_at: "2026-09-12" },        { notes: "travel", count: 1, sum_priority: 30000, avg_priority: 30000, max_due_at: "2026-09-14" },      ],      more: false,    });    const all = await answer(slug, reader, "summarize_records", { table: "todo", group_by: "notes", measures: [{ op: "count" }, { column: "notes", op: "count" }] });    expect(all).toMatchObject({ groups: [{ notes: "food", count: 2, count_notes: 2 }, { notes: "travel", count: 1, count_notes: 1 }, { notes: null, count: 1, count_notes: 0 }] });    const whole = await answer(slug, reader, "summarize_records", { table: "todo", measures: [{ column: "priority", op: "min" }, { column: "priority", op: "max" }] });    expect(whole).toEqual({ table: "todo", groups: [{ min_priority: 30000, max_priority: 900000 }], more: false });  });  it("refuses a figure a column cannot give, and a table no token sees", async () => {    expect(await refusal(slug, reader, "summarize_records", { table: "todo", measures: [{ column: "title", op: "sum" }] })).toBe('sum adds up a number or amount column; "title" is text');    expect(await refusal(slug, reader, "summarize_records", { table: "todo", measures: [{ column: "nope", op: "max" }] })).toBe('Todos have no column "nope"');    expect(await refusal(slug, reader, "summarize_records", { table: "mcp_token", measures: [{ op: "count" }] })).toBe("No tool draws this table.");    expect(await refusal(slug, reader, "summarize_records", { table: "todo", measures: [] })).toMatch(/^measures is a list of \{ column, op \}/);  });  it("says what the object holds against its caps, table by table", async () => {    const held = await answer<{ database: { bytes: number; cap: number }; media: { bytes: number; cap: number }; tables: { table: string; rows: number; tombstones: number; bytes: number }[]; change_log: { rows: number } }>(slug, reader, "storage_summary");    expect(held.database.bytes).toBeGreaterThan(0);    expect(held.database.cap).toBe(9_500_000_000);    expect(held.database).not.toHaveProperty("warning");    // The parts come by default (a client with a cached schema sends no argument), and `parts: false` leaves them out.    expect(held).toHaveProperty("parts");    expect(held).toHaveProperty("worker");    expect(await answer(slug, reader, "storage_summary", { parts: false })).not.toHaveProperty("parts");    expect(held.media).toMatchObject({ bytes: 0, cap: 50 * 1024 ** 3 });    expect(held.tables.find((t) => t.table === "todo")).toMatchObject({ rows: 5, tombstones: 0 });    expect(held.change_log.rows).toBeGreaterThanOrEqual(1);  });  // RULE (coordinator, 26 Nov 2026, the GENESIS KITS review): storage_summary answers an assistant as every read does,  // as if a CLOSED table (Sites' `site`) were not there: not named, not counted, not in the change log's writers.  it("never names or counts a closed table", async () => {    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance) => {      const store = (instance as unknown as { store: { sql: SqlStorage; counts(): Record<string, number> } }).store;      const at = "2026-11-26T09:00:00.000Z";      store.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('site', 's-invented', ?, NULL, 9000, 0, ?, ?)", JSON.stringify({ $sealed: "invented" }), at, at);      store.sql.exec("INSERT INTO row_counts (table_id, day, deleted, n) VALUES ('site', '', 0, 1) ON CONFLICT (table_id, day, deleted) DO UPDATE SET n = n + 1");      expect(store.counts().site, "the object itself holds the row").toBe(1);    });    const held = await answer<{ tables: { table: string }[] }>(slug, reader, "storage_summary");    expect(held.tables.map((t) => t.table)).not.toContain("site");    expect(held.tables.map((t) => t.table)).toContain("todo");    expect(JSON.stringify(held)).not.toContain('"site"');  });  it("says, part by part and in sizes only, where the file's bytes go", async () => {    const held = await answer<{ database: { bytes: number }; parts: { file: number; carried: number; overhead: number; parts: { name: string; kind: string; of?: string; entries: number; bytes: number }[] } }>(slug, reader, "storage_summary");    const { parts } = held;    expect(parts.file).toBe(held.database.bytes);    expect(parts.carried + parts.overhead).toBe(parts.file);    const named = (name: string) => parts.parts.find((p) => p.name === name);    expect(named("rows")).toMatchObject({ kind: "table" });    expect(named("rows")!.entries).toBeGreaterThanOrEqual(5);    // No blind_rid on an object made since the index went one way (src/blind.ts).    expect(named("blind_rid")).toBeUndefined();    for (const index of ["rows_cursor", "rows_made", "change_record", "links_target"]) expect(named(index), index).toMatchObject({ kind: "index" });    // A partial index counts only the entries its condition admits: no message here, so none.    expect(named("rows_message_minute")).toMatchObject({ entries: 0, bytes: 0 });    expect(parts.parts.find((p) => p.name.startsWith("sqlite_autoindex_rows"))).toMatchObject({ kind: "index", of: "rows" });    // Sizes only: no part says a value.    expect(JSON.stringify(parts)).not.toMatch(/Groceries|food|travel/);    expect(await refusal(slug, reader, "storage_summary", { parts: "yes" })).toBe("parts is true or false");  });});