/** * The one-off move of a person's old scripts into Story's new shape * (assets/design/story/CONTRACT.md, "Moving old scripts"): * * - `story_move_old { confirm?, limit? }`: every live scene whose lines are * not yet `story_line` rows (its `lines_sum` does not match its body) has * its body laid over its rows (`lay`): rows made for its lines, a row it * already holds keeps its id; then its body and `lines_sum` are kept from * them. A scene whose rows were made twice (two phones moving it at once) * is laid again the same way, the copies taken out. A line row * naming its speaker by `who` alone is linked to the story's character of * that name. Each story's character counts are taken again. * * Nothing is dropped: a scene whose lines would come back with fewer words * than its body holds, or that holds a line row its body no longer says (a * line has no bin, so taking it out would erase it), is left exactly as it * is and counted (`scenes_left_as_they_are`, `line_rows_not_in_text`). The * only rows taken out are copies of a line the scene keeps. * Running it again changes nothing (a moved scene's sum matches). * * Without `confirm: true` it is a dry run that writes nothing. Either way the * answer is counts only, never a title or a line. A real run moves at most * `limit` scenes (default 25) and says how many are `left`: call it again * until none are. It goes through the normal writes, so phones receive the * rows as they receive any change. Story is sealed: it reads and writes * inside the owner's window for this assistant (request_unlock). */ import { rule } from "../../rules/index.ts"; import type { Data, ToolContext } from "../context.ts"; import { resolveTable } from "./records/table.ts"; import { openStored, windowFor } from "./window.ts"; import { CHARACTER, NOTE, PLACE, SCENE, STORY, patch, recount, say, str, type Row } from "./story.ts"; import { beatOf, kept, lay, lineData, lineRows, type Beat, type Held } from "./story_ink.ts"; const TOOL = "story_move_old"; const PICTURE = "story_picture"; const DEFAULT_LIMIT = 25; /** Every live row of a table, opened. */ async function allRows(ctx: ToolContext, table: string): Promise { const t = resolveTable(ctx, table); const keys = await windowFor(ctx, t, TOOL); const out: Row[] = []; for (const stored of ctx.scan(t.id)) { 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; } /** The words of a text, any script, counted: letters, marks and digits, case folded. */ function words(text: string): Map { const out = new Map(); for (const word of text.normalize("NFC").toLowerCase().match(/[\p{L}\p{M}\p{N}]+/gu) ?? []) out.set(word, (out.get(word) ?? 0) + 1); return out; } /** How many of `before`'s words `after` no longer holds. */ export function wordsLost(before: string, after: string): number { const held = words(after); let lost = 0; for (const [word, count] of words(before)) lost += Math.max(0, count - (held.get(word) ?? 0)); return lost; } interface Plan { /** The lines the scene holds once moved. */ lines: number; /** "moved": nothing to do; "link": only rows to link to characters; "lay": the body laid over the rows; "leave": it would lose words or a row. */ act: "moved" | "link" | "lay" | "leave"; make: number; keep: number; /** Rows taken out that are copies of a line kept. */ copies: number; /** Rows its body no longer says: the scene is left for them. */ stale: number; link: string[]; /** The body the scene would be kept with differs from the one it has (spacing, a speaker's capitals); every word is kept. */ retyped: boolean; } function compose(beats: Beat[], names: string[]): string { return rule("story.beats.compose", { beats, names, enters: say("composer.enters_page") }); } /** What moving one scene does, written or not. */ async function planOf(ctx: ToolContext, scene: Row, cast: Row[], names: string[]): Promise { const rows = await lineRows(ctx, scene.id, TOOL); const held: Held[] = rows.map((row) => ({ id: row.id, ...beatOf(row, cast) })); const body = str(scene, "body"); const unlinked = (row: Row, beat: Beat) => !str(row, "character") && lineData(beat, cast).character !== null; if ((await kept(scene)) && compose(held, names) === body) { const link = rows.filter((row, at) => unlinked(row, held[at]!)).map((row) => row.id); return { lines: rows.length, act: link.length ? "link" : "moved", make: 0, keep: rows.length, copies: 0, stale: 0, link, retyped: false }; } const laid = rule<{ lines: (Beat & { id: string | null })[]; removed: string[] }>("story.beats.reconcile", { held, body, names }); const after = compose(laid.lines.map(({ id: _id, ...beat }) => beat), names); const link = laid.lines.filter((line) => line.id !== null).map((line) => [rows.find((row) => row.id === line.id)!, line] as const).filter(([row, line]) => unlinked(row, line)).map(([row]) => row.id); const said = (beat: Beat) => `${beat.kind}\u0000${beat.text.trim()}`; const keptLines = new Set(laid.lines.map(said)); const copies = laid.removed.filter((id) => keptLines.has(said(held.find((one) => one.id === id)!))).length; const stale = laid.removed.length - copies; return { lines: laid.lines.length, act: wordsLost(body, after) > 0 || stale > 0 ? "leave" : "lay", make: laid.lines.filter((line) => line.id === null).length, keep: laid.lines.filter((line) => line.id !== null).length, copies, stale, link, retyped: after !== body, }; } async function moveOld(ctx: ToolContext, args: Data): Promise { const confirm = args.confirm === true; const limit = typeof args.limit === "number" && args.limit >= 1 ? Math.floor(args.limit) : DEFAULT_LIMIT; const stories = await allRows(ctx, STORY); const scenes = await allRows(ctx, SCENE); const characters = await allRows(ctx, CHARACTER); const places = await allRows(ctx, PLACE); const pictures = await allRows(ctx, PICTURE); const notes = await allRows(ctx, NOTE); const lineCount = [...ctx.scan(resolveTable(ctx, "story_line").id)].filter((row) => resolveTable(ctx, "story_line").binned(row) === null).length; const found = { scripts: stories.length, scenes: scenes.length, lines: 0, line_rows: lineCount, characters: characters.length, places: places.length, notes: notes.length, pictures: pictures.length + characters.filter((row) => str(row, "picture")).length + places.filter((row) => str(row, "picture")).length, }; const work = { scenes_already_moved: 0, scenes_to_move: 0, scenes_to_link: 0, scenes_left_as_they_are: 0, line_rows_not_in_text: 0, lines_to_make: 0, line_rows_kept: 0, copies_to_remove: 0, lines_to_link: 0, bodies_retyped: 0 }; const done = { scenes_moved: 0, scenes_linked: 0, lines_made: 0, copies_removed: 0, lines_linked: 0, characters_made: 0 }; let left = 0; const touched = new Set(); const castOf = new Map(); for (const character of characters) castOf.set(str(character, "story"), [...(castOf.get(str(character, "story")) ?? []), character]); for (const scene of scenes) { const cast = castOf.get(str(scene, "story")) ?? []; const names = cast.map((row) => str(row, "name")).filter((name) => name.trim()); const plan = await planOf(ctx, scene, cast, names); found.lines += plan.lines; if (plan.act === "moved") work.scenes_already_moved += 1; if (plan.act === "leave") { work.scenes_left_as_they_are += 1; work.line_rows_not_in_text += plan.stale; } if (plan.act === "link") work.scenes_to_link += 1; if (plan.act === "moved" || plan.act === "leave") continue; if (plan.act === "lay") { work.scenes_to_move += 1; work.lines_to_make += plan.make; work.line_rows_kept += plan.keep; work.copies_to_remove += plan.copies; if (plan.retyped) work.bodies_retyped += 1; } work.lines_to_link += plan.link.length; if (!confirm) continue; if (done.scenes_moved + done.scenes_linked >= limit) { left += 1; continue; } if (plan.act === "lay") { await lay(ctx, scene.id, TOOL, true); done.scenes_moved += 1; done.lines_made += plan.make; done.copies_removed += plan.copies; } else { for (const id of plan.link) { const row = (await lineRows(ctx, scene.id, TOOL)).find((one) => one.id === id)!; const character = lineData(beatOf(row, cast), cast).character; if (character) await patch(ctx, "story_line", id, { character }); } done.scenes_linked += 1; } done.lines_linked += plan.link.length; touched.add(str(scene, "story")); } for (const story of touched) { const made: string[] = []; if (stories.some((row) => row.id === story)) await recount(ctx, story, made, TOOL); done.characters_made += made.length; } return confirm ? { dry_run: false, found, work, done, left } : { dry_run: true, found, work }; } export const STORY_MOVE_HANDLERS = { story_move_old: moveOld };