commit b5172fe49b1f4bf2d1bc78f3d88720a077795628
parent 64ae1b6831703d90d0241226b337248f8b7d7d1a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 15:33:48 -0500
reads.mjs: one model of a video's reads -- what each SAYS, where it is kept, the take that plays, its state
Every read of a project in cut order: a post's script read alone, each piece of a thread read (his
words, a parent, the quoted or a linked post), its screen lines, a recorded read, a card's narration.
The states are defined once: recorded, none, stale (words -- the script, the lexicon, a thread
piece against the read a press makes now via postThreadRead upToDate and its parts, a card with no
reading at its key; settings -- cast.mjs tuningStale's own rows, what `cast stale` and the bench
count; voice -- voiceDrift), unpicked (a newer take would be fresh if picked), fresh. Find over the
spoken text only: case, whole word, a phrase across spaces, regex characters literal.
structuralEdit takes snapshotEvery (a write that is always its own undo point).
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
4 files changed, 503 insertions(+), 2 deletions(-)
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -5247,7 +5247,9 @@ export async function redoStructural(dir, { token = null } = {}) {
* @param {string | null} token
* @param {(m: Record<string, any>) => T} mutate
*/
-export async function structuralEdit(dir, op, token, mutate) {
+export async function structuralEdit(dir, op, token, mutate, { snapshotEvery = undefined } = {}) {
if (!/^[a-z0-9-]{1,40}$/.test(op)) throw new Error(`not an op name: ${op}`);
- return structural(dir, op, token, mutate);
+ // `snapshotEvery: 0`: an undo point of its own every time (a replace over a video's reads is one step to take back,
+ // never folded into the one before it).
+ return structural(dir, op, token, mutate, snapshotEvery === undefined ? {} : { snapshotEvery });
}
diff --git a/umtool/lib/report/reads.fixtures.mjs b/umtool/lib/report/reads.fixtures.mjs
@@ -0,0 +1,76 @@
+// THE READS FIXTURE (lane reads-find): one project in a temp dir with every kind of read -- a post's script read alone,
+// a thread read with a screen (its parent, the quoted post, his words, two screen lines), a recorded read, and a
+// narrated card with a reading kept beside the build -- and a cast whose character reads the single post. Invented
+// people and places; the thread item is the reading pin's (post-reading-pin.fixtures.mjs), so the drawn hashes apply.
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { draftScript } from "umtool-report-to-video/post-narration";
+import { narrationsOf } from "umtool-report-to-video/narration";
+import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
+import { VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs";
+import { threadItem } from "../../report-to-video/post-reading-pin.fixtures.mjs";
+
+export const FERRY_TEXT = "The ferry runs at noon from the north pier.\n\nBring a coat for the crossing to the north shore.";
+export const CARD_TEXT = "Six months later, the north pier reopened.";
+export const LIVELY = { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 };
+
+export const wavOf = async (file, seconds = 0.6) => {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...VOICE_B, seconds }), { before: 0.1, after: 0.1 })));
+};
+
+/** The cast: the single post's author reads as Ferry Teller (orpheus:tara), with `tuning` when given. */
+export const castDoc = (tuning = null) => ({
+ format: "umtool-cast", version: 2,
+ characters: [{ id: "ferry", name: "Ferry Teller", handles: ["invented_ferry"], synthetic: { voice: "orpheus:tara", ...(tuning ? { tuning } : {}) } }],
+});
+
+export function singlePost() {
+ const script = draftScript(FERRY_TEXT).script;
+ return {
+ type: "post", id: "p-1", post: "ferry-x/1", platform: "x", author: "Ferry Teller", handle: "invented_ferry", date: "2026-10-30T10:00:00.000Z", text: FERRY_TEXT,
+ narration: { script, pick: 0, takes: [{ file: "narration/posts/1/take-1.orpheus-tara.wav", engine: "orpheus", voice: "tara", seconds: 6.2, script, tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }, reading: 0 }] },
+ };
+}
+
+/** The reading pin's thread item as p-2, its parent one paragraph long (so its read says it whole, as a press would). */
+export function threadPost() {
+ const e = threadItem();
+ return { ...e, id: "p-2", parents: e.parents.map((x) => ({ ...x, text: x.text.split("\n\n")[0] })) };
+}
+
+export function recordedPost() {
+ return {
+ type: "post", id: "p-3", post: "ferry-x/3", platform: "x", author: "Pier Watch", handle: "invented_pier", date: "2026-10-30T11:00:00.000Z", text: "The north pier is closed today.",
+ narration: { script: "The north pier is closed today.", pick: 0, takes: [{ file: "narration/posts/3/take-1.recorded-operator.wav", engine: "recorded", voice: "operator", seconds: 2.4, script: "The north pier is closed today.", source: { kind: "recorded", voice: "operator" } }] },
+ };
+}
+
+export const card = () => ({ type: "card", id: "c-1", seconds: "auto", heading: "Later", narration: { text: CARD_TEXT, engine: "orpheus", voice: "leo" } });
+
+/**
+ * The project: `<root>/<name>/p`, the cast beside it in `<root>/<name>/.umtool/cast.json`, the takes' files on disk
+ * and the card's reading kept in out/narration/. Returns `{ id, dir, root }`.
+ */
+export async function readsProject(root, name, { cast = castDoc(), timeline = null } = {}) {
+ const top = path.join(root, name);
+ const dir = path.join(top, "p");
+ await mkdir(path.join(dir, "narration"), { recursive: true });
+ await mkdir(path.join(top, ".umtool"), { recursive: true });
+ await writeFile(path.join(top, ".umtool", "cast.json"), JSON.stringify(cast, null, 1));
+ const tl = timeline ?? [singlePost(), threadPost(), recordedPost(), card()];
+ const manifest = { schemaVersion: 1, slug: name, title: name, render: { width: 1920, height: 1080, fps: 30, postNarration: { engine: "orpheus", voice: "zac" } }, timeline: tl };
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest, null, 2));
+ for (const e of tl) for (const t of e?.narration?.takes ?? []) await wavOf(path.join(dir, ...t.file.split("/")));
+ for (const n of narrationsOf(manifest)) await keepCardReading(dir, n);
+ return { id: name, dir, root: top };
+}
+
+/** A card's reading kept beside the build (narration-store.mjs's shape): its record and its sound. */
+export async function keepCardReading(dir, n, { createdAt = "2026-11-01T10:00:00.000Z" } = {}) {
+ const store = path.join(dir, "out", "narration");
+ await wavOf(path.join(store, `${n.key}.wav`), 1.2);
+ await writeFile(path.join(store, `${n.key}.json`), JSON.stringify({ id: n.id, key: n.key, text: n.text, engine: n.engine, voice: n.voice, speed: 1, seconds: 1.4, createdAt, ...(n.tuning ? { askedTuning: n.tuning } : {}), ...(n.reading ? { askedReading: n.reading } : {}) }));
+}
+
+export const readManifestOf = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
diff --git a/umtool/lib/report/reads.mjs b/umtool/lib/report/reads.mjs
@@ -0,0 +1,313 @@
+// A VIDEO's READS (lane reads-find, S4 of plans/orpheus-retune.md; umtool/docs/knobs.md, "The reads of a video"):
+// every line a voice reads in a project -- a post's script, a piece of a thread read, a screen line, a card's
+// narration -- with the words it SAYS (never what is shown: operator ruling 3), where those words are kept, the take
+// that plays, and whether that take still says them as a plain press would make them now. ONE model: `umtool reads`,
+// the Reads page and the re-read queue (readsQueue.mjs) read it; the stale rule is defined here and nowhere else.
+//
+// A READ, `{ id, kind, item, role, n, character, voice, spoken, said, storedAt, shownSpoken, editable, why, take,
+// newTake, state, because, legacy }`:
+// id "<item>" for a single read or a card, "<item>/<role>" for a piece of a thread read
+// kind post (a post's script, read alone) | thread (a piece of a thread read: his own words, a parent, the
+// quoted post, a linked post) | screen (a screen's line, a piece of the thread read) | card
+// spoken what the voice says, AS WRITTEN (what Find searches and Replace edits): the script, the screen line's
+// "said as" (else the line as shown), a context piece's words as shown, the card's narration
+// said the same after the redaction, the slurs and the pronunciation lexicon (what the editor is asked)
+// storedAt where `spoken` is kept; `shownSpoken`: it is still the SHOWN text (a replace creates its override)
+// editable whether These reads can rewrite it (a parent, the quoted or a linked post has no spoken-only words:
+// "said as shown: only Everywhere changes this"; a recorded read is yours)
+// take the take that plays: `{ index, file, key, reading, tuning, tunedBy: "line" | "character" | null }`
+// newTake (state unpicked) the newer take that would be fresh if picked
+//
+// THE STATES:
+// recorded the take that plays is recorded, converted or derived (or the piece comes from a take): never stale
+// none no synthesized take reads it yet
+// stale the take that plays is synthesized and, for any of `because`:
+// words it says other words than the spoken text now (a single read: its script, or the lexicon --
+// post-say.mjs staleLexicon; a thread piece: its parts against the read a press makes now,
+// postThreadRead.mjs upToDate first; a card: no reading kept at its key now)
+// settings made with other settings than its character's tuning now (cast.mjs tuningStale, the very
+// rows `umtool cast stale` and the bench's "made with other settings" count)
+// voice made in another voice than it reads in now (cast.mjs voiceDrift, the Voices page's drift)
+// unpicked stale, and a newer synthesized take of the item would be fresh if picked (a re-read waits for a Pick)
+// fresh none of these
+//
+// Plain ESM: the CLI runs it under bare node.
+import { readManifest } from "../projects/report.mjs";
+import { REPORTS_ROOT } from "../projects/core.mjs";
+import { LEGACY_EDIT_TEXT, legacyReadOf, shownDraftOf } from "umtool-report-to-video/post-item";
+import { pickedTake, takeSourceOf } from "umtool-report-to-video/post-narration";
+import { parseScreenRole, saidAsOf, screenLineSaid, screensOf } from "umtool-report-to-video/post-screens";
+import { spokenRead } from "umtool-report-to-video/post-redact";
+import { staleLexicon } from "umtool-report-to-video/post-say";
+import { narrationsOf } from "umtool-report-to-video/narration";
+
+export const READ_KINDS = Object.freeze({ post: "post script", thread: "thread part", screen: "screen line", card: "card narration" });
+export const READ_STATES = Object.freeze(["fresh", "stale", "unpicked", "none", "recorded"]);
+/** Why a context piece cannot be rewritten by These reads (said in the UI where it applies). */
+export const SAID_AS_SHOWN = "said as shown: only Everywhere changes this";
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const str = (v) => (typeof v === "string" ? v : "");
+const norm = (t) => str(t).replace(/\s+/g, " ").trim();
+
+/** A read's id: the item's id, and the piece's role for a piece of a thread read. */
+export const readIdOf = (item, role = null) => (role ? `${item}/${role}` : item);
+
+/** A thread take's `read` record as threadTake's options (as the read that plays was asked: castProject.mjs threadArgvOf). */
+export function threadOptsOfRead(read, takes = []) {
+ const r = isObj(read) ? read : {};
+ const byFile = (f) => {
+ const at = (Array.isArray(takes) ? takes : []).findIndex((t) => t?.file === f);
+ return at >= 0 ? at + 1 : null;
+ };
+ const lineTakes = {};
+ for (const [role, x] of Object.entries(isObj(r.lineTakes) ? r.lineTakes : {})) {
+ const n = typeof x?.file === "string" ? byFile(x.file) : null;
+ if (n) lineTakes[role] = n;
+ }
+ return {
+ parents: r.parents ?? "0", skip: Array.isArray(r.skip) ? r.skip : [], quoted: r.quoted !== false, linked: r.linked !== false, readSeen: r.seen === true,
+ overrides: isObj(r.voiceFor) ? r.voiceFor : {}, voice: typeof r.voice === "string" ? r.voice : null, speed: typeof r.speed === "number" ? r.speed : null,
+ postTake: isObj(r.postTake) && typeof r.postTake.file === "string" ? byFile(r.postTake.file) : null,
+ screens: r.screens !== false, lineTakes, inherit: isObj(r.tuned) ? r.tuned : {},
+ };
+}
+
+/** Whose a take's tuning is: the line's own, its character's, or not said. */
+const tunedByOf = (t) => (t?.tuningAsked === true ? "line" : t?.tuningAsked === "preset" ? "character" : null);
+
+/** A take as a read row carries it. */
+const takeView = (t, extra = {}) => (t ? { index: Number.isInteger(t.index) ? t.index : null, file: t.file ?? null, key: null, reading: Number.isInteger(t.reading) ? t.reading : 0, tuning: isObj(t.tuning) ? t.tuning : null, tunedBy: tunedByOf(t), ...extra } : null);
+
+/**
+ * THE CONTEXT a project's reads are judged in, loaded once: the manifest, the redaction (its lexicon), the lexicon,
+ * the character layers (characterLayers.mjs), the voices view's inputs (castCli.mjs projectView: the same layers
+ * `umtool cast stale` reads) and each card's readings. `red` / `lexicon` stand in for the project's own (a preview).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ reportsRoot?: string, manifest?: any, red?: any, lexicon?: any[] }} [o]
+ */
+export async function readsContext(project, { reportsRoot = REPORTS_ROOT, manifest = undefined, red = undefined, lexicon = undefined } = {}) {
+ const m = manifest ?? (await readManifest(project.dir));
+ if (!m) throw new Error(`${project.id} has no manifest`);
+ const { projectRedaction } = await import("./postRedaction.mjs");
+ const { readLexicon } = await import("./postSay.mjs");
+ const lex = lexicon ?? (await readLexicon(project.dir));
+ const r = red !== undefined ? red : await projectRedaction(project.dir, m);
+ const { readLayers } = await import("./characterLayers.mjs");
+ const { characterNames } = await import("./postThreadRead.mjs");
+ const L = await readLayers(project.dir).catch(() => null);
+ const { projectView } = await import("./castCli.mjs");
+ const v = await projectView(project, { reportsRoot });
+ const { orpheusTakesSetting } = await import("./characterTuning.mjs");
+ const settingTakes = await orpheusTakesSetting();
+ const { allCardReadings } = await import("./cardNarrationCli.mjs");
+ const cards = await allCardReadings(project.dir);
+ return { project, manifest: m, red: r, lexicon: lex, L, names: L ? characterNames(L) : {}, layers: { map: v.map, cast: v.castRead.cast, project: v.ownRead.doc, speakers: v.speakers }, settingTakes, cards, reportsRoot };
+}
+
+/** The voices view of a manifest (castProject.mjs projectCharacters: its tuningStale and its drift), and a resolver. */
+async function voicesOf(ctx, m) {
+ const { projectCharacters, resolverFor } = await import("./castProject.mjs");
+ const view = projectCharacters(m, { map: ctx.layers.map, cast: ctx.layers.cast, project: ctx.layers.project, speakers: ctx.layers.speakers, settingTakes: ctx.settingTakes });
+ const resolve = resolverFor({ map: ctx.layers.map, cast: ctx.layers.cast, project: ctx.layers.project, render: m.render ?? {} });
+ const names = new Map();
+ for (const c of view.characters ?? []) if (c.character?.id) names.set(c.character.id, c.character.name ?? c.name);
+ for (const c of view.own ?? []) if (c?.id) names.set(c.id, c.name ?? c.id);
+ const key = (id, role) => `${id}\u0000${role}`;
+ return {
+ view, resolve, names,
+ settings: new Set((view.tuningStale ?? []).map((r) => key(r.id, r.role))),
+ voice: new Set((view.characters ?? []).flatMap((c) => c.drift ?? []).map((d) => key(d.id, d.role))),
+ key,
+ };
+}
+
+const characterRow = (vs, id) => (id ? { id, name: vs.names.get(id) ?? id } : null);
+
+/** The rows of ONE post item, as the manifest `m` has it (its pick). */
+async function postRows(ctx, m, vs, e, n) {
+ const n0 = e.narration;
+ if (!isObj(n0) || n0.off === true) return [];
+ const take = pickedTake(e);
+ const base = { item: e.id, n, legacy: !!take && legacyReadOf(e) };
+ const slur = ctx.red?.slurs?.voice === "beep" ? { voice: "skip" } : {};
+ if (!take) {
+ const spoken = str(n0.script) || shownDraftOf(e);
+ if (!norm(spoken)) return [];
+ const want = vs.resolve(e, "post", e.handle ?? null, null);
+ return [{ ...base, id: readIdOf(e.id), kind: "post", role: null, character: characterRow(vs, want?.character), voice: want ? `${want.engine}:${want.voice}` : null, spoken, said: spokenRead(spoken, e, ctx.red, slur).text, storedAt: str(n0.script) ? "narration.script" : null, shownSpoken: !str(n0.script), editable: true, why: null, take: null, newTake: null, state: "none", because: [] }];
+ }
+ if (take.read?.kind === "thread") return threadRows(ctx, m, vs, e, take, base);
+ const src = takeSourceOf(take).kind;
+ const spoken = str(n0.script) || str(take.script);
+ const want = vs.resolve(e, "post", e.handle ?? null, take);
+ const row = {
+ ...base, id: readIdOf(e.id), kind: "post", role: null, character: characterRow(vs, want?.character),
+ voice: `${take.engine ?? "?"}:${take.voice ?? "?"}`, spoken, said: spokenRead(spoken, e, ctx.red, slur).text,
+ storedAt: str(n0.script) ? "narration.script" : null, shownSpoken: !str(n0.script), editable: src === "tts", why: src === "tts" ? null : "a recorded read is yours: record it again",
+ take: takeView(take), newTake: null,
+ };
+ if (src !== "tts") return [{ ...row, state: "recorded", because: [] }];
+ const because = [];
+ if (norm(take.script) !== norm(spoken)) because.push("words");
+ else if (staleLexicon(e, take, ctx.lexicon).length) because.push("lexicon");
+ if (vs.settings.has(vs.key(e.id, "post"))) because.push("settings");
+ if (vs.voice.has(vs.key(e.id, "post"))) because.push("voice");
+ return [{ ...row, state: because.length ? "stale" : "fresh", because }];
+}
+
+/** The pieces of a picked THREAD read, each a row: judged against the read a press would make now. */
+async function threadRows(ctx, m, vs, e, take, base) {
+ const { threadTake } = await import("./postThreadRead.mjs");
+ const takes = e.narration?.takes ?? [];
+ let dry;
+ try {
+ dry = await threadTake(ctx.project, e, {
+ manifest: m, red: ctx.red, map: ctx.L?.map ?? {}, cast: ctx.L?.castMap ?? {}, item: ctx.L?.itemOf?.(e) ?? null, names: ctx.names, dryRun: true,
+ ...threadOptsOfRead(take.read, takes),
+ });
+ } catch (err) {
+ // The read as it was asked cannot be made now (a take it named is gone, a line changed under a recording): one row
+ // that says so -- stale, re-made from the bench.
+ return [{ ...base, id: readIdOf(e.id, "post"), kind: "thread", role: "post", character: null, voice: str(take.voice) || null, spoken: str(e.narration?.script), said: null, storedAt: "narration.script", shownSpoken: false, editable: true, why: null, take: takeView(take), newTake: null, state: "stale", because: ["words"], error: err instanceof Error ? err.message : String(err) }];
+ }
+ const parts = Array.isArray(take.parts) ? take.parts : [];
+ const sayNow = (role) => dry.parts.filter((p) => p.role === role).map((p) => norm(p.text)).join(" ");
+ const saidThen = (role) => parts.filter((p) => p?.role === role && typeof p?.take !== "string").map((p) => norm(p.text)).join(" ");
+ const rows = [];
+ for (const pc of dry.plan.pieces) {
+ const sc = parseScreenRole(pc.role);
+ const kind = sc ? "screen" : "thread";
+ const screen = sc ? screensOf(e).find((s) => s.id === sc.id) ?? null : null;
+ const own = pc.role === "post";
+ const as = screen ? saidAsOf(screen, sc.n) : null;
+ const j = screen ? screensOf(e).indexOf(screen) : -1;
+ const storedAt = own ? (str(e.narration?.script) ? "narration.script" : null) : sc ? (as !== null ? `screens[${j}].saidAs.${sc.n}` : null) : null;
+ const editable = own || !!sc;
+ const want = pc.handle ? vs.resolve(e, pc.role, pc.handle, take) : null;
+ const part = parts.find((p) => p?.role === pc.role && typeof p?.take !== "string") ?? null;
+ const row = {
+ ...base, id: readIdOf(e.id, pc.role), kind, role: pc.role, character: characterRow(vs, pc.character ?? want?.character),
+ voice: `${pc.engine ?? take.engine ?? "?"}:${pc.voice ?? "?"}`, spoken: sc ? (as ?? screenLineSaid(screen, sc.n)) : str(pc.written), said: pc.text,
+ storedAt, shownSpoken: own ? !str(e.narration?.script) : sc ? as === null : true, editable: editable && !pc.take, why: pc.take ? "read from a take (a recording): record it again" : editable ? null : SAID_AS_SHOWN,
+ take: takeView(take, part ? { reading: Number.isInteger(part.reading) ? part.reading : 0, tuning: isObj(part.tuning) ? part.tuning : null, tunedBy: tunedByOf(part) ?? tunedByOf(take) } : {}), newTake: null,
+ };
+ if (pc.take) {
+ rows.push({ ...row, state: "recorded", because: [] });
+ continue;
+ }
+ const because = [];
+ if (!dry.upToDate && sayNow(pc.role) !== saidThen(pc.role)) because.push("words");
+ if (vs.settings.has(vs.key(e.id, pc.role))) because.push("settings");
+ if (vs.voice.has(vs.key(e.id, pc.role))) because.push("voice");
+ rows.push({ ...row, state: because.length ? "stale" : "fresh", because });
+ }
+ return rows;
+}
+
+/** The rows of ONE narrated card: its key now, and the readings kept beside the build. */
+function cardRows(ctx, n, at) {
+ const readings = ctx.cards.get(n.id) ?? [];
+ const plays = readings.find((r) => r.key === n.key) ?? null;
+ const same = readings.some((r) => norm(r.text) === norm(n.text));
+ const state = plays ? "fresh" : readings.length ? "stale" : "none";
+ return [{
+ id: readIdOf(n.id), kind: "card", item: n.id, role: null, n: at, character: null, voice: `${n.engine}:${n.voice}`, spoken: n.text, said: n.text,
+ storedAt: "narration.text", shownSpoken: false, editable: true, why: null, legacy: false,
+ take: plays ? { index: null, file: null, key: plays.key, reading: Number.isInteger(plays.askedReading) ? plays.askedReading : plays.reading ?? 0, tuning: plays.askedTuning ?? null, tunedBy: "line" } : null,
+ newTake: null, state, because: state === "stale" ? [same ? "settings" : "words"] : [],
+ readings: readings.map((r) => ({ key: r.key, text: r.text, createdAt: r.createdAt ?? null })),
+ }];
+}
+
+/** Every read of `m` (cut order), as judged in `ctx`. */
+async function rowsOf(ctx, m) {
+ const vs = await voicesOf(ctx, m);
+ const cards = new Map(narrationsOf(m).map((x) => [x.id, x]));
+ const rows = [];
+ const tl = Array.isArray(m.timeline) ? m.timeline : [];
+ for (let i = 0; i < tl.length; i += 1) {
+ const e = tl[i];
+ if (e?.type === "post") rows.push(...(await postRows(ctx, m, vs, e, i)));
+ else if (cards.has(e?.id)) rows.push(...cardRows(ctx, cards.get(e.id), i));
+ }
+ return { rows, vs };
+}
+
+/**
+ * EVERY READ OF A PROJECT: `{ rows, counts, tuningStale }` -- `tuningStale` the voices view's own rows (what `cast stale`
+ * lists), so every count of reads "made with other settings" is this one. A stale post read with a newer synthesized
+ * take that would be fresh if picked is `unpicked` (its `newTake`).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Parameters<typeof readsContext>[1] & { ctx?: any }} [o]
+ */
+export async function projectReads(project, o = {}) {
+ const ctx = o.ctx ?? (await readsContext(project, o));
+ const m = ctx.manifest;
+ const { rows, vs } = await rowsOf(ctx, m);
+ // UNPICKED: for each item with a stale read, its other synthesized takes, newest first -- picked in a copy, judged by
+ // the same rule.
+ const staleItems = [...new Set(rows.filter((r) => r.state === "stale" && r.kind !== "card").map((r) => r.item))];
+ for (const id of staleItems) {
+ const at = m.timeline.findIndex((x) => x?.id === id);
+ const e = m.timeline[at];
+ const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : [];
+ const pick = Number.isInteger(e.narration.pick) ? e.narration.pick : 0;
+ const mine = rows.filter((r) => r.item === id && r.state === "stale");
+ for (let j = takes.length - 1; j >= 0 && mine.some((r) => !r.newTake); j -= 1) {
+ if (j === pick || takeSourceOf(takes[j]).kind !== "tts") continue;
+ const m2 = { ...m, timeline: m.timeline.map((x, k) => (k === at ? { ...x, narration: { ...x.narration, pick: j } } : x)) };
+ const vs2 = await voicesOf(ctx, m2);
+ const again = await postRows(ctx, m2, vs2, m2.timeline[at], at);
+ for (const r of mine) {
+ if (r.newTake) continue;
+ const twin = again.find((x) => x.id === r.id);
+ if (twin?.state === "fresh") {
+ r.state = "unpicked";
+ r.newTake = twin.take;
+ }
+ }
+ }
+ }
+ const counts = Object.fromEntries(READ_STATES.map((s) => [s, rows.filter((r) => r.state === s).length]));
+ return { rows, counts, tuningStale: vs.view.tuningStale ?? [], ctx };
+}
+
+/** The reads a row filter keeps: `stale` (stale or unpicked: what a re-read is for), a character's (its id). */
+export function filterReads(rows, { stale = false, character = null } = {}) {
+ return rows.filter((r) => (!stale || r.state === "stale" || r.state === "unpicked") && (!character || r.character?.id === character));
+}
+
+// ---------------------------------------------------------------------------
+// FIND: plain text, case on or off, whole word -- over the SPOKEN text only.
+// ---------------------------------------------------------------------------
+
+const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+/** The pattern Find matches `text` with (a phrase across any spaces; regex characters literal), or null for none. */
+export function findPattern(text, { matchCase = false, word = false } = {}) {
+ const t = str(text).replace(/\s+/g, " ").trim();
+ if (!t) return null;
+ const body = t.split(" ").map(escRe).join("\\s+");
+ return new RegExp(word ? `(?<![\\p{L}\\p{N}_])${body}(?![\\p{L}\\p{N}_])` : body, matchCase ? "gu" : "giu");
+}
+
+/** Every match of `re` in `s`: `[{ start, end }]`. */
+export const matchesIn = (s, re) => (re ? [...str(s).matchAll(re)].filter((x) => x[0]).map((x) => ({ start: x.index, end: x.index + x[0].length })) : []);
+
+/**
+ * FIND over the reads' spoken text: `{ rows: [{ ...row, matches }], matches, lines }` -- only the rows with a match,
+ * each with where its matches stand in `spoken`.
+ */
+export function findInReads(rows, text, opts = {}) {
+ const re = findPattern(text, opts);
+ const hit = rows.map((r) => ({ ...r, matches: matchesIn(r.spoken, re) })).filter((r) => r.matches.length);
+ return { rows: hit, matches: hit.reduce((a, r) => a + r.matches.length, 0), lines: hit.length };
+}
+
+/** `s` with every match of `re` replaced by `to` (literally: no `$` patterns). */
+export const replaceIn = (s, re, to) => str(s).replace(re, () => to);
+
+/** Said when a replace leaves a post whose playing take predates the rule (post-item.mjs). */
+export { LEGACY_EDIT_TEXT };
diff --git a/umtool/lib/report/reads.test.mjs b/umtool/lib/report/reads.test.mjs
@@ -0,0 +1,110 @@
+// THE READ MODEL (lane reads-find, reads.mjs): every read of a video -- a post's script, a thread read's pieces, its
+// screen lines, a card's narration -- with what it SAYS, where that is kept, the take that plays, and its state; and
+// FIND over the spoken text only. Temp dirs, invented people.
+import assert from "node:assert/strict";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { tuningStale } from "umtool-report-to-video/cast";
+import { filterReads, findInReads, findPattern, projectReads, replaceIn } from "./reads.mjs";
+import { manifestToken, updatePostNarration } from "./manifest.mjs";
+import { resolverFor } from "./castProject.mjs";
+import { LIVELY, castDoc, readManifestOf, readsProject } from "./reads.fixtures.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-reads-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+const opts = (p) => ({ reportsRoot: p.root });
+
+test("every kind: a post's script, a thread read's pieces and screen lines, a recorded read, a card -- in cut order, fresh as made", async () => {
+ const p = await readsProject(ROOT, "kinds");
+ const { rows, counts } = await projectReads(p, opts(p));
+ assert.deepEqual(rows.map((r) => [r.id, r.kind]), [
+ ["p-1", "post"],
+ ["p-2/parent:0", "thread"], ["p-2/quoted", "thread"], ["p-2/post", "thread"], ["p-2/screen:s1:0", "screen"], ["p-2/screen:s1:1", "screen"],
+ ["p-3", "post"],
+ ["c-1", "card"],
+ ]);
+ const by = Object.fromEntries(rows.map((r) => [r.id, r]));
+ assert.equal(by["p-1"].state, "fresh");
+ assert.equal(by["p-1"].character?.id, "ferry");
+ assert.equal(by["p-1"].storedAt, "narration.script");
+ assert.equal(by["p-2/post"].state, "fresh", JSON.stringify(by["p-2/post"].because));
+ assert.equal(by["p-2/screen:s1:0"].spoken, "Are the tolls going up again?");
+ assert.equal(by["p-2/screen:s1:0"].storedAt, null, "no said-as yet: the line as shown");
+ assert.equal(by["p-2/screen:s1:0"].shownSpoken, true);
+ assert.equal(by["p-2/parent:0"].editable, false);
+ assert.match(by["p-2/parent:0"].why, /said as shown: only Everywhere changes this/);
+ assert.equal(by["p-3"].state, "recorded");
+ assert.equal(by["p-3"].editable, false);
+ assert.equal(by["c-1"].state, "fresh");
+ assert.equal(by["c-1"].storedAt, "narration.text");
+ assert.deepEqual(counts, { fresh: 7, stale: 0, unpicked: 0, none: 0, recorded: 1 });
+});
+
+test("stale: the words changed (post, screen, card), the lexicon, the character's settings -- and none, unpicked", async () => {
+ const p = await readsProject(ROOT, "stale");
+ const m = await readManifestOf(p);
+ const tl = m.timeline;
+ tl[0].narration.script = tl[0].narration.script.replace("noon", "twelve noon");
+ tl[1].screens[0].saidAs = { 1: "Not this year, they told us." };
+ tl[3].narration.text = "Six months later, the north pier opened again.";
+ await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m, null, 2));
+ let by = Object.fromEntries((await projectReads(p, opts(p))).rows.map((r) => [r.id, r]));
+ assert.deepEqual([by["p-1"].state, by["p-1"].because], ["stale", ["words"]]);
+ assert.deepEqual([by["p-2/screen:s1:1"].state, by["p-2/screen:s1:1"].because], ["stale", ["words"]]);
+ assert.equal(by["p-2/screen:s1:1"].storedAt, "screens[0].saidAs.1");
+ assert.equal(by["p-2/screen:s1:0"].state, "fresh");
+ assert.deepEqual([by["c-1"].state, by["c-1"].because], ["stale", ["words"]]);
+ // The lexicon: a word the single read says, said another way now.
+ const q = await readsProject(ROOT, "lexicon");
+ await writeFile(path.join(q.dir, "narration", "lexicon.json"), JSON.stringify([{ word: "pier", say: "peer" }]));
+ by = Object.fromEntries((await projectReads(q, opts(q))).rows.map((r) => [r.id, r]));
+ assert.deepEqual([by["p-1"].state, by["p-1"].because], ["stale", ["lexicon"]]);
+ assert.equal(by["p-1"].said.includes("north peer"), true);
+ // The character's tuning changed: the very rows tuningStale lists (cast stale, the bench's count).
+ const s = await readsProject(ROOT, "settings", { cast: castDoc(LIVELY) });
+ const r = await projectReads(s, opts(s));
+ const settings = r.rows.filter((x) => x.because.includes("settings")).map((x) => x.id);
+ assert.deepEqual(settings, ["p-1"]);
+ assert.deepEqual(r.tuningStale.map((x) => x.id), ["p-1"]);
+ assert.deepEqual(tuningStale(await readManifestOf(s), resolverFor({ cast: castDoc(LIVELY) }), { settingTakes: 3 }).map((x) => x.id), ["p-1"]);
+ assert.deepEqual(filterReads(r.rows, { stale: true, character: "ferry" }).map((x) => x.id), ["p-1"]);
+});
+
+test("unpicked: a re-read joined the list unpicked -- the row waits for a Pick; picked, fresh", async () => {
+ const p = await readsProject(ROOT, "unpicked");
+ const m = await readManifestOf(p);
+ const e = m.timeline[0];
+ e.narration.script = e.narration.script.replace("noon", "twelve noon");
+ e.narration.takes.push({ ...e.narration.takes[0], file: "narration/posts/1/take-2.orpheus-tara.wav", script: e.narration.script, forReading: true });
+ await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m, null, 2));
+ let row = (await projectReads(p, opts(p))).rows.find((r) => r.id === "p-1");
+ assert.equal(row.state, "unpicked");
+ assert.equal(row.newTake.index, 1);
+ await updatePostNarration(p.dir, "p-1", { pick: 1 }, { token: await manifestToken(p.dir) });
+ row = (await projectReads(p, opts(p))).rows.find((r) => r.id === "p-1");
+ assert.equal(row.state, "fresh");
+ // No take at all: none.
+ const q = await readsProject(ROOT, "none", { timeline: [{ type: "post", id: "p-9", post: "ferry-x/9", platform: "x", author: "A", handle: "invented_a", date: "2026-10-30T10:00:00.000Z", text: "Just words.", narration: { script: "Just words." } }] });
+ assert.equal((await projectReads(q, opts(q))).rows[0].state, "none");
+});
+
+test("FIND: plain text, case on or off, whole word -- matches in the spoken text only, with a count of matches and lines", async () => {
+ const p = await readsProject(ROOT, "find");
+ const { rows } = await projectReads(p, opts(p));
+ const all = findInReads(rows, "north");
+ assert.deepEqual(all.rows.map((r) => r.id), ["p-1", "p-3", "c-1"]);
+ assert.equal(all.matches, 4);
+ assert.equal(all.lines, 3);
+ assert.equal(findInReads(rows, "North", { matchCase: true }).matches, 0);
+ assert.equal(findInReads(rows, "nort").matches, 4);
+ assert.equal(findInReads(rows, "nort", { word: true }).matches, 0);
+ // A phrase across any spaces; regex characters literal.
+ assert.equal(findInReads(rows, "north pier").matches, 3);
+ assert.equal(findInReads(rows, "(north)").matches, 0);
+ // Shown text is never searched: the bridge post's card words that no read says.
+ assert.equal(findInReads(rows, "second paragraph nobody reads").matches, 0);
+ assert.equal(replaceIn("North north", findPattern("north"), "$&-x"), "$&-x $&-x");
+});