218 lines · 15.8 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { wordsLost } from "../src/mcp/tools/story_move.ts";import { answer, personalObject, put } from "./personal.ts";const STORY_OPEN = ["story_story", "story_scene", "story_character", "story_place", "story_note", "story_line", "story_answer", "story_sequence", "story_picture", "story_thing", "story_costume", "story_use", "story_draft", "story_draft_scene"];interface Listed { records: { id: string; created_at?: string; data: Record<string, unknown> }[];}interface Counts { dry_run: boolean; found: Record<string, number>; work: Record<string, number>; done?: Record<string, number>; left?: number;}/** A long invented scene: action, speech with an aside, a note, a transition. */function longBody(n: number): string { return [ `The night market, stall ${n}. Lanterns sway over crates of mangoes.`, `ASHA\n(under her breath)\nNumber ${n}. Still no bus.`, `RAVI\nIt comes when it comes.`, `[[Keep stall ${n} louder than the last.]]`, `A vendor counts coins, slowly, one by one, ${n} times.`, `ASHA\nThen we walk.`, `CUT TO:`, ].join("\n\n");}async function rowsIn(slug: string, owner: string, table: string, where: Record<string, unknown> = {}): Promise<Listed["records"]> { const out: Listed["records"] = []; let page: string | null = null; do { const listed: Listed & { next_page: string | null } = await answer(slug, owner, "list_records", { table, where, limit: 200, ...(page ? { page } : {}) }); out.push(...listed.records); page = listed.next_page; } while (page); return out;}async function linesOf(slug: string, owner: string, scene: string): Promise<{ id: string; text: string; who: unknown; character: unknown }[]> { return (await rowsIn(slug, owner, "story_line", { scene })) .sort((a, b) => Number(a.data.position) - Number(b.data.position)) .map((row) => ({ id: row.id, text: String(row.data.text), who: row.data.who ?? null, character: row.data.character ?? null }));}/** Every leaf of an answer is a count or a yes/no: no title, no line. */function onlyCounts(value: unknown): boolean { if (typeof value === "number" || typeof value === "boolean") return true; if (value && typeof value === "object") return Object.values(value).every(onlyCounts); return false;}async function version(slug: string): Promise<number> { return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_instance, state) => Number(state.storage.sql.exec("SELECT MAX(version) AS v FROM rows").one().v));}/** * Story's rows written past `version`, by table and id, so a failure names what moved. Only Story's * tables: the object's alarm writes on its own time (a window or request expiring, a repeating to-do's * next), and on a loaded box one landed between the two reads of MAX(version) (501, not 500), which is * not the move writing. */async function writtenSince(slug: string, version: number): Promise<string[]> { return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_instance, state) => state.storage.sql.exec("SELECT table_id, id, version FROM rows WHERE version > ? AND table_id LIKE 'story\\_%' ESCAPE '\\' ORDER BY version", version).toArray().map((row) => `${row.table_id} ${row.id} v${row.version}`));}/** * RULE (Story's move, 20 Nov 2026): a person's scripts written before every * line was a row are moved once, through the normal writes: every scene, * line, character, title, order and time is carried, a line already a row * keeps its id, a speaker named only by name is linked, a dry run prints * counts only and writes nothing, and a second run changes nothing. */describe("Story's old scripts moved into the new shape", () => { it("moves a long script, a Telugu and Hindi one, one with a renamed character and an empty one, and then moves nothing", async () => { const slug = "story-move-old"; const { owner } = await personalObject(slug, { open: STORY_OPEN }); const scenes = Array.from({ length: 60 }, (_, at) => ({ ref: `long${at}`, table: "story_scene", data: { story: "@long", position: at + 1, setting: at % 2 ? "EXT." : "INT.", heading: `${at % 2 ? "EXT." : "INT."} NIGHT MARKET - NIGHT`, time: "NIGHT", status: "draft", body: longBody(at + 1) } })); // One old body spaced loosely, as an older writer left it: three blank lines and trailing spaces. scenes[7]!.data.body = "Rain on the tin roof. \n\n\n\nASHA\nListen."; const ids = await put(slug, [ { ref: "long", table: "story_story", data: { title: "The Long Night Market", written_by: "An invented writer", made_at: "2026-03-01", chosen_at: "2026-11-01T10:00:00Z" } }, { ref: "asha", table: "story_character", data: { story: "@long", name: "ASHA", picture: "11111111-1111-4111-8111-111111111111/photos/aaaa.png" } }, { ref: "ravi", table: "story_character", data: { story: "@long", name: "RAVI" } }, ...scenes, { ref: "telugu", table: "story_story", data: { title: "వర్షం", language: "te" } }, { ref: "ravi_te", table: "story_character", data: { story: "@telugu", name: "రవి" } }, { ref: "meera_te", table: "story_character", data: { story: "@telugu", name: "मीरा" } }, { ref: "te1", table: "story_scene", data: { story: "@telugu", position: 1, heading: "INT. ఇల్లు - రాత్రి", status: "draft", body: "వర్షం పడుతోంది.\n\n@రవి\nనువ్వు ఎక్కడ ఉన్నావు?\n\n@मीरा\n(धीरे से)\nमैं यहीं हूँ।\n\nदरवाज़ा खुलता है।" } }, { ref: "te2", table: "story_scene", data: { story: "@telugu", position: 2, heading: "EXT. రోడ్డు - పగలు", status: "draft", body: "రోడ్డు ఖాళీగా ఉంది.\n\n@రవి\nRain again? ఇంకా వర్షమే." } }, // Renamed: lines written one by one as RAVI (rows with `who` and no character), then the character renamed, which rewrote the body. { ref: "renamed", table: "story_story", data: { title: "The Night Bus" } }, { ref: "ravi_k", table: "story_character", data: { story: "@renamed", name: "Ravi Kumar" } }, { ref: "asha_b", table: "story_character", data: { story: "@renamed", name: "ASHA" } }, { ref: "bus", table: "story_scene", data: { story: "@renamed", position: 1, heading: "EXT. BUS STOP - NIGHT", status: "draft", body: "Rain.\n\nASHA\nIs it late?\n\nRAVI KUMAR\nNot yet.", lines_sum: "0".repeat(64) } }, { ref: "l1", table: "story_line", data: { story: "@renamed", scene: "@bus", position: 1, kind: "action", text: "Rain." } }, { ref: "l2", table: "story_line", data: { story: "@renamed", scene: "@bus", position: 2, kind: "dialogue", who: "ASHA", text: "Is it late?" } }, { ref: "l3", table: "story_line", data: { story: "@renamed", scene: "@bus", position: 3, kind: "dialogue", who: "RAVI", text: "Not yet." } }, { ref: "empty", table: "story_story", data: { title: "Untitled" } }, { ref: "blank", table: "story_story", data: { title: "A blank page" } }, { ref: "blank1", table: "story_scene", data: { story: "@blank", position: 1, heading: "INT. ROOM - DAY", status: "draft", body: "" } }, ]); const before = { long: (await answer<{ text: string }>(slug, owner, "story_fountain_write", { story: ids.long })).text, telugu: (await answer<{ text: string }>(slug, owner, "story_fountain_write", { story: ids.telugu })).text, scenes: Object.fromEntries((await rowsIn(slug, owner, "story_scene")).map((row) => [row.id, { created_at: row.created_at, position: row.data.position, heading: row.data.heading, story: row.data.story }])), stories: Object.fromEntries((await rowsIn(slug, owner, "story_story")).map((row) => [row.id, { title: row.data.title, made_at: row.data.made_at ?? null, created_at: row.created_at }])), }; // Reading an old script makes no rows: the core does not move it by itself. expect(await linesOf(slug, owner, ids.long0!)).toEqual([]); const atStart = await version(slug); const dry = await answer<Counts>(slug, owner, "story_move_old", {}); expect(await version(slug), "a dry run writes nothing").toBe(atStart); expect(onlyCounts(dry), "counts only, never a title or a line").toBe(true); expect(dry).toEqual({ dry_run: true, found: { scripts: 5, scenes: 64, lines: 59 * 7 + 2 + 4 + 2 + 3, line_rows: 3, characters: 6, places: 0, notes: 0, pictures: 1 }, // Every long scene is retyped (its CUT TO: written >CUT TO:), and the loosely spaced one; every word kept. work: { scenes_already_moved: 0, scenes_to_move: 64, scenes_to_link: 0, scenes_left_as_they_are: 0, line_rows_not_in_text: 0, lines_to_make: 59 * 7 + 2 + 4 + 2, line_rows_kept: 3, copies_to_remove: 0, lines_to_link: 2, bodies_retyped: 60 }, }); let run = await answer<Counts>(slug, owner, "story_move_old", { confirm: true, limit: 25 }); expect([run.done!.scenes_moved, run.left]).toEqual([25, 39]); while (run.left) run = await answer<Counts>(slug, owner, "story_move_old", { confirm: true, limit: 25 }); // Nothing lost: every scene, every line, every word, every title, order and time. const after = await answer<Counts>(slug, owner, "story_move_old", {}); expect(after.found).toEqual({ ...dry.found, line_rows: dry.found.lines }); expect(after.work).toMatchObject({ scenes_already_moved: 64, scenes_to_move: 0, scenes_to_link: 0, lines_to_make: 0, lines_to_link: 0 }); for (const [story, text] of [[ids.long, before.long], [ids.telugu, before.telugu]] as const) { const now = (await answer<{ text: string }>(slug, owner, "story_fountain_write", { story })).text; expect(wordsLost(text, now), "every word is still in the script").toBe(0); } expect(Object.fromEntries((await rowsIn(slug, owner, "story_scene")).map((row) => [row.id, { created_at: row.created_at, position: row.data.position, heading: row.data.heading, story: row.data.story }]))).toEqual(before.scenes); expect(Object.fromEntries((await rowsIn(slug, owner, "story_story")).map((row) => [row.id, { title: row.data.title, made_at: row.data.made_at ?? null, created_at: row.created_at }]))).toEqual(before.stories); const asha = (await rowsIn(slug, owner, "story_character", { story: ids.long })).find((row) => row.data.name === "ASHA")!; expect(asha.data.picture, "a face's picture is untouched").toBe("11111111-1111-4111-8111-111111111111/photos/aaaa.png"); expect(asha.data.lines).toBe(59 * 2 + 1); // Any language: the caseless speakers are known by the story's names. const te = await linesOf(slug, owner, ids.te1!); expect(te.map((line) => [line.text, line.character])).toEqual([["వర్షం పడుతోంది.", null], ["నువ్వు ఎక్కడ ఉన్నావు?", ids.ravi_te], ["मैं यहीं हूँ।", ids.meera_te], ["दरवाज़ा खुलता है।", null]]); // Renamed: the rows written before keep their ids and are linked to the character as it is named now. const bus = await linesOf(slug, owner, ids.bus!); expect(bus).toEqual([ { id: ids.l1, text: "Rain.", who: null, character: null }, { id: ids.l2, text: "Is it late?", who: "ASHA", character: ids.asha_b }, { id: ids.l3, text: "Not yet.", who: "RAVI KUMAR", character: ids.ravi_k }, ]); // Empty: a story with no scenes and a scene with no lines stand as they were. expect(await linesOf(slug, owner, ids.blank1!)).toEqual([]); expect((await answer<{ text: string }>(slug, owner, "story_fountain_write", { story: ids.empty })).text).toContain("Untitled"); // A second run changes nothing. const settled = await version(slug); expect((await writtenSince(slug, 0)).length, "the check sees Story's rows").toBeGreaterThan(64); const again = await answer<Counts>(slug, owner, "story_move_old", { confirm: true }); expect(again.done).toEqual({ scenes_moved: 0, scenes_linked: 0, lines_made: 0, copies_removed: 0, lines_linked: 0, characters_made: 0 }); expect(await writtenSince(slug, settled), "the second run wrote these rows").toEqual([]); // The story_* tools read and write a moved script by its lines' ids. const long0 = await linesOf(slug, owner, ids.long0!); const split = await answer<{ scene: string }>(slug, owner, "story_scene_split", { id: ids.long0, at: long0[4]!.id }); expect((await linesOf(slug, owner, split.scene)).map((line) => line.id)).toEqual(long0.slice(4).map((line) => line.id)); const draft = (await answer<{ draft: string }>(slug, owner, "story_draft_mark", { story: ids.renamed, name: "First draft" })).draft; const read = await answer<{ scenes: { lines: { id: string }[] }[] }>(slug, owner, "story_draft_read", { draft }); expect(read.scenes[0]!.lines.map((line) => line.id)).toEqual([ids.l1, ids.l2, ids.l3]); }, 300_000); it("lays again a scene whose rows were made twice, the copy taken out, links a speaker named only by name, and leaves a scene holding a line its text no longer says", async () => { const slug = "story-move-twice"; const { owner } = await personalObject(slug, { open: STORY_OPEN }); const ids = await put(slug, [ { ref: "story", table: "story_story", data: { title: "Two phones" } }, { ref: "maya", table: "story_character", data: { story: "@story", name: "MAYA" } }, { ref: "scene", table: "story_scene", data: { story: "@story", position: 1, heading: "INT. KITCHEN - NIGHT", status: "draft", body: "MAYA\nI'm almost done." } }, // Lines written one by one, then the body rewritten whole by an older writer that did not lay it: the second row's line is in no text now. { ref: "stale", table: "story_scene", data: { story: "@story", position: 2, heading: "INT. HALL - NIGHT", status: "draft", body: "The hall is dark.", lines_sum: "0".repeat(64) } }, { ref: "s1", table: "story_line", data: { story: "@story", scene: "@stale", position: 1, kind: "action", text: "The hall is dark." } }, { ref: "s2", table: "story_line", data: { story: "@story", scene: "@stale", position: 2, kind: "action", text: "A phone rings somewhere upstairs." } }, ]); // Moved once on this side: a row with a who and no character, summed. await answer(slug, owner, "story_scene_write", { id: ids.scene, body: "MAYA\nI'm almost done." }); const [first] = await linesOf(slug, owner, ids.scene!); await answer(slug, owner, "update_record", { table: "story_line", id: first!.id, patch: { character: null } }); // And again on another phone before it heard: a second row for the same line. await put(slug, [{ ref: "twin", table: "story_line", data: { story: ids.story, scene: ids.scene, position: 1, kind: "dialogue", who: "MAYA", text: "I'm almost done." } }]); const dry = await answer<Counts>(slug, owner, "story_move_old", {}); expect(dry.work).toMatchObject({ scenes_to_move: 1, line_rows_kept: 1, copies_to_remove: 1, lines_to_make: 0, lines_to_link: 1, scenes_left_as_they_are: 1, line_rows_not_in_text: 1 }); const run = await answer<Counts>(slug, owner, "story_move_old", { confirm: true }); expect(run.done).toMatchObject({ scenes_moved: 1, copies_removed: 1, lines_linked: 1 }); const lines = await linesOf(slug, owner, ids.scene!); expect(lines.map((line) => [line.text, line.character])).toEqual([["I'm almost done.", ids.maya]]); expect((await linesOf(slug, owner, ids.stale!)).map((line) => line.id), "the scene left as it is: both its rows kept").toEqual([ids.s1, ids.s2]); expect((await answer<Counts>(slug, owner, "story_move_old", {})).work).toMatchObject({ scenes_to_move: 0, scenes_left_as_they_are: 1 }); }, 60_000); it("counts a word lost in any script", () => { expect(wordsLost("RAVI\nNot yet.", "RAVI\nNot yet.")).toBe(0); expect(wordsLost("@రవి\nనువ్వు ఎక్కడ?", "రవి\nనువ్వు")).toBe(1); expect(wordsLost("Ravi waits.", "RAVI WAITS.")).toBe(0); });});