Cotton code
129 lines · 9.0 KB · TypeScriptRaw
/** * RULE (owner, 17 Nov 2026; KEEP_RULE 15): the old screenplay tables go, and * Cotton Story is the one screenwriting app. An object holding them keeps * every row in storage, untouched, and holds the seven definitions and the * Screenplays tool as retired (src/retired.ts `KIT_RETIRED`): never served, * so never drawn, never offered over MCP, and no sync carries their rows. A * fresh object never has them. Story's tables are the kit's throughout. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { KIT_VERSION } from "../src/kit_keep.ts";import { PERSONAL } from "../src/kits.ts";import { GONE_TABLES, GONE_TOOLS, KIT_RETIRED, readRetired, retiring, served } from "../src/retired.ts";import { ruled } from "../src/seal.ts";import { ADMIN, http, personalObject } from "./personal.ts";import SCREENPLAY from "./fixtures/screenplay-old/screenplay.json";import SCENE from "./fixtures/screenplay-old/screenplay_scene.json";import CHARACTER from "./fixtures/screenplay-old/screenplay_character.json";import PLACE from "./fixtures/screenplay-old/screenplay_place.json";import DRAFT from "./fixtures/screenplay-old/screenplay_draft.json";import DRAFT_SCENE from "./fixtures/screenplay-old/screenplay_draft_scene.json";import DOCUMENT from "./fixtures/screenplay-old/screenplay_document.json";import SCREENPLAYS from "./fixtures/screenplay-old/screenplays.json";type Doc = Record<string, unknown>;type Defs = { tools: Doc[]; tables: Doc[]; etag: string };const OLD_TABLES = [SCREENPLAY, SCENE, CHARACTER, PLACE, DRAFT, DRAFT_SCENE, DOCUMENT] as Doc[];const STORY = ["story_story", "story_scene", "story_character", "story_place", "story_note"];const ids = (docs: Doc[]): string[] => docs.map((d) => String(d.id)).sort();const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));/** The object as an older Worker left it: the seven tables and the Screenplays tool defined, rows in two of them, and a kit to keep to. */async function heldBefore(slug: string): Promise<void> {  await runInDurableObject(stub(slug), (_instance, state) => {    for (const t of OLD_TABLES) state.storage.sql.exec("INSERT OR REPLACE INTO definitions (id, kind, json) VALUES (?, 'table', ?)", `table:${String(t.id)}`, JSON.stringify(t));    state.storage.sql.exec("INSERT OR REPLACE INTO definitions (id, kind, json) VALUES ('tool:screenplays', 'tool', ?)", JSON.stringify(SCREENPLAYS));    const at = "2026-11-10T06:00:00.000Z";    const row = (table: string, id: string, data: Doc) =>      state.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES (?, ?, ?, NULL, 1, 0, ?, ?)", table, id, JSON.stringify(data), at, at);    row("screenplay", "sp1", { title: "The Lantern Orchard" });    row("screenplay_scene", "sc1", { screenplay_id: "sp1", heading: "INT. ORCHARD - NIGHT", position: 1 });    row("screenplay_character", "ch1", { screenplay_id: "sp1", name: "MEERA" });    state.storage.sql.exec("UPDATE meta SET value = 'an-older-kit' WHERE key = ?", KIT_VERSION);  });}async function storedRows(slug: string): Promise<string[]> {  return runInDurableObject(stub(slug), (_instance, state) =>    state.storage.sql      .exec<{ table_id: string; id: string; data: string; deleted: number }>("SELECT table_id, id, data, deleted FROM rows WHERE table_id LIKE 'screenplay%' ORDER BY table_id, id")      .toArray()      .map((r) => `${r.table_id} ${r.id} ${r.deleted} ${r.data}`),  );}async function retiredMeta(slug: string): Promise<string | null> {  return runInDurableObject(stub(slug), (_instance, state) => state.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", KIT_RETIRED).toArray()[0]?.value ?? null);}describe("the old screenplay tables, held as retired", () => {  it("the kit ships none of them, and a fresh object never has them", async () => {    const slug = "retired-fresh";    // The kit as an object is made from (TABLE DROP 1: the kit may list a retired table until its definition leaves the tree).    expect(served(PERSONAL).tables.map((t) => String(t.id)).filter((id) => (GONE_TABLES as readonly string[]).includes(id))).toEqual([]);    expect(served(PERSONAL).tools.map((t) => String(t.id)).filter((id) => (GONE_TOOLS as readonly string[]).includes(id))).toEqual([]);    const { credential } = await personalObject(slug);    const defs = (await http<Defs>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` })).body;    expect(ids(defs.tables).filter((id) => id.startsWith("screenplay"))).toEqual([]);    expect(ids(defs.tools)).not.toContain("screenplays");    expect(ids(defs.tables)).toEqual(expect.arrayContaining(STORY));    expect(await retiredMeta(slug), "nothing was held, so nothing is retired").toBeNull();  });  it("an object holding them keeps every row and stops serving the definitions; Story's tables are unaffected", async () => {    const slug = "retired-held";    const { credential, owner } = await personalObject(slug);    const auth = { authorization: `Bearer ${credential}` };    const mcp = { authorization: `Bearer ${owner}` };    const storyBefore = (await http<Defs>(slug, "GET", "/v1/definitions", undefined, auth)).body.tables.filter((t) => STORY.includes(String(t.id)));    await heldBefore(slug);    const rowsBefore = await storedRows(slug);    expect(rowsBefore).toHaveLength(3);    const defs = (await http<Defs>(slug, "GET", "/v1/definitions", undefined, auth)).body;    expect(ids(defs.tables).filter((id) => id.startsWith("screenplay")), "no screenplay table is served").toEqual([]);    expect(ids(defs.tools), "the Screenplays tool is not served").not.toContain("screenplays");    expect(defs.tables.filter((t) => STORY.includes(String(t.id))), "Story's tables as they were").toEqual(storyBefore);    expect(storyBefore.map((t) => t).sort((a, b) => String(a.id).localeCompare(String(b.id)))).toEqual(      PERSONAL.tables.filter((t) => STORY.includes(String(t.id))).map(ruled).sort((a, b) => String(a.id).localeCompare(String(b.id))),    );    expect(await storedRows(slug), "every row stays in storage, untouched").toEqual(rowsBefore);    const held = readRetired(await retiredMeta(slug));    expect(Object.keys(held.table).sort(), "the definitions are held as retired").toEqual(ids(OLD_TABLES));    expect(held.table.screenplay).toEqual(SCREENPLAY);    expect(Object.keys(held.tool)).toEqual(["screenplays"]);    const sync = (await http<{ rows: { table: string }[] }>(slug, "GET", "/v1/sync?since=0&limit=10000", undefined, auth)).body;    expect(sync.rows.filter((r) => r.table.startsWith("screenplay")), "no sync carries a retired table's rows").toEqual([]);    const listed = await http<{ result: { tools: { name: string; description?: string }[] } }>(slug, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" }, mcp);    expect(listed.body.result.tools.map((t) => t.name).filter((n) => /screenplay|^(add|update|move|archive|get)_scene$/.test(n)), "nothing is offered over MCP").toEqual([]);    const toolsCall = await http<{ result: { content: { text: string }[] } }>(slug, "POST", "/mcp", { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "list_tools", arguments: {} } }, mcp);    const offered = (JSON.parse(toolsCall.body.result.content[0]!.text) as { tools: { definition: { id: string; tables?: string[] } }[] }).tools.map((t) => t.definition);    expect(offered.map((t) => t.id), "the Screenplays tool is not offered over MCP").not.toContain("screenplays");    expect(offered.flatMap((t) => t.tables ?? []).filter((t) => t.startsWith("screenplay")), "no offered tool names a retired table").toEqual([]);    const create = await http<{ code: string }>(slug, "POST", "/v1/act", { act: "create", args: { table: "screenplay", data: { title: "Another" } } }, auth);    expect(create.status, "no new row is written").not.toBe(200);    // A second keep changes nothing: what was retired stays retired, the rows stay.    await runInDurableObject(stub(slug), (_instance, state) => state.storage.sql.exec("UPDATE meta SET value = 'an-older-kit' WHERE key = ?", KIT_VERSION));    expect((await http<Defs>(slug, "GET", "/v1/definitions", undefined, auth)).body.tables).toEqual(defs.tables);    expect(readRetired(await retiredMeta(slug))).toEqual(held);    expect(await storedRows(slug)).toEqual(rowsBefore);    expect((await http(slug, "GET", "/v1/admin/export?limit=1", undefined, ADMIN)).status).toBe(200);  });  it("retiring is pure: only the named definitions, added to what was held", () => {    const before = { table: { screenplay_place: { id: "screenplay_place", old: true } }, tool: {} };    const out = retiring({ table: [SCREENPLAY, { id: "story_story" }], tool: [SCREENPLAYS, { id: "story" }] }, before);    expect(out.tables).toEqual(["screenplay"]);    expect(out.tools).toEqual(["screenplays"]);    expect(Object.keys(out.retired.table).sort()).toEqual(["screenplay", "screenplay_place"]);    expect(before.table, "what was held is not changed in place").toEqual({ screenplay_place: { id: "screenplay_place", old: true } });  });});