Cotton code
516 lines · 28.9 KB · TypeScriptRaw
/** * Cotton Story's rings one to four over MCP (assets/design/story/CONTRACT.md), * the same rules the phone's core keeps (crates/cotton-ffi/src/phone/ * story_ink.rs, story_drafts.rs), run from the WASM rules: * * - every line of a scene is a story_line row whose id survives any rewrite: *   a body written whole is laid over the rows (story.beats.reconcile) and *   the body is kept from them (`lay`, `keep`); * - `story_line_write`, `story_line_remove`: one line at a time; * - `story_scene_split`, `story_scene_merge`: lines move with their ids; * - `story_rename`, `story_merge`: a character or a place, everywhere; * - `story_picture_add`: a picture of a place, a person, a person on a story *   day, a costume, a thing or a scene, from bytes or a url; * - `story_draft_mark`, `story_draft_read`, `story_draft_changes`, *   `story_draft_restore`: drafts frozen, read, compared by identity, gone back to; * - `story_fdx_write`: the story as a Final Draft file. * * Story suggests nothing: these write only what the person or their Claude asks. */import { rule } from "../../rules/index.ts";import { fail, optionalString, requireString, type Data, type Handler, type ToolContext } from "../context.ts";import { restoreFromBin } from "./records/bin.ts";import { resolveTable } from "./records/table.ts";import { deleteRecord } from "./records/write.ts";import { bytesOf, extensionOf, TYPES_BY_EXTENSION } from "./media.ts";import { openStored, windowFor } from "./window.ts";import { CHARACTER, NOTE, PLACE, SCENE, STORY, derived, fileName, make, namesOf, num, patch, recount, rowOf, rowsOf, sameName, say, scenesOf, str, type Row, type SceneDoc } from "./story.ts";const LINE = "story_line";const PICTURE = "story_picture";const THING = "story_thing";const COSTUME = "story_costume";const USE = "story_use";const DRAFT = "story_draft";const DRAFT_SCENE = "story_draft_scene";const KINDS = new Set(["action", "dialogue", "note", "enters"]);// Spelled out, not from story.ts: the two modules import each other, so its constants are not there yet as this one loads.const OF: Record<string, string> = { character: "story_character", place: "story_place", scene: "story_scene", costume: COSTUME, thing: THING };export interface Beat {  kind: string;  who?: string;  aside?: string;  form?: string;  text: string;}export type Held = Beat & { id: string; character?: string | null };export async function sha256(text: string): Promise<string> {  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");}/** A scene's line rows in order. */export async function lineRows(ctx: ToolContext, scene: string, tool: string): Promise<Row[]> {  const t = resolveTable(ctx, LINE);  const keys = await windowFor(ctx, t, tool);  const out: Row[] = [];  for (const stored of ctx.where(t.id, "scene", scene)) {    if (t.binned(stored) !== null) continue;    const { row } = await openStored(ctx, t, keys, stored);    out.push({ ...row.data, id: row.id, created_at: row.created_at });  }  return out.sort((a, b) => num(a, "position") - num(b, "position") || str(a, "created_at").localeCompare(str(b, "created_at")) || a.id.localeCompare(b.id));}export function beatOf(row: Row, cast: Row[]): Beat {  const named = cast.find((one) => one.id === str(row, "character"));  const beat: Beat = { kind: KINDS.has(str(row, "kind")) ? str(row, "kind") : "action", text: str(row, "text") };  const who = named ? str(named, "name") : str(row, "who").trim();  if (who) beat.who = who;  for (const key of ["aside", "form"] as const) if (str(row, key).trim()) beat[key] = str(row, key).trim();  return beat;}export function lineData(beat: Beat, cast: Row[]): Data {  const who = beat.who?.trim() || null;  const character = who ? (cast.find((one) => sameName(str(one, "name"), who))?.id ?? null) : null;  return { kind: beat.kind, text: beat.text, who, character, aside: beat.aside ?? null, form: beat.form ?? null };}/** A patch without the keys the row already holds as they are, nulls for keys it does not hold left out. */function moved(row: Row, values: Data): Data {  const out: Data = {};  for (const [key, value] of Object.entries(values)) {    const held = row[key] ?? null;    if (held !== value) out[key] = value;  }  return out;}/** Does the scene's body still say what its rows say? */export async function kept(scene: Row): Promise<boolean> {  return str(scene, "lines_sum") !== "" && str(scene, "lines_sum") === (await sha256(str(scene, "body")));}/** Write the scene's body from its rows, with its figures. */export async function keep(ctx: ToolContext, sceneId: string, tool: string): Promise<void> {  const scene = await rowOf(ctx, SCENE, sceneId, tool, say("refusal.no_scene"));  const cast = await rowsOf(ctx, CHARACTER, str(scene, "story"), tool);  const names = cast.map((row) => str(row, "name")).filter((name) => name.trim());  const beats = (await lineRows(ctx, sceneId, tool)).map((row) => beatOf(row, cast));  const body = rule<string>("story.beats.compose", { beats, names, enters: say("composer.enters_page") });  await patch(ctx, SCENE, sceneId, { body, lines_sum: await sha256(body), ...derived(str(scene, "heading"), body, names) });}/** Lay the scene's body over its rows: kept and edited lines keep their ids. `force` lays a body its rows are summed to as well (rows made twice, story_move_old). */export async function lay(ctx: ToolContext, sceneId: string, tool: string, force = false): Promise<Row[]> {  const scene = await rowOf(ctx, SCENE, sceneId, tool, say("refusal.no_scene"));  if (!force && (await kept(scene))) return lineRows(ctx, sceneId, tool);  const story = str(scene, "story");  const cast = await rowsOf(ctx, CHARACTER, story, tool);  const rows = await lineRows(ctx, sceneId, tool);  const held: Held[] = rows.map((row) => ({ id: row.id, ...beatOf(row, cast) }));  const names = cast.map((row) => str(row, "name")).filter((name) => name.trim());  const laid = rule<{ lines: (Beat & { id: string | null })[]; removed: string[] }>("story.beats.reconcile", { held, body: str(scene, "body"), names });  for (const gone of laid.removed) deleteRecord(ctx, { table: LINE, id: gone });  for (const [at, line] of laid.lines.entries()) {    const data = { ...lineData(line, cast), position: at + 1 };    const row = line.id ? rows.find((one) => one.id === line.id) : undefined;    if (row) await patch(ctx, LINE, row.id, moved(row, data));    else await make(ctx, LINE, { ...Object.fromEntries(Object.entries(data).filter(([, v]) => v !== null)), story, scene: sceneId });  }  await keep(ctx, sceneId, tool);  return lineRows(ctx, sceneId, tool);}/** The order key between two neighbours (cotton_rules beats::between). */function between(low: number | null, high: number | null): number | null {  if (low !== null && high !== null) return high - low > 1e-6 ? low + (high - low) / 2 : null;  if (low !== null) return low + 1;  if (high !== null) return high - 1;  return 1;}// ── lines ────────────────────────────────────────────────────────────────────async function lineWrite(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_line_write";  const sceneId = requireString(args, "scene", "scene is the scene's id");  const scene = await rowOf(ctx, SCENE, sceneId, tool, say("refusal.no_scene"));  const story = str(scene, "story");  let rows = await lay(ctx, sceneId, tool);  const id = optionalString(args, "id");  const row = id ? (rows.find((one) => one.id === id) ?? fail(say("refusal.no_line_id"))) : null;  const kind = optionalString(args, "kind") ?? (row ? str(row, "kind") : "action");  if (!KINDS.has(kind)) fail(say("refusal.not_a_kind", { kind }));  const values: Data = { kind };  if (typeof args.text === "string") values.text = args.text.trim();  if (args.aside !== undefined) values.aside = typeof args.aside === "string" && args.aside.trim() ? args.aside.trim() : null;  const characterId = optionalString(args, "character");  if (characterId) {    const character = await rowOf(ctx, CHARACTER, characterId, tool, say("refusal.no_character"));    values.character = character.id;    values.who = str(character, "name");  }  const text = typeof values.text === "string" ? values.text : row ? str(row, "text") : "";  if (!text && kind !== "enters") fail(say("refusal.empty_line"));  if ((kind === "dialogue" || kind === "enters") && !(values.who ?? (row ? str(row, "who") : ""))) fail(say("refusal.needs_character"));  let lineId: string;  if (row) {    await patch(ctx, LINE, row.id, moved(row, values));    lineId = row.id;  } else {    const after = optionalString(args, "after");    const keyAt = (at: number): number | null => (rows[at] ? num(rows[at]!, "position") : null);    let at = after === null ? rows.length - 1 : after === "start" ? -1 : rows.findIndex((one) => one.id === after);    if (after !== null && after !== "start" && at < 0) fail(say("refusal.no_line_id"));    let position = between(at >= 0 ? keyAt(at) : null, keyAt(at + 1));    if (position === null) {      for (const [n, one] of rows.entries()) await patch(ctx, LINE, one.id, { position: n + 1 });      rows = await lineRows(ctx, sceneId, tool);      at = after === null ? rows.length - 1 : after === "start" ? -1 : rows.findIndex((one) => one.id === after);      position = between(at >= 0 ? keyAt(at) : null, keyAt(at + 1)) ?? rows.length + 1;    }    lineId = await make(ctx, LINE, { ...Object.fromEntries(Object.entries(values).filter(([, v]) => v !== null)), text, story, scene: sceneId, position });  }  await keep(ctx, sceneId, tool);  await recount(ctx, story, [], tool);  return { line: lineId, lines: (await lineRows(ctx, sceneId, tool)).map((one) => ({ id: one.id, kind: str(one, "kind"), who: one.who ?? null, character: one.character ?? null, aside: one.aside ?? null, text: str(one, "text") })) };}async function lineRemove(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_line_remove";  const sceneId = requireString(args, "scene", "scene is the scene's id");  const id = requireString(args, "id", "id is the line's id");  const rows = await lay(ctx, sceneId, tool);  if (!rows.some((one) => one.id === id)) fail(say("refusal.no_line_id"));  deleteRecord(ctx, { table: LINE, id });  await keep(ctx, sceneId, tool);  const scene = await rowOf(ctx, SCENE, sceneId, tool, say("refusal.no_scene"));  await recount(ctx, str(scene, "story"), [], tool);  return { removed: id };}// ── scenes split and merged ──────────────────────────────────────────────────async function relink(ctx: ToolContext, table: string, story: string, column: string, from: string, to: string, tool: string): Promise<void> {  for (const row of await rowsOf(ctx, table, story, tool)) if (str(row, column) === from) await patch(ctx, table, row.id, { [column]: to });}async function sceneSplit(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_scene_split";  const id = requireString(args, "id", "id is the scene's id");  const at = requireString(args, "at", "at is the id of the line the new scene starts with");  const rows = await lay(ctx, id, tool);  const from = rows.findIndex((one) => one.id === at);  if (from < 0) fail(say("refusal.no_line_id"));  const scene = await rowOf(ctx, SCENE, id, tool, say("refusal.no_scene"));  const story = str(scene, "story");  const ordered = await scenesOf(ctx, story, tool);  const index = ordered.findIndex((one) => one.id === id);  const next = ordered[index + 1];  const position = next ? (num(scene, "position") + num(next, "position")) / 2 : num(scene, "position") + 1;  const data: Data = { story, position, status: "draft", words: 0, pages: 0, minutes: 0, speakers: "" };  for (const key of ["setting", "place", "time", "heading", "day"]) if (scene[key] !== undefined && scene[key] !== null) data[key] = scene[key];  const made = await make(ctx, SCENE, data);  for (const [n, row] of rows.slice(from).entries()) await patch(ctx, LINE, row.id, { scene: made, position: n + 1 });  await keep(ctx, id, tool);  await keep(ctx, made, tool);  await recount(ctx, story, [], tool);  return { scene: made };}async function sceneMerge(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_scene_merge";  const id = requireString(args, "id", "id is the scene that goes");  const into = requireString(args, "into", "into is the scene that stays");  if (id === into) fail("a scene is merged into another scene");  const gone = await rowOf(ctx, SCENE, id, tool, say("refusal.no_scene"));  const stays = await rowOf(ctx, SCENE, into, tool, say("refusal.no_scene"));  const story = str(gone, "story");  if (str(stays, "story") !== story) fail("both scenes are of one story");  const count = (await lay(ctx, into, tool)).length;  for (const [n, row] of (await lay(ctx, id, tool)).entries()) await patch(ctx, LINE, row.id, { scene: into, position: count + n + 1 });  for (const table of [PICTURE, USE, NOTE]) await relink(ctx, table, story, "scene", id, into, tool);  await keep(ctx, into, tool);  deleteRecord(ctx, { table: SCENE, id });  await recount(ctx, story, [], tool);  return { scene: into };}// ── characters and places ────────────────────────────────────────────────────async function rename(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_rename";  const table = requireString(args, "table", "table is story_character or story_place");  const id = requireString(args, "id", "id is the character's or the place's id");  const name = requireString(args, "name", "name is the new name").trim();  if (table !== CHARACTER && table !== PLACE) fail("table is story_character or story_place");  const row = await rowOf(ctx, table, id, tool, say(table === CHARACTER ? "refusal.no_character" : "refusal.no_place"));  const story = str(row, "story");  let scenes = 0;  if (table === CHARACTER) {    // Every scene laid first, so each line already knows its speaker by id.    for (const scene of await scenesOf(ctx, story, tool)) await lay(ctx, scene.id, tool);    await patch(ctx, CHARACTER, id, { name });    for (const scene of await scenesOf(ctx, story, tool)) {      let touched = false;      for (const line of await lineRows(ctx, scene.id, tool)) {        if (str(line, "character") === id) {          await patch(ctx, LINE, line.id, { who: name });          touched = true;        }      }      if (touched) {        scenes += 1;        await keep(ctx, scene.id, tool);      }    }    await recount(ctx, story, [], tool);  } else {    await patch(ctx, PLACE, id, { name });    const names = await namesOf(ctx, story, tool);    for (const scene of await scenesOf(ctx, story, tool)) {      if (str(scene, "place") !== id) continue;      const heading = rule<string>("story.heading.compose", { setting: str(scene, "setting") || null, place: name, time: str(scene, "time") || null });      await patch(ctx, SCENE, scene.id, { heading, ...derived(heading, str(scene, "body"), names) });      scenes += 1;    }  }  return { scenes };}async function merge(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_merge";  const table = requireString(args, "table", "table is story_character or story_place");  const id = requireString(args, "id", "id is the row that goes");  const into = requireString(args, "into", "into is the row that stays");  if (table !== CHARACTER && table !== PLACE) fail("table is story_character or story_place");  if (id === into) fail("a row is merged into another row");  const missing = say(table === CHARACTER ? "refusal.no_character" : "refusal.no_place");  const gone = await rowOf(ctx, table, id, tool, missing);  const stays = await rowOf(ctx, table, into, tool, missing);  const story = str(gone, "story");  if (str(stays, "story") !== story) fail("both are of one story");  let scenes = 0;  if (table === CHARACTER) {    for (const scene of await scenesOf(ctx, story, tool)) {      let touched = false;      for (const line of await lay(ctx, scene.id, tool)) {        if (str(line, "character") === id || (!str(line, "character") && sameName(str(line, "who"), str(gone, "name")))) {          await patch(ctx, LINE, line.id, { character: into, who: str(stays, "name") });          touched = true;        }      }      if (touched) {        scenes += 1;        await keep(ctx, scene.id, tool);      }    }    for (const t of [PICTURE, COSTUME, USE]) await relink(ctx, t, story, "character", id, into, tool);    deleteRecord(ctx, { table: CHARACTER, id });    await recount(ctx, story, [], tool);  } else {    const names = await namesOf(ctx, story, tool);    for (const scene of await scenesOf(ctx, story, tool)) {      if (str(scene, "place") !== id) continue;      const heading = rule<string>("story.heading.compose", { setting: str(scene, "setting") || null, place: str(stays, "name"), time: str(scene, "time") || null });      await patch(ctx, SCENE, scene.id, { place: into, heading, ...derived(heading, str(scene, "body"), names) });      scenes += 1;    }    await relink(ctx, PICTURE, story, "place", id, into, tool);    deleteRecord(ctx, { table: PLACE, id });  }  return { scenes, into };}// ── pictures ─────────────────────────────────────────────────────────────────async function pictureAdd(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_picture_add";  const of = (args.of && typeof args.of === "object" ? args.of : {}) as Data;  const data: Data = {};  let story: string | null = null;  for (const [key, table] of Object.entries(OF)) {    const id = optionalString(of, key);    if (!id) continue;    const row = await rowOf(ctx, table, id, tool, `there is no ${table} ${id}`);    if (story !== null && story !== str(row, "story")) fail("a picture is of rows of one story");    story = str(row, "story");    data[key] = id;  }  if (story === null) fail("of names what the picture is of: { character | place | scene | costume | thing: id }");  if (typeof args.day === "number") data.day = args.day;  const caption = optionalString(args, "caption");  if (caption?.trim()) data.caption = caption.trim();  const name = optionalString(args, "name") ?? "picture.jpg";  const { bytes, type: came } = await bytesOf(args);  if (!bytes.byteLength) fail("the picture is empty");  const type = optionalString(args, "content_type") ?? came ?? TYPES_BY_EXTENSION[extensionOf(name) ?? ""] ?? "image/jpeg";  if (!type.startsWith("image/")) fail(`that is ${type}, not a picture`);  const sha = [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join("");  const extension = Object.entries(TYPES_BY_EXTENSION).find(([, v]) => v === type)?.[0] ?? extensionOf(name) ?? "jpg";  const key = `${ctx.database.id}/photos/${sha}.${extension}`;  await ctx.media.store(ctx.media.at(key), bytes, type);  const siblings = (await rowsOf(ctx, PICTURE, story, tool)).filter((row) => Object.keys(OF).every((k) => (row[k] ?? null) === (data[k] ?? null)) && (row.day ?? null) === (data.day ?? null));  const last = siblings.reduce<number | null>((max, row) => (max === null || num(row, "position") > max ? num(row, "position") : max), null);  const id = await make(ctx, PICTURE, { ...data, story, picture: key, position: between(last, null) ?? 1 });  return { picture: { id, picture: key, ...data } };}// ── drafts ───────────────────────────────────────────────────────────────────async function draftMark(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_draft_mark";  const story = requireString(args, "story", "story is the story's id (list_records { table: \"story_story\" })");  const name = requireString(args, "name", "name is the draft's name, like Second draft").trim();  await rowOf(ctx, STORY, story, tool, say("refusal.no_story"));  const scenes = await scenesOf(ctx, story, tool);  for (const scene of scenes) await lay(ctx, scene.id, tool);  const cast = await rowsOf(ctx, CHARACTER, story, tool);  const places = await rowsOf(ctx, PLACE, story, tool);  const named = (list: Row[]): string => JSON.stringify(list.map((row) => ({ id: row.id, name: str(row, "name") })));  const now = await scenesOf(ctx, story, tool);  const pages = now.reduce((sum, scene) => sum + num(scene, "pages"), 0);  const draft = await make(ctx, DRAFT, { story, name, made_at: new Date().toISOString(), scenes: now.length, pages: Math.round(pages * 10) / 10, cast: named(cast), places: named(places) });  for (const [at, scene] of now.entries()) {    const lines = (await lineRows(ctx, scene.id, tool)).map((row) => ({ id: row.id, ...beatOf(row, cast), character: row.character ?? null }));    const data: Data = { draft, story, scene: scene.id, position: at + 1, lines: JSON.stringify(lines) };    for (const key of ["heading", "setting", "place", "time", "day", "summary", "body"]) if (scene[key] !== undefined && scene[key] !== null) data[key] = scene[key];    await make(ctx, DRAFT_SCENE, data);  }  return { draft, scenes: now.length };}async function draftOf(ctx: ToolContext, args: Data, tool: string): Promise<{ draft: Row; scenes: Row[] }> {  const id = requireString(args, "draft", "draft is the draft's id (list_records { table: \"story_draft\" })");  const draft = await rowOf(ctx, DRAFT, id, tool, say("refusal.no_draft"));  const scenes = (await rowsOf(ctx, DRAFT_SCENE, str(draft, "story"), tool)).filter((row) => str(row, "draft") === id).sort((a, b) => num(a, "position") - num(b, "position"));  return { draft, scenes };}function linesIn(row: Row): Held[] {  try {    const parsed: unknown = JSON.parse(str(row, "lines") || "[]");    return Array.isArray(parsed) ? (parsed as Held[]) : [];  } catch {    return [];  }}async function draftRead(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_draft_read";  const { draft, scenes } = await draftOf(ctx, args, tool);  const story = await rowOf(ctx, STORY, str(draft, "story"), tool, say("refusal.no_story"));  const title: [string, string][] = [["Title", str(story, "title")]];  if (str(story, "written_by").trim()) title.push(["Credit", say("script.title_page_by")], ["Author", str(story, "written_by")]);  title.push(["Draft", str(draft, "name")], ["Draft date", str(draft, "made_at").slice(0, 10)]);  const docs: SceneDoc[] = scenes.map((scene) => ({ heading: str(scene, "heading"), ...(str(scene, "summary").trim() ? { summary: str(scene, "summary") } : {}), body: str(scene, "body") }));  return {    draft: { id: draft.id, name: str(draft, "name"), made_at: str(draft, "made_at"), scenes: num(draft, "scenes"), pages: num(draft, "pages") },    scenes: scenes.map((scene, at) => ({ scene: str(scene, "scene"), number: at + 1, heading: str(scene, "heading"), summary: scene.summary ?? null, day: scene.day ?? null, lines: linesIn(scene) })),    text: rule<string>("story.fountain.write", { title, scenes: docs }),    name: fileName(`${str(story, "title")} - ${str(draft, "name")}`),  };}async function draftChanges(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_draft_changes";  const { draft, scenes } = await draftOf(ctx, args, tool);  const story = str(draft, "story");  const then = scenes.map((scene) => ({ scene: str(scene, "scene"), heading: str(scene, "heading"), summary: str(scene, "summary").trim() ? str(scene, "summary") : null, lines: linesIn(scene) }));  const cast = await rowsOf(ctx, CHARACTER, story, tool);  const names = cast.map((row) => str(row, "name")).filter((name) => name.trim());  const now = [];  for (const scene of await scenesOf(ctx, story, tool)) {    const held: Held[] = (await lineRows(ctx, scene.id, tool)).map((row) => ({ id: row.id, ...beatOf(row, cast) }));    const laid = rule<{ lines: (Beat & { id: string | null })[] }>("story.beats.reconcile", { held, body: str(scene, "body"), names });    now.push({ scene: scene.id, heading: str(scene, "heading"), summary: str(scene, "summary").trim() ? str(scene, "summary") : null, lines: laid.lines.map((line, at) => ({ ...line, id: line.id ?? `new:${at}` })) });  }  return { draft: { id: draft.id, name: str(draft, "name"), made_at: str(draft, "made_at") }, ...rule<Data>("story.drafts.changes", { then, now }) };}/** A row by id, brought back from Deleted when it went there; null when it is gone for good. */function liveOrBack(ctx: ToolContext, table: string, id: string): boolean {  const t = resolveTable(ctx, table);  const held = ctx.get(t.id, id);  if (!held) return false;  if (t.binned(held) !== null) restoreFromBin(ctx, { table, id });  return true;}async function draftRestore(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_draft_restore";  const { draft, scenes } = await draftOf(ctx, args, tool);  const story = str(draft, "story");  const cast = await rowsOf(ctx, CHARACTER, story, tool);  const keptScenes: string[] = [];  // Every line the draft names brought back from Deleted first, then read once.  const named = new Set<string>();  for (const then of scenes) for (const line of linesIn(then)) if (line.id && liveOrBack(ctx, LINE, line.id)) named.add(line.id);  const lines = new Map((await rowsOf(ctx, LINE, story, tool)).map((row) => [row.id, row]));  for (const [at, then] of scenes.entries()) {    const values: Data = { position: at + 1 };    for (const key of ["heading", "setting", "place", "time", "day", "summary"]) values[key] = then[key] ?? null;    if (typeof values.place === "string" && !liveOrBack(ctx, PLACE, values.place)) values.place = null;    let sceneId = str(then, "scene");    if (liveOrBack(ctx, SCENE, sceneId)) {      const row = await rowOf(ctx, SCENE, sceneId, tool, say("refusal.no_scene"));      await patch(ctx, SCENE, sceneId, moved(row, values));    } else {      sceneId = await make(ctx, SCENE, { ...Object.fromEntries(Object.entries(values).filter(([, v]) => v !== null)), story, status: "draft" });    }    const wanted: string[] = [];    for (const [n, line] of linesIn(then).entries()) {      const data: Data = { ...lineData(line, cast), scene: sceneId, position: n + 1 };      if (typeof line.character === "string" && cast.some((one) => one.id === line.character)) data.character = line.character;      if (line.id && named.has(line.id)) {        const row = lines.get(line.id);        if (row) {          await patch(ctx, LINE, row.id, moved(row, data));          wanted.push(row.id);          continue;        }      }      wanted.push(await make(ctx, LINE, { ...Object.fromEntries(Object.entries(data).filter(([, v]) => v !== null)), story }));    }    for (const row of await lineRows(ctx, sceneId, tool)) if (!wanted.includes(row.id)) deleteRecord(ctx, { table: LINE, id: row.id });    await keep(ctx, sceneId, tool);    keptScenes.push(sceneId);  }  for (const scene of await scenesOf(ctx, story, tool)) if (!keptScenes.includes(scene.id)) deleteRecord(ctx, { table: SCENE, id: scene.id });  await recount(ctx, story, [], tool);  return { scenes: keptScenes.length, draft: { id: draft.id, name: str(draft, "name") } };}// ── Final Draft out ──────────────────────────────────────────────────────────async function fdxWrite(ctx: ToolContext, args: Data): Promise<Data> {  const tool = "story_fdx_write";  const id = requireString(args, "story", "story is the story's id (list_records { table: \"story_story\" })");  const story = await rowOf(ctx, STORY, id, tool, say("refusal.no_story"));  const title: [string, string][] = [["Title", str(story, "title")]];  if (str(story, "written_by").trim()) title.push(["Credit", say("script.title_page_by")], ["Author", str(story, "written_by")]);  if (str(story, "made_at").trim()) title.push(["Draft date", str(story, "made_at")]);  const scenes: SceneDoc[] = (await scenesOf(ctx, id, tool)).map((scene) => ({ heading: str(scene, "heading"), ...(str(scene, "summary").trim() ? { summary: str(scene, "summary") } : {}), body: str(scene, "body") }));  const names = await namesOf(ctx, id, tool);  return { text: rule<string>("story.fdx.write", { title, scenes, names }), name: fileName(str(story, "title")).replace(/\.fountain$/, ".fdx") };}export const STORY_INK_HANDLERS: Record<string, Handler> = {  story_line_write: lineWrite,  story_line_remove: lineRemove,  story_scene_split: sceneSplit,  story_scene_merge: sceneMerge,  story_rename: rename,  story_merge: merge,  story_picture_add: pictureAdd,  story_draft_mark: draftMark,  story_draft_read: draftRead,  story_draft_changes: draftChanges,  story_draft_restore: draftRestore,  story_fdx_write: fdxWrite,};