commit 4541cddc429c49301a22f5ebcef294b53bd0c20f
parent 80d8d43632bed7dd2fa6e3b9601e77d058502cb7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 21:22:48 -0500
Merge main (63fbbd30f) into lane/x-trending
editor/CHANGELOG.md: both sides kept under [Unreleased].
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
58 files changed, 4213 insertions(+), 152 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -33,6 +33,41 @@
and an X post capture that starts during one fails with the same sentence. Before, the second browser failed with
Chromium's own error.
- **Fetch posts on an X trending library is refused with a sentence**, and the X run does not list a library.
+- **umtool: a video's reads, found, replaced and re-read in one press, with no agent (the Reads page).**
+ `/projects/<p>/reads` lists every line a synthetic voice reads: a post's script, the pieces of a thread read, screen
+ lines and card narration. Each line shows what it SAYS, the take that plays and its state:
+ - `fresh`, `stale` (other words, the lexicon, or its character's settings or voice since then), `unpicked`,
+ `none` or `recorded`.
+ - **Find** searches the spoken text only, with case and whole-word options and a count of matches and lines.
+ - **Replace** offers two scopes, each previewed first. Neither synthesizes anything, and neither ever changes
+ what is shown:
+ - **These reads** rewrites the matched lines' spoken text as one undo point: a post's script, a screen line's
+ "said as" (created when the line has none), a card's narration. A parent, the quoted post or a linked post is
+ "said as shown: only Everywhere changes this". A recorded read is never replaced.
+ - **Everywhere, from now on** adds a pronunciation entry. It matches whole words only and never reaches a card.
+ - **Re-read N changed lines** queues them on the app's queue: one step per item, in cut order, one at a time.
+ Each step runs the command the item's bench button runs. The view says in one line why a step is waiting.
+ **Stop** and **Retry** work per line. A re-read joins the list unpicked.
+ - **Listen through** plays each re-read next to what played before, with a Pick on either and "Pick every new
+ read".
+ - The CLI twin is `umtool reads <p>` with `replace`, `undo`, `reread`, `queue` and `pick`, all with `--json`.
+ Every subcommand refuses a flag it does not take, and `--dry-run` works on undo, reread and pick.
+ - The page acts only on the reads it counted, by their ids.
+ - Undo is offered only while nothing has been written since the replace, and an Everywhere's undo puts back the
+ entry it changed.
+ - A line that owns its takes is never judged against its character's, so `cast stale` changes too.
+- **umtool: unit test runs can no longer reach a running editor.** `pnpm test:scripts` and umtool's tests set a
+ dead editor address and no token.
+ - The "made with other settings" lines in the character preset, on the Voices page and in the bench's Keep note
+ now link here.
+- **umtool: a plain Read again passes back only the values the line owns.** Each take records `tuningOwn`. The
+ character's values and the editor's setting, `takes` included, are worked out again at each read. A read that went
+ stale because its character's takes changed now comes back fresh once its re-read is picked.
+ - Known limit: an older take that owned only its takes now reads with the character's takes, or the setting's.
+- **umtool: the queue's read of a post asks exactly what a bench press asks.** Both go through one shared module, and
+ the slur rule is included (`posts narrate … --take --bench-slurs`).
+- **umtool: an imported script that is edited for reading is marked as such.** `posts narrate --import` now marks it
+ the way Save script does, so the card keeps following the shown text.
- **Connect X account, Connect archive session and Connect forum session open their window even when the editor
started before the desktop.** The editor runs as a user service that starts at boot, so it had no display, and every
Connect failed with "launched a headed browser without having a XServer running" until a restart. Each press now looks
diff --git a/package.json b/package.json
@@ -24,8 +24,8 @@
"wt": "node scripts/worktree.mjs",
"e2e:sharded": "node scripts/run-sharded-e2e.mjs",
"e2e:all": "node scripts/e2e-all.mjs",
- "test:files": "node scripts/test-files.mjs",
- "test:scripts": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs umtool/lib/ingredients/*.test.mjs umtool/lib/cli/*.test.mjs",
+ "test:files": "ARCHILYZER_EDITOR_URL=http://127.0.0.1:9 WORKER_TOKEN= UMTOOL_URL=http://127.0.0.1:9 node scripts/test-files.mjs",
+ "test:scripts": "ARCHILYZER_EDITOR_URL=http://127.0.0.1:9 WORKER_TOKEN= UMTOOL_URL=http://127.0.0.1:9 ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs umtool/lib/ingredients/*.test.mjs umtool/lib/cli/*.test.mjs",
"test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]",
"typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit",
"lint": "pnpm --filter export run lint",
diff --git a/plans/orpheus-retune.md b/plans/orpheus-retune.md
@@ -2,7 +2,7 @@
Status: **planned 15 Nov 2026; S1 done (merged 2dff0a631, shipped 16 Nov 2026); S3 done (`lane/line-rerun`,
merged 17 Nov 2026; S3b, re-read one sentence, is a follow-up after S4); S2 done (`lane/character-tuning`,
-merged 17 Nov 2026).** Written to be picked up cold (after a usage reset). S4 is not started.
+merged 17 Nov 2026); S4 built on `lane/reads-find` (17 Nov 2026), in review.** Written to be picked up cold (after a usage reset).
## The ask (operator, 15 Nov 2026)
@@ -185,6 +185,12 @@ test must pin the drawn structure (blocks, hidden paragraphs, tile modes), not o
### S4. Find and replace over the whole video, and the re-read queue (`lane/reads-find`)
+**Built** (17 Nov 2026, in review): the Reads page `/projects/<p>/reads`, `umtool reads`, `lib/report/reads.mjs` (the
+one read model), `readsReplace.mjs`, `readsQueue.mjs` (the durable queue), `readAgainArgv.mjs`; umtool/docs/knobs.md,
+"The reads of a video". The orchestrator's rulings for it: a queue re-read joins unpicked (Listen through's Pick);
+a plain press passes back only what the LINE owned (`tuningOwn`), so a re-read comes back fresh; the queue's read of a
+post is the bench's ask (one module, the slur rule included).
+
- A **Reads** view per project (a tab of the workspace, or a section of the Voices page; implementer
proposes): every line a synthetic voice reads in the cut (posts, screen lines, cards, thread reads),
with its character, its picked take, and whether that take still matches its text and tuning
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -1,7 +1,7 @@
import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import {
- POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, isNarrated, nextReadingOf, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takeIdOf, takesDirOf,
+ POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, isNarrated, nextReadingOf, nextTakeNumber, pickedTake, postIdOf, takeFileOf, takeIdOf, takesDirOf,
} from "umtool-report-to-video/post-narration";
import { postItemPlan } from "umtool-report-to-video/post-item";
import { jobState, resultLine, startJob } from "@/lib/research/case-editor";
@@ -19,10 +19,10 @@ import { withTakeScope } from "@/lib/report/takeScope.mjs";
import { isTakeId } from "@/lib/report/takes.mjs";
import { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs";
import { fitPostItem } from "@/lib/report/postFit.mjs";
-import { itemReadVoice } from "@/lib/report/readVoice.mjs";
+import { askBody, benchSlurVoice, benchTakeAskOf } from "@/lib/report/postTakeAsk.mjs";
+import { readAgainArgv } from "@/lib/report/readAgainArgv.mjs";
import { projectRedaction } from "@/lib/report/postRedaction.mjs";
import { spokenRead } from "umtool-report-to-video/post-redact";
-import { tuningAskOf } from "umtool-report-to-video/post-say";
import { characterById, recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast";
import { readLayers, recordedTrimFor } from "@/lib/report/characterLayers.mjs";
import { convertAskOf, derivePitchOf, deriveRefusalOf, stepPitchOf } from "@/lib/report/derivePitch.mjs";
@@ -32,8 +32,8 @@ import { renderWaitSentence } from "@/lib/report/renderMode.mjs";
export const dynamic = "force-dynamic";
-/** The slur filter's voice for a take synthesized on the bench: beep falls back to skip (no word timings yet to beep by). */
-const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?.slurs?.voice === "beep" ? "skip" : undefined) as "skip" | undefined;
+/** The slur filter's voice for a take synthesized on the bench: beep falls back to skip (lib/report/postTakeAsk.mjs, one rule). */
+const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => benchSlurVoice(red) as "skip" | undefined;
// A NARRATED POST ITEM's bench (report-to-video/post-narration.mjs; knobs.md,
// "A narrated post item"): the recording session, the takes, the mix's knobs.
@@ -262,12 +262,14 @@ export async function GET(request: Request) {
const { slurs, lexicon } = spoken;
// What the POST asked (its speed and where it came from), kept beside the file until the take is made.
const askFile = `${abs}.ask.json`;
- const ask = (await readFile(askFile, "utf8").then(JSON.parse, () => null)) as { speed?: number; speedAsked?: true | "item" | "preset"; keepPick?: boolean; tuningAsked?: true | "preset" } | null;
+ const ask = (await readFile(askFile, "utf8").then(JSON.parse, () => null)) as { speed?: number; speedAsked?: true | "item" | "preset"; keepPick?: boolean; tuningAsked?: true | "preset"; tuningOwn?: Record<string, number> } | null;
await rm(askFile, { force: true });
const take = {
...(typeof ask?.speed === "number" ? { speed: ask.speed } : {}), ...(ask?.speedAsked !== undefined ? { speedAsked: ask.speedAsked } : {}),
// Where its tuning came from (lane character-tuning): its line's own, or its character's.
...(ask?.tuningAsked === true || ask?.tuningAsked === "preset" ? { tuningAsked: ask.tuningAsked } : {}),
+ // The line's own values as asked (lane reads-find): what a plain press passes back.
+ ...(ask?.tuningOwn && typeof ask.tuningOwn === "object" && Object.keys(ask.tuningOwn).length ? { tuningOwn: ask.tuningOwn } : {}),
// What it said, when an anonymous handle made that differ from the script (post-anon.mjs; the lint reads it).
...(spoken.anonymised ? { said: spoken.text } : {}),
...(slurs ? { slurs } : {}),
@@ -395,7 +397,6 @@ async function postHere(request: Request) {
}
if (body.op === "take") {
// The EDITOR synthesizes (its tts op, a job on its queue); the take is kept when the job is done (GET ?job).
- const k = postNarrationKnobs(e, (m.render ?? {}) as Record<string, unknown>);
const script = String(body.script ?? e.narration?.script ?? "").trim();
if (!script) return Response.json({ error: `${id} has no script to read` }, { status: 400 });
// Its tuning and reading (another reading of the same words): refused here in the editor's words, sent as asked.
@@ -408,6 +409,10 @@ async function postHere(request: Request) {
// ONE READ OF A POST AT A TIME: a second press while one is made is refused, never asked twice. The marker is
// TAKEN before the editor is asked (created exclusively: two presses at once cannot both take it; review 1,
// finding 4); a marker whose job ended, or one never given a job within two minutes, is stale and taken over.
+ // ITS RE-READ IN THE READS QUEUE (lane reads-find): while that step runs, a press here would make a second read
+ // of the same post -- said, as a sentence, never asked.
+ const queued = await (await import("@/lib/report/readsQueue.mjs")).rereadRunningFor(r.project.id, id, { queueDir: (await import("@/lib/queue/runner")).queueDir() }).catch(() => null);
+ if (queued) return Response.json({ error: `this post is being re-read by the Reads queue (${queued.qid}): read it again when that lands`, busy: true }, { status: 409 });
const pendingFile = pendingFileOf(r.project.dir, e);
await mkdir(path.dirname(pendingFile), { recursive: true });
const claim = () => writeFile(pendingFile, JSON.stringify({ starting: true, at: new Date().toISOString() }), { flag: "wx" }).then(() => true, () => false);
@@ -423,41 +428,27 @@ async function postHere(request: Request) {
// .ask.json) away, so a failed press never answers 409 for two minutes.
let askFile: string | null = null;
try {
- // The voice: the one asked for, the item's own character, the project's characters and voice map, the CAST, the
- // narrator's -- a single read's rule (readVoice.mjs).
- const said = await itemReadVoice(r.project, e, {
- render: (m.render ?? {}) as Record<string, unknown>,
- engine: typeof body.engine === "string" && body.engine ? body.engine : null,
- voice: typeof body.voice === "string" && body.voice ? body.voice : null,
- });
- const engine = String(said.engine ?? k.engine);
- const voice = String(said.voice ?? k.voice);
+ // THE ASK (lib/report/postTakeAsk.mjs, the one `posts narrate --take` and the re-read queue build too; lane
+ // reads-find): the voice (the one asked for, the item's own character, the project's characters and voice map,
+ // the CAST, the narrator's), its speed (the one asked for, else the item's own, else its character's; none for
+ // Orpheus), its tuning (the line's own -- the Tune -- over its character's, field by field; a character with no
+ // tuning asks as it always did) and what the voice SAYS (the redaction, the slurs, the lexicon; the script kept
+ // as written). The bench cannot word-time a take as it is made, so a beep falls back to skip (benchSlurVoice).
+ const red = await projectRedaction(r.project.dir, m);
+ const A = await benchTakeAskOf(r.project, e, { manifest: m, script, body, tuning: tuned?.ok ? tuned.value : null, reading: reading === null ? null : Number(reading), red });
+ const { engine, voice, tuning, tuningAsked } = A;
const pid = postIdOf(e);
const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/"));
await mkdir(dir, { recursive: true });
const rel = takeFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), engine, voice);
- // Its speed: the one asked for, else the item's own (`narration.speed`), else its character's (the synthetic
- // preset's that answered for the voice) -- makeTake's order.
- const askedSpeed = body.speed === undefined || body.speed === null ? (e.narration as { speed?: number } | undefined)?.speed ?? (said as { speed?: number }).speed : Number(body.speed);
- const speed = askedSpeed === undefined || askedSpeed === null || engine === "orpheus" ? undefined : Number(askedSpeed);
- // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's
- // filter has it (post-slurs.mjs) and the project's pronunciation lexicon applied (post-say.mjs); the script is kept as written. The bench cannot word-time a take as it is made,
- // so a beep falls back to skip here (the CLI's --take times it and beeps).
- const red = await projectRedaction(r.project.dir, m);
- const spoken = spokenRead(script, e, red, { voice: benchVoice(red) }).text;
const out = path.join(r.project.dir, ...rel.split("/"));
// Its speed and where it came from, for the take the GET makes when the job is done (a sidecar, removed then).
// A re-read (`keepPick`, the bench's Read again) joins the list unpicked: said here too.
const keepPick = body.keepPick === true;
- // Its tuning: the line's own (the Tune), else -- Orpheus only -- its character's (the synthetic preset's that
- // answered for the voice: lane character-tuning); a character with no tuning asks as it always did.
- // Field by field, as makeTake and every thread piece: the line's own values over the character's (tuningAskOf).
- const ta = tuningAskOf({ own: tuned?.ok ? tuned.value : null, preset: (said as { tuning?: Record<string, number> }).tuning ?? null, engine });
- const tuning = ta.tuning;
- const tuningAsked = ta.asked;
+ const speed = A.speed ?? undefined;
askFile = `${out}.ask.json`;
- if (speed || keepPick || tuningAsked) await writeFile(`${out}.ask.json`, JSON.stringify({ ...(speed ? { speed, speedAsked: body.speed !== undefined && body.speed !== null ? true : (e.narration as { speed?: number } | undefined)?.speed != null ? "item" : "preset" } : {}), ...(keepPick ? { keepPick: true } : {}), ...(tuningAsked ? { tuningAsked } : {}) }));
- const jobId = await startJob("/api/ops/tts", { text: spoken, engine, voice, out, ...(speed ? { speed } : {}), ...(tuning ? { tuning } : {}), ...(reading !== null ? { reading } : {}) });
+ if (speed || keepPick || tuningAsked || A.tuningOwn) await writeFile(`${out}.ask.json`, JSON.stringify({ ...(speed ? { speed, speedAsked: A.speedAsked } : {}), ...(keepPick ? { keepPick: true } : {}), ...(tuningAsked ? { tuningAsked } : {}), ...(A.tuningOwn ? { tuningOwn: A.tuningOwn } : {}) }));
+ const jobId = await startJob("/api/ops/tts", askBody(A, out));
// The marker names its job, its file and what the take keeps (its words, its note): a bench that lost the job
// finds it again here and lands its take (GET ?pending).
await writeFile(pendingFile, JSON.stringify({ jobId, file: rel, script, ...(typeof body.note === "string" && body.note ? { note: body.note } : {}), at: new Date().toISOString() }));
@@ -637,32 +628,8 @@ const cliPath = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "
/** The read of a post being made now (one at a time): `{ jobId, file, at }` beside its takes, removed when it ends. */
const pendingFileOf = (dir: string, e: Entry) => path.join(dir, ...takesDirOf(postIdOf(e)).split("/"), ".reading.json");
-const TUNING_FLAG_OF: Record<string, string> = { temperature: "--temperature", top_p: "--top-p", top_k: "--top-k", min_p: "--min-p", repeat_penalty: "--repeat-penalty", takes: "--chunk-takes" };
-const ROLE_RE = /^(post|quoted|parent:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/;
-
-/** A Read again's words for the CLI (lane line-rerun): `--for`, `--reading`, the tuning flags, `--no-pick`. */
-function readAgainArgv(body: Record<string, unknown>): string[] {
- const a: string[] = [];
- if (body.for !== undefined && body.for !== null) {
- if (typeof body.for !== "string" || !ROLE_RE.test(body.for)) throw new Error("for must name one piece of the read (screen:<id>:<line>, post, quoted, parent:<i>)");
- a.push("--for", body.for);
- }
- if (body.reading !== undefined && body.reading !== null) {
- if (body.reading !== "next") {
- const err = ttsReadingError(body.reading);
- if (err) throw new Error(err);
- }
- a.push("--reading", String(body.reading));
- }
- if (body.tuning !== undefined && body.tuning !== null) {
- const t = parseTtsTuning(body.tuning);
- if (!t.ok) throw new Error(t.error);
- for (const [k, v] of Object.entries(t.value)) a.push(TUNING_FLAG_OF[k], String(v));
- }
- if (a.includes("--for") && !a.includes("--reading") && !Object.values(TUNING_FLAG_OF).some((f) => a.includes(f))) throw new Error("for goes with a reading or a tuning");
- if (body.keepPick === true || body.op === "thread-read") a.push("--no-pick");
- return a;
-}
+// A Read again's words for the CLI (lane line-rerun): lib/report/readAgainArgv.mjs, which the re-read queue builds
+// its steps with too (lane reads-find: the queue's read is the bench's).
/** The jobs of one post item's screens: a line recorded, its read made. */
const screenJobKinds = (project: string, id: string) => [`screen-line ${project} ${id}`, `screen-read ${project} ${id}`];
diff --git a/umtool/app/api/report/reads/route.ts b/umtool/app/api/report/reads/route.ts
@@ -0,0 +1,48 @@
+import { projectRef } from "@/lib/projects";
+import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
+import { REPORTS_ROOT } from "@/lib/projects/core.mjs";
+import { readsGet, readsPost } from "@/lib/report/readsApi.mjs";
+import { kickQueue, queueDir, queueRunnerStatus } from "@/lib/queue/runner";
+
+export const dynamic = "force-dynamic";
+
+// A VIDEO's READS (lane reads-find; the Reads page, components/projects/ReadsPanel.tsx): lib/report/readsApi.mjs
+// answers -- the functions `umtool reads` runs, called directly (never an argv built from what a page typed).
+//
+// GET ?project[&find&case=1&word=1&stale=1&character=<id>] the reads (and Find's matches), the queue, the undo
+// POST {project, op: "preview", from, to, scope: "reads"|"say", case?, word?, only?}
+// POST {project, op: "replace", from, to, scope, case?, word?, only} (These reads names the previewed reads)
+// POST {project, op: "undo"} the newest replace (These reads, or an Everywhere) taken back
+// POST {project, op: "reread", only} the reads counted, queued on the app's queue
+// POST {project, op: "stop"} · {op: "retry", read} · {op: "pick", which: "new"|"old", only}
+const headers = { "cache-control": "no-store" };
+const ctx = () => ({ reportsRoot: REPORTS_ROOT, queueDir: queueDir(), runner: queueRunnerStatus(), kick: kickQueue });
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const project = await projectRef(String(url.searchParams.get("project") ?? ""));
+ if (!project) return Response.json({ error: "no such project" }, { status: 404 });
+ try {
+ return Response.json(await readsGet(project, url.searchParams, ctx()), { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers });
+ }
+}
+
+export async function POST(request: Request) {
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
+ const refused = refuseCaller(request, "/api/report/reads");
+ if (refused) return refused;
+ const b = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!b) return Response.json({ error: "bad json" }, { status: 400 });
+ const project = await projectRef(String(b.project ?? ""));
+ if (!project) return Response.json({ error: "no such project" }, { status: 404 });
+ try {
+ const r = await readsPost(project, b, ctx());
+ return Response.json(r.json, { status: r.status, headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -17,6 +17,7 @@
// umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json)
// umtool cast [ls|add|set|rm|undo|project|audition|use|reread] … the characters' voices across projects (castCli.mjs)
// umtool narration <project> [<card>] [--read|--pick <key>|--text …] a card's narration and its readings (cardNarrationCli.mjs)
+// umtool reads <project> [--find …|replace|undo|reread|queue|pick] … a video's reads: find, replace, re-read (readsCli.mjs)
// umtool speaker-check <project> [--clip <id> …] [--set 'Name=…'] [--list] which named voice each clip is (speaker-check.json)
// umtool quote-check <project> [--take <t>] [--clips a,b] [--status] is each clip's quote in the seconds it plays (quote-check.json; a take's: takes/<t>/)
// umtool check-joins <project> --take <id> [--json] [--all] do the post joins of a rendered take carry on, or jump
@@ -976,6 +977,8 @@ const COMMANDS = {
cast: async () => process.exit(await (await import("../lib/report/castCli.mjs")).castCommand(argv.slice(argv.indexOf("cast") + 1))),
// A card's narration: its words, reading and tuning, its readings read again and picked (lane line-rerun): lib/report/cardNarrationCli.mjs.
narration: async () => process.exit(await (await import("../lib/report/cardNarrationCli.mjs")).cardNarrationCommand(argv.slice(argv.indexOf("narration") + 1))),
+ // A video's reads: Find, Replace (these reads / everywhere), the re-read queue, the picks (lane reads-find): lib/report/readsCli.mjs.
+ reads: async () => process.exit(await (await import("../lib/report/readsCli.mjs")).readsCommand(argv.slice(argv.indexOf("reads") + 1))),
// Which named voice each clip is (UI notes #15): lib/report/speakerCheck.mjs.
"speaker-check": async () => process.exit(await (await import("../lib/report/speakerCheck.mjs")).speakerCheckCommand(argv.slice(argv.indexOf("speaker-check") + 1))),
// Is each clip's quote in the seconds it plays (lane one-clock): the editor transcribes, quote-check.json keeps the rows.
diff --git a/umtool/components/projects/CharacterTuning.tsx b/umtool/components/projects/CharacterTuning.tsx
@@ -3,7 +3,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
-import { postBenchHref } from "@/lib/hrefs";
+import { postBenchHref, readsHref } from "@/lib/hrefs";
import { ORPHEUS_TUNING_NAMED, ORPHEUS_TUNING_NAMES, TTS_TUNING_RANGES, ttsTuningNameOf, type TtsTuningName } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
// ---------------------------------------------------------------------------
@@ -320,6 +320,8 @@ export function CharacterTuning({
<a href={postBenchHref(project, x)} className="ink-link font-mono" data-tuning-stale-item={x}>{x}</a>
</span>
))}
+ {" · "}
+ <a href={readsHref(project, { state: "stale", character: id })} className="ink-link" data-tuning-stale-reads="" aria-label={`Re-read ${name}'s stale reads in the Reads view`}>Re-read them</a>
</span>
) : (
<span className="text-muted">no read by this character was made with other settings</span>
diff --git a/umtool/components/projects/NarrationReview.tsx b/umtool/components/projects/NarrationReview.tsx
@@ -456,6 +456,7 @@ function NarrationCard({
onReadAgain={(t) => void readAgain(t, null)}
onReadEdited={(t) => void readAgain(t, text)}
madeWith={r.madeWith ?? r.tuning ?? null}
+ lineOwn={r.tuning ?? null}
autoplay={auto}
onAutoplay={setAuto}
/>
diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx
@@ -1,7 +1,7 @@
import { notFound } from "next/navigation";
import AppShell from "@/components/shell/AppShell";
import PostBench from "./PostBench";
-import { projectHref, playHref } from "@/lib/hrefs";
+import { projectHref, playHref, readsHref } from "@/lib/hrefs";
import PlayLink from "./PlayLink";
import { postBenchData } from "@/lib/report/postBenchData";
import type { ProjectRef } from "@/lib/project-types";
@@ -39,6 +39,8 @@ async function postBenchBody({ project, id, search }: { project: ProjectRef; id:
<p className="mb-2 flex flex-wrap items-center gap-2 text-[12px]" data-post-bench-scope="cut">
<span className="micro">edits go to</span>
<span className="font-medium text-text">the draft</span>
+ <span className="text-muted">·</span>
+ <a href={readsHref(project.id)} className="ink-link" data-post-bench-reads="" aria-label="Every read of this video: find, replace, re-read">Reads</a>
</p>
<PostBench
project={project.id}
diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx
@@ -6,7 +6,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Waveform from "@/components/Waveform";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
-import { postBenchHref } from "@/lib/hrefs";
+import { postBenchHref, readsHref } from "@/lib/hrefs";
import { CAST_CONVERT_ENGINES, CAST_CONVERT_PITCH, CAST_PITCH_ENGINES, CAST_SEMITONES_MAX, convertPitchLabel } from "umtool-report-to-video/cast";
import { POST_DERIVE_OPS, POST_NARRATION_DEFAULTS, mixPhaseAt, pickedTake, postNarrationKnobs, scriptParts, takeIdOf, takeSourceOf } from "umtool-report-to-video/post-narration";
import { projectFileMedia } from "./bench/benchMedia";
@@ -17,6 +17,7 @@ import type { PostPlan } from "./review/PostItemPlayer";
import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom";
import PostAttachmentLane from "./PostAttachmentLane";
import ReadAgain, { madeWithText, playNow, useAutoPlay, type KeepForCharacter, type Tuning } from "./read/ReadAgain";
+import { lineOwnOf } from "@/lib/report/tuneAsk.mjs";
import { useKeepForCharacter } from "./read/keepForCharacter";
import { LEGACY_EDIT_TEXT, legacyReadOf } from "umtool-report-to-video/post-item";
@@ -712,6 +713,7 @@ export default function PostNarrationPanel({
</span>
<span className="tabular-nums">{Number(t.seconds).toFixed(1)} s</span>
{madeWithText(t) && <span className="font-mono text-text-2" data-post-take-made={i + 1}>{madeWithText(t)}</span>}
+ {(t as { tuningOwn?: Tuning }).tuningOwn && <span className="font-mono text-text-2" data-post-take-own={i + 1}>line's own: {Object.entries((t as { tuningOwn?: Tuning }).tuningOwn ?? {}).map(([k, v]) => `${k.replace("_", " ")} ${v}`).join(", ")}</span>}
{landed === t.file && <span className="micro text-[var(--color-sel)]" data-post-take-new={i + 1}>new</span>}
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
<audio src={fileUrl(project, t.file)} controls preload="none" className="h-7" data-post-take-audio={i + 1} />
@@ -821,6 +823,8 @@ export default function PostNarrationPanel({
onReadAgain={(t) => void press(() => readAgain(n.script ?? "", t))}
onReadEdited={(t) => void press(() => readEdited(t))}
madeWith={madeWith}
+ lineOwn={lineOwnOf(madeTake as Parameters<typeof lineOwnOf>[0]) as Tuning | null}
+ staleHref={project && readsAs.character ? readsHref(project, { state: "stale", character: readsAs.character.id }) : null}
baseline={readsAs.baseline}
madeOwn={readsAs.madeOwn}
refreshBaseline={readsAs.refresh}
diff --git a/umtool/components/projects/PostThreadPanel.tsx b/umtool/components/projects/PostThreadPanel.tsx
@@ -1,9 +1,10 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
+import { readsHref } from "@/lib/hrefs";
import ReadAgain, { playNow, useAutoPlay, type Tuning } from "./read/ReadAgain";
import { useKeepForCharacter } from "./read/keepForCharacter";
-import { threadTuneMadeOf } from "@/lib/report/tuneAsk.mjs";
+import { pieceOwnOf, threadTuneMadeOf } from "@/lib/report/tuneAsk.mjs";
import { THREAD_DEFAULTS, THREAD_LIMITS, THREAD_MODES, partRoles, readPieces, threadKnobs, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread";
import { followKnobs } from "umtool-report-to-video/read-follow";
import { pickedTake } from "umtool-report-to-video/post-narration";
@@ -176,6 +177,8 @@ export default function PostThreadPanel({
waiting={again?.state === "running" ? again.waiting ?? null : null}
onReadAgain={(t) => void readThreadAgain(t)}
madeWith={postPart?.tuning ?? null}
+ lineOwn={pieceOwnOf(playing, "post") as Tuning | null}
+ staleHref={project && readsAs.character ? readsHref(project, { state: "stale", character: readsAs.character.id }) : null}
baseline={readsAs.baseline}
madeOwn={readsAs.madeOwn}
refreshBaseline={readsAs.refresh}
diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx
@@ -13,6 +13,7 @@ import TakesComparePage from "./TakesComparePage";
import NarrationPage from "./NarrationPage";
import RecordPage from "./RecordPage";
import VoicesPage from "./VoicesPage";
+import ReadsPage from "./ReadsPage";
import ReviewPage from "./ReviewPage";
import ClipDeckPage from "./ClipDeckPage";
import PlayCutPage from "./PlayCutPage";
@@ -94,6 +95,8 @@ export default async function ProjectView({
if (rest.length === 2 && rest[0] === "narration" && rest[1] === "record") return <RecordPage project={project} search={search} />;
// `/projects/<project>/voices` -- each character's voice, auditions, the cast (lib/report/castCli.mjs).
if (rest.length === 1 && rest[0] === "voices") return <VoicesPage project={project} search={search} />;
+ // `/projects/<project>/reads` -- every line a voice reads: Find, Replace, the re-read queue (lib/report/readsCli.mjs).
+ if (rest.length === 1 && rest[0] === "reads") return <ReadsPage project={project} search={search} />;
// `/browse/<project>/review` -- every drafted field, approved / rejected
// before a final build, and the alternatives a draft task kept.
if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} view={search.view} />;
diff --git a/umtool/components/projects/ReadsPage.tsx b/umtool/components/projects/ReadsPage.tsx
@@ -0,0 +1,29 @@
+import { notFound } from "next/navigation";
+import AppShell from "@/components/shell/AppShell";
+import ReadsPanel from "./ReadsPanel";
+import { readManifest } from "@/lib/projects/report.mjs";
+import { projectHref } from "@/lib/hrefs";
+import type { ProjectRef } from "@/lib/project-types";
+
+// THE READS PAGE (lane reads-find, S4 of plans/orpheus-retune.md): /projects/<p>/reads -- every line a synthetic voice
+// reads in the video (posts, thread pieces, screen lines, cards), Find over what is SPOKEN, Replace in two stated
+// scopes, the re-read queue and Listen through. A page of its own beside /voices (which is per character): this is
+// per line, across posts and cards, and the bench's and the preset's "made with other settings" lines link here
+// filtered (`?state=stale&character=<id>`). The routes: /api/report/reads (`umtool reads`'s own commands).
+export default async function ReadsPage({ project, search = {} }: { project: ProjectRef; search?: Record<string, string | undefined> }) {
+ const m = await readManifest(project.dir);
+ if (!m) notFound();
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell
+ active="projects"
+ crumbs={[{ href: "/projects", label: "Projects" }, { href: projectHref(project.id, { tab: "cut" }), label: project.name }, { label: "reads" }]}
+ note="every line a voice reads · find · replace · re-read"
+ actions={<a href={`/projects/${project.id.split("/").map(encodeURIComponent).join("/")}/voices`} className="ink-link text-[12px]" data-reads-voices="">Voices</a>}
+ />
+ <main className="deck-main flex-1 overflow-auto p-4">
+ <ReadsPanel project={project.id} initialState={search.state === "stale" ? "stale" : "all"} initialCharacter={search.character ?? null} />
+ </main>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/ReadsPanel.tsx b/umtool/components/projects/ReadsPanel.tsx
@@ -0,0 +1,384 @@
+"use client";
+
+import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { narrationHref, playHref, postBenchHref } from "@/lib/hrefs";
+
+// ---------------------------------------------------------------------------
+// THE READS PANEL (lane reads-find): every line a voice reads in this video, from GET /api/report/reads (`umtool
+// reads <p> --json`). Find searches what is SPOKEN only; Replace offers two scopes, each previewed before it is
+// applied, and neither synthesizes; Re-read queues the changed lines on the app's queue (one step per item, each the
+// bench's own command); Listen through plays the re-reads one after another, each with what played before one press
+// away and a Pick on either. Every button is a form and a job; nothing here asks a model.
+// ---------------------------------------------------------------------------
+
+type Take = { index: number | null; takeFile?: string | null; file: string | null; files?: string[]; key: string | null; reading: number; tuning: Record<string, number> | null; tunedBy: string | null } | null;
+type Read = {
+ id: string; kind: "post" | "thread" | "screen" | "card"; item: string; role: string | null; character: { id: string; name: string } | null; voice: string | null;
+ spoken: string; said: string | null; storedAt: string | null; editable: boolean; why: string | null; queueable?: boolean; state: string; because: string[]; take: Take; newTake: Take; matches?: { start: number; end: number }[];
+};
+type QueueRow = { read: string; item: string; kind: string; qid: string; state: string; error: string | null; before: Take; batch: string };
+type Queue = { rows: QueueRow[]; waiting: string | null; counts: Record<string, number>; batch: string | null };
+type Undo = { scope: "reads" | "say"; available: boolean; why: string | null; entry?: { word: string; say: string }; was?: { word: string; say: string } | null } | null;
+type View = { counts: Record<string, number>; reads: Read[]; find?: { matches: number; lines: number }; queue: Queue; undo: Undo };
+type Line = { id: string; kind: string; item: string; before: string; after: string; creates: string | null };
+type Preview =
+ | { scope: "reads"; lines: Line[]; skipped: { id: string; why: string }[]; notes: Record<string, string[]>; refused: Record<string, string[]>; matches: number; token: string }
+ | { scope: "say"; entry: { word: string; say: string }; was: string | null; stale: { id: string }[]; cards: string[]; matches: number };
+
+const KIND: Record<Read["kind"], string> = { post: "post script", thread: "thread part", screen: "screen line", card: "card narration" };
+const BECAUSE: Record<string, string> = { words: "other words", lexicon: "the lexicon", settings: "other settings", voice: "another voice" };
+const STATE_CLASS: Record<string, string> = { fresh: "text-text-2", stale: "text-doubt-text", unpicked: "text-[var(--color-sel)]", none: "text-muted", recorded: "text-muted" };
+const btn = buttonVariants({ variant: "outline", size: "sm" });
+
+async function post(body: Record<string, unknown>) {
+ const r = await fetch("/api/report/reads", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).catch(() => null);
+ const j = (await r?.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!r?.ok) throw new Error(String(j?.error ?? (r ? `HTTP ${r.status}` : "umtool could not be reached")));
+ return j ?? {};
+}
+
+/** A read's spoken text with its matches marked. */
+function Marked({ text, matches }: { text: string; matches?: { start: number; end: number }[] }) {
+ if (!matches?.length) return <>{text}</>;
+ const out: React.ReactNode[] = [];
+ let at = 0;
+ matches.forEach((m, i) => {
+ out.push(text.slice(at, m.start));
+ out.push(<mark key={i} className="rounded-sm bg-[var(--color-sel)]/25 text-text" data-reads-match="">{text.slice(m.start, m.end)}</mark>);
+ at = m.end;
+ });
+ out.push(text.slice(at));
+ return <>{out.map((x, i) => <Fragment key={i}>{x}</Fragment>)}</>;
+}
+
+export default function ReadsPanel({ project, initialState = "all", initialCharacter = null }: { project: string; initialState?: "all" | "stale"; initialCharacter?: string | null }) {
+ const [view, setView] = useState<View | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [state, setState] = useState<"all" | "stale">(initialState);
+ const [character, setCharacter] = useState<string | null>(initialCharacter);
+ const [find, setFind] = useState("");
+ const [matchCase, setMatchCase] = useState(false);
+ const [word, setWord] = useState(false);
+ const [to, setTo] = useState("");
+ const [preview, setPreview] = useState<Preview | null>(null);
+ const [skip, setSkip] = useState<Set<string>>(new Set());
+ const [ticked, setTicked] = useState<Set<string>>(new Set());
+ const [characters, setCharacters] = useState<{ id: string; name: string }[]>([]);
+
+ const load = useCallback(async () => {
+ const q = new URLSearchParams({ project });
+ if (find.trim()) q.set("find", find);
+ if (matchCase) q.set("case", "1");
+ if (word) q.set("word", "1");
+ if (state === "stale") q.set("stale", "1");
+ if (character) q.set("character", character);
+ const r = await fetch(`/api/report/reads?${q}`, { cache: "no-store" }).catch(() => null);
+ const j = (await r?.json().catch(() => null)) as (View & { error?: string }) | null;
+ if (!r?.ok || !j) {
+ setError(j?.error ?? "the reads could not be read");
+ return;
+ }
+ setError(null);
+ setView(j);
+ setCharacters((had) => {
+ const all = new Map(had.map((c) => [c.id, c]));
+ for (const x of j.reads) if (x.character) all.set(x.character.id, x.character);
+ return [...all.values()].sort((a, b) => a.name.localeCompare(b.name));
+ });
+ }, [project, find, matchCase, word, state, character]);
+ useEffect(() => {
+ const t = setTimeout(() => void load(), find ? 250 : 0);
+ return () => clearTimeout(t);
+ }, [load, find]);
+ // The queue fills in as each re-read lands: polled while anything waits or runs.
+ const going = !!view && (view.queue.counts.waiting > 0 || view.queue.counts.running > 0);
+ useEffect(() => {
+ if (!going) return;
+ const t = setInterval(() => void load(), 2500);
+ return () => clearInterval(t);
+ }, [going, load]);
+ // A new find or replace text: the preview is of other words now.
+ useEffect(() => setPreview(null), [find, to, matchCase, word]);
+
+ const run = async (what: () => Promise<void>) => {
+ if (busy) return;
+ setBusy(true);
+ setError(null);
+ setNotice(null);
+ try {
+ await what();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ void load();
+ }
+ };
+ const ask = (scope: "reads" | "say") => run(async () => {
+ // These reads previews the rows Find counted in this view (its filter too) -- never every match of the video.
+ const j = await post({ project, op: "preview", from: find, to, scope, case: matchCase, word, ...(scope === "reads" ? { only: reads.map((r) => r.id) } : {}) });
+ setPreview({ ...(j as object), scope } as Preview);
+ setSkip(new Set());
+ });
+ const apply = () => run(async () => {
+ if (!preview) return;
+ const only = preview.scope === "reads" ? preview.lines.map((l) => l.id).filter((id) => !skip.has(id)) : [];
+ if (preview.scope === "reads" && !only.length) throw new Error("no line is ticked");
+ // Apply goes with its preview's token: the draft changed since, and it is refused ("preview again").
+ await post({ project, op: "replace", from: find, to, scope: preview.scope, case: matchCase, word, ...(preview.scope === "reads" ? { only, token: preview.token } : {}) });
+ setNotice(preview.scope === "reads" ? `rewritten: ${only.length} read${only.length === 1 ? "" : "s"} (the shown text untouched) -- they are stale now` : `"${preview.entry.word}" is said "${preview.entry.say}" in every read of a post now -- ${preview.stale.length} read${preview.stale.length === 1 ? "" : "s"} stale`);
+ setPreview(null);
+ });
+ // UNDO: offered only while it applies (the route's replaceUndoState: the draft still as the replace left it, the
+ // entry still as Everywhere set it) -- else said why, quietly.
+ const undo = view?.undo ?? null;
+ const takeBack = () => run(async () => {
+ if (!undo?.available) return;
+ await post({ project, op: "undo" });
+ setNotice(undo.scope === "reads" ? "the replace is taken back: every line as it was" : undo.was ? `"${undo.was.word}" is said "${undo.was.say}" again, as before` : "the pronunciation entry is removed");
+ });
+
+ const reads = useMemo(() => view?.reads ?? [], [view]);
+ // What Re-read can queue: a stale read the queue can re-read (a piece from a synthesized take is re-read on the bench).
+ const queueableRow = (r: Read) => r.queueable !== false && (r.state === "stale" || r.state === "unpicked" || r.state === "none");
+ const changed = reads.filter((r) => r.state === "stale" && r.queueable !== false);
+ const toQueue = ticked.size ? [...ticked] : changed.map((r) => r.id);
+ // A tick lasts only while its row is shown and can still be re-read (a filter, a re-read landing, a replace).
+ const tickable = useMemo(() => new Set(reads.filter(queueableRow).map((r) => r.id)), [reads]);
+ useEffect(() => {
+ setTicked((t) => (([...t].every((id) => tickable.has(id))) ? t : new Set([...t].filter((id) => tickable.has(id)))));
+ }, [tickable]);
+ const reread = () => run(async () => {
+ // EXACTLY the reads the button counts -- never "every stale read of the video" (the route refuses an unscoped one).
+ const j = (await post({ project, op: "reread", only: toQueue })) as { steps?: { reads: string[] }[]; skipped?: { id: string; why: string }[] };
+ const n = (j.steps ?? []).reduce((a, s) => a + s.reads.length, 0);
+ const skipped = j.skipped ?? [];
+ const why = skipped.length ? `${skipped.length} not queued: ${skipped.map((s) => `${s.id} (${s.why})`).join(", ")}` : "";
+ setNotice(n ? `${n} line${n === 1 ? "" : "s"} queued, one item at a time, in cut order -- each joins its list unpicked${why ? ` · ${why}` : ""}` : `nothing queued${why ? `: ${why}` : ""}`);
+ setTicked(new Set());
+ });
+
+ // ---- Listen through: the newest batch's re-reads, played one after another ----
+ const queue = view?.queue ?? null;
+ const batchRows = (queue?.rows ?? []).filter((r) => r.batch === queue?.batch);
+ const byId = useMemo(() => new Map(reads.map((r) => [r.id, r])), [reads]);
+ // What a read plays: a card's reading; a post's take; a thread piece's OWN parts, one after another (never the joined take).
+ const audioOf = (item: string, t: Take): string[] => (!t ? [] : t.key ? [`/api/report/narration/audio?${new URLSearchParams({ project, card: item, key: t.key })}`] : (t.files?.length ? t.files : t.file ? [t.file] : []).map((f) => `/api/report/file?${new URLSearchParams({ project, path: f })}`));
+ const newOf = (q: QueueRow) => {
+ const r = byId.get(q.read);
+ return r ? (r.state === "unpicked" ? r.newTake : r.take) : null;
+ };
+ const player = useRef<HTMLAudioElement | null>(null);
+ const [playing, setPlaying] = useState<string | null>(null);
+ const playOne = (key: string, urls: string[], then?: () => void) => {
+ player.current?.pause();
+ if (!urls.length) return then?.();
+ const [url, ...more] = urls;
+ const a = new Audio(url);
+ player.current = a;
+ setPlaying(key);
+ a.onended = () => {
+ if (more.length) return playOne(key, more, then);
+ setPlaying(null);
+ then?.();
+ };
+ void a.play().catch(() => setPlaying(null));
+ };
+ const listenThrough = () => {
+ const list = batchRows.filter((q) => q.state === "done").map((q) => ({ key: `${q.read}:new`, urls: audioOf(q.item, newOf(q)) })).filter((x) => x.urls.length);
+ const next = (i: number) => (i < list.length ? playOne(list[i].key, list[i].urls, () => next(i + 1)) : setPlaying(null));
+ next(0);
+ };
+ const pick = (which: "new" | "old", only?: string[]) => run(async () => {
+ const j = (await post({ project, op: "pick", which, ...(only ? { only } : {}) })) as { picked?: { item: string }[] };
+ setNotice(`picked (${which === "new" ? "the new reads" : "what played before"}): ${(j.picked ?? []).map((x) => x.item).join(", ")}`);
+ });
+
+ if (!view) return <p className="text-[12px] text-muted" data-reads-loading="">{error ?? "reading…"}</p>;
+ const c = view.counts;
+ const unpickedIds = reads.filter((r) => r.state === "unpicked").map((r) => r.id);
+ const unpicked = unpickedIds.length;
+
+ return (
+ <div className="space-y-4 text-[12.5px]" data-reads={project}>
+ <div className="flex flex-wrap items-center gap-2" data-reads-filters="">
+ <span className="tabular-nums text-text-2" data-reads-counts={JSON.stringify(c)}>
+ {Object.entries(c).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(" · ") || "no reads"}
+ </span>
+ <div className="flex gap-1" role="group" aria-label="Which reads">
+ {(["all", "stale"] as const).map((s) => (
+ <button key={s} type="button" className={buttonVariants({ variant: state === s ? "pressed" : "outline", size: "sm" })} aria-pressed={state === s} aria-label={s === "all" ? "Show every read" : "Show the stale reads"} data-reads-state={s} onClick={() => setState(s)}>
+ {s === "all" ? "All" : "Stale"}
+ </button>
+ ))}
+ </div>
+ <select className="rounded border border-seam bg-transparent px-1 py-0.5" aria-label="Character" value={character ?? ""} onChange={(e) => setCharacter(e.target.value || null)} data-reads-character="">
+ <option value="">every character</option>
+ {characters.map((x) => <option key={x.id} value={x.id}>{x.name}</option>)}
+ {character && !characters.some((x) => x.id === character) && <option value={character}>{character}</option>}
+ </select>
+ </div>
+
+ <form className="flex flex-wrap items-center gap-2" onSubmit={(e) => e.preventDefault()} data-reads-find-form="">
+ <input type="search" value={find} onChange={(e) => setFind(e.target.value)} placeholder="find in what is said" aria-label="Find in spoken text" className="min-w-48 flex-1 rounded border border-seam bg-transparent px-2 py-1" data-reads-find="" />
+ <label className="flex items-center gap-1"><input type="checkbox" checked={matchCase} onChange={(e) => setMatchCase(e.target.checked)} aria-label="Match case" data-reads-case="" /> case</label>
+ <label className="flex items-center gap-1"><input type="checkbox" checked={word} onChange={(e) => setWord(e.target.checked)} aria-label="Whole word" data-reads-word="" /> whole word</label>
+ {find.trim() && (
+ <span className="tabular-nums text-text-2" data-reads-found={view.find?.matches ?? 0}>
+ {view.find?.matches ?? 0} match{view.find?.matches === 1 ? "" : "es"} in {view.find?.lines ?? 0} line{view.find?.lines === 1 ? "" : "s"} · spoken text only
+ </span>
+ )}
+ </form>
+
+ {find.trim() && (
+ <div className="flex flex-wrap items-center gap-2" data-reads-replace-form="">
+ <input type="text" value={to} onChange={(e) => setTo(e.target.value)} placeholder="say instead" aria-label="Replace with" className="min-w-48 flex-1 rounded border border-seam bg-transparent px-2 py-1" data-reads-to="" />
+ <button type="button" className={btn} disabled={busy || !view.find?.matches} onClick={() => void ask("reads")} aria-label="Replace in these reads" data-reads-scope="reads" title="the matched lines' spoken text, one undo point; the shown text untouched">These reads</button>
+ <button type="button" className={btn} disabled={busy || !to.trim() || !word} onClick={() => void ask("say")} aria-label="Add a pronunciation entry" data-reads-scope="say">Everywhere, from now on</button>
+ <span className="text-[11px] text-muted" data-reads-say-limit="">{word ? "Everywhere: whole words, every read of a post; never a card" : "Everywhere needs Whole word (a pronunciation entry is whole words)"}</span>
+ </div>
+ )}
+
+ {preview && (
+ <div className="rounded border border-seam p-2" data-reads-preview={preview.scope}>
+ {preview.scope === "reads" ? (
+ <>
+ <p className="m-0 mb-1 text-text">These reads: {preview.lines.length} line{preview.lines.length === 1 ? "" : "s"} rewritten in what is SAID, one undo point -- the shown text is never changed; nothing is read until you press Re-read</p>
+ <ul className="m-0 list-none space-y-1 p-0">
+ {preview.lines.map((l) => (
+ <li key={l.id} className="flex flex-wrap items-baseline gap-2" data-reads-preview-line={l.id}>
+ <input type="checkbox" checked={!skip.has(l.id)} onChange={(e) => setSkip((s) => { const n = new Set(s); if (e.target.checked) n.delete(l.id); else n.add(l.id); return n; })} aria-label={`Rewrite ${l.id}`} />
+ <span className="font-mono">{l.id}</span>
+ <span className="text-text-2 line-through decoration-1">{l.before}</span>
+ <span>→</span>
+ <span className="text-text">{l.after}</span>
+ {l.creates && <span className="text-[11px] text-muted">({l.creates})</span>}
+ {(preview.notes[l.item] ?? []).map((n) => <span key={n} className="text-[11px] text-doubt-text" data-reads-preview-note="">{n}</span>)}
+ </li>
+ ))}
+ {preview.skipped.map((s) => (
+ <li key={s.id} className="text-[11px] text-muted" data-reads-preview-skipped={s.id}><span className="font-mono">{s.id}</span>: not changed -- {s.why}</li>
+ ))}
+ {Object.entries(preview.refused).map(([i, es]) => (
+ <li key={i} className="text-[11px] text-doubt-text" data-reads-preview-refused={i}>{i}: refused -- {es.join("; ")} (untick it)</li>
+ ))}
+ </ul>
+ </>
+ ) : (
+ <p className="m-0 text-text" data-reads-preview-say="">
+ Everywhere, from now on: “{preview.entry.word}” said “{preview.entry.say}” in every read of a post, present and future (a pronunciation entry){preview.was ? ` -- changes the existing entry (was "${preview.was}")` : ""} -- {preview.stale.length} read{preview.stale.length === 1 ? "" : "s"} made stale{preview.stale.length ? `: ${preview.stale.map((s) => s.id).join(", ")}` : ""}
+ {preview.cards.length > 0 && <span className="block text-[11px] text-muted" data-reads-preview-cards="">cards are not said through the lexicon: use These reads for {preview.cards.join(", ")}</span>}
+ </p>
+ )}
+ <div className="mt-2 flex gap-2">
+ <button type="button" className={buttonVariants({ variant: "go", size: "sm" })} disabled={busy || (preview.scope === "reads" && Object.keys(preview.refused).some((i) => preview.lines.some((l) => l.item === i && !skip.has(l.id))))} onClick={() => void apply()} aria-label="Apply the replace" data-reads-apply="">Apply</button>
+ <button type="button" className={btn} onClick={() => setPreview(null)} aria-label="Close the preview">Close</button>
+ </div>
+ </div>
+ )}
+
+ {(notice || error || undo) && (
+ <p className="m-0 flex flex-wrap items-center gap-2" data-reads-notice="">
+ {notice && <span className="text-text-2">{notice}</span>}
+ {error && <span className="text-doubt-text" data-reads-error="">{error}</span>}
+ {undo?.available && (
+ <button type="button" className="ink-link" disabled={busy} onClick={() => void takeBack()} aria-label={undo.scope === "reads" ? "Undo the replace" : undo.was ? "Put the pronunciation entry back as it was" : "Remove the pronunciation entry"} data-reads-undo={undo.scope}>
+ {undo.scope === "reads" ? "Undo the replace" : undo.was ? `Back to "${undo.was.say}"` : "Remove the entry"}
+ </button>
+ )}
+ {undo && !undo.available && undo.why && <span className="text-[11px] text-muted" data-reads-undo-gone="">no undo of the last replace: {undo.why}</span>}
+ </p>
+ )}
+
+ <div className="flex flex-wrap items-center gap-2" data-reads-reread-bar="">
+ <button type="button" className={buttonVariants({ variant: "go", size: "sm" })} disabled={busy || !toQueue.length} onClick={() => void reread()} aria-label={`Re-read ${toQueue.length} changed line${toQueue.length === 1 ? "" : "s"}`} data-reads-reread={toQueue.length}>
+ Re-read {toQueue.length} {ticked.size ? "ticked" : "changed"} line{toQueue.length === 1 ? "" : "s"}
+ </button>
+ {unpicked > 0 && <button type="button" className={btn} disabled={busy} onClick={() => void pick("new", unpickedIds)} aria-label="Pick every new read" data-reads-pick-all="">Pick every new read ({unpicked})</button>}
+ </div>
+
+ {queue && queue.rows.length > 0 && (
+ <div className="rounded border border-seam p-2" data-reads-queue={queue.batch ?? ""}>
+ <div className="mb-1 flex flex-wrap items-center gap-2">
+ <span className="tabular-nums text-text-2" data-reads-queue-counts={JSON.stringify(queue.counts)}>{Object.entries(queue.counts).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(" · ")}</span>
+ {(queue.counts.waiting > 0) && <button type="button" className={btn} disabled={busy} onClick={() => void run(async () => { await post({ project, op: "stop" }); })} aria-label="Stop the re-reads not started" data-reads-stop="">Stop</button>}
+ {batchRows.some((q) => q.state === "done") && <button type="button" className={btn} onClick={listenThrough} aria-label="Listen through the re-read lines" data-reads-listen="">Listen through</button>}
+ </div>
+ {queue.waiting && <p className="m-0 mb-1 text-[11.5px] text-doubt-text" data-reads-waiting="">{queue.waiting}</p>}
+ <ul className="m-0 list-none space-y-1 p-0">
+ {queue.rows.map((q) => {
+ const fresh = newOf(q);
+ return (
+ <li key={`${q.batch}:${q.read}`} className="flex flex-wrap items-center gap-2" data-reads-queue-row={q.read} data-state={q.state}>
+ <span className={cn("w-16", q.state === "failed" ? "text-doubt-text" : "text-text-2")}>{q.state}</span>
+ <span className="font-mono">{q.read}</span>
+ {q.error && <span className="text-[11px] text-doubt-text" data-reads-queue-error="">{q.error}</span>}
+ {(q.state === "failed" || q.state === "stopped") && <button type="button" className="ink-link" disabled={busy} onClick={() => void run(async () => { await post({ project, op: "retry", read: q.read }); })} aria-label={`Retry ${q.read}`} data-reads-retry={q.read}>Retry</button>}
+ {q.state === "done" && q.batch === queue.batch && (
+ <>
+ <button type="button" className="ink-link" onClick={() => playOne(`${q.read}:new`, audioOf(q.item, fresh))} aria-label={`Play the new read of ${q.read}`} data-reads-play-new={q.read} data-playing={playing === `${q.read}:new` ? "1" : undefined}>▶ new</button>
+ <button type="button" className="ink-link" disabled={!q.before} onClick={() => playOne(`${q.read}:old`, audioOf(q.item, q.before))} aria-label={`Play what ${q.read} said before`} data-reads-play-old={q.read} data-playing={playing === `${q.read}:old` ? "1" : undefined}>▶ before</button>
+ <button type="button" className="ink-link" disabled={busy || byId.get(q.read)?.state !== "unpicked"} onClick={() => void pick("new", [q.read])} aria-label={`Pick the new read of ${q.read}`} data-reads-pick-new={q.read}>Pick new</button>
+ <button type="button" className="ink-link" disabled={busy || !q.before} onClick={() => void pick("old", [q.read])} aria-label={`Pick what ${q.read} said before`} data-reads-pick-old={q.read}>Pick before</button>
+ <a className="ink-link" href={playHref(project, { clip: q.item })} aria-label={`Play ${q.item} in the cut`} data-reads-play-cut={q.item}>play in the cut</a>
+ </>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ )}
+
+ <table className="w-full border-collapse" data-reads-rows={reads.length}>
+ <thead>
+ <tr className="text-left text-[11px] text-muted">
+ <th className="px-1 font-normal"><span className="sr-only">re-read</span></th>
+ <th className="px-2 font-normal">read</th>
+ <th className="px-2 font-normal">character</th>
+ <th className="px-2 font-normal">what is said</th>
+ <th className="px-2 font-normal">state</th>
+ <th className="px-2 font-normal">plays</th>
+ </tr>
+ </thead>
+ <tbody>
+ {reads.map((r) => {
+ const cell = "border-t border-seam px-2 py-1 align-top";
+ const href = r.kind === "card" ? narrationHref(project) : postBenchHref(project, r.item);
+ const url = audioOf(r.item, r.take);
+ return (
+ <tr key={r.id} data-read={r.id} data-read-state={r.state}>
+ <td className={cn(cell, "px-1")}>
+ {queueableRow(r) && (
+ <input type="checkbox" checked={ticked.has(r.id)} onChange={(e) => setTicked((s) => { const n = new Set(s); if (e.target.checked) n.add(r.id); else n.delete(r.id); return n; })} aria-label={`Re-read ${r.id}`} data-read-tick={r.id} />
+ )}
+ </td>
+ <td className={cell}>
+ <a href={href} className="ink-link font-mono" aria-label={`${r.id}'s bench`}>{r.id}</a>
+ <span className="block text-[11px] text-muted">{KIND[r.kind]}</span>
+ </td>
+ <td className={cn(cell, "text-text-2")}>{r.character?.name ?? <span className="text-muted">—</span>}</td>
+ <td className={cn(cell, "max-w-[42ch]")} data-read-spoken={r.id}>
+ <Marked text={r.spoken} matches={r.matches} />
+ {r.said && r.said !== r.spoken && <span className="block text-[11px] text-muted">said as: {r.said}</span>}
+ {r.kind === "card" && r.state === "stale" && r.because.includes("words") && <span className="block text-[11px] text-doubt-text">its words changed with the replace: Re-read makes them play</span>}
+ {r.why && <span className="block text-[11px] text-muted" data-read-why={r.id}>{r.why}</span>}
+ </td>
+ <td className={cn(cell, STATE_CLASS[r.state])} data-read-because={r.because.join(",")}>
+ {r.state}{r.because.length ? <span className="block text-[11px]">{r.because.map((b) => BECAUSE[b] ?? b).join(", ")}</span> : null}
+ </td>
+ <td className={cell}>
+ {url.length ? <button type="button" className="ink-link" onClick={() => playOne(`${r.id}:take`, url)} aria-label={`Play what ${r.id} plays now`} data-read-play={r.id}>▶ play</button> : <span className="text-muted">—</span>}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/ScreenLineVoice.tsx b/umtool/components/projects/ScreenLineVoice.tsx
@@ -2,8 +2,10 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useMic, ls } from "./useMic";
+import { readsHref } from "@/lib/hrefs";
import ReadAgain, { playNow, useAutoPlay, type Tuning } from "./read/ReadAgain";
import { useKeepForCharacter } from "./read/keepForCharacter";
+import { pieceOwnOf } from "@/lib/report/tuneAsk.mjs";
// ---------------------------------------------------------------------------
// A SCREEN LINE IN THE OPERATOR's VOICE, on the post bench's screens section (lib/report/screenLineRecord.mjs; the
@@ -185,7 +187,7 @@ export type ScreenVoice = ReturnType<typeof useScreenVoice>;
export type LineTakeOption = { id: string; label: string; current: boolean };
/** One synthesized reading of a line: the take it is in (index), its part's file, words, reading and tuning. */
-export type LineReading = { take: number; picked: boolean; file: string | null; text: string; reading: number; tuning: Tuning | null; tuningAsked?: true | "preset" };
+export type LineReading = { take: number; picked: boolean; file: string | null; text: string; reading: number; tuning: Tuning | null; tuningAsked?: true | "preset"; own?: Tuning | null };
/** The readings of a line (`role`) in an item's takes: each take whose parts read it, synthesized. */
export function lineReadings(entry: Record<string, unknown>, role: string): LineReading[] {
@@ -194,7 +196,7 @@ export function lineReadings(entry: Record<string, unknown>, role: string): Line
return (n.takes ?? []).flatMap((t, i) => {
const p = (t.parts ?? []).find((x) => x.role === role && !(x as { take?: string }).take);
const asked = (p as { tuningAsked?: unknown } | undefined)?.tuningAsked;
- return p ? [{ take: i, picked: i === pick, file: p.file ?? null, text: String(p.text ?? ""), reading: Number.isInteger(p.reading) ? (p.reading as number) : 0, tuning: p.tuning ?? null, ...(asked === true || asked === "preset" ? { tuningAsked: asked } : {}) }] : [];
+ return p ? [{ take: i, picked: i === pick, file: p.file ?? null, text: String(p.text ?? ""), reading: Number.isInteger(p.reading) ? (p.reading as number) : 0, tuning: p.tuning ?? null, ...(asked === true || asked === "preset" ? { tuningAsked: asked } : {}), own: pieceOwnOf(t, role) as Tuning | null }] : [];
});
}
@@ -249,6 +251,8 @@ export function ScreenLineVoice({ role, n, voice, dirty, options, chosen, onChoo
onReadAgain={(t) => void voice.readLine(role, t)}
onReadEdited={(t) => void voice.readLine(role, t)}
madeWith={playedLine?.tuning ?? null}
+ lineOwn={playedLine?.own ?? null}
+ staleHref={voice.project && readsAs.character ? readsHref(voice.project, { state: "stale", character: readsAs.character.id }) : null}
baseline={readsAs.baseline}
madeOwn={readsAs.madeOwn}
refreshBaseline={readsAs.refresh}
diff --git a/umtool/components/projects/VoicesPage.tsx b/umtool/components/projects/VoicesPage.tsx
@@ -2,7 +2,7 @@ import { notFound } from "next/navigation";
import AppShell from "@/components/shell/AppShell";
import VoicesPanel from "./VoicesPanel";
import { readManifest } from "@/lib/projects/report.mjs";
-import { projectHref } from "@/lib/hrefs";
+import { projectHref, readsHref } from "@/lib/hrefs";
import type { ProjectRef } from "@/lib/project-types";
// THE VOICES PAGE (operator, 6 Nov 2026: "pick different voices for different characters, and in UI alone be able
@@ -25,6 +25,7 @@ export default async function VoicesPage({ project, search = {} }: { project: Pr
active="projects"
crumbs={[{ href: "/projects", label: "Projects" }, { href: projectHref(project.id, { tab: "cut" }), label: project.name }, { label: "voices" }]}
note="each character's voice · auditions · the cast"
+ actions={<a href={readsHref(project.id)} className="ink-link text-[12px]" data-voices-reads="" aria-label="Every read of this video: find, replace, re-read">Reads</a>}
/>
<main className="deck-main flex-1 overflow-auto p-4">
<VoicesPanel project={project.id} posts={posts} initialWho={search.who ?? null} />
diff --git a/umtool/components/projects/VoicesPanel.tsx b/umtool/components/projects/VoicesPanel.tsx
@@ -3,7 +3,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
-import { jobsHref, postBenchHref } from "@/lib/hrefs";
+import { jobsHref, postBenchHref, readsHref } from "@/lib/hrefs";
import { PresetEditor, ProjectCharacters, recordedWords, type ItemCharacter, type PresetCharacter } from "./CharacterPresets";
import type { StaleRead } from "./CharacterTuning";
import { ProposedCharacters, type Proposal } from "./ProposedCharacters";
@@ -346,7 +346,8 @@ export default function VoicesPanel({ project, posts, initialWho = null }: { pro
)}
{c.stale && c.stale.length > 0 && (
<div className="text-[11px] text-doubt-text" data-voice-stale={new Set(c.stale.map((d) => d.id)).size} title={c.stale.map((d) => `${d.id} ${d.role}: made with temperature ${d.made.temperature}, top_p ${d.made.top_p}, repeat penalty ${d.made.repeat_penalty}, takes ${d.made.takes}`).join("\n")}>
- {new Set(c.stale.map((d) => d.id)).size} made with other settings
+ {new Set(c.stale.map((d) => d.id)).size} made with other settings{" · "}
+ <a href={readsHref(project, { state: "stale", character: c.character?.id ?? null })} className="ink-link" data-voice-stale-reads={c.character?.id ?? ""} aria-label={`${c.name}'s stale reads in the Reads view`}>Reads</a>
</div>
)}
</td>
diff --git a/umtool/components/projects/read/ReadAgain.tsx b/umtool/components/projects/read/ReadAgain.tsx
@@ -34,7 +34,7 @@ export type KeepForCharacter = (tuning: Tuning) => Promise<string | null>;
* from the character's (all of it when the last read was the line's own); nothing changed on a character's line sends
* none of the sampler, so the character's is asked as it is then.
*/
-export type TuneBaseline = { character: { name: string; tuning: Tuning | null } | null; madeOwn: boolean };
+export type TuneBaseline = { character: { name: string; tuning: Tuning | null } | null; madeOwn: boolean; ownTakes?: number | null };
/** Was a read the line's own? (lib/report/tuneAsk.mjs: the one rule.) */
export const madeOwnOf = (tuning: Tuning | null | undefined, tuningAsked: unknown): boolean => tuneMadeOwnOf(tuning, tuningAsked);
const NAMED: Record<string, string> = { steady: "Steady", default: "Default", lively: "Lively", custom: "custom" };
@@ -94,7 +94,7 @@ export function madeWithText(t: { reading?: number | null; tuning?: Tuning | nul
}
export default function ReadAgain({
- what = "", busy = false, waiting = null, canReadAgain = true, edited = false, onReadAgain, onReadEdited, madeWith = null, baseline = undefined, madeOwn = false, refreshBaseline, baselineError = null, onRetryBaseline, character = null, keepForCharacter, error = null, note = null, autoplay, onAutoplay,
+ what = "", busy = false, waiting = null, canReadAgain = true, edited = false, onReadAgain, onReadEdited, madeWith = null, lineOwn = null, staleHref = null, baseline = undefined, madeOwn = false, refreshBaseline, baselineError = null, onRetryBaseline, character = null, keepForCharacter, error = null, note = null, autoplay, onAutoplay,
}: {
/** What is read, in the controls' names: "" (the post), "line 2", "the thread", "the card". */
what?: string;
@@ -117,6 +117,13 @@ export default function ReadAgain({
baseline?: TuneBaseline | null;
/** Its last read was the line's own (known before the baseline is: an untouched press while it is read). */
madeOwn?: boolean;
+ /**
+ * The values its last read's LINE owned (lib/report/tuneAsk.mjs lineOwnOf: the take's `tuningOwn`, else an older
+ * take's every value when it asked true) -- a plain press passes back only these; the rest is resolved now.
+ */
+ lineOwn?: Tuning | null;
+ /** The Reads view at this character's stale reads (lane reads-find): linked beside a Keep that leaves reads stale. */
+ staleHref?: string | null;
/** The baseline as it is NOW: a press asking a sampler value of its own checks it first (review 3 #1). */
refreshBaseline?: () => Promise<TuneBaseline | null>;
/** Why the baseline could not be read, and a retry: said in place. */
@@ -133,12 +140,14 @@ export default function ReadAgain({
onAutoplay: (on: boolean) => void;
}) {
// The numbers a plain press would read with now: the line's own last numbers, else its character's, else the
- // defaults; the takes the last read's (lib/report/tuneAsk.mjs).
+ // defaults; the takes the line owned, else the character's, else the settings' (lib/report/tuneAsk.mjs).
// "Use <character>'s" (review 3 #3): the line back to its character -- the baseline as if its last read were the
// character's, until a new read lands.
const [fromCharacter, setFromCharacter] = useState(false);
- const eff: TuneBaseline | null | undefined = baseline && fromCharacter ? (characterTuneOf(madeWith, baseline).baseline as TuneBaseline) : baseline;
- const start = (): Record<string, string> => tuneStartOf({ madeWith, baseline: eff }) as Record<string, string>;
+ // The takes the line owns ride on the baseline (a press sends them back; a takes it did not own is resolved now).
+ const own = fromCharacter ? null : lineOwn;
+ const eff: TuneBaseline | null | undefined = baseline && fromCharacter ? (characterTuneOf(madeWith, baseline).baseline as TuneBaseline) : baseline ? { ...baseline, ownTakes: typeof own?.takes === "number" ? own.takes : null } : baseline;
+ const start = (): Record<string, string> => tuneStartOf({ madeWith, baseline: eff, own }) as Record<string, string>;
const [draft, setDraft] = useState<Record<string, string>>(start);
const [kept, setKept] = useState<string | null>(null);
const [keeping, setKeeping] = useState(false);
@@ -155,7 +164,7 @@ export default function ReadAgain({
setDraft(start());
setTakesTyped(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [JSON.stringify(madeWith), JSON.stringify(eff)]);
+ }, [JSON.stringify(madeWith), JSON.stringify(eff), JSON.stringify(own)]);
const edit = (next: Record<string, string>) => {
setDraft(next);
setDirty(true);
@@ -294,6 +303,9 @@ export default function ReadAgain({
)}
</div>
{kept && <span className="text-text-2" data-read-tune-kept="">{kept}</span>}
+ {kept && staleHref && / made with other settings/.test(kept) && (
+ <a href={staleHref} className="ink-link" data-read-tune-stale-reads="" aria-label={character ? `Re-read ${character.name}'s stale reads in the Reads view` : "Re-read the stale reads in the Reads view"}>Re-read them</a>
+ )}
</div>
</details>
<label className="flex items-center gap-1 text-text-2">
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -49,6 +49,9 @@ Inbox cannot disagree about what is wrong with one.
| `review-pass <project> [ls] [--json]` · `review-pass <project> mark <block> keep\|fix\|clear [--note T]` | the workspace's **review pass** (`?mode=review`): every block but the intro and a clip rejected for a cut reason, its answer and the block the pass resumes on; a Fix ("needs work", saying what) is a mark in `<project>/review-pass.json` on any block, a clip too — never a clip's verdict (`incorrect` is the bench's fact-error ruling, never written or overwritten here); a clip's Keep is its walk verdict (`window --verdict confirmed`), a post's or a card's a mark — `mark` writes one (a Fix needs `--note`; a clip takes `fix` and `clear`) ([knobs.md](knobs.md#the-review-pass)) |
| `review-pass <project> verdict like\|maybe\|no\|clear [--note T] [--json]` | the pass's **verdict on the draft**, one locked call: a draft that differs from its parent version only by what the walk and the review pass write (verdict, correction, reason, reject note, walk note, ★) judges the PARENT and saves nothing; otherwise the draft is saved as the next version and that is judged (`takes/verdicts.json`) |
| `narration <project> [<card>] [--list] [--json]` · `<card> --read [--text "…"] [--reading N|next] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n]` · `<card> --pick <key>` · `<card> [--text "…"] [--reading N] [tuning flags | --tuning-off]` | a **card's narration** and its readings ([knobs.md](knobs.md#a-cards-narration-read-again), `lib/report/cardNarrationCli.mjs`): the words a stock voice says over a card (spoken only — no card draws them), its reading and Orpheus tuning; `--read` asks the editor for one reading (a job; it waits while render mode holds the machine) and keeps it in `out/narration/` without changing the card (`--reading next`: one past the highest these words were read at); `--pick <key>` makes the card play a kept reading (its words, reading and tuning; nothing synthesized) — a verdict on the same words is kept; without either, the card's words, reading and tuning are set. The narration page's Read again, Read edited text, Tune and Pick run these. |
+| `reads <project> [--find <text> [--case] [--word]] [--stale] [--character <id>] [--json]` | **a video's reads** ([knobs.md](knobs.md#the-reads-of-a-video), `lib/report/reads.mjs`): every line a voice reads — a post's script, a thread read's pieces (his words, a parent, the quoted or a linked post), its screen lines, a card's narration — with the words it SAYS (never what is shown), where they are kept, the take that plays and its state: `fresh`, `stale` (other words, the lexicon, a character's settings — the rows `cast stale` lists — or its voice since), `unpicked` (re-read, waiting for a pick), `none`, `recorded` (yours: never stale, never re-read). An id is the item's, `<item>/<role>` for a thread piece. `--find` searches the spoken text only (`--case`, `--word`). |
+| `reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only <id>,…] [--dry-run] [--json]` · `reads <project> undo [--dry-run]` | **Replace**, two scopes, neither synthesizing and neither touching what is shown (operator ruling 3; `lib/report/readsReplace.mjs`): **these reads** rewrites the matched reads' spoken text in ONE undo point (`auto-before-reads-replace`) — a post's script (marked for reading), a screen line's said-as (made when it has none), a card's narration; a parent, the quoted or a linked post is said as shown (only `--say-only` changes it); a recorded read is never replaced; the preview names what a changed post loses (its approval, as a new script takes it), a card's review verdict given on the old words, and what the build would refuse (refused whole). **`--say-only`: everywhere, from now on** — a pronunciation entry (`posts say add`'s writer): every read of a post says it that way; whole words; never a card. `undo` takes back the newest replace -- These reads only while the draft is still exactly what it left (a re-read landing or any edit since: refused, said why), an Everywhere back to the entry it changed (its spoken form and note) or the entry it added removed; `--dry-run` says which, or why not. A flag a subcommand does not take is refused; `--` ends the flags. |
+| `reads <project> reread [--stale] [--only <id>,…] [--wait [--timeout <s>]] [--dry-run] [--json]` · `reads <project> queue [--stop] [--retry <id>] [--json]` · `reads <project> pick --new|--old [--only <id>,…] [--dry-run] [--json]` | **the re-read queue** (`lib/report/readsQueue.mjs`): the stale reads (or `--only` those) queued on the app's durable queue (`umtool queue ls`), ONE step per item in cut order, none waiting on another — `reads <p> reread --one <item> --only <ids>`, which judges the item again and runs the item's bench command (`readAgainArgv.mjs`: a post's take as the bench asks it, `--bench-slurs`; a thread piece's `--for`/`--tuned … reading:next`; a card's own reading), the tuning a plain press asks (only what the line owned). The editor's `tts-file` jobs, one at a time; render mode holds them. A re-read joins its list UNPICKED. `queue` says each row's state and, in one sentence, why they wait; `--stop` cancels what has not started; `--retry` puts one back. `pick --new` makes every unpicked re-read play, `--old` goes back to what played before (a card: its old words and reading) — one undo point. |
| `present <project> [--take <take> \| --cut] [--json] [--public] [--open] [--url <origin>]` | **present mode**: the cut as slides, navigated like a deck (`/projects/<p>/present`) — prints the address and every slide (its kind, id — a post's `<channel>/<id>`, a clip's id, `section-<n>`, `day-<YYYY-MM-DD>` — date, words and censor counts); `--json` the payload (each post's card as Play draws it and its censor data by kind, each clip's spans, the dividers); `--public` the payload a public page would carry (censored, no reveal data); `--open` opens it; `<address>#<slide id>` opens a slide ([knobs.md](knobs.md#present-mode-the-cut-as-slides-navigated-like-a-deck)) |
| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); on ANY entry (a post item, a still, a clip) `hideModules=diet,streak`, `shelfNote='…'` and `chapter='…'` (its name in the chapter list, one line of at most 100 characters; `chapter=` none); `--take <t>` writes the entry knobs into that take's patch; `key=` clears one ([knobs.md](knobs.md#marks)) |
| `intro <project> [key=value …] [--off] [--json]` · `intro <project> --take <take> --off\|--on` | **the intro** the cut opens on (`render.intro`): with no key, prints it as written, what the cut opens with (a `title-card`'s words resolved) and each version's on/off; `key=value` writes it through the look writer (`style` `seconds` 3.5–8 `mark` `ground` `sound` (`false` silent) `site` `title` `lines` (`a\|b`, ≤ 3) and the brand's keys; `key=` clears one; a new intro starts as `boot-dark`); `--off` takes it off the cut; `--take <t> --off` that version opens on no intro (its patch's `render.intro: null`), `--on` on the cut's again. **Exit 1** on a value the build refuses ([knobs.md](knobs.md#the-intro-played-and-edited)) |
@@ -137,7 +140,7 @@ Inbox cannot disagree about what is wrong with one.
| `posts progress <project> [auto\|on\|off\|default] [--json]` | the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it |
| `posts screen <project> <item> list\|add\|set\|rm\|check\|read\|record …` (add: `--media <i> [--at <from>,<to>] --kind dm\|email\|post\|text [--id <id>] [--title "…"] [--from <file>] [--line "who: words"]… [--read all\|none\|<n>,…] [--unread omit\|dim] [--ref <channel>/<postId>]` or `--from-read [--media <i>] [--kind …]`; record: `<id> <line> --recording <file> [--as <the speaker's character>] [--no-clean\|--clean] [--no-trim\|--trim] [--no-convert] [--pitch target\|source\|contour] [--semitones n] [--label l] [--check-words [--worker w]] [--events]`; set: `<id> kind= title= media= at=<a>,<b>\|off unread= ref= read=all\|none\|<n>,… read.<n>="excerpt"\|on\|off line.add="who: words" line.<n>=off line.<n>.who= line.<n>.side=left\|right\|auto line.<n>.text= line.<n>.time= line.<n>.redact=on\|off take.<n>=<take n>\|off said.<n>="…"\|off [--from <file>]`; check: `<id> [--by <name>] [--undo]`; read: `[--post-take <n>] [--line-take screen:<id>:<line>=<n>]… [--voice-for h=v]… [--reading N\|next] [tuning flags] [--for screen:<id>:<line>] [--tuned <role>=reading:N,…]… [--no-pick] [--force] [--dry-run]`; `--json`, `--dry-run`, `--take <take>`) | a post's **SCREENS** ([report-video.md](report-video.md#screens-text-screenshots-read-as-part-of-the-post), [knobs.md](knobs.md#screens-a-posts-text-screenshots), `post-screens.mjs`): the text screenshots its attachments carry -- a DM exchange or an email shown in its video (`--at`: the seconds it is visible), an image that is a screenshot -- transcribed once (`--from`: a JSON screen, or text lines `[right] who: words \| time`, `- words`, `[redact] …`), checked by a person (`check`; a screen not checked is a lint WARNING; new words take the check away), and read whole or in excerpts. Each write is the post item's one writer (`updatePostItem`'s `screens`, one undo point), refused in the build's words (**exit 1**); an attachment a screen is in cannot be removed. An e-mail address, a phone number, an order or long number in a line is masked on the card and never said. `said.<n>=` is what the voice SAYS for line n (`saidAs`: an acronym spelled out, a typo said right) -- never drawn, never the line's identity; one that says a masked shape or a redacted line is refused. `read` makes the THREAD READ with the screens (as `posts narrate <p> <item> --take --thread`): her own line from the take that plays (or the one the thread read used; `--post-take n` another), never made again; each read line in its speaker's voice (`who`: the post's author in hers, a handle or a character's name in theirs); `--line-take` takes a line from the item's take n (a recording of it), and a line's CHOSEN take (`take.<n>=`, the bench's select) is read in its place -- a recording nobody chose is named, never read in. `add --from-read`: a PICTURE-ONLY post's read (its `narration.script`) made its screen, a line per line, on its picture, read whole, NOT checked -- no speaker parsed out of it. `record`: ONE LINE in your voice ([report-video.md](report-video.md#a-line-in-your-own-voice), `lib/report/screenLineRecord.mjs`) -- the line as the read says it (its shapes and the redaction left out, an anonymous handle as its shown name), kept as new takes through `posts narrate --recording`'s chain: recorded, cleaned, converted to its SPEAKER's character's stock voice (none: kept as recorded, said), NONE picked, each carrying `screenLine`; refused on an item with no read of its own (**exit 1**). A line take is refused picked as the item's read, as `--post-take`, for another line, or once its line's words or speaker changed. `--as` may name only that character (another, or the narrator, **exit 1**). A take is a line's by its content (its screen, words and speaker), not its index. `--check-words` (the editor's transcribe op; opt-in, CLI only): refused when it is heard saying a shape or a number in words, an @handle, an anonymous author's handle or name, or a redacted term -- nothing kept -- and a warning on other words; the take keeps what it was heard saying. Without it nothing hears the recording: the lint warns for each chosen take not heard. A screen made `--from-read` is the post's read: `read` leaves his own piece out and refuses `--post-take`. Usage errors: **exit 2** |
| `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) |
-| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"] [--reading N\|next] [--no-pick]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it -- with `--reading N` it is ANOTHER READING of the same words (0 the first; Orpheus's seeds move, a new cached file) and `--temperature` `--top-p` `--top-k` `--min-p` `--repeat-penalty` `--chunk-takes` its tuning (the editor's ranges; one item's `--take` only, not `--thread` or `--all`), and the take records every tuning value and the reading it was made with; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans. |
+| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"] [--reading N\|next] [--no-pick] [--bench-slurs]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it -- with `--reading N` it is ANOTHER READING of the same words (0 the first; Orpheus's seeds move, a new cached file) and `--temperature` `--top-p` `--top-k` `--min-p` `--repeat-penalty` `--chunk-takes` its tuning (the editor's ranges; one item's `--take` only, not `--thread` or `--all`), and the take records every tuning value and the reading it was made with; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans. |
| `posts narrate <project> <item> --take --thread [--parents 0\|all\|none\|<n>] [--skip-parent <id\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s] [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--reading N\|next] [tuning flags] [--for <role>] [--tuned <role\|*>=reading:N,…]… [--no-pick] [--note "…"] [--force] [--no-hold] [--dry-run] [--json]` | a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). **`--post-take <n>`**: his OWN line is the item's take n (as `--list` numbers them) -- a recording, or one converted to his character's voice -- not synthesized; the context pieces are, in their authors' voices, and each part of the new take records where it came from (a synthesized part its parts-cache file and voice; the take's part its file and `take`: that take's id; the read's `postTake`). A thread take, or one whose file is gone: **exit 1**. A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** Its SCREENS (`posts screen`) are read after his words, each line in its speaker's voice (`--no-screens`: left out); `--line-take screen:<id>:<line>=<n>` takes a line from the item's take n as `--post-take` does his own |
| `posts say <project> [ls] [--item <id>]` · `add <word\|phrase> "<spoken>" [--case] [--item <id>] [--note "…"]` · `remove <word\|n> [--item <id>]` · `try "<text>" [--item <id>]` · `stale` `[--json]` | **THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2** |
| `posts character <project> <item> [<character> \| --clear] [--json]` | **THE CHARACTER ONE ITEM's OWN READ IS MADE WITH** (`narration.character`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the id of one of this video's own characters, else of the cast's -- its presets answer for that item before its author's handle does (the synthetic one for `--take` and a thread read, the recorded one for `--recording`). No character: the one it names and what its read resolves to now; `--clear`: by its handle again. One undoable write; no take is made. An id nobody has: **exit 2** |
@@ -214,6 +217,12 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `review-pass <project> mark <block> keep\|fix\|clear [--note NOTE]` | a block's review-pass mark: keep (a post, a card), fix (needs work, saying what; any block) or clear | form · *project* |
| `review-pass <project> verdict like\|maybe\|no\|clear [--note NOTE]` | the draft's verdict at the pass's end: its parent's when only review fields differ, else saved as a version and judged | form · *project* |
| `narration <project> [<card>] [--read] [--text TEXT] [--reading READING] [--pick PICK] [--temperature N] [--top-p N] [--top-k N] [--min-p N] [--repeat-penalty N] [--chunk-takes N] [--tuning-off] [--list]` | a card's narration: its words, reading and tuning; a reading made, or picked | form · *draft* |
+| `reads <project> [--find FIND] [--case] [--word] [--stale] [--character CHARACTER]` | every line a voice reads: what it says, the take that plays, fresh or stale; Find over the spoken text only | form · *project* |
+| `reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only ONLY] [--dry-run]` | Replace in the spoken text: these reads (one undo point), or everywhere from now on (a pronunciation entry); never the shown text, never a synthesis | form · *draft* |
+| `reads <project> undo [--dry-run]` | the newest replace taken back: These reads only while nothing was written since; an Everywhere back to the entry it changed | form · *draft* |
+| `reads <project> reread [--stale] [--only ONLY] [--wait] [--timeout N] [--one ONE] [--dry-run]` | the stale reads queued, one step per item in cut order, each the bench's own command; re-reads join unpicked | form · *project* |
+| `reads <project> queue [--stop] [--retry RETRY]` | each queued read's state and why they wait; stop what has not started, retry one | form · *project* |
+| `reads <project> pick [--new] [--old] [--only ONLY] [--dry-run]` | Pick: every unpicked re-read made the one that plays (--new), or back to what played before (--old); one undo point | form · *draft* |
| `present <project> [--take TAKE] [--cut] [--public]` | present mode's address and slides | form · *project* |
| `set <project> <clip> key=value… [--mark MARK] [--take TAKE]` | a clip's knobs: claim, marks, audio, blur, fx … | form · *draft* |
| `intro <project> [key=value…] [--off] [--take TAKE] [--on]` | the intro the cut opens on (render.intro) | form · *draft* |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -1581,6 +1581,116 @@ the tuning it was asked with).
**A pick keeps the verdict** given on the same words (the review keys a verdict by the narration's key, which a
reading moves: the pick moves the verdict with it). New words are not the words anybody approved.
+## The reads of a video
+
+Find a word across every read of a video, replace it in what is SAID, re-read only what changed, and listen
+through. No agent is needed (lane reads-find, S4 of `plans/orpheus-retune.md`; the operator's rulings of 15 Nov 2026).
+The page is `/projects/<p>/reads` (**Reads**, linked from the Voices page, the post bench, and every "made with other
+settings" line). The CLI twin is `umtool reads`, and every press runs its commands (`lib/report/readsCli.mjs`).
+
+**What is shown never changes** (operator ruling 3). That covers every card's drawn text and structure: its blocks,
+hidden paragraphs, tile modes and screens. This is pinned by `lib/report/reads-pin.test.mjs`, after a replace in
+either scope and after the queue's re-reads are picked.
+
+**A read** (`lib/report/reads.mjs`, the one model) is one of these kinds:
+- a post's script read alone;
+- a piece of a thread read: his words, a parent, the quoted post or a linked post;
+- a screen line;
+- a card's narration.
+
+Each read has the words it says *as written* (what Find searches and Replace edits), where those words are kept, the
+take that plays, and a state:
+
+| state | when |
+|---|---|
+| `fresh` | the take that plays says these words, made as a plain press would make it now |
+| `stale` | it says other **words** (the script, the said-as, the card's text, or the **lexicon**), or was made with other **settings** than its character's tuning now, or in another **voice** |
+| `unpicked` | stale, but a newer take would be fresh if picked: a re-read waiting for a Pick |
+| `none` | no synthesized take reads it yet |
+| `recorded` | yours: never stale, never re-read, never replaced |
+
+The **settings** rows are `cast.mjs tuningStale`'s own. So the bench's and the preset's "made with other settings"
+counts and `umtool cast stale` are one count.
+
+| what | where | the CLI |
+|---|---|---|
+| Find: plain text, case, whole word; marks the matches and counts matches and lines | **Find in spoken text**, **Match case**, **Whole word** | `umtool reads <p> --find <text> [--case] [--word] [--json]` |
+| the stale reads, or one character's | **Stale**, **Character** | `--stale`, `--character <id>` |
+| **These reads**, after a preview (line, before → after, each line ticked): one undo point, `auto-before-reads-replace` | **Replace with** → **These reads** → **Apply** · **Undo the replace** | `umtool reads <p> replace <from> <to> [--case] [--word] [--only <ids>] [--dry-run]` · `umtool reads <p> undo` |
+| **Everywhere, from now on**: a pronunciation entry (`posts say add`'s writer) | **Everywhere, from now on** → **Apply** · **Remove the entry** | `… replace <from> <to> --say-only [--dry-run]` · `umtool posts say <p> remove <word>` |
+| **Re-read N changed lines** (or the ticked ones) | **Re-read N changed lines** · **Stop** · **Retry** | `umtool reads <p> reread [--only <ids>] [--wait]` · `umtool reads <p> queue [--stop] [--retry <id>]` |
+| **Listen through**: each re-read, with what played before | **Listen through** · **▶ new** · **▶ before** · **play in the cut** | — |
+| **Pick** the new read or what played before; one undo point | **Pick new** · **Pick before** · **Pick every new read** | `umtool reads <p> pick --new\|--old [--only <ids>]` |
+
+### What These reads changes, kind by kind
+
+- **A post's script, or his own words in a thread read:** the item's `narration.script`. A post with no script gets
+ one, made from its words as drafted and then edited. The script is marked for reading as Save script marks it, so
+ the card follows the shown text. As a new script does today, the edit takes the item's approval away, and the
+ preview says so.
+- **A screen line:** its `screens[j].saidAs.<n>`. One is created from the line as it is read when it has none, and
+ removed when the words go back to the line as read. The line as shown (`lines[n].text`) is never touched. A said-as
+ that says what a screen masks is refused, and the whole write with it (the preview names it).
+- **A card:** `narration.text`. The card's narration review verdict was given on the old words, and the preview says
+ so. Picking its reading from before (**Pick before**) brings back its old words too.
+- **A parent, the quoted post or a linked post:** its spoken words are its shown words. It is listed as "said as
+ shown: only Everywhere changes this", and never rewritten.
+- **An item playing a take read before the rule** (unstamped, other words): the preview names it. Picking its re-read
+ moves its card to the shown-text rule.
+
+**Everywhere** matches whole words only, and never reaches a card: cards are not said through the lexicon. Both
+limits are said where the button is.
+
+**Undo** (`umtool reads <p> undo`; on the page, offered only while it applies) takes back the newest replace:
+- **These reads:** only while the draft is still exactly what the replace left. Its token and its bytes' hash are
+ kept in `<p>/narration/reads/replaces.json`. Other writers keep one undo point per op for two minutes, so a write
+ after a replace (a re-read landing, a bench edit) could otherwise be taken back with it. Such an undo is refused,
+ and the page says why.
+- **Everywhere:** puts back the entry it changed (its spoken form and its note), or removes only the entry it added
+ (by its word, case and item).
+- `--dry-run` says which, or why not.
+
+**The page acts only on what it counted.** Re-read sends the ids of the rows it counts, Pick every new read the
+unpicked ones in view, and a replace the previewed ones that are ticked. The route refuses a request with no ids,
+or one naming an id no read could have, and never narrows it to every read of the video. An unscoped re-read is the
+CLI's alone (`reread` with no `--only`). Every `umtool reads` subcommand refuses a flag it does not take, and `--`
+ends the flags.
+
+### The re-read queue
+
+The re-reads run on the umtool app's **durable queue** (`lib/queue`, `umtool queue ls`):
+- **Order:** one step per item, in cut order, none waiting on another (a failure never holds the rest).
+- **One at a time:** the queue runs one step at a time, and only while the app's own job runner is idle, so a step
+ and a bench press never run together. The bench's single-post take answers, in a sentence, while that post's
+ re-read runs.
+- **The step:** `umtool reads <p> reread --one <item> --only <ids>`. It judges the item again (a read that is no
+ longer stale is left alone), then runs in-process the command the item's bench button runs
+ (`lib/report/readAgainArgv.mjs`):
+
+| the item | its re-read |
+|---|---|
+| a post read alone | `posts narrate <p> <item> --take --reading next --no-pick [tuning] --bench-slurs` -- the bench's ask (`lib/report/postTakeAsk.mjs`), the bench's slur rule |
+| one stale piece of a thread read | exactly its line's Read again: `posts screen <p> <item> read --for <role> --reading next [tuning] --no-pick` (with screens), else `posts narrate … --take --thread <as it was read> …` |
+| several pieces | `--tuned <role>=reading:next,<tuning>` each; the others as they were read |
+| a card | `narration <p> <card> --read`: its own words, reading and tuning |
+
+- **The tuning:** the **plain press**'s (`tuneAsk.mjs plainPressAskOf`). Only the values the LINE owned are passed
+ back (a take's `tuningOwn`). The character's values and the editor's setting, `takes` included, are resolved anew,
+ so a re-read of a settings-stale read, once picked, is fresh. An older take with no `tuningOwn` owns every
+ recorded value when it asked true, and none otherwise. The known limit: an old take that owned only its takes
+ re-reads with the character's or the setting's.
+- **Synthesis:** each one is the editor's `tts-file` job on its `tts` lane, one at a time. A thread step asks one job
+ per piece it re-reads, one after another. Render mode holds them.
+- **Picks:** a re-read joins its list **unpicked** (S3's ruling). A card's re-read is what the card now says, so it
+ plays.
+- **What the page shows:** each line's state (waiting, running, done, failed with its reason, stopped). When lines
+ wait, it says why in one line: the runner is not running, render mode, a bench read of that post in flight, or
+ another step or job. The state is the batch file (`<p>/narration/reads/queue.json`) and the queue's steps, so it
+ survives a reload and a restart. A step whose app died reads failed, and Retry puts it back.
+- **Where the runner runs:** inside the umtool app's server (`instrumentation.ts`): under `next start`, the systemd
+ unit's server and the e2e suite's, unless `UMTOOL_QUEUE_RUNNER=0`. Under `next dev` it runs only with
+ `UMTOOL_QUEUE_RUNNER=1`.
+
## Pronunciation and voices (the lexicon, the voice map, a thread read)
Three plain commands do what hand-made scripts used to (operator, 4 Nov 2026: "we want the plain apps to do as much
diff --git a/umtool/e2e/character-tuning.spec.ts b/umtool/e2e/character-tuning.spec.ts
@@ -248,7 +248,8 @@ test("the post bench: Read again asks the character's Lively (\"preset\"); the T
await panel.locator('[aria-label="Read again"]').click();
await expect(panel.locator("[data-post-take]")).toHaveCount(2, { timeout: 30_000 });
expect(benchAsks().length).toBe(asked0 + 1);
- // (The Read again carries the takes its last read was made with -- S3's rule -- and the character's sampler under it.)
+ // (The Read again carries the character's sampler, and only the takes the LINE owned -- none here: they are the
+ // character's or the editor's setting, resolved now, never copied from the last read; lane reads-find.)
expect(benchAsks().at(-1)!.tuning).toMatchObject({ temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 });
expect(takesOf("p-1")[1]).toMatchObject({ tuningAsked: "preset", tuning: { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 } });
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -40,6 +40,7 @@ import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs";
import { makeUiOpsFixture } from "./ui-ops-fixture.mjs";
import { makeVoicesFixture } from "./voices-fixture.mjs";
import { makeTuningFixture } from "./tuning-fixture.mjs";
+import { makeReadsFixture } from "./reads-fixture.mjs";
import { makeRecordFilterFixture } from "./record-filter-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
@@ -1934,6 +1935,8 @@ makeUiOpsFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.joi
makeVoicesFixture({ reports, channels: CHANNELS, manifest, ff });
// A character's Orpheus tuning on the Voices page (character-tuning.spec.ts): its own character, three reads.
makeTuningFixture({ reports, manifest, ff });
+// A video's reads (reads-find.spec.ts): Find, Replace, the re-read queue, Listen through -- posts, a recorded read, a card.
+makeReadsFixture({ reports, manifest, ff });
// Record -> filter -> preview on the record page (record-filter.spec.ts): three one-part post items, no cast.
makeRecordFilterFixture({ reports, manifest });
// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
diff --git a/umtool/e2e/fixtures/reads-fixture.mjs b/umtool/e2e/fixtures/reads-fixture.mjs
@@ -0,0 +1,95 @@
+// A VIDEO's READS (reads-find.spec.ts; components/projects/ReadsPanel.tsx, lib/report/readsCli.mjs): two post items read
+// by this video's own "ferry" character (orpheus · tara), one recorded read, and a narrated card whose reading is kept
+// beside the build -- the words "north pier" in three of them, so Find counts, Replace rewrites what is SAID, and the
+// re-read queue re-reads through the suite's editor stub (no real synthesis).
+//
+// reports/reads-fixture/
+// p-1 @invented_ferry_reads picked take orpheus · tara (made with the defaults): "… the north pier …" twice
+// p-2 @invented_ferry_reads picked take orpheus · tara: no match
+// p-3 @invented_pier_reads picked take RECORDED: "… north pier …" -- found, never replaced
+// c-1 a card, its narration "… the north pier reopened." (orpheus · leo), its reading kept in out/narration/
+// p-4 @invented_ferry_reads a THREAD read: its parent (said as shown: "… north pier …"), his words, a DM screen of
+// two lines ("Is the north pier open?" -- a said-as made by a replace), each part a file of the parts cache
+//
+// Invented people, like every fixture.
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { narrationsOf } from "../../report-to-video/narration.mjs";
+import { draftScript } from "../../report-to-video/post-narration.mjs";
+import { screenLineSaid } from "../../report-to-video/post-screens.mjs";
+
+export const READS = "reads-fixture";
+export const READS_P1 = "The ferry leaves the north pier at noon.\n\nBring a coat for the north pier wind.";
+
+const write = (dir, name, doc) => {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n");
+};
+
+/** @param {{ reports: string, manifest: Function, ff: (args: string[]) => void }} o */
+export function makeReadsFixture({ reports, manifest, ff }) {
+ const dir = path.join(reports, READS);
+ const made = { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 };
+ const post = (id, handle, text, take) => ({
+ type: "post", id: `p-${id}`, post: `readsx/${id}`, platform: "x", author: handle === "invented_ferry_reads" ? "Ferry Teller" : "Pier Watch", handle, date: `2026-10-30T1${id}:00:00.000Z`, text,
+ url: `https://x.com/${handle}/status/${id}`, engagement: { likes: 1 }, section: 0,
+ narration: { script: text, takes: [{ seconds: 2, script: text, at: "2026-11-02T00:00:00.000Z", ...take }], pick: 0 },
+ });
+ const tone = (abs) => {
+ mkdirSync(path.dirname(abs), { recursive: true });
+ ff(["-f", "lavfi", "-i", "sine=frequency=262:sample_rate=48000:duration=2", "-ac", "1", "-c:a", "pcm_s16le", abs]);
+ };
+ const timeline = [
+ post("1", "invented_ferry_reads", READS_P1, { file: "narration/posts/1/take-1.orpheus-tara.wav", engine: "orpheus", voice: "tara", tuning: made, reading: 0 }),
+ post("2", "invented_ferry_reads", "The ferry fares go up in the spring.", { file: "narration/posts/2/take-1.orpheus-tara.wav", engine: "orpheus", voice: "tara", tuning: made, reading: 0 }),
+ post("3", "invented_pier_reads", "The north pier is closed today.", { file: "narration/posts/3/take-1.recorded.wav", engine: "recorded", voice: "operator" }),
+ { type: "card", id: "c-1", seconds: "auto", heading: "Later", narration: { text: "Six months later, the north pier reopened.", engine: "orpheus", voice: "leo" } },
+ threadPost(),
+ ];
+ for (const e of timeline) for (const t of e.narration?.takes ?? []) {
+ tone(path.join(dir, ...t.file.split("/")));
+ for (const x of t.parts ?? []) tone(path.join(dir, ...x.file.split("/")));
+ }
+ // p-4's picture (its screen is in it).
+ mkdirSync(path.join(dir, "posts-media", "readsx", "4"), { recursive: true });
+ ff(["-f", "lavfi", "-i", "color=c=gray:s=90x140", "-frames:v", "1", path.join(dir, "posts-media", "readsx", "4", "4_1.png")]);
+ const m = manifest(READS, "The Reads Fixture", {}, timeline);
+ write(dir, "video.manifest.json", m);
+ // The card's reading, kept beside the build as narrate-via-editor keeps it (out/narration/<key>.{wav,json}).
+ for (const n of narrationsOf(m)) {
+ const store = path.join(dir, "out", "narration");
+ tone(path.join(store, `${n.key}.wav`));
+ write(store, `${n.key}.json`, { id: n.id, key: n.key, text: n.text, engine: n.engine, voice: n.voice, speed: 1, seconds: 2, createdAt: "2026-11-02T00:00:00.000Z" });
+ }
+ write(path.join(dir, "narration"), "characters.json", {
+ format: "umtool-project-characters", version: 1,
+ characters: [{ id: "ferry", name: "Ferry Teller", handles: ["invented_ferry_reads"], synthetic: { voice: "orpheus:tara" } }],
+ });
+ return dir;
+}
+
+/** p-4: a thread read -- its parent, his words, a DM screen of two lines -- each part a file of the parts cache. */
+export function threadPost() {
+ const text = "The ferry timetable changes next week.";
+ const parent = { id: "41", handle: "invented_pier_reads", author: "Pier Watch", date: "2026-10-30T13:00:00.000Z", text: "They say the north pier will stay shut." };
+ const dm = { id: "s1", media: 0, kind: "dm", read: "all", lines: [{ who: "invented_pier_reads", text: "Is the north pier open?" }, { who: "invented_ferry_reads", text: "Not until spring." }] };
+ const parts = [];
+ let t = 0;
+ const add = (words, role, piece, more = {}) => {
+ t += parts.length ? 0.8 : 0;
+ parts.push({ n: parts.length + 1, para: piece * 100, text: words, voice: role === "post" || more.speaker === "invented_ferry_reads" ? "tara" : "leo", role, start: Math.round(t * 1000) / 1000, seconds: 2, file: `narration/parts-cache/reads-fixture-${parts.length + 1}.wav`, ...more });
+ t += 2;
+ };
+ add(draftScript(parent.text).script, "parent:0", 0);
+ add(draftScript(text).script, "post", 1);
+ dm.lines.forEach((l, n) => {
+ const said = draftScript(screenLineSaid(dm, n)).script;
+ add(said, `screen:s1:${n}`, 2 + n, { line: said, speaker: l.who });
+ });
+ return {
+ type: "post", id: "p-4", post: "readsx/4", platform: "x", author: "Ferry Teller", handle: "invented_ferry_reads", date: "2026-10-30T14:00:00.000Z", text,
+ url: "https://x.com/invented_ferry_reads/status/4", engagement: { likes: 1 }, section: 0, parents: [parent],
+ media: [{ src: "posts-media/readsx/4/4_1.png", kind: "image", width: 900, height: 1400 }], screens: [dm],
+ narration: { script: draftScript(text).script, pick: 0, takes: [{ file: "narration/posts/4/take-1.orpheus-thread.wav", engine: "orpheus", voice: "tara+leo", seconds: Math.round(t * 1000) / 1000, script: parts.map((p) => p.text).join("\n\n"), parts, read: { kind: "thread", parents: "0" }, at: "2026-11-02T00:00:00.000Z" }] },
+ };
+}
diff --git a/umtool/e2e/reads-find.spec.ts b/umtool/e2e/reads-find.spec.ts
@@ -0,0 +1,256 @@
+import { test, expect } from "@playwright/test";
+import { copyFileSync, existsSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { createHash } from "node:crypto";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+import { READS_P1 } from "./fixtures/reads-fixture.mjs";
+
+// ---------------------------------------------------------------------------
+// A VIDEO's READS (lane reads-find, S4 of plans/orpheus-retune.md; components/projects/ReadsPanel.tsx,
+// /api/report/reads, lib/report/readsCli.mjs). Fixture: e2e/fixtures/reads-fixture.mjs -- two post items read by this
+// video's "ferry" character, a recorded read, a narrated card; "north pier" in three of them. Every step a press:
+//
+// every control there (aria-labels); Find "north pier": a count of matches and of lines, spoken text only
+// Replace -> These reads: a preview (line, before -> after; the recorded read not changed), Apply -> the changed
+// rows stale, nothing synthesized, every drawn card byte-identical
+// Re-read 2 changed lines -> the app's queue runs them one at a time through the editor STUB to done: the post's
+// re-read unpicked, the card's playing; Listen through plays; Pick new -> fresh; the cards still drawn the same
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const P = "reports/reads-fixture";
+const DIR = path.join(FIXTURE, "reports", "reads-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+
+type Tts = { route: string; text?: string; voice?: string };
+const ttsAsks = () => (existsSync(STUB_LOG) ? (JSON.parse(readFileSync(STUB_LOG, "utf8")) as Tts[]) : []).filter((r) => r.route === "tts");
+const sha = (s: string) => createHash("sha1").update(s).digest("hex");
+const files = (d: string) => (existsSync(d) ? readdirSync(d, { recursive: true }).map(String).sort() : []);
+/**
+ * What the cut DRAWS: each post item's card as the reading pin hashes it (plain, following, its blocks and hidden
+ * paragraphs, its tile modes, its screens -- never its read's timing, which a new take changes), and every other entry
+ * but its narration.
+ */
+const drawn = async () => {
+ const { drawn: drawnOf } = (await import("../report-to-video/post-reading-pin.fixtures.mjs")) as unknown as { drawn: (e: unknown) => Record<string, string> };
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<Record<string, unknown>> };
+ return m.timeline.map((e) => (e.type === "post" ? drawnOf(e) : sha(JSON.stringify(Object.fromEntries(Object.entries(e).filter(([k]) => k !== "narration"))))));
+};
+const pristine = { takes: [] as string[], readings: [] as string[], parts: [] as string[] };
+
+test.beforeAll(() => {
+ if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
+ pristine.takes = files(path.join(DIR, "narration", "posts"));
+ pristine.readings = files(path.join(DIR, "out", "narration"));
+ pristine.parts = files(path.join(DIR, "narration", "parts-cache"));
+});
+const reset = () => {
+ copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
+ for (const d of ["reads", "lexicon.json"]) rmSync(path.join(DIR, "narration", d), { recursive: true, force: true });
+ rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
+ for (const f of files(path.join(DIR, "narration", "posts"))) if (!pristine.takes.includes(f) && f.endsWith(".wav")) rmSync(path.join(DIR, "narration", "posts", f), { force: true });
+ for (const f of files(path.join(DIR, "out", "narration"))) if (!pristine.readings.includes(f)) rmSync(path.join(DIR, "out", "narration", f), { force: true });
+ for (const f of files(path.join(DIR, "narration", "parts-cache"))) if (!pristine.parts.includes(f)) rmSync(path.join(DIR, "narration", "parts-cache", f), { force: true });
+};
+test.beforeEach(() => {
+ test.setTimeout(240_000);
+ reset();
+});
+test.afterAll(reset);
+
+test("Find, Replace these reads, Re-read the changed lines on the queue, Listen through, Pick -- what is shown never changes", async ({ page }) => {
+ const cardsBefore = await drawn();
+ const takesBefore = files(path.join(DIR, "narration", "posts"));
+ const asksBefore = ttsAsks().length;
+
+ await page.goto(urls.readsHref(P));
+ const panel = page.locator(`[data-reads="${P}"]`);
+ await expect(panel.locator("[data-reads-rows]")).toHaveAttribute("data-reads-rows", "8", { timeout: 30_000 });
+ // Every control, by its name.
+ for (const name of ["Find in spoken text", "Match case", "Whole word", "Show every read", "Show the stale reads", "Character"]) await expect(panel.getByLabel(name, { exact: true }).or(panel.getByRole("button", { name, exact: true })).first()).toBeVisible();
+ await expect(panel.getByRole("button", { name: "Re-read 0 changed lines" })).toBeDisabled();
+ await expect(panel.locator('[data-read="p-3"]')).toHaveAttribute("data-read-state", "recorded");
+
+ // FIND: a count of matches and of lines -- the spoken text only.
+ await panel.getByLabel("Find in spoken text").fill("north pier");
+ await expect(panel.locator("[data-reads-found]")).toHaveAttribute("data-reads-found", "6");
+ await expect(panel.locator("[data-reads-found]")).toContainText("6 matches in 5 lines · spoken text only");
+ await expect(panel.locator('[data-read="p-1"] [data-reads-match]')).toHaveCount(2);
+
+ // REPLACE, these reads: previewed first, then applied -- nothing synthesized, the shown text untouched.
+ await panel.getByLabel("Replace with").fill("northern pier");
+ await expect(panel.locator("[data-reads-say-limit]")).toContainText("Everywhere needs Whole word");
+ await panel.getByRole("button", { name: "Replace in these reads" }).click();
+ const preview = panel.locator('[data-reads-preview="reads"]');
+ await expect(preview).toBeVisible();
+ await expect(preview.locator("[data-reads-preview-line]")).toHaveCount(3);
+ await expect(preview.locator('[data-reads-preview-line="p-1"]')).toContainText("northern pier");
+ await expect(preview.locator('[data-reads-preview-line="p-4/screen:s1:0"]')).toContainText("creates its said-as (the line as shown is untouched)");
+ await expect(preview.locator('[data-reads-preview-skipped="p-3"]')).toContainText("a recorded read is yours");
+ await expect(preview.locator('[data-reads-preview-skipped="p-4/parent:0"]')).toContainText("said as shown: only Everywhere changes this");
+ // This test re-reads the post and the card; the screen line is left for the queue test below (untick it).
+ await preview.getByLabel("Rewrite p-4/screen:s1:0").uncheck();
+ expect(readFileSync(MANIFEST, "utf8")).toBe(readFileSync(`${MANIFEST}.pristine`, "utf8"));
+ await panel.getByRole("button", { name: "Apply the replace" }).click();
+ await expect(panel.locator('[data-reads-undo="reads"]')).toBeVisible();
+ expect((JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; screens?: Array<{ saidAs?: unknown }> }> }).timeline.find((e) => e.id === "p-4")?.screens?.[0].saidAs).toBeUndefined();
+ await panel.getByLabel("Find in spoken text").fill("");
+ await expect(panel.locator('[data-read="p-1"]')).toHaveAttribute("data-read-state", "stale");
+ await expect(panel.locator('[data-read="c-1"]')).toHaveAttribute("data-read-state", "stale");
+ await expect(panel.locator('[data-read="c-1"]')).toContainText("its words changed with the replace");
+ await expect(panel.locator('[data-read="p-2"]')).toHaveAttribute("data-read-state", "fresh");
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; text?: string; narration?: { script?: string; forReading?: boolean; text?: string } }> };
+ expect(m.timeline[0].narration?.script).toBe(READS_P1.replaceAll("north pier", "northern pier"));
+ expect(m.timeline[0].narration?.forReading).toBe(true);
+ expect(m.timeline[0].text).toBe(READS_P1);
+ expect(await drawn()).toEqual(cardsBefore);
+ expect(files(path.join(DIR, "narration", "posts"))).toEqual(takesBefore);
+ expect(ttsAsks().length).toBe(asksBefore);
+
+ // RE-READ the changed lines: the app's queue runs them, one at a time, through the editor stub.
+ await panel.getByRole("button", { name: "Re-read 2 changed lines" }).click();
+ await expect(panel.locator("[data-reads-queue]")).toBeVisible();
+ await expect(panel.locator('[data-reads-queue-row="p-1"]')).toHaveAttribute("data-state", "done", { timeout: 120_000 });
+ await expect(panel.locator('[data-reads-queue-row="c-1"]')).toHaveAttribute("data-state", "done", { timeout: 120_000 });
+ const asks = ttsAsks().slice(asksBefore);
+ expect(asks.some((a) => /northern pier/.test(a.text ?? "") && a.voice === "tara")).toBe(true);
+ expect(asks.some((a) => /closed today/.test(a.text ?? ""))).toBe(false);
+ // The post's re-read joined its list UNPICKED; the card's words play.
+ await expect(panel.locator('[data-read="p-1"]')).toHaveAttribute("data-read-state", "unpicked", { timeout: 20_000 });
+ await expect(panel.locator('[data-read="c-1"]')).toHaveAttribute("data-read-state", "fresh");
+ expect((JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ narration?: { pick?: number } }> }).timeline[0].narration?.pick).toBe(0);
+
+ // LISTEN THROUGH: the re-reads played one after another (the new one of p-1 first), what played before a press away.
+ await panel.getByRole("button", { name: "Listen through the re-read lines" }).click();
+ await expect(panel.locator('[data-reads-play-new="p-1"][data-playing="1"]')).toBeVisible({ timeout: 10_000 });
+ await expect(panel.getByRole("button", { name: "Play what p-1 said before" })).toBeEnabled();
+ await expect(panel.locator('[data-reads-play-cut="p-1"]')).toHaveAttribute("href", urls.playHref(P, { clip: "p-1" }));
+
+ // PICK the new read: fresh; the cards still drawn as before.
+ await panel.getByRole("button", { name: "Pick the new read of p-1" }).click();
+ await expect(panel.locator('[data-read="p-1"]')).toHaveAttribute("data-read-state", "fresh", { timeout: 20_000 });
+ expect((JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ narration?: { pick?: number } }> }).timeline[0].narration?.pick).toBe(1);
+ expect(await drawn()).toEqual(cardsBefore);
+});
+
+test("a thread read: a screen line's said-as made by a replace, its re-read a queue step through the stub, Stop and Retry, Listen through per part", async ({ page }) => {
+ const cardsBefore = await drawn();
+ await page.goto(urls.readsHref(P));
+ const panel = page.locator(`[data-reads="${P}"]`);
+ await expect(panel.locator("[data-reads-rows]")).toHaveAttribute("data-reads-rows", "8", { timeout: 30_000 });
+ await panel.getByLabel("Find in spoken text").fill("north pier");
+ await panel.getByLabel("Replace with").fill("northern pier");
+ await panel.getByRole("button", { name: "Replace in these reads" }).click();
+ await panel.getByRole("button", { name: "Apply the replace" }).click();
+ await expect(panel.locator('[data-reads-undo="reads"]')).toBeVisible();
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; screens?: Array<{ saidAs?: Record<string, string>; lines: Array<{ text: string }> }>; parents?: Array<{ text: string }> }> };
+ const e4 = m.timeline.find((e) => e.id === "p-4")!;
+ expect(e4.screens![0].saidAs).toEqual({ 0: "Is the northern pier open?" });
+ expect(e4.screens![0].lines[0].text).toBe("Is the north pier open?");
+ expect(e4.parents![0].text).toBe("They say the north pier will stay shut.");
+ await panel.getByLabel("Find in spoken text").fill("");
+ await expect(panel.locator('[data-read="p-4/screen:s1:0"]')).toHaveAttribute("data-read-state", "stale");
+ await expect(panel.locator('[data-read="p-4/parent:0"]')).toHaveAttribute("data-read-state", "fresh");
+ // Three items to re-read, queued; Stop at once: what has not started is stopped.
+ await panel.getByRole("button", { name: "Re-read 3 changed lines" }).click();
+ await panel.getByRole("button", { name: "Stop the re-reads not started" }).click();
+ await expect(panel.locator('[data-reads-queue-row][data-state="stopped"]').first()).toBeVisible({ timeout: 20_000 });
+ // Retry every stopped one; then all of them done.
+ for (const read of ["p-1", "c-1", "p-4/screen:s1:0"]) {
+ const row = panel.locator(`[data-reads-queue-row="${read}"]`);
+ if ((await row.getAttribute("data-state")) === "stopped") await panel.getByRole("button", { name: `Retry ${read}` }).click();
+ }
+ for (const read of ["p-1", "c-1", "p-4/screen:s1:0"]) await expect(panel.locator(`[data-reads-queue-row="${read}"]`)).toHaveAttribute("data-state", "done", { timeout: 120_000 });
+ // The screen line's re-read: a new take of the item, unpicked; its own part plays, not the joined read.
+ await expect(panel.locator('[data-read="p-4/screen:s1:0"]')).toHaveAttribute("data-read-state", "unpicked", { timeout: 20_000 });
+ const asks = ttsAsks().filter((a) => /northern pier open/.test(a.text ?? ""));
+ expect(asks.length).toBeGreaterThan(0);
+ await panel.getByRole("button", { name: "Play the new read of p-4/screen:s1:0" }).click();
+ await expect(panel.locator('[data-reads-play-new="p-4/screen:s1:0"][data-playing="1"]')).toBeVisible({ timeout: 10_000 });
+ const reads = (await (await page.request.get(`/api/report/reads?project=${encodeURIComponent(P)}`)).json()) as { reads: Array<{ id: string; newTake: { files: string[]; takeFile: string } | null; take: { files: string[] } }> };
+ const line = reads.reads.find((r) => r.id === "p-4/screen:s1:0")!;
+ expect(line.newTake!.files).toHaveLength(1);
+ expect(line.newTake!.files[0]).toMatch(/^narration\/parts-cache\//);
+ expect(line.newTake!.files[0]).not.toBe(line.take.files[0]);
+ await panel.getByRole("button", { name: "Pick the new read of p-4/screen:s1:0" }).click();
+ await expect(panel.locator('[data-read="p-4/screen:s1:0"]')).toHaveAttribute("data-read-state", "fresh", { timeout: 20_000 });
+ expect(await drawn()).toEqual(cardsBefore);
+});
+
+test("Everywhere, from now on: a pronunciation entry previewed, applied (the reads it makes stale), taken back", async ({ page }) => {
+ await page.goto(urls.readsHref(P));
+ const panel = page.locator(`[data-reads="${P}"]`);
+ await expect(panel.locator("[data-reads-rows]")).toHaveAttribute("data-reads-rows", "8", { timeout: 30_000 });
+ await panel.getByLabel("Find in spoken text").fill("pier");
+ await panel.getByLabel("Whole word").check();
+ await panel.getByLabel("Replace with").fill("peer");
+ await expect(panel.locator("[data-reads-say-limit]")).toContainText("never a card");
+ await panel.getByRole("button", { name: "Add a pronunciation entry" }).click();
+ const preview = panel.locator('[data-reads-preview="say"]');
+ await expect(preview).toContainText("in every read of a post, present and future");
+ await expect(preview.locator("[data-reads-preview-cards]")).toContainText("cards are not said through the lexicon");
+ await panel.getByRole("button", { name: "Apply the replace" }).click();
+ await panel.getByLabel("Find in spoken text").fill("");
+ await expect(panel.locator('[data-read="p-1"]')).toHaveAttribute("data-read-state", "stale");
+ await expect(panel.locator('[data-read="p-1"]')).toHaveAttribute("data-read-state", "stale");
+ await expect(panel.locator('[data-read="p-1"] [data-read-because]')).toHaveAttribute("data-read-because", "lexicon");
+ expect(JSON.parse(readFileSync(path.join(DIR, "narration", "lexicon.json"), "utf8"))).toEqual([{ word: "pier", say: "peer" }]);
+ await panel.getByRole("button", { name: "Remove the pronunciation entry" }).click();
+ await expect(panel.locator('[data-read="p-1"]')).toHaveAttribute("data-read-state", "fresh", { timeout: 20_000 });
+ expect(JSON.parse(readFileSync(path.join(DIR, "narration", "lexicon.json"), "utf8"))).toEqual([]);
+});
+
+test("MUST 1: a filtered view (one character's stale reads) re-reads ONLY its rows", async ({ page }) => {
+ const asksBefore = ttsAsks().length;
+ await page.goto(urls.readsHref(P));
+ const panel = page.locator(`[data-reads="${P}"]`);
+ await expect(panel.locator("[data-reads-rows]")).toHaveAttribute("data-reads-rows", "8", { timeout: 30_000 });
+ await panel.getByLabel("Find in spoken text").fill("north pier");
+ await panel.getByLabel("Replace with").fill("northern pier");
+ await panel.getByRole("button", { name: "Replace in these reads" }).click();
+ await panel.getByRole("button", { name: "Apply the replace" }).click();
+ await expect(panel.locator('[data-reads-undo="reads"]')).toBeVisible();
+ // Three stale reads now: p-1 (the ferry's), p-4's screen line (said by the pier's account: no character) and the
+ // card (no one's). The ferry's view counts one.
+ await page.goto(urls.readsHref(P, { state: "stale", character: "ferry" }));
+ await expect(panel.locator("[data-reads-rows]")).toHaveAttribute("data-reads-rows", "1", { timeout: 30_000 });
+ await expect(panel.locator('[data-read="c-1"]')).toHaveCount(0);
+ await panel.getByRole("button", { name: "Re-read 1 changed line" }).click();
+ await expect(panel.locator("[data-reads-queue-row]")).toHaveCount(1, { timeout: 20_000 });
+ await expect(panel.locator('[data-reads-queue-row="p-1"]')).toHaveAttribute("data-state", "done", { timeout: 120_000 });
+ // The card and the screen line were never asked: still stale, never synthesized.
+ const card = (await (await page.request.get(`/api/report/reads?project=${encodeURIComponent(P)}`)).json()) as { reads: Array<{ id: string; state: string }> };
+ expect(card.reads.find((r) => r.id === "c-1")?.state).toBe("stale");
+ expect(card.reads.find((r) => r.id === "p-4/screen:s1:0")?.state).toBe("stale");
+ expect(ttsAsks().slice(asksBefore).some((a) => /pier reopened/.test(a.text ?? ""))).toBe(false);
+});
+
+test("N1: a replace from a filtered view rewrites ONLY the rows its Find counted there", async ({ page }) => {
+ const before = JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; narration?: { text?: string } }> };
+ await page.goto(urls.readsHref(P, { character: "ferry" }));
+ const panel = page.locator(`[data-reads="${P}"]`);
+ await expect(panel.locator('[data-read="c-1"]')).toHaveCount(0, { timeout: 30_000 });
+ await panel.getByLabel("Find in spoken text").fill("north pier");
+ await expect(panel.locator("[data-reads-found]")).toContainText("2 matches in 1 line");
+ await panel.getByLabel("Replace with").fill("northern pier");
+ await panel.getByRole("button", { name: "Replace in these reads" }).click();
+ const preview = panel.locator('[data-reads-preview="reads"]');
+ await expect(preview.locator("[data-reads-preview-line]")).toHaveCount(1);
+ await expect(preview.locator('[data-reads-preview-line="p-1"]')).toBeVisible();
+ await panel.getByRole("button", { name: "Apply the replace" }).click();
+ await expect(panel.locator('[data-reads-undo="reads"]')).toBeVisible();
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; narration?: { text?: string; script?: string }; screens?: Array<{ saidAs?: unknown }> }> };
+ expect(m.timeline.find((e) => e.id === "p-1")?.narration?.script).toContain("northern pier");
+ expect(m.timeline.find((e) => e.id === "c-1")?.narration?.text).toBe(before.timeline.find((e) => e.id === "c-1")?.narration?.text);
+ expect(m.timeline.find((e) => e.id === "p-4")?.screens?.[0].saidAs).toBeUndefined();
+});
+
+test("the bench links here: the Voices page and a post's bench", async ({ page }) => {
+ await page.goto(urls.voicesHref(P));
+ await expect(page.locator("[data-voices-reads]").first()).toHaveAttribute("href", urls.readsHref(P));
+ await page.goto(urls.postBenchHref(P, "p-1"));
+ await expect(page.locator("[data-post-bench-reads]")).toHaveAttribute("href", urls.readsHref(P));
+});
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -299,6 +299,28 @@ export const GROUPS = [
],
},
{
+ cmd: "reads",
+ usage: [
+ " umtool reads <project> [--find <text> [--case] [--word]] [--stale] [--character <id>] [--json] A VIDEO's READS:",
+ " every line a voice reads (posts, thread pieces, screen lines, cards), what it SAYS, the take that plays,",
+ " fresh / stale / unpicked / none / recorded; --find over the spoken text only",
+ " umtool reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only <ids>] [--dry-run] THESE READS'",
+ " spoken text (one undo point; never the shown text), or --say-only EVERYWHERE (a pronunciation entry);",
+ " neither synthesizes · undo [--dry-run]: the newest replace taken back while nothing was written since",
+ " umtool reads <project> reread [--only <ids>] [--wait] the stale reads queued on the app's queue, one step per",
+ " item, each the bench's command; re-reads join unpicked · queue [--stop] [--retry <id>] · pick --new|--old",
+ " (--dry-run on reread and pick: what would be queued or picked; a flag a subcommand does not take is refused)",
+ ],
+ docs: [
+ ["`reads <project> [--find <text> [--case] [--word]] [--stale] [--character <id>] [--json]`",
+ "**a video's reads** ([knobs.md](knobs.md#the-reads-of-a-video), `lib/report/reads.mjs`): every line a voice reads — a post's script, a thread read's pieces (his words, a parent, the quoted or a linked post), its screen lines, a card's narration — with the words it SAYS (never what is shown), where they are kept, the take that plays and its state: `fresh`, `stale` (other words, the lexicon, a character's settings — the rows `cast stale` lists — or its voice since), `unpicked` (re-read, waiting for a pick), `none`, `recorded` (yours: never stale, never re-read). An id is the item's, `<item>/<role>` for a thread piece. `--find` searches the spoken text only (`--case`, `--word`)."],
+ ["`reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only <id>,…] [--dry-run] [--json]` · `reads <project> undo [--dry-run]`",
+ "**Replace**, two scopes, neither synthesizing and neither touching what is shown (operator ruling 3; `lib/report/readsReplace.mjs`): **these reads** rewrites the matched reads' spoken text in ONE undo point (`auto-before-reads-replace`) — a post's script (marked for reading), a screen line's said-as (made when it has none), a card's narration; a parent, the quoted or a linked post is said as shown (only `--say-only` changes it); a recorded read is never replaced; the preview names what a changed post loses (its approval, as a new script takes it), a card's review verdict given on the old words, and what the build would refuse (refused whole). **`--say-only`: everywhere, from now on** — a pronunciation entry (`posts say add`'s writer): every read of a post says it that way; whole words; never a card. `undo` takes back the newest replace -- These reads only while the draft is still exactly what it left (a re-read landing or any edit since: refused, said why), an Everywhere back to the entry it changed (its spoken form and note) or the entry it added removed; `--dry-run` says which, or why not. A flag a subcommand does not take is refused; `--` ends the flags."],
+ ["`reads <project> reread [--stale] [--only <id>,…] [--wait [--timeout <s>]] [--dry-run] [--json]` · `reads <project> queue [--stop] [--retry <id>] [--json]` · `reads <project> pick --new\|--old [--only <id>,…] [--dry-run] [--json]`",
+ "**the re-read queue** (`lib/report/readsQueue.mjs`): the stale reads (or `--only` those) queued on the app's durable queue (`umtool queue ls`), ONE step per item in cut order, none waiting on another — `reads <p> reread --one <item> --only <ids>`, which judges the item again and runs the item's bench command (`readAgainArgv.mjs`: a post's take as the bench asks it, `--bench-slurs`; a thread piece's `--for`/`--tuned … reading:next`; a card's own reading), the tuning a plain press asks (only what the line owned). The editor's `tts-file` jobs, one at a time; render mode holds them. A re-read joins its list UNPICKED. `queue` says each row's state and, in one sentence, why they wait; `--stop` cancels what has not started; `--retry` puts one back. `pick --new` makes every unpicked re-read play, `--old` goes back to what played before (a card: its old words and reading) — one undo point."],
+ ],
+ },
+ {
cmd: "present",
usage: [
" umtool present <project> [--take <id> | --cut] [--json] [--public] [--open] PRESENT MODE: the cut as slides,",
@@ -1104,7 +1126,7 @@ export const GROUPS = [
"a post's **SCREENS** ([report-video.md](report-video.md#screens-text-screenshots-read-as-part-of-the-post), [knobs.md](knobs.md#screens-a-posts-text-screenshots), `post-screens.mjs`): the text screenshots its attachments carry -- a DM exchange or an email shown in its video (`--at`: the seconds it is visible), an image that is a screenshot -- transcribed once (`--from`: a JSON screen, or text lines `[right] who: words \\| time`, `- words`, `[redact] …`), checked by a person (`check`; a screen not checked is a lint WARNING; new words take the check away), and read whole or in excerpts. Each write is the post item's one writer (`updatePostItem`'s `screens`, one undo point), refused in the build's words (**exit 1**); an attachment a screen is in cannot be removed. An e-mail address, a phone number, an order or long number in a line is masked on the card and never said. `said.<n>=` is what the voice SAYS for line n (`saidAs`: an acronym spelled out, a typo said right) -- never drawn, never the line's identity; one that says a masked shape or a redacted line is refused. `read` makes the THREAD READ with the screens (as `posts narrate <p> <item> --take --thread`): her own line from the take that plays (or the one the thread read used; `--post-take n` another), never made again; each read line in its speaker's voice (`who`: the post's author in hers, a handle or a character's name in theirs); `--line-take` takes a line from the item's take n (a recording of it), and a line's CHOSEN take (`take.<n>=`, the bench's select) is read in its place -- a recording nobody chose is named, never read in. `add --from-read`: a PICTURE-ONLY post's read (its `narration.script`) made its screen, a line per line, on its picture, read whole, NOT checked -- no speaker parsed out of it. `record`: ONE LINE in your voice ([report-video.md](report-video.md#a-line-in-your-own-voice), `lib/report/screenLineRecord.mjs`) -- the line as the read says it (its shapes and the redaction left out, an anonymous handle as its shown name), kept as new takes through `posts narrate --recording`'s chain: recorded, cleaned, converted to its SPEAKER's character's stock voice (none: kept as recorded, said), NONE picked, each carrying `screenLine`; refused on an item with no read of its own (**exit 1**). A line take is refused picked as the item's read, as `--post-take`, for another line, or once its line's words or speaker changed. `--as` may name only that character (another, or the narrator, **exit 1**). A take is a line's by its content (its screen, words and speaker), not its index. `--check-words` (the editor's transcribe op; opt-in, CLI only): refused when it is heard saying a shape or a number in words, an @handle, an anonymous author's handle or name, or a redacted term -- nothing kept -- and a warning on other words; the take keeps what it was heard saying. Without it nothing hears the recording: the lint warns for each chosen take not heard. A screen made `--from-read` is the post's read: `read` leaves his own piece out and refuses `--post-take`. Usage errors: **exit 2**"],
["`posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]`",
"a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**)"],
- ["`posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script \"…\"] [--pick <n>] [--approve\\|--unapprove] [--off\\|--on] [lead= tail= ramp= linger= clip=read\\|full wet= lowpass= duck=on\\|off short=hold\\|loop attach=under\\|after lufs= pace=fast\\|normal]` · `<item> --take [--note \"…\"] [--voice v] [--engine e] [--speed s] [--script \"…\"] [--reading N\\|next] [--no-pick]` · `<item> --derive <n> --op enhance\\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…`",
+ ["`posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script \"…\"] [--pick <n>] [--approve\\|--unapprove] [--off\\|--on] [lead= tail= ramp= linger= clip=read\\|full wet= lowpass= duck=on\\|off short=hold\\|loop attach=under\\|after lufs= pace=fast\\|normal]` · `<item> --take [--note \"…\"] [--voice v] [--engine e] [--speed s] [--script \"…\"] [--reading N\\|next] [--no-pick] [--bench-slurs]` · `<item> --derive <n> --op enhance\\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…`",
"a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it -- with `--reading N` it is ANOTHER READING of the same words (0 the first; Orpheus's seeds move, a new cached file) and `--temperature` `--top-p` `--top-k` `--min-p` `--repeat-penalty` `--chunk-takes` its tuning (the editor's ranges; one item's `--take` only, not `--thread` or `--all`), and the take records every tuning value and the reading it was made with; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; \"not installed\" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said \"at <handle>\", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans."],
["`posts narrate <project> <item> --take --thread [--parents 0\\|all\\|none\\|<n>] [--skip-parent <id\\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--speed s] [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--reading N\\|next] [tuning flags] [--for <role>] [--tuned <role\\|*>=reading:N,…]… [--no-pick] [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]`",
"a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the item's own character, this video's characters and voice map, the cast: `cast project`; his own: the narrator's) and at its character's speed (its synthetic preset's; `--speed`: every part at that one; Orpheus has none; a part at another speed is another cached part), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). **`--post-take <n>`**: his OWN line is the item's take n (as `--list` numbers them) -- a recording, or one converted to his character's voice -- not synthesized; the context pieces are, in their authors' voices, and each part of the new take records where it came from (a synthesized part its parts-cache file and voice; the take's part its file and `take`: that take's id; the read's `postTake`). A thread take, or one whose file is gone: **exit 1**. A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** Its SCREENS (`posts screen`) are read after his words, each line in its speaker's voice (`--no-screens`: left out); `--line-take screen:<id>:<line>=<n>` takes a line from the item's take n as `--post-take` does his own"],
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -239,6 +239,24 @@ export const VERBS = Object.freeze([
opt("--text", { type: "text" }), opt("--reading", { help: "0-99999, or next (with --read)" }), opt("--pick", { help: "a kept reading's key" }),
num("--temperature"), num("--top-p"), num("--top-k"), num("--min-p"), num("--repeat-penalty"), num("--chunk-takes"), bool("--tuning-off"), bool("--list"),
]),
+ // A video's reads (lane reads-find, lib/report/readsCli.mjs): the Reads page's twin.
+ form("reads", "project", "every line a voice reads: what it says, the take that plays, fresh or stale; Find over the spoken text only", [
+ project(), opt("--find", { type: "text", help: "plain text, searched in what is SPOKEN only" }), bool("--case", "with case"), bool("--word", "whole words"),
+ bool("--stale", "the stale and the unpicked"), opt("--character", { help: "one character's (its id)" }),
+ ]),
+ form("reads replace", "draft", "Replace in the spoken text: these reads (one undo point), or everywhere from now on (a pronunciation entry); never the shown text, never a synthesis", [
+ project(), arg("from", { type: "text", help: "the words to find" }), arg("to", { type: "text", help: "what to say instead" }), bool("--case", "with case"), bool("--word", "whole words"),
+ bool("--say-only", "everywhere, from now on: a pronunciation entry (whole words; never a card)"), opt("--only", { help: "these read ids only, comma separated" }), dry(),
+ ], { shape: "reads <project> replace <from> <to>" }),
+ form("reads undo", "draft", "the newest replace taken back: These reads only while nothing was written since; an Everywhere back to the entry it changed", [project(), dry()], { shape: "reads <project> undo" }),
+ form("reads reread", "project", "the stale reads queued, one step per item in cut order, each the bench's own command; re-reads join unpicked", [
+ project(), bool("--stale", "every stale read (the default)"), opt("--only", { help: "these read ids only, comma separated" }), bool("--wait", "until they end"), num("--timeout", { help: "--wait's limit, s" }),
+ opt("--one", { help: "one queue step's item (the umtool app runs it)" }), dry(),
+ ], { shape: "reads <project> reread" }),
+ form("reads queue", "project", "each queued read's state and why they wait; stop what has not started, retry one", [project(), bool("--stop", "cancel what has not started"), opt("--retry", { help: "a failed or stopped read's id" })], { shape: "reads <project> queue" }),
+ form("reads pick", "draft", "Pick: every unpicked re-read made the one that plays (--new), or back to what played before (--old); one undo point", [
+ project(), bool("--new", "the new reads"), bool("--old", "what played before"), opt("--only", { help: "these read ids only, comma separated" }), dry(),
+ ], { shape: "reads <project> pick" }),
form("present", "project", "present mode's address and slides", [project(), takeOpt({ help: "that take's cut (default the latest)" }), bool("--cut", "the manifest alone"), bool("--public", "as a public page would carry it")]),
form("set", "draft", "a clip's knobs: claim, marks, audio, blur, fx …", [project(), clip(), pairs({ help: "key=value, one per line (claim.at=190.2, audio.gain=-3, `key=` clears)" }), opt("--mark", { help: "the mark the claim.* keys set" }), takeOpt()], B(["clip"], { clip: "{id}" })),
form("intro", "draft", "the intro the cut opens on (render.intro)", [project(), pairs({ required: false, help: "key=value, one per line (style=boot-dark, seconds=4); none: print it" }), bool("--off", "take the intro off"), takeOpt({ help: "a version: --off opens it on no intro, --on on the cut's" }), bool("--on")], B(["intro"], {})),
diff --git a/umtool/lib/cli/verbs.test.mjs b/umtool/lib/cli/verbs.test.mjs
@@ -35,6 +35,7 @@ const SUBVERBS = [
{ cmd: "posts", file: "lib/report/postsCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g },
{ cmd: "trailer-beats", file: "lib/report/trailerBeatsCli.mjs", re: /\bverb === "([a-z][a-z-]*)"|case "([a-z][a-z-]*)":/g },
{ cmd: "cast", file: "lib/report/castCli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g, ignore: ["help", "remove"] },
+ { cmd: "reads", file: "lib/report/readsCli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g },
{ cmd: "queue", file: "lib/queue/cli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g },
{ cmd: "notes", file: "lib/annotations/cli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g, ignore: ["help"] },
{ cmd: "rulings", file: "lib/report/rulingsCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g },
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -494,6 +494,11 @@ export function presentHref(project: string, q: { take?: string | null; bare?: b
return workspaceHref(project, { mode: "present", take: q.take ?? null, slide: q.slide ?? null });
}
+/** A video's READS (lane reads-find): every line a voice reads, Find / Replace, the re-read queue -- filtered by state or character. */
+export function readsHref(project: string, q: { state?: "stale" | null; character?: string | null } = {}): string {
+ return withQuery(`/projects/${encodePath(project)}/reads`, { ...(q.state ? { state: q.state } : {}), ...(q.character ? { character: q.character } : {}) });
+}
+
/** The narration script, card by card. */
export function narrationHref(project: string, q: NoteOpt = {}): string {
return withQuery(`/projects/${encodePath(project)}/narration`, {}, q.note);
diff --git a/umtool/lib/report/benchQueueParity.test.mjs b/umtool/lib/report/benchQueueParity.test.mjs
@@ -0,0 +1,98 @@
+// THE QUEUE's READ IS THE BENCH's (lane reads-find, the orchestrator's ruling 3): a post's read made by the re-read
+// queue (makeTake with the bench's slur rule) asks the editor EXACTLY what the bench's take op asks
+// (postTakeAsk.mjs: the one module both build from) -- the slur case included: a cut that beeps a slur has it left
+// out of a bench read, and out of the queue's. Temp dirs, a stub tts, invented people.
+import "./noLiveEditor.mjs";
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+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 { makeTake } from "./postNarrationCli.mjs";
+import { askBody, benchTakeAskOf } from "./postTakeAsk.mjs";
+import { projectRedaction } from "./postRedaction.mjs";
+
+const LIST = JSON.parse(readFileSync(new URL("../../report-to-video/slurs.json", import.meta.url), "utf8"));
+const F = LIST.entries.find((e) => e.id === "f-slur").word;
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-bench-parity-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+
+const item = (o = {}) => ({ 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: "post one", ...o });
+async function project(name, timeline, render = {}) {
+ const dir = path.join(ROOT, name, "p");
+ await mkdir(dir, { recursive: true });
+ await mkdir(path.join(ROOT, name, ".umtool"), { recursive: true });
+ await writeFile(path.join(ROOT, name, ".umtool", "cast.json"), JSON.stringify({ format: "umtool-cast", version: 2, characters: [{ id: "ferry", name: "Ferry Teller", handles: ["invented_ferry"], synthetic: { voice: "orpheus:tara", tuning: { temperature: 0.75 } } }] }));
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, render: { width: 1920, height: 1080, fps: 30, postNarration: { engine: "orpheus", voice: "zac" }, ...render }, timeline }, null, 2));
+ return { id: name, dir };
+}
+const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+const asker = (asked) => async (body) => {
+ asked.push(body);
+ await mkdir(path.dirname(body.out), { recursive: true });
+ await writeFile(body.out, encodeWav16(withSilence(syntheticVoice({ ...VOICE_B, seconds: 0.6 }), { before: 0.1, after: 0.1 })));
+ return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice } };
+};
+/** The bench's take op's body for one press: through the route's OWN builder (benchTakeAskOf, from the POST's body). */
+async function benchBody(p, press) {
+ const m = await manifest(p);
+ const e = m.timeline[0];
+ const red = await projectRedaction(p.dir, m);
+ const a = await benchTakeAskOf(p, e, { manifest: m, script: String(press.script ?? e.narration.script), body: { ...(press.speed !== undefined ? { speed: press.speed } : {}) }, tuning: press.tuning ?? null, reading: press.reading ?? null, red });
+ return askBody(a, "OUT");
+}
+async function queueBody(p, press) {
+ const asked = [];
+ const r = await makeTake(p, (await manifest(p)).timeline[0], { ask: asker(asked), benchSlurs: true, keepPick: true, ...press, askOp: async () => { throw new Error("the queue's read is never word-timed"); } });
+ assert.equal(asked.length, 1, "one ask, never a second for a beep");
+ return { body: { ...asked[0], out: "OUT" }, take: r.take };
+}
+
+test("the same press, the same ask: the character's tuning, the line's own over it, a reading", async () => {
+ for (const [name, press] of [["plain", {}], ["own", { tuning: { temperature: 0.9, takes: 5 } }], ["reading", { reading: 2 }]]) {
+ const p = await project(`same-${name}`, [item({ narration: { script: "The ferry runs at noon." } })]);
+ const want = await benchBody(p, press);
+ const got = await queueBody(p, press);
+ assert.deepEqual(got.body, want, name);
+ }
+});
+
+test("THE SLUR CASE: a cut that beeps -- the bench leaves the slur out, and so does the queue's read (no word timing)", async () => {
+ const script = `Hello, you ${F}. Welcome.`;
+ const p = await project("beep", [item({ narration: { script } })], { posts: { slurs: { voice: "beep" } } });
+ const want = await benchBody(p, {});
+ assert.equal(want.text, "Hello, you. Welcome.");
+ const got = await queueBody(p, {});
+ assert.deepEqual(got.body, want);
+ assert.equal(got.take.slurs, "skip");
+ assert.equal(got.take.words, undefined);
+});
+
+// REVIEW 1, a nit: the UNTUNED bench ask is byte-identical to the one the route made before this lane -- its keys in
+// their order, a speed only when it is a number (never NaN, never 0), none for Orpheus.
+test("the untuned bench ask, byte for byte as before: Orpheus (no speed), Kokoro with the item's speed, a speed that is no number", async () => {
+ const p = await project("bytes", [item({ narration: { script: "The ferry runs at noon." } })]);
+ // No character for a handle that is not the cast's: the narrator, Orpheus zac.
+ const m = await manifest(p);
+ const e = { ...m.timeline[0], handle: "invented_nobody" };
+ const red = await projectRedaction(p.dir, m);
+ const old = (spoken, engine, voice, speed, tuning, reading) => JSON.stringify({ text: spoken, engine, voice, out: "OUT", ...(speed ? { speed } : {}), ...(tuning ? { tuning } : {}), ...(reading !== null ? { reading } : {}) });
+ // `old` is the pre-lane route's own body expression (4e42b042f, app/api/report/post-narration/route.ts:460), and the
+ // literals below are what it made for these asks: the pin holds both.
+ let a = await benchTakeAskOf(p, e, { manifest: m, script: e.narration.script, body: {}, red });
+ assert.equal(JSON.stringify(askBody(a, "OUT")), old("The ferry runs at noon.", "orpheus", "zac", undefined, null, null));
+ assert.equal(JSON.stringify(askBody(a, "OUT")), '{"text":"The ferry runs at noon.","engine":"orpheus","voice":"zac","out":"OUT"}');
+ const k = { ...e, narration: { ...e.narration, engine: "kokoro", voice: "af_heart", speed: 1.1 } };
+ a = await benchTakeAskOf(p, k, { manifest: m, script: k.narration.script, body: {}, red });
+ assert.equal(JSON.stringify(askBody(a, "OUT")), old("The ferry runs at noon.", "kokoro", "af_heart", 1.1, null, null));
+ assert.equal(JSON.stringify(askBody(a, "OUT")), '{"text":"The ferry runs at noon.","engine":"kokoro","voice":"af_heart","out":"OUT","speed":1.1}');
+ a = await benchTakeAskOf(p, k, { manifest: m, script: k.narration.script, body: { speed: "fast" }, red });
+ assert.equal(JSON.stringify(askBody(a, "OUT")), old("The ferry runs at noon.", "kokoro", "af_heart", undefined, null, null), "a speed that is no number is left out");
+ assert.equal(JSON.stringify(askBody(a, "OUT")), '{"text":"The ferry runs at noon.","engine":"kokoro","voice":"af_heart","out":"OUT"}');
+ a = await benchTakeAskOf(p, k, { manifest: m, script: k.narration.script, body: { speed: 0 }, red });
+ assert.equal(JSON.stringify(askBody(a, "OUT")), '{"text":"The ferry runs at noon.","engine":"kokoro","voice":"af_heart","out":"OUT"}', "a speed of 0 is left out, as the route left it");
+});
diff --git a/umtool/lib/report/cardNarrationCli.mjs b/umtool/lib/report/cardNarrationCli.mjs
@@ -78,6 +78,19 @@ export function nextCardReading(readings, text) {
/** A reading as a line: its key, words, reading, tuning, length -- and whether the card plays it. */
const readingLine = (r, current) => ` ${r.key === current ? "▶" : " "} ${r.key.slice(0, 12)} ${Number(r.seconds).toFixed(2)} s reading ${readingOfRecord(r)}${r.askedTuning ? ` ${Object.entries(r.askedTuning).map(([k, v]) => `${k} ${v}`).join(", ")}` : ""} "${spacing(r.text).slice(0, 70)}"`;
+/**
+ * A VERDICT ON THESE WORDS IS KEPT (lane line-rerun ruling; `narration --pick` and `reads pick`, one rule): the review
+ * keys a verdict by the narration's key, which a reading moves -- a verdict given on the card as it played (`nowKey`,
+ * its key before the pick), on the same words, moves to the reading picked (`rec`). Returns `{ kept, row }`.
+ */
+export async function keepCardVerdict(projectDir, cardId, { nowKey, rec }) {
+ const { readNarrationReview, setNarrationReview } = await import("umtool-report-to-video/narration-review");
+ const row = (await readNarrationReview(projectDir)).rows?.[cardId];
+ const kept = !!row?.verdict && row.key === nowKey && spacing(row.text) === spacing(rec.text);
+ if (kept) await setNarrationReview(projectDir, cardId, { verdict: row.verdict, key: rec.key, text: rec.text });
+ return { kept, row };
+}
+
/** `umtool narration <project> …` */
export async function cardNarrationCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), narrate = null } = {}) {
const flags = new Map();
@@ -146,12 +159,7 @@ export async function cardNarrationCommand(args, { root = REPORTS_ROOT, out = (s
const want = resolveNarration({ ...e, narration: { ...e.narration, text: patch.text, reading: patch.reading ?? undefined, tuning: patch.tuning ?? undefined } }, manifest.render);
if (narrationKey(want) !== rec.key) throw new NarrateError(`${cardId}: reading ${rec.key.slice(0, 12)} was made with another voice or speed than the card's now -- read it again (--read)`);
const { result } = await write(patch);
- // A VERDICT ON THESE WORDS IS KEPT (lane line-rerun ruling): the review keys a verdict by the narration's key,
- // which a reading moves -- a verdict given on the card as it played, on the same words, moves with the pick.
- const { readNarrationReview, setNarrationReview } = await import("umtool-report-to-video/narration-review");
- const row = (await readNarrationReview(project.dir)).rows?.[cardId];
- const kept = !!row?.verdict && row.key === now.key && spacing(row.text) === spacing(rec.text);
- if (kept) await setNarrationReview(project.dir, cardId, { verdict: row.verdict, key: rec.key, text: rec.text });
+ const { kept, row } = await keepCardVerdict(project.dir, cardId, { nowKey: now.key, rec });
if (json) out(JSON.stringify({ ok: true, id: cardId, key: rec.key, narration: result.entry.narration, verdictKept: kept, token: result.token ?? null }, null, 2));
else out(`${cardId}: plays reading ${readingOfRecord(rec)} (${rec.key.slice(0, 12)})${kept ? ` -- still ${row.verdict} (the same words)` : ""}`);
return 0;
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -2959,6 +2959,12 @@ const POST_REF_FIELDS = Object.freeze(["id", "author", "handle", "badge", "date"
* @param {{ token?: string | null }} [opts]
*/
export async function updatePostItem(dir, id, patch, { token = null } = {}) {
+ postItemPatchCheck(patch);
+ return structural(dir, "post-item", token, (m) => postItemIn(m, id, patch));
+}
+
+/** A post item patch's keys checked (updatePostItem, postItemIn): throws naming one that is no knob. */
+function postItemPatchCheck(patch) {
if (!isObj(patch)) throw new Error("a post item's patch is an object");
for (const k of Object.keys(patch)) {
if (!["media", "mediaAdd", "mediaHide", "mediaShow", "quoted", "parents", "links", "linksAdd"].includes(k) && !POST_ITEM_KNOBS.includes(k)) throw new Error(`${k} is not a post item knob (${[...POST_ITEM_KNOBS, "media", "mediaAdd", "mediaHide", "mediaShow", "quoted", "parents", "links", "linksAdd"].join(", ")})`);
@@ -2967,7 +2973,17 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) {
// whole between `media` and `mediaOff` (post-item.mjs), its knobs kept -- alone in its write, so no index moves under it.
const toggles = ["mediaHide", "mediaShow"].filter((k) => k in patch);
if (toggles.length && Object.keys(patch).length !== toggles.length) throw new Error("mediaHide / mediaShow go alone in a write");
- return structural(dir, "post-item", token, (m) => {
+ return toggles;
+}
+
+/**
+ * ONE POST ITEM's KNOBS, changed in place (`m` the manifest inside a write) -- updatePostItem's mutation, and the one a
+ * write of several items runs for each (lane reads-find: a replace over a video's reads, one undo point). Refused in
+ * the build's words, as updatePostItem is.
+ */
+export function postItemIn(m, id, patch) {
+ const toggles = postItemPatchCheck(patch);
+ {
const i = entryIndex(m.timeline, id);
const e = m.timeline[i];
if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`);
@@ -3153,7 +3169,7 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) {
if (now.length) throw new StructureRefused(now);
}
return { id, at: i, entry: e };
- });
+ }
}
/**
@@ -3574,7 +3590,9 @@ export async function updatePostNarration(dir, id, patch, { token = null } = {})
*/
export async function updatePostNarrations(dir, patches, { token = null, op = "post-narration" } = {}) {
if (!Array.isArray(patches) || !patches.length) throw new Error("nothing to change");
- return structural(dir, op, token, (m) => ({ ids: patches.map((p) => postNarrationIn(m, p.id, p.patch).id) }));
+ // A script among them is a spoken edit like the single writer's (lane reads-find, ruling 3): marked for reading when
+ // it is not the post's words as drafted (the import's scripts; a drafted script is not an edit, so it is unmarked).
+ return structural(dir, op, token, (m) => ({ ids: patches.map((p) => postNarrationIn(m, p.id, p.patch, { forReading: true }).id) }));
}
/**
@@ -4473,7 +4491,17 @@ export async function updateNarration(dir, id, text, { token = null, at = null }
export async function updateCardNarration(dir, id, patch, { token = null } = {}) {
if (!isObj(patch) || !Object.keys(patch).length) throw new Error("a card narration patch is { text?, reading?, tuning? }");
for (const k of Object.keys(patch)) if (!["text", "reading", "tuning"].includes(k)) throw new Error(`${k} is not a card narration's (text, reading, tuning)`);
- return structural(dir, "narration", token, (m) => {
+ return structural(dir, "narration", token, (m) => cardNarrationIn(m, id, patch));
+}
+
+/**
+ * ONE CARD's NARRATION changed in place (`m` the manifest inside a write): updateCardNarration's mutation, and the one a
+ * write of several reads runs for each card (lane reads-find). Refused in the build's words.
+ */
+export function cardNarrationIn(m, id, patch) {
+ if (!isObj(patch) || !Object.keys(patch).length) throw new Error("a card narration patch is { text?, reading?, tuning? }");
+ for (const k of Object.keys(patch)) if (!["text", "reading", "tuning"].includes(k)) throw new Error(`${k} is not a card narration's (text, reading, tuning)`);
+ {
const e = m.timeline[entryIndex(m.timeline, id)];
if (e.type !== "card" || !e.narration || typeof e.narration !== "object") throw new Error(`${id} is not a card with a narration`);
const before = JSON.stringify(e.narration);
@@ -4489,7 +4517,7 @@ export async function updateCardNarration(dir, id, patch, { token = null } = {})
const errors = validateNarration({ render: m.render, timeline: [e] });
if (errors.length) throw new StructureRefused(errors);
return { id, entry: e, changed: before !== JSON.stringify(e.narration) };
- });
+ }
}
/**
@@ -5219,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/noLiveEditor.mjs b/umtool/lib/report/noLiveEditor.mjs
@@ -0,0 +1,19 @@
+// NO TEST REACHES A LIVE EDITOR (lane reads-find, 17 Nov 2026: a unit run's read fell through to the operator's running
+// editor). Imported FIRST by a test (or a scratch script), before any module that could ask the editor: the editor's
+// address is set to one that cannot answer (the discard port on loopback) and the token to none -- so no tts, no lane
+// hold, no job can be asked of a real editor, and editor/.env's token is never read (agentToken takes the empty one
+// set here). Then it CHECKS what the modules that ask the editor would resolve, and throws when either still points
+// anywhere real: a test that needs an editor brings a stub of its own (an injected ask), never a port.
+//
+// Plain ESM, side effects only.
+import { editorConfig } from "./fetchWindows.mjs";
+import { editorLanes } from "./renderMode.mjs";
+
+export const DEAD_EDITOR = "http://127.0.0.1:9";
+process.env.ARCHILYZER_EDITOR_URL = DEAD_EDITOR;
+process.env.WORKER_TOKEN = "";
+process.env.UMTOOL_URL = "http://127.0.0.1:9";
+
+const cfg = editorConfig(process.env);
+if (cfg.url !== DEAD_EDITOR || cfg.token !== "") throw new Error(`noLiveEditor: the editor resolves to ${cfg.url}${cfg.token ? " with a token" : ""} -- a test must never reach a real editor`);
+if (editorLanes(cfg) !== null) throw new Error("noLiveEditor: the editor's lanes would be held -- a test must never reach a real editor");
diff --git a/umtool/lib/report/plainPressFresh.test.mjs b/umtool/lib/report/plainPressFresh.test.mjs
@@ -0,0 +1,100 @@
+// A RE-READ COMES BACK FRESH (lane reads-find, the orchestrator's ruling 2): a plain press passes back only the values
+// the LINE owned (`tuningOwn`); the character's and the settings' -- takes included -- are resolved now. The character's
+// takes change -> its read is stale -> a plain press re-reads it -> picked -> fresh. A line that owned its takes keeps
+// them. No editor (a stub tts); temp dirs; invented people.
+import "./noLiveEditor.mjs";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+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 { tuningStale } from "umtool-report-to-video/cast";
+import { makeTake } from "./postNarrationCli.mjs";
+import { resolverFor } from "./castProject.mjs";
+import { manifestToken, updatePostNarration } from "./manifest.mjs";
+import { lineOwnOf, madeOwnOf, plainPressAskOf } from "./tuneAsk.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-plain-press-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+const LIVELY = { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 };
+const NO_RED = { terms: [], markup: {}, slurs: null };
+const wavOf = async (file) => {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...VOICE_B, seconds: 0.6 }), { before: 0.1, after: 0.1 })));
+};
+/** The editor's answer: what was asked over the defaults, the setting's 3 takes when none was asked. */
+const stubAsk = (asked) => async (body) => {
+ asked.push(body);
+ await wavOf(body.out);
+ return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice, tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3, ...(body.tuning ?? {}) }, reading: body.reading ?? 0 } };
+};
+const castDoc = (tuning) => ({ format: "umtool-cast", version: 2, characters: [{ id: "ferry", name: "Ferry Teller", handles: ["invented_ferry"], synthetic: { voice: "orpheus:tara", tuning } }] });
+const ITEM = { type: "post", id: "p-7", post: "ferry-x/7", platform: "x", author: "Ferry Teller", handle: "invented_ferry", date: "2026-10-02T10:00:00.000Z", text: "Here is what they sent.", narration: { script: "Here is what they sent." } };
+
+async function project(name, cast) {
+ const root = path.join(ROOT, name);
+ const dir = path.join(root, "p");
+ await mkdir(path.join(dir, "narration"), { recursive: true });
+ await mkdir(path.join(root, ".umtool"), { recursive: true });
+ await writeFile(path.join(root, ".umtool", "cast.json"), JSON.stringify(cast, null, 1));
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, render: { width: 1920, height: 1080, fps: 30, postNarration: { engine: "orpheus", voice: "zac" } }, timeline: [ITEM] }, null, 2));
+ return { id: name, dir, root };
+}
+const read = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+const setCast = (p, cast) => writeFile(path.join(p.root, ".umtool", "cast.json"), JSON.stringify(cast, null, 1));
+/** The bench's untouched Read again, as its ask is built (ReadAgain: the Tune's start, the line's own values). */
+const plainPress = (take, characterTuning) => plainPressAskOf({ madeWith: take.tuning ?? null, baseline: { character: { name: "Ferry Teller", tuning: characterTuning }, madeOwn: madeOwnOf(take.tuning, take.tuningAsked) }, own: lineOwnOf(take) });
+const pick = async (p, n) => updatePostNarration(p.dir, "p-7", { pick: n }, { token: await manifestToken(p.dir) });
+
+test("the character's takes change: its read is stale; a plain press re-reads it with the takes resolved now; picked, it is fresh", async () => {
+ const p = await project("takes-change", castDoc(LIVELY));
+ const asked = [];
+ const first = (await makeTake(p, (await read(p)).timeline[0], { ask: stubAsk(asked), redaction: NO_RED })).take;
+ assert.equal(first.tuningAsked, "preset");
+ assert.equal(first.tuning.takes, 3, "made with the editor's setting");
+ assert.equal("tuningOwn" in first, false, "the line owned nothing");
+ // The character names 4 takes now: stale.
+ const now = { ...LIVELY, takes: 4 };
+ await setCast(p, castDoc(now));
+ assert.deepEqual(tuningStale(await read(p), resolverFor({ cast: castDoc(now) }), { settingTakes: 3 }).map((r) => r.id), ["p-7"]);
+ // A plain press asks nothing of its own: the character's 4 takes are resolved now, not the last read's 3.
+ const ask = plainPress(first, now);
+ assert.equal(ask, null);
+ const again = (await makeTake(p, (await read(p)).timeline[0], { ask: stubAsk(asked), redaction: NO_RED, tuning: ask, keepPick: true })).take;
+ assert.deepEqual(asked.at(-1).tuning, now);
+ assert.equal(again.tuning.takes, 4);
+ // Not picked yet: still stale (what plays is the old read). Picked: fresh.
+ assert.equal(tuningStale(await read(p), resolverFor({ cast: castDoc(now) }), { settingTakes: 3 }).length, 1);
+ await pick(p, 1);
+ assert.deepEqual(tuningStale(await read(p), resolverFor({ cast: castDoc(now) }), { settingTakes: 3 }), []);
+});
+
+test("a line that owned its takes keeps them through a plain press (tuningOwn), the sampler still the character's", async () => {
+ const p = await project("takes-own", castDoc(LIVELY));
+ const asked = [];
+ const own = (await makeTake(p, (await read(p)).timeline[0], { ask: stubAsk(asked), redaction: NO_RED, tuning: { takes: 5 } })).take;
+ assert.deepEqual(own.tuningOwn, { takes: 5 });
+ assert.equal(own.tuningAsked, "preset");
+ const now = { ...LIVELY, takes: 4 };
+ await setCast(p, castDoc(now));
+ const ask = plainPress(own, now);
+ assert.deepEqual(ask, { takes: 5 });
+ const again = (await makeTake(p, (await read(p)).timeline[0], { ask: stubAsk(asked), redaction: NO_RED, tuning: ask, keepPick: true })).take;
+ assert.equal(again.tuning.takes, 5);
+ assert.deepEqual(again.tuningOwn, { takes: 5 });
+ assert.equal(again.tuning.temperature, 0.75, "the character's sampler");
+ // REVIEW 1, SHOULD 3: a value the line owns is never judged against the character's -- picked, it is fresh (it was
+ // stale for ever before: 5 takes against the character's 4, passed back on every press).
+ await pick(p, 1);
+ assert.deepEqual(tuningStale(await read(p), resolverFor({ cast: castDoc(now) }), { settingTakes: 3 }), []);
+ assert.deepEqual(tuningStale(await read(p), resolverFor({ cast: castDoc({ ...LIVELY, temperature: 0.4, takes: 4 }) }), { settingTakes: 3 }).map((r) => r.id), ["p-7"], "the sampler it does not own is still judged");
+});
+
+test("an older take (no tuningOwn) asked true owns every recorded value; one recorded \"preset\" owns none (the known limit)", () => {
+ const made = { temperature: 0.9, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 5 };
+ assert.deepEqual(plainPress({ tuning: made, tuningAsked: true }, LIVELY), { temperature: 0.9, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 5 });
+ assert.equal(plainPress({ tuning: { ...LIVELY, top_k: 50, min_p: 0, takes: 5 }, tuningAsked: "preset" }, LIVELY), null);
+});
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -48,7 +48,7 @@ export const NARRATE_USAGE = [
"usage: umtool posts narrate <project> --import [--dry-run] [--json]",
" umtool posts narrate <project> --list [--json]",
" umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]",
- " [--reading N|next] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n] [--no-pick]",
+ " [--reading N|next] [--temperature t] [--top-p p] [--top-k k] [--min-p m] [--repeat-penalty r] [--chunk-takes n] [--no-pick] [--bench-slurs]",
" [--pick <n>] [--approve|--unapprove] [--off|--on] [lead=… tail=… ramp=… linger=… clip=read|full",
" wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=… pace=fast|normal] [--json]",
" umtool posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean|--clean] [--no-trim|--trim] [--no-convert]",
@@ -102,7 +102,8 @@ export const NARRATE_USAGE = [
" Orpheus's TUNING for this read, any of them, the rest its defaults. The take records the tuning (every value) and",
" the reading it was made with. Kokoro and eSpeak NG ignore both (the editor says so). One item's --take only, not",
" --all. --reading next: one past the highest reading these words were read at (0 for new words). --no-pick: the",
- " new take joins the list unpicked (--pick <n> makes it the one; the bench's Read again does this).",
+ " new take joins the list unpicked (--pick <n> makes it the one; the bench's Read again does this). --bench-slurs:",
+ " the bench's slur rule (a cut that beeps has the slur left out, not word-timed): what `umtool reads … reread` asks.",
" With --thread: the whole read's, every synthesized piece read anew (next: each one past its own highest); --for",
" <role> (post, quoted, parent:<i>, linked:<i>, screen:<id>:<line>) one piece's only, the others from the cache;",
" --tuned <role|*>=reading:N,temperature:t,… (repeatable) each piece's exactly (what a read's `read.tuned` says).",
@@ -376,19 +377,23 @@ export async function transcriptionLaneHeld() {
}
}
-export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, tuning = null, reading = null, keepPick = false, render = {}, emit = () => {}, editor = null, ask = null, askOp = null, redaction = undefined, laneHeld = null, timingDeadlineMs = BEEP_TIMING_DEADLINE_MS } = {}) {
- const k = postNarrationKnobs(e, render);
+export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, tuning = null, reading = null, keepPick = false, render = {}, emit = () => {}, editor = null, ask = null, askOp = null, redaction = undefined, laneHeld = null, timingDeadlineMs = BEEP_TIMING_DEADLINE_MS, benchSlurs = false } = {}) {
const words = String(script ?? e.narration?.script ?? "").trim();
if (!words) throw new NarrateError(`${e.id} has no script to read (--script "…", or --all --draft-scripts)`);
- // The voice his own read is said in: the one asked for, the item's own character, the project's characters and voice
- // map, the CAST, the narrator's (readVoice.mjs).
- const { itemReadVoice } = await import("./readVoice.mjs");
- const said0 = await itemReadVoice(project, e, { render, engine, voice });
- const eng = said0.engine;
- const vox = said0.voice;
- // Its speed: the one asked for (--speed), else the item's own (`narration.speed`: set on this one item), else its
- // character's (the synthetic preset's that answered for the voice).
- const spd = speed ?? e.narration?.speed ?? said0.speed ?? null;
+ // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's
+ // filter has it (post-slurs.mjs: skipped, its stand-in, or said for a beep), and each word of the project's
+ // pronunciation lexicon said its way (post-say.mjs) -- the script itself is kept as written.
+ const red = redaction !== undefined ? redaction : await projectRedaction(project.dir, (await readManifest(project.dir)) ?? {});
+ // THE ASK (postTakeAsk.mjs, the one the bench's take op builds too; lane reads-find): the voice his own read is said
+ // in (the one asked for, the item's own character, the project's characters and voice map, the CAST, the
+ // narrator's), its speed (the one asked for, else the item's own, else its character's), its tuning (the line's own
+ // values over its character's, field by field; a character with no tuning: the ask as it always was) and what is
+ // said. `benchSlurs` (the re-read queue): the bench's slur rule -- a beep left out, as a bench press leaves it.
+ const { askBody, benchSlurVoice, postTakeAskOf } = await import("./postTakeAsk.mjs");
+ const A = await postTakeAskOf(project, e, { render, script: words, engine, voice, speed, tuning, reading, red, slurVoice: benchSlurs ? benchSlurVoice(red) : undefined });
+ const eng = A.engine;
+ const vox = A.voice;
+ const spd = A.speed;
const pid = postIdOf(e);
const dir = path.join(project.dir, ...takesDirOf(pid).split("/"));
await mkdir(dir, { recursive: true });
@@ -397,24 +402,10 @@ export async function makeTake(project, e, { script = null, note = null, engine
const rel = takeFileOf(pid, n, eng, vox);
const out = path.join(project.dir, ...rel.split("/"));
const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts;
- // What the voice SAYS: the script with every redacted term left out (post-redact.mjs), each slur as the cut's
- // filter has it (post-slurs.mjs: skipped, its stand-in, or said for a beep), and each word of the project's
- // pronunciation lexicon said its way (post-say.mjs) -- the script itself is kept as written.
- const red = redaction !== undefined ? redaction : await projectRedaction(project.dir, (await readManifest(project.dir)) ?? {});
- const said = spokenRead(words, e, red);
- // Its tuning and reading (--reading, --temperature, …): sent only when asked -- an ask without them is the one it always was.
- // ITS CHARACTER's TUNING (lane character-tuning): the synthetic preset's that answered for the voice, asked when the
- // line asks none of its own (the line's beats it; an engine with no sampler is asked none of the character's). A
- // character with no tuning: the ask, and the take, as they always were.
- // Field by field: the line's own values over the character's (post-say.mjs tuningAskOf, the thread read's rule too).
- const { tuningAskOf } = await import("umtool-report-to-video/post-say");
- const ta = tuningAskOf({ own: tuning, preset: said0.tuning ?? null, engine: eng });
- const asked = ta.tuning;
- const tuningAsked = ta.asked;
- const ttsBody = (text) => ({
- text, engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}),
- ...(asked ? { tuning: asked } : {}), ...(reading !== null ? { reading } : {}),
- });
+ const said = A.said;
+ const tuningAsked = A.tuningAsked;
+ const ta = { own: A.tuningOwn };
+ const ttsBody = (text) => askBody(A, out, text);
let { jobId, result } = await askTts(ttsBody(said.text), { ...(editor ? { editor } : {}), emit });
if (result?.note) emit("note", { message: `${e.id}: ${result.note}` });
if (!(await stat(out).catch(() => null))?.isFile()) throw new NarrateError(`the editor's job ${jobId} finished but ${rel} is not there (its result names ${result?.wav ?? "no file"})`);
@@ -464,6 +455,8 @@ export async function makeTake(project, e, { script = null, note = null, engine
...tunedOfResult(result),
// Where that tuning came from: its line's own (true) or its character's ("preset": stale when that changes).
...(tuningAsked ? { tuningAsked } : {}),
+ // The line's own values as asked (lane reads-find): what a plain press passes back; none owned, no key.
+ ...(ta.own ? { tuningOwn: ta.own } : {}),
// What its audio does with the slurs the script holds (post-slurs.mjs), and its words when timed for a beep.
...(slurs ? { slurs } : {}), ...(timed ? { words: timed } : {}),
// The pronunciation entries it said (post-say.mjs; `umtool posts say <p> stale` reads them).
@@ -591,7 +584,7 @@ async function timeTakeWords(project, rel, script, { askOp = null, emit = () =>
}
/** `umtool posts narrate …` (postsCli.mjs routes it here). */
-export async function narrateCommand(project, words, flags, { json = false, dryRun = false, out = (s) => console.log(s), str, multi = () => [], ask = null }) {
+export async function narrateCommand(project, words, flags, { json = false, dryRun = false, out = (s) => console.log(s), str, multi = () => [], ask = null, tts = null }) {
const manifest = await readManifest(project.dir);
if (!manifest) throw new NarrateError(`${project.id} has no manifest`);
const render = manifest.render ?? {};
@@ -851,6 +844,8 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
screens: !flags.has("--no-screens"), lineTakes: lineTakesOf(multi("--line-take")),
// Its readings and tunings (lane line-rerun): the whole read's, one piece's (--for), each piece's (--tuned).
tuned: threadTunedOf(tuned, { str, multi }), keepPick: flags.has("--no-pick"), events: flags.has("--events"),
+ // The editor's tts op as the caller hands it (postsCommand's `tts`: a test's stub) -- the lanes then never held.
+ ...(tts ? { ask: tts, lanes: null } : {}),
});
}
if (str("--post-take") !== null) throw new NarrateError("--post-take is a thread read's (umtool posts narrate <p> <item> --take --thread --post-take <n>)");
@@ -864,6 +859,10 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
const r = await makeTake(project, e, {
script: str("--script"), note: str("--note"), engine: str("--engine"), voice: str("--voice"),
speed: speedFlag(str), ...(asked ? { tuning: asked.tuning, reading: asked.reading } : {}), keepPick, render, emit: (_ev, f) => !json && f?.message && out(f.message),
+ // --bench-slurs (the re-read queue's): the bench's slur rule -- a beep left out, as a bench press leaves it.
+ benchSlurs: flags.has("--bench-slurs"),
+ // The editor's tts op as the caller hands it (postsCommand's `tts`: a test's stub).
+ ...(tts ? { ask: tts, laneHeld: async () => false } : {}),
});
if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, picked: !keepPick, narration: r.result.narration, token: r.result.token }, null, 2));
else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), ${keepPick ? "not picked (--pick to play it)" : "picked"}${r.take.note ? ` — note: ${r.take.note}` : ""}${tunedLabel(asked)}`);
diff --git a/umtool/lib/report/postNarrationsForReading.test.mjs b/umtool/lib/report/postNarrationsForReading.test.mjs
@@ -0,0 +1,46 @@
+// A SCRIPT WRITTEN BY THE SEVERAL-ITEMS WRITER IS MARKED FOR READING TOO (lane reads-find; operator ruling 3): the
+// import (`posts narrate --import`, narration/posts/index.json) sets a script through updatePostNarrations, and a script
+// that is not the post's words as drafted must leave the card on the shown text -- as the single writer does
+// (postNarrationIn's forReading). Pinned with the reading pin's hashes: the card draws what it drew before.
+import "./noLiveEditor.mjs";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { manifestToken, updatePostNarrations } from "./manifest.mjs";
+import { scriptEditOf } from "umtool-report-to-video/post-item";
+import { PINNED_SHAS, drawn, singleItem } from "../../report-to-video/post-reading-pin.fixtures.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-narrations-for-reading-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+
+async function project(timeline) {
+ const dir = path.join(ROOT, "p");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: "p", title: "p", render: { width: 1920, height: 1080, fps: 30 }, timeline }, null, 2));
+ return dir;
+}
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+
+test("updatePostNarrations: an edited script (no take yet) is marked for reading, and the card draws as it did", async () => {
+ const { narration: _n, ...bare } = singleItem();
+ void _n;
+ const dir = await project([bare]);
+ const edited = "The council met on Tuesday about the new bridge, the B R I D G E.\n\nNobody from the ministry came to explain the delay.";
+ await updatePostNarrations(dir, [{ id: bare.id, patch: { script: edited } }], { token: await manifestToken(dir), op: "post-narration-import" });
+ const e = (await read(dir)).timeline[0];
+ assert.equal(e.narration.forReading, true);
+ assert.equal(scriptEditOf(e), "reading");
+ const d = drawn(e);
+ assert.equal(d.plain, PINNED_SHAS.single.plain);
+ assert.equal(d.blocks, drawn({ ...e, narration: { ...e.narration, script: singleItem().narration.script } }).blocks);
+});
+
+test("updatePostNarrations: a script that says the post's words as drafted is not marked; other patches are as before", async () => {
+ const dir = await project([singleItem()]);
+ await updatePostNarrations(dir, [{ id: "p-7003", patch: { script: singleItem().narration.script } }, { id: "p-7003", patch: { character: "teller" } }], { token: await manifestToken(dir) });
+ const e = (await read(dir)).timeline[0];
+ assert.equal("forReading" in e.narration, false);
+ assert.equal(e.narration.character, "teller");
+});
diff --git a/umtool/lib/report/postScreensCli.mjs b/umtool/lib/report/postScreensCli.mjs
@@ -254,7 +254,7 @@ export function screenListing(e, sc) {
* `umtool posts screen <p> <item> <verb> …`. `project` is resolved; `rest` the words after the project
* (`<item> <verb> [<id>] [pairs…]`); `opt` the posts command's flags and helpers.
*/
-export async function screenCommand(project, rest, { flags, str: flag, multi, json = false, out = (s) => console.log(s), dryRun = false }) {
+export async function screenCommand(project, rest, { flags, str: flag, multi, json = false, out = (s) => console.log(s), dryRun = false, tts = null }) {
const [ref, verb, ...words] = rest;
if (!ref || !verb || flags.has("--help")) {
out(SCREEN_USAGE);
@@ -406,6 +406,8 @@ export async function screenCommand(project, rest, { flags, str: flag, multi, js
// Its readings and tunings (lane line-rerun): the flags' (--reading, the tuning flags, --for, --tuned), over the
// playing read's -- each piece's kept while it says the same words.
tuned: threadTunedOf(tuningFlags(flag), { str: flag, multi }), inherit: playingTuned(e), keepPick: flags.has("--no-pick"), events: flags.has("--events"),
+ // The editor's tts op as the caller hands it (postsCommand's `tts`: a test's stub) -- the lanes then never held.
+ ...(tts ? { ask: tts, lanes: null } : {}),
});
}
if (verb === "record") {
diff --git a/umtool/lib/report/postTakeAsk.mjs b/umtool/lib/report/postTakeAsk.mjs
@@ -0,0 +1,72 @@
+// ONE POST's TAKE, AS ASKED OF THE EDITOR (lane reads-find, the orchestrator's ruling 3: the queue's read of a post is
+// the same ask a bench press makes): the voice (readVoice.mjs: the one asked for, the item's own character, the
+// project's characters and voice map, the cast, the narrator), the speed (the one asked for, the item's own, the
+// character's; none for Orpheus), the tuning (post-say.mjs tuningAskOf: the line's own values over the character's,
+// field by field, and whose it is) and what the voice SAYS (post-redact.mjs spokenRead: the redaction, the slurs, the
+// lexicon, an anonymous handle as its shown name). The bench's take op (app/api/report/post-narration) and
+// `umtool posts narrate <p> <item> --take` (makeTake) both build their ask here; the re-read queue asks through
+// makeTake with the bench's slur rule, so the two can never drift apart.
+//
+// THE SLURS: the bench cannot word-time a take as it is made, so a cut that BEEPS a slur has it left out of a bench
+// read (`benchSlurVoice`); the CLI's own --take says it and times its words for the beep (makeTake).
+//
+// Plain ESM: the CLI runs it under bare node.
+import { postNarrationKnobs } from "umtool-report-to-video/post-narration";
+import { spokenRead } from "umtool-report-to-video/post-redact";
+import { tuningAskOf } from "umtool-report-to-video/post-say";
+
+/** The slur filter's voice for a read made on the bench (and by the re-read queue): a beep falls back to skip. */
+export const benchSlurVoice = (red) => (red?.slurs?.voice === "beep" ? "skip" : undefined);
+
+/**
+ * THE ASK: `{ engine, voice, speed, speedAsked, tuning, tuningAsked, tuningOwn, reading, said }` -- `said` spokenRead's
+ * result; askBody makes the editor's tts op body of it. `speed`/`tuning`/`reading` are the press's own (null: none);
+ * `slurVoice` the slur rule (benchSlurVoice for a bench read; undefined: the cut's own).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} e
+ * @param {{ render?: Record<string, any>, script: string, engine?: string | null, voice?: string | null, speed?: number | null,
+ * tuning?: Record<string, number> | null, reading?: number | null, red: any, slurVoice?: string }} o
+ */
+export async function postTakeAskOf(project, e, { render = {}, script, engine = null, voice = null, speed = null, tuning = null, reading = null, red, slurVoice = undefined }) {
+ const k = postNarrationKnobs(e, render);
+ const { itemReadVoice } = await import("./readVoice.mjs");
+ const v = await itemReadVoice(project, e, { render, engine, voice });
+ const eng = String(v.engine ?? k.engine);
+ const vox = String(v.voice ?? k.voice);
+ // Its speed: the press's, else the item's own (`narration.speed`), else its character's -- none for Orpheus.
+ const asked = speed ?? e.narration?.speed ?? v.speed ?? null;
+ // A speed only when it is a number other than 0 (a falsy or NaN one left out, as the bench always left it).
+ const n = asked === null || asked === undefined || eng === "orpheus" ? null : Number(asked);
+ const spd = n !== null && Number.isFinite(n) && n ? n : null;
+ const speedAsked = spd === null ? undefined : speed !== null && speed !== undefined ? true : e.narration?.speed != null ? "item" : "preset";
+ // Its tuning: the line's own values over its character's, field by field; whose it is; the line's own as asked.
+ const ta = tuningAskOf({ own: tuning, preset: v.tuning ?? null, engine: eng });
+ const said = spokenRead(script, e, red, slurVoice ? { voice: slurVoice } : {});
+ return { engine: eng, voice: vox, speed: spd, speedAsked, tuning: ta.tuning, tuningAsked: ta.asked, tuningOwn: ta.own, reading: reading ?? null, said };
+}
+
+/** The editor's tts op body of an ask, writing `out` (`text`: other words than the ask's, e.g. a slur left out). */
+export const askBody = (a, out, text = a.said.text) => ({
+ text, engine: a.engine, voice: a.voice, out, ...(a.speed !== null ? { speed: a.speed } : {}),
+ ...(a.tuning ? { tuning: a.tuning } : {}), ...(a.reading !== null ? { reading: a.reading } : {}),
+});
+
+/**
+ * THE BENCH's TAKE OP's ASK (app/api/report/post-narration, op "take"): from the POST's body -- its engine and voice
+ * when named, its speed when given -- with the press's tuning and reading (checked by the route) and the bench's slur
+ * rule. The route builds with this; the parity test compares the queue's read with it.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} e
+ * @param {{ manifest: any, script: string, body: Record<string, unknown>, tuning?: Record<string, number> | null, reading?: number | null, red: any }} o
+ */
+export function benchTakeAskOf(project, e, { manifest, script, body, tuning = null, reading = null, red }) {
+ return postTakeAskOf(project, e, {
+ render: manifest?.render ?? {}, script,
+ engine: typeof body.engine === "string" && body.engine ? body.engine : null,
+ voice: typeof body.voice === "string" && body.voice ? body.voice : null,
+ speed: body.speed === undefined || body.speed === null ? null : Number(body.speed),
+ tuning, reading: reading === null || reading === undefined ? null : Number(reading), red, slurVoice: benchSlurVoice(red),
+ });
+}
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -448,10 +448,12 @@ export async function addPostFromArchive(project, { slug, postId, attach = null,
/**
* @param {string[]} args the words after `posts`
- * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, ask?: Function | null, tts?: Function | null }} [opts]
+ * `ask` the editor's voice ops (a recording's chain); `tts` the editor's tts op for every READ made here (`narrate
+ * --take`, `--take --thread`, `screen … read`; askEditorTts's shape) -- a test's stub, the editor's lanes then never held
* @returns {Promise<number>} the exit code
*/
-export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), ask = null } = {}) {
+export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), ask = null, tts = null } = {}) {
// A TAKE-SCOPED EDIT (`--in-take <take>`, takeScope.mjs): the same command over the take's manifest, written into its patch.
let scoped;
try {
@@ -500,7 +502,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
err(SCREEN_USAGE);
return 2;
}
- return await screenCommand(await projectOf(projectArg, root), words.slice(2), { flags, str, multi, json, out, dryRun });
+ return await screenCommand(await projectOf(projectArg, root), words.slice(2), { flags, str, multi, json, out, dryRun, tts });
}
if (verb === "set-item" && projectArg && ref && !flags.has("--help")) return await setItemCommand(projectArg, ref, words.slice(3), { root, json, out, reread: !flags.has("--no-reread") });
if (verb === "reread") {
@@ -559,7 +561,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
const named = words.slice(3).find((w) => takes.has(w));
if (named) throw new CliError(`posts narrate: --take makes a NEW READ (TTS); "${named}" is a take of ${project.id} -- to edit take ${named}, say --in-take ${named}`);
}
- return await narrateCommand(project, words.slice(2), flags, { json, dryRun, out, str, multi, ask });
+ return await narrateCommand(project, words.slice(2), flags, { json, dryRun, out, str, multi, ask, tts });
}
if (verb === "fx") {
const { FX_USAGE, fxCommand } = await import("./postFxCli.mjs");
diff --git a/umtool/lib/report/postsTtsSeam.test.mjs b/umtool/lib/report/postsTtsSeam.test.mjs
@@ -0,0 +1,44 @@
+// THE TTS SEAM OF THE READ COMMANDS (lane reads-find, a finding of 17 Nov 2026): `postsCommand`'s `tts` (askEditorTts's
+// shape) reaches EVERY read the posts commands make -- `narrate <item> --take`, `--take --thread`, and `screen <item>
+// read` -- and with it the editor's lanes are never held. Before, the screen read (and the narrate paths) ignored the
+// caller's stub and asked the editor at its address. Temp dirs, a stub tts, invented people; noLiveEditor first.
+import "./noLiveEditor.mjs";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { postsCommand } from "./postsCli.mjs";
+import { readManifestOf, readsProject, wavOf } from "./reads.fixtures.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-tts-seam-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+const stubAsk = (asked) => async (body) => {
+ asked.push(body);
+ await wavOf(body.out);
+ return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice, tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }, reading: body.reading ?? 0 } };
+};
+const run = (p, args, asked) => postsCommand(args, { root: p.root, tts: stubAsk(asked), out: () => {}, err: () => {} });
+
+test("screen … read takes the injected tts: every piece it synthesizes is asked of the stub, none of an editor", async () => {
+ const p = await readsProject(ROOT, "screen");
+ const asked = [];
+ assert.equal(await run(p, ["screen", "p", "p-2", "read", "--for", "screen:s1:1", "--reading", "next", "--no-pick"], asked), 0);
+ assert.ok(asked.length >= 1);
+ assert.ok(asked.some((b) => /Not this year/.test(b.text)));
+ const e = (await readManifestOf(p)).timeline[1];
+ assert.equal(e.narration.takes.length, 2, "a new take, unpicked");
+ assert.equal(e.narration.pick, 0);
+});
+
+test("narrate --take and --take --thread take it too", async () => {
+ const p = await readsProject(ROOT, "narrate");
+ const asked = [];
+ assert.equal(await run(p, ["narrate", "p", "p-1", "--take", "--reading", "next", "--no-pick", "--bench-slurs"], asked), 0);
+ assert.equal(asked.length, 1);
+ assert.equal((await readManifestOf(p)).timeline[0].narration.takes.length, 2);
+ const before = asked.length;
+ assert.equal(await run(p, ["narrate", "p", "p-2", "--take", "--thread", "--no-screens", "--tuned", "post=reading:next", "--no-pick"], asked), 0);
+ assert.ok(asked.length > before);
+});
diff --git a/umtool/lib/report/readAgainArgv.mjs b/umtool/lib/report/readAgainArgv.mjs
@@ -0,0 +1,89 @@
+// THE WORDS OF A RE-READ (lane reads-find, the orchestrator's ruling 3: the queue's read is the bench's): the umtool
+// argv a bench button runs to read a line again -- the screen line's and the thread's Read again (the post-narration
+// route's screen-read and thread-read ops), and the re-read queue's step for an item (readsQueue.mjs), built from the
+// same pieces so the two can never drift apart. Pure.
+//
+// a card `narration <p> <card> --read`: its own words, reading and tuning (what its Play makes)
+// a post read alone `posts narrate <p> <item> --take --reading next --no-pick [tuning flags] --bench-slurs` -- the
+// bench's take op, as the CLI asks it (postTakeAsk.mjs: one ask), its slur rule the bench's
+// a thread read `posts screen <p> <item> read …` with screens, else `posts narrate <p> <item> --take --thread
+// <as the read that plays was asked> …`: ONE stale piece exactly as its line's Read again
+// (`--for <role> --reading next [tuning flags] --no-pick`), several each `--tuned
+// <role>=reading:next,<its tuning>` -- the others from the cache, as they were read
+//
+// The tuning a re-read asks is the PLAIN PRESS's (tuneAsk.mjs plainPressAskOf, carried by the read as `ask`): only
+// what the line owned; the character's and the settings' are resolved anew (ruling 2).
+//
+// Plain ESM.
+import { parseTtsTuning, ttsReadingError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
+import { threadArgvOf } from "./castProject.mjs";
+
+/** Each tuning field's flag (readTuning.mjs TUNING_FLAGS, the other way round). */
+export const TUNING_FLAG_OF = Object.freeze({ temperature: "--temperature", top_p: "--top-p", top_k: "--top-k", min_p: "--min-p", repeat_penalty: "--repeat-penalty", takes: "--chunk-takes" });
+const ROLE_RE = /^(post|quoted|parent:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/;
+
+/** A tuning as flags (`--temperature 0.7 …`), in the fields' order. */
+export function tuningFlagsOf(tuning) {
+ const a = [];
+ for (const [k, flag] of Object.entries(TUNING_FLAG_OF)) if (typeof tuning?.[k] === "number") a.push(flag, String(tuning[k]));
+ return a;
+}
+
+/**
+ * A READ AGAIN's words for the CLI (the post-narration route's screen-read / thread-read ops; lane line-rerun):
+ * `--for`, `--reading`, the tuning flags, `--no-pick`. Throws a sentence for a body it refuses.
+ * @param {Record<string, unknown>} body
+ */
+export function readAgainArgv(body) {
+ const a = [];
+ if (body.for !== undefined && body.for !== null) {
+ if (typeof body.for !== "string" || !ROLE_RE.test(body.for)) throw new Error("for must name one piece of the read (screen:<id>:<line>, post, quoted, parent:<i>)");
+ a.push("--for", body.for);
+ }
+ if (body.reading !== undefined && body.reading !== null) {
+ if (body.reading !== "next") {
+ const err = ttsReadingError(body.reading);
+ if (err) throw new Error(err);
+ }
+ a.push("--reading", String(body.reading));
+ }
+ if (body.tuning !== undefined && body.tuning !== null) {
+ const t = parseTtsTuning(body.tuning);
+ if (!t.ok) throw new Error(t.error);
+ for (const [k, v] of Object.entries(t.value)) a.push(TUNING_FLAG_OF[k], String(v));
+ }
+ if (a.includes("--for") && !a.includes("--reading") && !Object.values(TUNING_FLAG_OF).some((f) => a.includes(f))) throw new Error("for goes with a reading or a tuning");
+ if (body.keepPick === true || body.op === "thread-read") a.push("--no-pick");
+ return a;
+}
+
+/** One piece's `--tuned` value: the next reading, and the tuning a plain press asks (`ask`). */
+const tunedOf = (role, ask) => `${role}=${["reading:next", ...Object.entries(ask ?? {}).filter(([k, v]) => k in TUNING_FLAG_OF && typeof v === "number").map(([k, v]) => `${k}:${v}`)].join(",")}`;
+
+/**
+ * THE RE-READ OF ONE ITEM's stale reads (`reads`: reads.mjs rows of that item, each with its plain press's `ask`) as
+ * the umtool argv its bench button runs. `e` the item as the manifest has it.
+ * @param {string} projectId
+ * @param {Record<string, any>} e
+ * @param {Array<{ kind: string, role: string | null, ask?: Record<string, number> | null }>} reads
+ */
+export function itemRereadArgv(projectId, e, reads) {
+ if (!reads.length) throw new Error(`${e?.id}: nothing to re-read`);
+ if (e?.type === "card") return ["narration", projectId, e.id, "--read"];
+ const pieces = reads.filter((r) => r.kind === "thread" || r.kind === "screen");
+ if (!pieces.length) return ["posts", "narrate", projectId, e.id, "--take", "--reading", "next", "--no-pick", ...tuningFlagsOf(reads[0].ask), "--bench-slurs"];
+ const withScreens = Array.isArray(e.screens) && e.screens.length > 0;
+ const one = pieces.length === 1;
+ const asked = one
+ ? readAgainArgv({ for: pieces[0].role, reading: "next", ...(pieces[0].ask ? { tuning: pieces[0].ask } : {}), keepPick: true })
+ : [...pieces.flatMap((r) => ["--tuned", tunedOf(r.role, r.ask)]), "--no-pick"];
+ if (withScreens) return ["posts", "screen", projectId, e.id, "read", ...asked];
+ const takes = e.narration?.takes ?? [];
+ const t = takes[Number.isInteger(e.narration?.pick) ? e.narration.pick : 0] ?? null;
+ // As the read that plays was asked -- but a stale piece's own recorded `--tuned` gives way to its re-read (a later
+ // --tuned of a role beats an earlier one, but --for is laid UNDER every --tuned).
+ const stale = new Set(pieces.map((r) => r.role));
+ const base = threadArgvOf(t?.read, { takes });
+ const kept = base.filter((x, i) => !(x === "--tuned" && stale.has(String(base[i + 1]).split("=")[0])) && !(base[i - 1] === "--tuned" && stale.has(String(x).split("=")[0])));
+ return ["posts", "narrate", projectId, e.id, "--take", "--thread", ...kept, ...asked];
+}
diff --git a/umtool/lib/report/reads-pin.test.mjs b/umtool/lib/report/reads-pin.test.mjs
@@ -0,0 +1,77 @@
+// THE RULING-3 PIN FOR A VIDEO's READS (lane reads-find; operator ruling 3, 15 Nov 2026: "edits change only what is
+// SPOKEN -- shown text never changes"). After a Replace in EITHER scope and after the re-read queue has run and its
+// re-reads are picked, every card draws byte-identically to before: the reading pin's drawn() -- its plain card, its
+// followed card, its blocks (and the paragraphs an excerpt tile hides), its thread tiles' modes, its screens -- and a
+// narrated card's every field but its narration. One exception, named and not pinned: an item whose playing take was
+// read BEFORE the rule (unstamped, other words) moves to the shown-text rule when its re-read is picked -- the preview
+// says so (post-item.mjs LEGACY_EDIT_TEXT). Temp dirs, a stub tts, invented people; noLiveEditor first.
+import "./noLiveEditor.mjs";
+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 { applyReplace, applySayOnly, replacePlan } from "./readsReplace.mjs";
+import { enqueueRereads, pickReads, readBatches, runOneItem } from "./readsQueue.mjs";
+import { postsCommand } from "./postsCli.mjs";
+import { cardNarrationCommand } from "./cardNarrationCli.mjs";
+import { projectReads } from "./reads.mjs";
+import { keepCardReading, readManifestOf, readsProject, wavOf } from "./reads.fixtures.mjs";
+import { drawn } from "../../report-to-video/post-reading-pin.fixtures.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-reads-pin-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+
+const stubAsk = async (body) => {
+ await wavOf(body.out);
+ return { jobId: "job", result: { wav: body.out, engine: body.engine, voice: body.voice, tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }, reading: body.reading ?? 0 } };
+};
+const run = (p) => async (argv) => {
+ if (argv[0] === "posts") return postsCommand(argv.slice(1), { root: p.root, tts: stubAsk, out: () => {}, err: () => {} });
+ return cardNarrationCommand(argv.slice(1), { root: p.root, narrate: async ({ narrations }) => {
+ for (const n of narrations) await keepCardReading(p.dir, n, { createdAt: new Date().toISOString() });
+ return new Map(narrations.map((n) => [n.id, { seconds: 1.4 }]));
+ }, out: () => {}, err: () => {} });
+};
+/** What every item DRAWS: a post's drawn() hashes; any other entry, every field but its narration. */
+const drawnCut = (m) => m.timeline.map((e) => (e.type === "post" ? { id: e.id, ...drawn(e) } : (({ narration: _n, ...rest }) => rest)(e)));
+
+test("THE PIN: replace (these reads, then everywhere), re-read every changed line, pick the new reads -- the cut draws as before", async () => {
+ const p = await readsProject(ROOT, "pin");
+ const before = drawnCut(await readManifestOf(p));
+ // These reads: a post's script, a thread read's own words, a screen line (said-as made), the card.
+ await applyReplace(p, "north", "northern", { reportsRoot: p.root });
+ await applyReplace(p, "Tuesday", "Tuesday evening", { reportsRoot: p.root });
+ await applyReplace(p, "tolls", "toll charges", { reportsRoot: p.root });
+ assert.deepEqual(drawnCut(await readManifestOf(p)), before, "after These reads");
+ // Everywhere: a pronunciation entry.
+ await applySayOnly(p, "ministry", "min-is-tree", { reportsRoot: p.root });
+ assert.deepEqual(drawnCut(await readManifestOf(p)), before, "after Everywhere");
+ // The re-read queue, each step as the app runs it, then Pick every new read.
+ const q = await enqueueRereads(p, { reportsRoot: p.root, queueDir: path.join(p.root, ".umtool-queue") });
+ assert.deepEqual(q.steps.map((s) => s.item), ["p-1", "p-2", "c-1"]);
+ for (const s of q.steps) assert.equal((await runOneItem(p, s.item, s.reads, { reportsRoot: p.root, run: run(p), log: () => {} })).code, 0, s.item);
+ assert.deepEqual(drawnCut(await readManifestOf(p)), before, "after the re-reads (unpicked)");
+ await pickReads(p, { which: "new", reportsRoot: p.root });
+ const m = await readManifestOf(p);
+ assert.deepEqual(drawnCut(m), before, "after the picks");
+ // The reads say the new words, and are fresh.
+ const rows = (await projectReads(p, { reportsRoot: p.root })).rows;
+ assert.deepEqual(rows.filter((r) => r.state !== "fresh" && r.state !== "recorded").map((r) => `${r.id} ${r.state}`), []);
+ assert.match(m.timeline[0].narration.takes.at(-1).script, /northern pier/);
+ assert.equal(m.timeline[0].narration.takes.at(-1).forReading, true);
+ assert.ok((await readBatches(p.dir)).length === 1);
+});
+
+test("THE EXCEPTION, named: an item playing a take read before the rule is said in the replace's preview", async () => {
+ const p = await readsProject(ROOT, "legacy");
+ const m = await readManifestOf(p);
+ // His playing take says other words than the post, unstamped (made before reads were kept apart from the card).
+ const t = m.timeline[0].narration.takes[0];
+ t.script = "The ferry leaves at noon.\n\nBring a coat.";
+ m.timeline[0].narration.script = t.script;
+ await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m, null, 2));
+ const plan = await replacePlan(p, "coat", "warm coat", { reportsRoot: p.root });
+ assert.match(plan.notes["p-1"].join(" "), /read before reads were kept apart from the card/);
+});
diff --git a/umtool/lib/report/reads.fixtures.mjs b/umtool/lib/report/reads.fixtures.mjs
@@ -0,0 +1,84 @@
+// 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";
+import { PROJECT_KINDS } from "../projects/kinds.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();
+ // Each part its own file in the parts cache, as a thread read keeps them (made on disk by readsProject).
+ const takes = e.narration.takes.map((t) => ({ ...t, parts: t.parts.map((x) => ({ ...x, file: `narration/parts-cache/fixture-${x.n}.wav` })) }));
+ return { ...e, id: "p-2", parents: e.parents.map((x) => ({ ...x, text: x.text.split("\n\n")[0] })), narration: { ...e.narration, takes } };
+}
+
+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: `p` under the reports root `<root>/<name>`, the cast in `<root>/<name>/.umtool/cast.json`, the takes'
+ * files on disk and the card's reading kept in out/narration/. Returns `{ id: "p", dir, root }` (`root` the reports 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));
+ // A project of the reports root `top` (projects/core.mjs walks it): `umtool … p` finds it there.
+ await writeFile(path.join(dir, "project.json"), `${JSON.stringify({ kind: PROJECT_KINDS.find((k) => k.makesTakes).id, title: name })}\n`);
+ for (const e of tl) for (const t of e?.narration?.takes ?? []) {
+ await wavOf(path.join(dir, ...t.file.split("/")));
+ for (const x of t.parts ?? []) if (typeof x.file === "string") await wavOf(path.join(dir, ...x.file.split("/")));
+ }
+ for (const n of narrationsOf(manifest)) await keepCardReading(dir, n);
+ return { id: "p", 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,365 @@
+// 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, takeFile, file, files, key, reading, tuning, tunedBy: "line" | "character" |
+// null }` -- `takeFile` the take's own file, `files` what THIS read plays (a thread piece: its parts' files)
+// ask the tuning a plain press asks for it now (tuneAsk.mjs plainPressAskOf: only what its line owned; the
+// character's and the settings' resolved anew) -- what its re-read asks (readAgainArgv.mjs)
+// 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";
+import { lineOwnOf, madeOwnOf, pieceOwnOf, plainPressAskOf } from "./tuneAsk.mjs";
+
+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);
+
+/**
+ * Every id the model makes (readIdOf): an item's id -- any timeline id, no slash, no space -- and, for a piece of a
+ * thread read, its role (post, quoted, parent:<i>, linked:<i>, screen:<screen id>:<line>).
+ */
+export const READ_ID_RE = /^[^/\s]{1,200}(?:\/(?:post|quoted|parent:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2}))?$/;
+
+/**
+ * A list of read ids as a caller hands it (`only`): `{ ids }`, or `{ error }` naming what is refused -- not a list,
+ * empty, or an id no read could have. Never silently narrowed: a list that names one bad id is refused whole.
+ */
+export function readIdsOf(list) {
+ if (!Array.isArray(list)) return { error: "only is a list of read ids" };
+ const bad = list.filter((x) => typeof x !== "string" || !READ_ID_RE.test(x));
+ if (bad.length) return { error: `not a read's id: ${bad.slice(0, 5).map((x) => JSON.stringify(x)).join(", ")}` };
+ if (!list.length) return { error: "only names no read" };
+ return { ids: [...new Set(list)] };
+}
+
+/** 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);
+
+/**
+ * THE PLAIN PRESS's TUNING for a read (tuneAsk.mjs plainPressAskOf: the bench's untouched Read again, and the re-read
+ * queue's): `made` how it was last made (`{ tuning, tuningAsked }`), `own` what its line owned, `want` its voice now
+ * (resolverFor's: its character and the character's tuning). Null: nothing of its own -- the character's, or the
+ * defaults, as they are when it is read. An engine with no sampler asks none.
+ */
+function plainAskOf(made, own, want, names) {
+ if ((want?.engine ?? "orpheus") !== "orpheus") return null;
+ const baseline = { character: want?.character ? { name: names.get(want.character) ?? want.character, tuning: want.tuning ?? null } : null, madeOwn: madeOwnOf(made?.tuning ?? null, made?.tuningAsked) };
+ return plainPressAskOf({ madeWith: made?.tuning ?? null, baseline, own });
+}
+
+/** A take as a read row carries it. */
+const takeView = (t, extra = {}) => (t ? { index: Number.isInteger(t.index) ? t.index : null, takeFile: t.file ?? null, file: t.file ?? null, files: typeof t.file === "string" ? [t.file] : [], 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, ask: 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, ask: src === "tts" ? plainAskOf(take, lineOwnOf(take), want ?? { engine: take.engine }, vs.names) : 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, ask: 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 roleFiles = parts.filter((p) => p?.role === pc.role && typeof p?.take !== "string" && typeof p?.file === "string").map((p) => p.file);
+ 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,
+ // ITS PART's files (a paragraph each), in order -- what it says in the take, never the whole joined read.
+ take: takeView(take, part ? { file: roleFiles[0] ?? take.file, files: roleFiles, reading: Number.isInteger(part.reading) ? part.reading : 0, tuning: isObj(part.tuning) ? part.tuning : null, tunedBy: tunedByOf(part) ?? tunedByOf(take) } : {}), newTake: null,
+ ask: pc.take ? null : plainAskOf(part ? { tuning: part.tuning, tuningAsked: part.tuningAsked ?? take.tuningAsked } : null, pieceOwnOf(take, pc.role), want ?? { engine: pc.engine, character: pc.character, tuning: pc.tuningAsked === "preset" ? pc.tuning : null }, vs.names),
+ };
+ if (pc.take) {
+ // A PIECE READ FROM ANOTHER TAKE of the item (`--post-take`, a line's chosen take): judged as that take is --
+ // a recording, or one converted from one, is yours; a SYNTHESIZED one is stale as cast.mjs madeOf follows it
+ // (`cast stale` lists it), its re-read that take's own (not queued here: re-read it on the bench, then this).
+ const src = takes.find((t) => t?.file === pc.take.file) ?? null;
+ if (!src || takeSourceOf(src).kind !== "tts") {
+ rows.push({ ...row, state: "recorded", because: [] });
+ continue;
+ }
+ // Its WORDS: the source take's, against what this piece says now (his script; a screen line's said-as or line).
+ const now = own ? (str(e.narration?.script) || str(dry.plan.script) || str(pc.written)) : sc ? (as ?? screenLineSaid(screen, sc.n)) : str(pc.written);
+ const then = sc ? (str(src.screenLine?.said) || str(src.said) || str(src.script)) : str(src.script) || str(src.said);
+ const because = [];
+ if (norm(then) !== norm(now)) 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, why: `${pc.role === "post" ? "his line" : pc.role} is take ${pc.take.n} (synthesized): read it again on the bench, then this thread read`, queueable: false, state: because.length ? "stale" : "fresh", 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, ask: 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,116 @@
+// 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 "./noLiveEditor.mjs";
+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 });
+ // REVIEW 1, SHOULD 5: a thread read's piece plays ITS part (its paragraphs' parts, in order), never the joined take.
+ assert.equal(by["p-2/screen:s1:0"].take.file, "narration/parts-cache/fixture-5.wav");
+ assert.deepEqual(by["p-2/screen:s1:0"].take.files, ["narration/parts-cache/fixture-5.wav"]);
+ assert.deepEqual(by["p-2/post"].take.files, ["narration/parts-cache/fixture-3.wav", "narration/parts-cache/fixture-4.wav"]);
+ assert.equal(by["p-1"].take.file, "narration/posts/1/take-1.orpheus-tara.wav");
+});
+
+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");
+});
diff --git a/umtool/lib/report/readsApi.mjs b/umtool/lib/report/readsApi.mjs
@@ -0,0 +1,141 @@
+// THE READS PAGE's REQUESTS (lane reads-find; app/api/report/reads/route.ts is this, behind its guards): every
+// request answered by the same functions `umtool reads` runs (reads.mjs, readsReplace.mjs, readsQueue.mjs), called
+// directly -- never an argv built from what a page typed. A write that acts on reads names them (`only`): the ids
+// the page counted, each checked; a list that names one id no read could have is refused whole (400), never
+// narrowed -- an unscoped re-read, pick or replace is the CLI's alone (no --only).
+//
+// Plain ESM: tested without the app (readsApi.test.mjs).
+import { READ_KINDS, filterReads, findInReads, projectReads, readIdsOf } from "./reads.mjs";
+import { manifestToken } from "./manifest.mjs";
+
+const view = (x) => ({ id: x.id, kind: x.kind, item: x.item, role: x.role, character: x.character, voice: x.voice, spoken: x.spoken, said: x.said, storedAt: x.storedAt, editable: x.editable, why: x.why, queueable: x.queueable !== false, state: x.state, because: x.because, take: x.take, newTake: x.newTake, ...(x.matches ? { matches: x.matches } : {}) });
+void READ_KINDS;
+
+class Refused extends Error {
+ constructor(message, status = 400) {
+ super(message);
+ this.status = status;
+ }
+}
+
+/** `only` from a body: required here (`need`), each id checked. */
+function onlyOf(body, need) {
+ if (body.only === undefined || body.only === null) {
+ if (need) throw new Refused("which reads? (only: the ids of the reads this acts on)");
+ return null;
+ }
+ const r = readIdsOf(body.only);
+ if (r.error) throw new Refused(r.error);
+ return r.ids;
+}
+
+const text = (v, what) => {
+ if (typeof v !== "string") throw new Refused(`${what} is text`);
+ return v;
+};
+
+/**
+ * The queue as the page shows it: its waiting sentence completed with the app's own runner -- its specific reason
+ * (its last turn's error, what it waits for, not armed in this process) before the general one.
+ */
+export async function queueOf(project, { reportsRoot, queueDir, runner = null }) {
+ const { queueView } = await import("./readsQueue.mjs");
+ const v = await queueView(project, { reportsRoot, queueDir });
+ if (!v.counts.waiting) return v;
+ const st = runner ?? {};
+ const specific = st.lastError ? `waiting: the app's queue runner's last turn failed -- ${st.lastError}` : st.waiting ? `waiting: ${st.waiting}` : st.armed === false && st.enabled === false ? "waiting: this umtool app does not run the queue (UMTOOL_QUEUE_RUNNER is off here) -- the app that holds the queue's lease runs it" : null;
+ return { ...v, waiting: specific && !/render mode/.test(v.waiting ?? "") ? specific : v.waiting };
+}
+
+/** GET: the reads (filtered, with Find's matches), the queue, and whether the newest replace can be taken back. */
+export async function readsGet(project, q, o) {
+ const { rows, counts, tuningStale } = await projectReads(project, { reportsRoot: o.reportsRoot });
+ const character = q.get("character");
+ let list = filterReads(rows, { stale: q.get("stale") === "1", character: character && /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(character) ? character : null });
+ const find = q.get("find");
+ const opts = { matchCase: q.get("case") === "1", word: q.get("word") === "1" };
+ let found = null;
+ if (find && find.trim()) {
+ found = findInReads(list, find, opts);
+ list = found.rows;
+ }
+ const { replaceUndoState } = await import("./readsReplace.mjs");
+ return {
+ ok: true, project: project.id, counts, settingsStale: tuningStale.length, reads: list.map(view),
+ ...(found ? { find: { text: find, ...opts, matches: found.matches, lines: found.lines } } : {}),
+ queue: await queueOf(project, o), undo: await replaceUndoState(project),
+ };
+}
+
+/**
+ * POST: one op -- `{ status, json }`. preview / replace (`scope` "reads" | "say"; a replace of These reads names the
+ * previewed reads), undo (the newest replace, of either scope), reread (the reads counted), stop, retry, pick (the
+ * reads it picks).
+ */
+export async function readsPost(project, body, o) {
+ try {
+ const op = String(body.op ?? "");
+ const R = await import("./readsReplace.mjs");
+ const Q = await import("./readsQueue.mjs");
+ const opts = { matchCase: body.case === true, word: body.word === true, reportsRoot: o.reportsRoot };
+ const qo = { reportsRoot: o.reportsRoot, queueDir: o.queueDir };
+ let json;
+ if (op === "preview" || op === "replace") {
+ const from = text(body.from, "from");
+ const to = text(body.to ?? "", "to");
+ if (!from.trim()) throw new Refused("find what? (the words to replace)");
+ if (body.scope === "say") {
+ if (!opts.word) throw new Refused(R.SAY_WHOLE_WORDS);
+ if (op === "preview") {
+ const plan = await R.sayOnlyPlan(project, from, to, opts);
+ json = { scope: "say", entry: plan.entry, was: plan.was, stale: plan.stale, cards: plan.cards, matches: plan.matches };
+ } else {
+ const done = await R.applySayOnly(project, from, to, opts);
+ json = { scope: "say", entry: done.result.entry, changed: done.result.changed, was: done.plan.was, stale: done.plan.stale };
+ }
+ } else if (body.scope === "reads") {
+ // The reads it acts on, on the preview as on Apply: the rows the page's Find counted.
+ const only = onlyOf(body, true);
+ if (op === "preview") {
+ // The draft's token as the preview read it: Apply writes only over that draft (409 otherwise).
+ const token = await manifestToken(project.dir);
+ const plan = await R.replacePlan(project, from, to, { ...opts, only });
+ json = { scope: "reads", lines: plan.lines, skipped: plan.skipped, notes: plan.notes, refused: plan.refused, matches: plan.matches, token };
+ } else {
+ if (typeof body.token !== "string" || !body.token) throw new Refused("Apply goes with its preview's token (preview first)");
+ let done;
+ try {
+ done = await R.applyReplace(project, from, to, { ...opts, only, token: body.token });
+ } catch (err) {
+ if (err?.constructor?.name === "StaleToken") throw new Refused("the draft changed since the preview: preview again", 409);
+ throw err;
+ }
+ json = { scope: "reads", lines: done.plan.lines, token: done.result.token ?? null };
+ }
+ } else throw new Refused("scope is reads or say");
+ } else if (op === "undo") {
+ const st = await R.replaceUndoState(project);
+ if (!st) throw new Refused("nothing to undo: no replace was made here");
+ json = st.scope === "say" ? { scope: "say", ...(await R.undoSayOnly(project)) } : { scope: "reads", ...(await R.undoReplace(project)) };
+ } else if (op === "reread") {
+ const only = onlyOf(body, true);
+ json = await Q.enqueueRereads(project, { ...qo, only, by: "the Reads page" });
+ o.kick?.();
+ } else if (op === "stop") json = await Q.stopQueue(project, qo);
+ else if (op === "retry") {
+ const [read] = onlyOf({ only: [body.read] }, true);
+ json = await Q.retryRead(project, read, qo);
+ o.kick?.();
+ } else if (op === "pick") {
+ if (body.which !== "new" && body.which !== "old") throw new Refused("pick which: new or old");
+ const only = onlyOf(body, true);
+ const r = await Q.pickReads(project, { which: body.which, only, reportsRoot: o.reportsRoot });
+ json = { picked: r.picked, token: r.result?.token ?? null };
+ } else throw new Refused(`no op ${op}`);
+ return { status: 200, json: { ok: true, ...json, queue: await queueOf(project, o), undo: await R.replaceUndoState(project) } };
+ } catch (e) {
+ const known = e instanceof Refused || ["ReplaceError", "QueueError", "StructureRefused", "StaleToken", "SayError"].includes(e?.constructor?.name);
+ if (!known) throw e;
+ return { status: e instanceof Refused ? e.status : e?.constructor?.name === "StaleToken" ? 409 : 400, json: { ok: false, error: e?.constructor?.name === "StructureRefused" ? e.errors.join("; ") : e.message } };
+ }
+}
diff --git a/umtool/lib/report/readsApi.test.mjs b/umtool/lib/report/readsApi.test.mjs
@@ -0,0 +1,65 @@
+// THE READS PAGE's REQUESTS (lane reads-find, review 1 MUST 1; readsApi.mjs, the route's body): a write acts only on
+// the reads it names -- the ids the page counted -- and a list naming an id no read could have is refused whole, never
+// narrowed to an unscoped run. Temp dirs, invented people; noLiveEditor first.
+import "./noLiveEditor.mjs";
+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 { readsGet, readsPost } from "./readsApi.mjs";
+import { listSteps } from "../queue/store.mjs";
+import { readManifestOf, readsProject } from "./reads.fixtures.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-reads-api-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+
+async function changed(name) {
+ const p = await readsProject(ROOT, name);
+ const m = await readManifestOf(p);
+ m.timeline[0].narration.script = m.timeline[0].narration.script.replace("noon", "twelve noon");
+ m.timeline[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));
+ return { p, o: { reportsRoot: p.root, queueDir: path.join(p.root, ".umtool-queue") } };
+}
+
+test("MUST 1: a filtered view re-reads ONLY the reads it counted; no `only`, a bad id, an empty list: 400, nothing queued", async () => {
+ const { p, o } = await changed("only");
+ // The page's view: the stale reads of the ferry character -- p-1 only (the card has no character).
+ const g = await readsGet(p, new URLSearchParams({ stale: "1", character: "ferry" }), o);
+ assert.deepEqual(g.reads.map((r) => r.id), ["p-1"]);
+ for (const body of [{ op: "reread" }, { op: "reread", only: [] }, { op: "reread", only: ["p-1", "p 1"] }, { op: "reread", only: "p-1" }]) {
+ const r = await readsPost(p, body, o);
+ assert.equal(r.status, 400, JSON.stringify(body));
+ }
+ assert.deepEqual(await listSteps(o.queueDir), [], "nothing queued by a refused request");
+ const r = await readsPost(p, { op: "reread", only: g.reads.map((x) => x.id) }, o);
+ assert.equal(r.status, 200);
+ assert.deepEqual(r.json.steps.map((s) => s.item), ["p-1"], "the card, stale too, is not re-read");
+ // An id as long as the model makes (a 64-character item, a 24-character screen id, line 12): accepted.
+ const long = `${"x".repeat(64)}/screen:${"s".repeat(24)}:12`;
+ const r2 = await readsPost(p, { op: "reread", only: [long] }, o);
+ assert.equal(r2.status, 200);
+ assert.match(r2.json.skipped[0].why, /no such read/);
+});
+
+test("MUST 1: pick and a replace of These reads name their reads; refused unscoped", async () => {
+ const { p, o } = await changed("scoped");
+ assert.equal((await readsPost(p, { op: "pick", which: "new" }, o)).status, 400);
+ assert.equal((await readsPost(p, { op: "replace", scope: "reads", from: "north", to: "northern" }, o)).status, 400);
+ const before = await readManifestOf(p);
+ assert.equal((await readsPost(p, { op: "replace", scope: "reads", from: "north", to: "northern", only: ["c-1", "bad id"] }, o)).status, 400);
+ assert.deepEqual(await readManifestOf(p), before);
+ // The previewed ids: only those change.
+ const prev = await readsPost(p, { op: "preview", scope: "reads", from: "north", to: "northern", only: ["p-1", "p-3", "c-1"] }, o);
+ assert.deepEqual(prev.json.lines.map((l) => l.id), ["p-1", "c-1"]);
+ const done = await readsPost(p, { op: "replace", scope: "reads", from: "north", to: "northern", only: ["c-1"], token: prev.json.token }, o);
+ assert.equal(done.status, 200);
+ const m = await readManifestOf(p);
+ assert.match(m.timeline[3].narration.text, /northern/);
+ assert.doesNotMatch(m.timeline[0].narration.script, /northern/);
+ assert.equal(done.json.undo.available, true);
+ // Everywhere with Whole word off: refused in the page's words.
+ assert.match((await readsPost(p, { op: "preview", scope: "say", from: "pier", to: "peer" }, o)).json.error, /whole words only/);
+});
diff --git a/umtool/lib/report/readsCli.mjs b/umtool/lib/report/readsCli.mjs
@@ -0,0 +1,254 @@
+// `umtool reads` -- A VIDEO's READS from the CLI (lane reads-find, S4 of plans/orpheus-retune.md; reads.mjs,
+// readsReplace.mjs, readsQueue.mjs; umtool/docs/knobs.md, "The reads of a video"): every line a voice reads, Find over
+// what is SPOKEN, Replace in two stated scopes, the re-read queue, and the picks after it. The Reads page
+// (/projects/<p>/reads) runs these same functions.
+//
+// umtool reads <p> [--find <text> [--case] [--word]] [--stale] [--character <id>] [--json]
+// umtool reads <p> replace <from> <to> [--case] [--word] [--say-only] [--only <ids>] [--dry-run] [--json]
+// umtool reads <p> undo [--json]
+// umtool reads <p> reread [--stale] [--only <ids>] [--wait [--timeout <s>]] [--json]
+// umtool reads <p> reread --one <item> --only <ids> one queue step (the app runs it)
+// umtool reads <p> queue [--stop] [--retry <id>] [--json]
+// umtool reads <p> pick --new|--old [--only <ids>] [--json]
+//
+// Plain ESM: the CLI runs it under bare node.
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { READ_KINDS, filterReads, findInReads, projectReads } from "./reads.mjs";
+
+export const READS_USAGE = [
+ "usage: umtool reads <project> [--find <text> [--case] [--word]] [--stale] [--character <id>] [--json]",
+ " umtool reads <project> replace <from> <to> [--case] [--word] [--say-only] [--only <id>,…] [--dry-run] [--json]",
+ " umtool reads <project> undo [--dry-run] [--json]",
+ " umtool reads <project> reread [--stale] [--only <id>,…] [--wait [--timeout <s>]] [--dry-run] [--json]",
+ " umtool reads <project> queue [--stop] [--retry <id>] [--json]",
+ " umtool reads <project> pick --new|--old [--only <id>,…] [--dry-run] [--json]",
+ " A VIDEO's READS: every line a voice reads -- a post's script, a thread read's pieces (his words, a parent, the",
+ " quoted or a linked post), its screen lines, a card's narration -- with what it SAYS (never what is shown), the",
+ " take that plays and its state: fresh, stale (other words, the lexicon, a character's settings or voice since),",
+ " unpicked (re-read, waiting for a pick), none (no take yet), recorded (yours: never stale, never re-read). A read's",
+ " id is its item's, and <item>/<role> for a piece of a thread read (p-2/screen:s1:0). --find: the spoken text only,",
+ " without case unless --case, --word for whole words; --stale: the stale and unpicked; --character: one character's.",
+ " replace: THESE READS -- the spoken text of the matched reads rewritten in ONE undo point (a post's script, a",
+ " screen line's said-as made when it has none, a card's narration); a parent, the quoted or a linked post is said",
+ " as shown (only --say-only changes it), a recorded read is never replaced. --say-only: EVERYWHERE, FROM NOW ON --",
+ " a pronunciation entry (umtool posts say add): every read of a post says it that way; whole words always (--word",
+ " is implied), never a card. --dry-run: the preview (line, before -> after; what goes; what the build would refuse), nothing written.",
+ " Neither synthesizes: the changed reads show as stale. undo: the newest replace taken back -- These reads only",
+ " while the draft is still as it left it (nothing written since), an Everywhere back to the entry it changed (or",
+ " the entry removed); --dry-run says which, or why not. Every subcommand refuses a flag it does not take; -- ends",
+ " the flags (a `to` that starts with dashes). --dry-run on reread and pick: what would be queued or picked. reread: the stale reads (--only: those) queued, one step per item in cut order",
+ " on the umtool app's queue (umtool queue ls), each the bench's own command; a re-read joins the list UNPICKED.",
+ " --wait: until they end (exit 1 when one failed). queue: each queued read's state, and why they wait; --stop",
+ " cancels what has not started; --retry <id> puts a failed or stopped one back. pick --new: every unpicked",
+ " re-read made the one that plays; --old: the newest re-reads' reads back to what played before; one undo point.",
+].join("\n");
+
+class ReadsUsage extends Error {}
+
+/** Each subcommand's flags (besides --json, --help). */
+const FLAGS_OF = Object.freeze({
+ "": ["--find", "--case", "--word", "--stale", "--character"],
+ replace: ["--case", "--word", "--say-only", "--only", "--dry-run"],
+ undo: ["--dry-run"],
+ reread: ["--stale", "--only", "--wait", "--timeout", "--one", "--dry-run"],
+ queue: ["--stop", "--retry"],
+ pick: ["--new", "--old", "--only", "--dry-run"],
+});
+
+const VALUED = new Set(["--find", "--character", "--only", "--one", "--retry", "--timeout"]);
+
+/**
+ * `umtool reads …`
+ * @param {string[]} args
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, sleep?: (ms: number) => Promise<void>, queueDir?: string, tts?: Function | null }} [o]
+ * `tts`: the editor's tts op as a test hands it (postsCommand's), for `reread --one`
+ */
+export async function readsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), queueDir = undefined, tts = null } = {}) {
+ const flags = new Map();
+ const words = [];
+ let ended = false;
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ // `--`: every word after it is a word (a `to` that starts with dashes), never a flag.
+ if (!ended && a === "--") ended = true;
+ else if (!ended && VALUED.has(a)) {
+ // A valued flag followed by another flag (or nothing) has no value: "" (refused where it matters, never eaten).
+ const v = args[i + 1];
+ if (v === undefined || (v.startsWith("--") && v !== "--")) flags.set(a, "");
+ else {
+ flags.set(a, v);
+ i += 1;
+ }
+ } else if (!ended && a.startsWith("--")) flags.set(a, true);
+ else words.push(a);
+ }
+ const str = (k) => (typeof flags.get(k) === "string" ? flags.get(k) : null);
+ // A list of ids: none when the flag is absent; refused when it is given and names none ("", ",", no value) -- an
+ // `--only` that names nothing never widens to every read.
+ const ids = (k) => {
+ const list = (str(k) ?? "").split(",").map((x) => x.trim()).filter(Boolean);
+ if (flags.has(k) && !list.length) throw new ReadsUsage(`${k} names no read (give the read ids, comma separated)`);
+ return list;
+ };
+ const json = flags.has("--json");
+ const [projectArg, sub = null, ...rest] = words;
+ if (!projectArg || flags.has("--help")) {
+ out(READS_USAGE);
+ return projectArg ? 0 : 2;
+ }
+ const say = (j, text) => out(json ? JSON.stringify(j, null, 2) : text);
+ try {
+ // Each subcommand's own flags; any other is refused (never ignored: `undo --dry-run` must not undo).
+ const allowed = Object.hasOwn(FLAGS_OF, sub ?? "") ? FLAGS_OF[sub ?? ""] : null;
+ if (!allowed) throw new ReadsUsage(`reads: replace, undo, reread, queue or pick (not ${sub}); none lists the reads`);
+ const unknown = [...flags.keys()].filter((f) => f !== "--json" && f !== "--help" && !allowed.includes(f));
+ if (unknown.length) throw new ReadsUsage(`${unknown.join(", ")}: not a flag of \`reads <p>${sub ? ` ${sub}` : ""}\` (its flags: ${allowed.join(" ") || "none"}; -- ends the flags)`);
+ const r = await resolveProject(projectArg, root);
+ if (r.ambiguous) throw new ReadsUsage(`"${projectArg}" is the name of ${r.ambiguous.length} projects -- pass its id`);
+ if (!r.project) throw new ReadsUsage(`no project matches "${projectArg}"`);
+ const project = r.project;
+ const qo = { reportsRoot: root, ...(queueDir ? { queueDir } : {}) };
+ const opts = { matchCase: flags.has("--case"), word: flags.has("--word") };
+
+ if (sub === null) {
+ const { rows, counts, tuningStale } = await projectReads(project, { reportsRoot: root });
+ let list = filterReads(rows, { stale: flags.has("--stale"), character: str("--character") });
+ let found = null;
+ if (str("--find") !== null) {
+ found = findInReads(list, str("--find"), opts);
+ list = found.rows;
+ }
+ const view = (x) => ({ id: x.id, kind: x.kind, item: x.item, role: x.role, character: x.character, voice: x.voice, spoken: x.spoken, said: x.said, storedAt: x.storedAt, editable: x.editable, why: x.why, state: x.state, because: x.because, take: x.take, newTake: x.newTake, ...(x.matches ? { matches: x.matches } : {}) });
+ say({ ok: true, project: project.id, counts, ...(found ? { find: { text: str("--find"), ...opts, matches: found.matches, lines: found.lines } } : {}), reads: list.map(view), settingsStale: tuningStale.length }, [
+ found ? `"${str("--find")}": ${found.matches} match${found.matches === 1 ? "" : "es"} in ${found.lines} line${found.lines === 1 ? "" : "s"} (spoken text only)` : `${project.id}: ${rows.length} read(s) -- ${Object.entries(counts).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(", ") || "none"}`,
+ ...list.map((x) => ` ${x.state.padEnd(8)} ${x.id.padEnd(22)} ${READ_KINDS[x.kind]}${x.character ? ` · ${x.character.name}` : ""}${x.because.length ? ` (${x.because.join(", ")})` : ""} "${x.spoken.replace(/\s+/g, " ").slice(0, 80)}"`),
+ ].join("\n"));
+ return 0;
+ }
+ if (sub === "replace") {
+ const [from, to] = rest;
+ if (from === undefined || to === undefined) throw new ReadsUsage('replace takes the words to find and what to say instead: replace "BRT" "B R T"');
+ const R = await import("./readsReplace.mjs");
+ if (flags.has("--say-only")) {
+ const plan = await R.sayOnlyPlan(project, from, to, { ...opts, word: true, reportsRoot: root });
+ const head = `EVERYWHERE, FROM NOW ON: "${plan.entry.word}" said "${plan.entry.say}" in every read of a post${plan.was ? ` -- changes the existing entry (was "${plan.was}")` : ""} -- ${plan.stale.length} read(s) made stale: ${plan.stale.map((s) => s.id).join(", ") || "none"}${plan.cards.length ? `; ${R.SAY_NOT_CARDS} (${plan.cards.join(", ")})` : ""}`;
+ if (flags.has("--dry-run")) {
+ say({ ok: true, dryRun: true, scope: "say", entry: plan.entry, was: plan.was, stale: plan.stale, cards: plan.cards, matches: plan.matches }, head);
+ return 0;
+ }
+ const done = await R.applySayOnly(project, from, to, { ...opts, word: true, reportsRoot: root });
+ say({ ok: true, scope: "say", entry: done.result.entry, changed: done.result.changed, stale: plan.stale, cards: plan.cards }, `${head}\n ${done.result.changed}; undo: umtool reads ${project.id} undo (${plan.was ? `back to "${plan.was}"` : "the entry removed"})`);
+ return 0;
+ }
+ const only = ids("--only");
+ const plan = await R.replacePlan(project, from, to, { ...opts, only: only.length ? only : null, reportsRoot: root });
+ const lines = [
+ `THESE READS: "${from}" -> "${to}" in ${plan.lines.length} read(s) (${plan.matches} match${plan.matches === 1 ? "" : "es"}); the shown text is never changed`,
+ ...plan.lines.map((l) => ` ${l.id}: "${l.before.replace(/\s+/g, " ").slice(0, 70)}" -> "${l.after.replace(/\s+/g, " ").slice(0, 70)}"${l.creates ? ` (${l.creates})` : ""}`),
+ ...plan.skipped.map((s) => ` ${s.id}: not changed -- ${s.why}`),
+ ...Object.entries(plan.notes).flatMap(([i, ns]) => ns.map((n) => ` ${i}: ${n}`)),
+ ...Object.entries(plan.refused).flatMap(([i, es]) => es.map((e) => ` ${i}: REFUSED -- ${e}`)),
+ ];
+ const view = { scope: "reads", find: from, to, ...opts, lines: plan.lines, skipped: plan.skipped, notes: plan.notes, refused: plan.refused, matches: plan.matches };
+ if (flags.has("--dry-run")) {
+ say({ ok: true, dryRun: true, ...view }, lines.join("\n"));
+ return 0;
+ }
+ const done = await R.applyReplace(project, from, to, { ...opts, only: only.length ? only : null, reportsRoot: root });
+ say({ ok: true, ...view, snapshot: done.result.snapshot?.rel ?? null, token: done.result.token ?? null }, `${lines.join("\n")}\n written: one undo point (umtool reads ${project.id} undo); the changed reads are stale -- umtool reads ${project.id} reread`);
+ return 0;
+ }
+ if (sub === "undo") {
+ const R = await import("./readsReplace.mjs");
+ const st = await R.replaceUndoState(project);
+ if (!st) throw new R.ReplaceError("nothing to undo: no replace was made here");
+ if (flags.has("--dry-run")) {
+ say({ ok: true, dryRun: true, ...st }, st.available ? `would take back the newest ${st.scope === "say" ? `Everywhere ("${st.entry.word}"${st.was ? `, back to "${st.was.say}"` : ", the entry removed"})` : "replace of These reads"}` : `would refuse: ${st.why}`);
+ return 0;
+ }
+ const res = st.scope === "say" ? await R.undoSayOnly(project) : await R.undoReplace(project);
+ say({ ok: true, scope: st.scope, ...res }, st.scope === "say" ? (res.restored ? `"${res.restored.word}" is said "${res.restored.say}" again` : `the entry for "${res.removed.word}" removed`) : `${project.id}: the newest replace taken back`);
+ return 0;
+ }
+ const Q = await import("./readsQueue.mjs");
+ if (sub === "reread" && flags.has("--one")) {
+ // THE QUEUE STEP's FORM (the app runs it): one item, the reads it names -- never a dry run, a wait or every stale.
+ if (!str("--one")) throw new ReadsUsage("--one names the item (the queue's step: reread --one <item> --only <ids>)");
+ const clash = ["--dry-run", "--wait", "--stale", "--timeout"].filter((f) => flags.has(f));
+ if (clash.length) throw new ReadsUsage(`--one is the queue's step: it takes no ${clash.join(", ")} (umtool reads <p> reread [--only …] [--dry-run] [--wait] queues)`);
+ if (!flags.has("--only")) throw new ReadsUsage("--one takes --only <ids> (the reads its step was queued for)");
+ // With --json, stdout is one JSON document: the re-read command's own words go to stderr.
+ const res = await Q.runOneItem(project, str("--one"), ids("--only"), { reportsRoot: root, log: (s) => (json ? err(s) : out(s)), quiet: json ? { out: err, err } : null, ...(tts ? { tts } : {}) });
+ if (json) out(JSON.stringify({ ok: res.code === 0, item: str("--one"), argv: res.argv, reads: res.reads, code: res.code }, null, 2));
+ return res.code;
+ }
+ if (sub === "reread") {
+ const only = ids("--only");
+ const res = await Q.enqueueRereads(project, { ...qo, only: only.length ? only : null, dryRun: flags.has("--dry-run") });
+ const head = res.steps.length ? `${res.steps.reduce((a, s) => a + s.reads.length, 0)} read(s) ${res.dryRun ? "would be queued" : "queued"}, ${res.steps.length} step(s), in cut order: ${res.steps.map((s) => `${s.qid ?? "-"} ${s.item}`).join(", ")}` : "nothing queued";
+ if (res.dryRun) {
+ say({ ok: true, dryRun: true, steps: res.steps, skipped: res.skipped }, [head, ...res.skipped.map((s) => ` ${s.id}: ${s.why}`)].join("\n"));
+ return 0;
+ }
+ const tail = res.skipped.map((s) => ` ${s.id}: ${s.why}`);
+ if (!flags.has("--wait") || !res.steps.length) {
+ say({ ok: true, batch: res.batch?.id ?? null, steps: res.steps, skipped: res.skipped }, [head, ...tail].join("\n"));
+ return 0;
+ }
+ if (!json) out([head, ...tail].join("\n"));
+ const until = Date.now() + 1000 * (Number(str("--timeout")) > 0 ? Number(str("--timeout")) : 3600);
+ const mine = new Set(res.steps.map((s) => s.qid));
+ let said = null;
+ for (;;) {
+ const v = await Q.queueView(project, qo);
+ const rows = v.rows.filter((x) => mine.has(x.qid));
+ if (!rows.some((x) => x.state === "waiting" || x.state === "running")) {
+ const failed = rows.filter((x) => x.state !== "done");
+ say({ ok: !failed.length, rows }, failed.length ? `${failed.length} read(s) not re-read: ${failed.map((x) => `${x.read} (${x.state}${x.error ? `: ${x.error}` : ""})`).join("; ")}` : `re-read: ${rows.map((x) => x.read).join(", ")} -- each joined its list unpicked (umtool reads ${project.id} pick --new)`);
+ return failed.length ? 1 : 0;
+ }
+ if (!json && v.waiting && v.waiting !== said) out(` ${(said = v.waiting)}`);
+ if (Date.now() > until) {
+ say({ ok: false, rows, waiting: v.waiting }, `still going after --timeout: ${rows.map((x) => `${x.read} ${x.state}`).join(", ")}`);
+ return 3;
+ }
+ await sleep(2000);
+ }
+ }
+ if (sub === "queue") {
+ if (flags.has("--stop")) {
+ const res = await Q.stopQueue(project, qo);
+ say({ ok: true, ...res }, `${res.cancelled.length} step(s) stopped${res.running.length ? `; ${res.running.join(", ")} running: it finishes` : ""}`);
+ return 0;
+ }
+ if (str("--retry") !== null) {
+ const res = await Q.retryRead(project, str("--retry"), qo);
+ say({ ok: true, requeued: res.requeued }, res.said);
+ return 0;
+ }
+ const v = await Q.queueView(project, qo);
+ say({ ok: true, ...v }, [
+ v.rows.length ? `${project.id}: ${Object.entries(v.counts).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(", ")}` : `${project.id}: nothing queued`,
+ ...(v.waiting ? [` ${v.waiting}`] : []),
+ ...v.rows.map((x) => ` ${x.state.padEnd(8)} ${x.read.padEnd(22)} ${x.qid}${x.error ? ` -- ${x.error}` : ""}`),
+ ].join("\n"));
+ return 0;
+ }
+ if (sub === "pick") {
+ if (flags.has("--new") === flags.has("--old")) throw new ReadsUsage("pick takes --new or --old");
+ const only = ids("--only");
+ const res = await Q.pickReads(project, { which: flags.has("--new") ? "new" : "old", only: only.length ? only : null, reportsRoot: root, dryRun: flags.has("--dry-run") });
+ if (res.dryRun) say({ ok: true, dryRun: true, picked: res.picked }, `would pick (${flags.has("--new") ? "the new reads" : "what played before"}): ${res.picked.map((x) => x.item).join(", ")}`);
+ else say({ ok: true, picked: res.picked, token: res.result.token ?? null }, `picked (${flags.has("--new") ? "the new reads" : "what played before"}): ${res.picked.map((x) => x.item).join(", ")} -- one undo point`);
+ return 0;
+ }
+ throw new ReadsUsage(`reads: replace, undo, reread, queue or pick (not ${sub}); none lists the reads`);
+ } catch (e) {
+ const known = ["ReadsUsage", "ReplaceError", "QueueError", "StructureRefused", "StaleToken", "SayError"].includes(e?.constructor?.name) || e instanceof ReadsUsage;
+ if (!known) throw e;
+ const msg = e?.constructor?.name === "StructureRefused" ? e.errors.join("; ") : e.message;
+ if (json) out(JSON.stringify({ ok: false, error: msg }, null, 2));
+ else err(`umtool reads: ${msg}`);
+ return e instanceof ReadsUsage ? 2 : 1;
+ }
+}
diff --git a/umtool/lib/report/readsCli.test.mjs b/umtool/lib/report/readsCli.test.mjs
@@ -0,0 +1,138 @@
+// `umtool reads` (lane reads-find, readsCli.mjs): the CLI twin of the Reads page, every verb with --json -- the list
+// and Find, Replace (dry run, applied, undone), Everywhere, the queue, the picks -- and THE ONE COUNT: the reads "made
+// with other settings" here are exactly `umtool cast stale`'s. Temp dirs, invented people; noLiveEditor first.
+import "./noLiveEditor.mjs";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { readsCommand } from "./readsCli.mjs";
+import { castCommand } from "./castCli.mjs";
+import { LIVELY, castDoc, readManifestOf, readsProject } from "./reads.fixtures.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-reads-cli-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+
+async function cli(p, args) {
+ const lines = [];
+ const code = await readsCommand(["p", ...args], { root: p.root, out: (s) => lines.push(s), err: (s) => lines.push(s), queueDir: path.join(p.root, ".umtool-queue") });
+ const text = lines.join("\n");
+ let json = null;
+ try {
+ json = JSON.parse(text);
+ } catch {
+ json = null;
+ }
+ return { code, text, json };
+}
+
+test("reads --find --json: the matches and lines; --stale; replace --dry-run writes nothing; replace; undo", async () => {
+ const p = await readsProject(ROOT, "cli");
+ let r = await cli(p, ["--find", "north", "--json"]);
+ assert.equal(r.code, 0);
+ assert.deepEqual([r.json.find.matches, r.json.find.lines], [4, 3]);
+ const m0 = await readManifestOf(p);
+ r = await cli(p, ["replace", "north", "northern", "--dry-run", "--json"]);
+ assert.equal(r.json.dryRun, true);
+ assert.deepEqual(r.json.lines.map((l) => l.id), ["p-1", "c-1"]);
+ assert.deepEqual(await readManifestOf(p), m0);
+ r = await cli(p, ["replace", "north", "northern"]);
+ assert.equal(r.code, 0, r.text);
+ assert.match(r.text, /one undo point/);
+ r = await cli(p, ["--stale", "--json"]);
+ assert.deepEqual(r.json.reads.map((x) => x.id), ["p-1", "c-1"]);
+ r = await cli(p, ["undo", "--json"]);
+ assert.equal(r.code, 0, r.text);
+ assert.deepEqual(await readManifestOf(p), m0);
+ r = await cli(p, ["undo"]);
+ assert.equal(r.code, 1);
+ // Everywhere: the preview, whole words implied.
+ r = await cli(p, ["replace", "pier", "peer", "--say-only", "--dry-run", "--json"]);
+ assert.deepEqual(r.json.stale.map((x) => x.id), ["p-1"]);
+ assert.deepEqual(r.json.cards, ["c-1"]);
+});
+
+test("THE ONE COUNT: the reads made with other settings are `cast stale`'s, read by read", async () => {
+ const p = await readsProject(ROOT, "count", { cast: castDoc(LIVELY) });
+ const r = await cli(p, ["--json"]);
+ const logs = [];
+ await castCommand(["stale", "p", "--json"], { reportsRoot: p.root, log: (s) => logs.push(s), err: (s) => logs.push(s) });
+ const cast = JSON.parse(logs.join("\n"));
+ assert.ok(cast.count >= 1);
+ assert.equal(r.json.settingsStale, cast.count);
+ assert.deepEqual(r.json.reads.filter((x) => x.because.includes("settings")).map((x) => x.id).sort(), cast.reads.map((x) => (x.role === "post" && !x.thread ? x.id : `${x.id}/${x.role}`)).sort());
+});
+
+test("reread queues one step per item; queue --json says why they wait; --stop; pick with none waiting is refused", async () => {
+ const p = await readsProject(ROOT, "q");
+ await cli(p, ["replace", "north", "northern"]);
+ let r = await cli(p, ["reread", "--json"]);
+ assert.deepEqual(r.json.steps.map((s) => s.item), ["p-1", "c-1"]);
+ r = await cli(p, ["queue", "--json"]);
+ assert.equal(r.json.counts.waiting, 2);
+ assert.match(r.json.waiting, /queue runner is not running/);
+ r = await cli(p, ["queue", "--stop", "--json"]);
+ assert.equal(r.json.cancelled.length, 2);
+ r = await cli(p, ["pick", "--new", "--json"]);
+ assert.equal(r.code, 1);
+ assert.match(r.json.error, /no read waits for a pick/);
+ r = await cli(p, ["bogus"]);
+ assert.equal(r.code, 2);
+});
+
+// REVIEW 1, SHOULD 6: a thread read whose own line is ANOTHER take of the item (`--post-take`) that was SYNTHESIZED is
+// judged as that take is (madeOf follows it, so `cast stale` lists it): stale by settings here too, never "recorded".
+test("SHOULD 6: his line from a synthesized take (--post-take) -- the page and `cast stale` agree it is stale", async () => {
+ const { postsCommand } = await import("./postsCli.mjs");
+ const { wavOf } = await import("./reads.fixtures.mjs");
+ const p = await readsProject(ROOT, "post-take", { cast: castDoc(LIVELY) });
+ const stub = async (body) => {
+ await wavOf(body.out);
+ return { jobId: "j", result: { wav: body.out, engine: body.engine, voice: body.voice, tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }, reading: 0 } };
+ };
+ // p-1's take 1 was made with the defaults (the fixture); a thread read of it with his line from that take.
+ assert.equal(await postsCommand(["narrate", "p", "p-1", "--take", "--thread", "--post-take", "1"], { root: p.root, tts: stub, out: () => {}, err: () => {} }), 0);
+ const r = await cli(p, ["--json"]);
+ const row = r.json.reads.find((x) => x.id === "p-1/post");
+ const logs = [];
+ await castCommand(["stale", "p", "--json"], { reportsRoot: p.root, log: (s) => logs.push(s), err: (s) => logs.push(s) });
+ const cast = JSON.parse(logs.join("\n"));
+ assert.ok(cast.reads.some((x) => x.id === "p-1" && x.role === "post"), JSON.stringify(cast.reads));
+ assert.deepEqual([row.state, row.because], ["stale", ["settings"]]);
+ assert.match(row.why, /take 1/);
+ assert.equal(r.json.settingsStale, cast.count);
+});
+
+// REVIEW 1, SHOULD 8: each subcommand refuses a flag it does not take (never ignores it); `--` ends the flags;
+// --dry-run on undo, reread and pick changes nothing; errors keep the --json shape.
+test("SHOULD 8: unknown flags refused; -- ends the flags; --dry-run changes nothing; --json errors", async () => {
+ const p = await readsProject(ROOT, "flags");
+ let r = await cli(p, ["reread", "--bogus", "--json"]);
+ assert.equal(r.code, 2);
+ assert.match(r.json.error, /--bogus: not a flag of `reads <p> reread`/);
+ r = await cli(p, ["queue", "--dry-run"]);
+ assert.equal(r.code, 2, "queue takes no --dry-run");
+ // A `to` that starts with dashes, after --.
+ r = await cli(p, ["replace", "--dry-run", "--json", "--", "north", "--north--"]);
+ assert.equal(r.code, 0, r.text);
+ assert.equal(r.json.lines[0].after.includes("--north-- pier"), true);
+ const m0 = await readManifestOf(p);
+ await cli(p, ["replace", "north", "northern"]);
+ const m1 = await readManifestOf(p);
+ r = await cli(p, ["undo", "--dry-run", "--json"]);
+ assert.deepEqual([r.code, r.json.dryRun, r.json.available], [0, true, true]);
+ assert.deepEqual(await readManifestOf(p), m1, "undo --dry-run undoes nothing");
+ r = await cli(p, ["reread", "--dry-run", "--json"]);
+ assert.deepEqual(r.json.steps.map((s) => s.item), ["p-1", "c-1"]);
+ r = await cli(p, ["queue", "--json"]);
+ assert.equal(r.json.rows.length, 0, "reread --dry-run queues nothing");
+ r = await cli(p, ["pick", "--new", "--dry-run", "--json"]);
+ assert.equal(r.code, 1, "nothing to pick: refused, as the real one would be");
+ // queue --retry of a read never queued, and of a step that cannot be retried: the --json error shape.
+ r = await cli(p, ["queue", "--retry", "p-1", "--json"]);
+ assert.deepEqual([r.code, r.json.ok], [1, false]);
+ await cli(p, ["undo"]);
+ assert.deepEqual(await readManifestOf(p), m0);
+});
diff --git a/umtool/lib/report/readsQueue.mjs b/umtool/lib/report/readsQueue.mjs
@@ -0,0 +1,371 @@
+// THE RE-READ QUEUE (lane reads-find; operator ruling 4: re-reading happens only on a press): one press queues the
+// stale reads of a video -- or the ones ticked -- as steps of the DURABLE QUEUE (lib/queue/store.mjs), which the umtool
+// app runs one at a time, in order, only while its own job runner is idle (so a step and a bench press never run
+// at once), surviving a page reload and a restart (a step whose app died reads failed, and is retried by a press).
+//
+// ONE STEP PER ITEM, in cut order, none waiting on another (a failed one never holds the rest): `umtool reads <p>
+// reread --one <item> --only <ids>` -- which judges the item AGAIN when it runs (a read no longer stale is left
+// alone) and then runs, in-process, the very command the item's bench button runs (readAgainArgv.mjs): a post's
+// take (the bench's ask: postTakeAsk.mjs), a thread read's pieces (`--for`/`--tuned`), a screen line's, a card's
+// reading. Each synthesis is the editor's `tts-file` job on its `tts` lane, one at a time; a thread step asks one
+// job per piece it re-reads, one after another. A re-read joins the list UNPICKED (S3's ruling): its row reads
+// `unpicked` until a Pick (`umtool reads <p> pick`); a card's re-read is what the card says now, so it plays.
+//
+// <project>/narration/reads/queue.json { version: 1, batches: [{ id, at, by, rows: [{ read, item, kind, qid,
+// before }] }] }, newest last -- which step re-reads which read, and the take
+// that played before (Listen through's "old")
+//
+// Plain ESM: the CLI runs it under bare node.
+import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
+import { postIdOf, takesDirOf } from "umtool-report-to-video/post-narration";
+import { REPORTS_ROOT } from "../projects/core.mjs";
+import { withNotesLock } from "../annotations/store.mjs";
+import { addStep, cancelStep, getStep, listSteps, queueDirOf, readLease, resolveStep, retryStep, TERMINAL } from "../queue/store.mjs";
+import { projectReads } from "./reads.mjs";
+import { itemRereadArgv } from "./readAgainArgv.mjs";
+
+export const BATCH_FILE = "narration/reads/queue.json";
+/** How long a bench read's marker counts as a read in flight (the route's own, a job's longest wait). */
+export const BENCH_MARKER_MS = 45 * 60 * 1000;
+/** A re-read step's time limit (minutes): a thread read of several pieces behind a render. */
+export const REREAD_TIMEOUT_MIN = 120;
+
+export class QueueError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "QueueError";
+ }
+}
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const batchPath = (dir) => path.join(/* turbopackIgnore: true */ dir, ...BATCH_FILE.split("/"));
+
+/** The project's batches, oldest first (none, or a file that does not parse: `[]`). */
+export async function readBatches(dir) {
+ try {
+ const j = JSON.parse(await readFile(batchPath(dir), "utf8"));
+ return Array.isArray(j?.batches) ? j.batches.filter((b) => isObj(b) && Array.isArray(b.rows)) : [];
+ } catch {
+ return [];
+ }
+}
+
+async function withBatches(dir, fn, { dryRun = false } = {}) {
+ // A DRY RUN WRITES NOTHING: no lock file, no directory, no rewrite of the batches.
+ if (dryRun) return (await fn(await readBatches(dir))).result;
+ const file = batchPath(dir);
+ await mkdir(path.dirname(file), { recursive: true });
+ return withNotesLock(file, async () => {
+ const had = await readBatches(dir);
+ const { batches, result } = await fn(had);
+ // Nothing changed (nothing queued): the file is left as it is.
+ if (batches === had) return result;
+ const tmp = tmpPathFor(file);
+ await writeFile(tmp, `${JSON.stringify({ version: 1, batches: batches.slice(-20) }, null, 1)}\n`);
+ await rename(tmp, file);
+ return result;
+ });
+}
+
+const queueDirFor = (o) => o.queueDir ?? queueDirOf({ reportsRoot: o.reportsRoot ?? REPORTS_ROOT });
+
+/** The steps of the project's batches as they read now (a running one whose app died: failed). */
+async function stepsOf(qdir, batches) {
+ const out = new Map();
+ for (const b of batches) for (const r of b.rows) if (r.qid && !out.has(r.qid)) {
+ const s = await getStep(qdir, r.qid);
+ if (s) out.set(r.qid, resolveStep(s));
+ }
+ return out;
+}
+
+/** A step's state in the Reads page's words: waiting, running, done, failed, stopped. */
+const stateOf = (s) => (!s ? "gone" : s.state === "queued" || s.state === "blocked" ? "waiting" : s.state === "cancelled" ? "stopped" : s.state);
+
+/**
+ * RE-READ: the reads to queue (`only` their ids, else every stale one; an unpicked read already has its re-read and is
+ * queued only when named), one step per item, in cut order. A read whose item already has a step waiting or running
+ * is not queued twice. Returns `{ batch, steps: [{ qid, item, reads }], skipped: [{ id, why }] }`.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ only?: string[] | null, reportsRoot?: string, queueDir?: string, ctx?: any, by?: string }} [o]
+ */
+export async function enqueueRereads(project, o = {}) {
+ const { rows } = await projectReads(project, { ...(o.ctx ? { ctx: o.ctx } : {}), ...(o.reportsRoot ? { reportsRoot: o.reportsRoot } : {}) });
+ const only = o.only?.length ? new Set(o.only) : null;
+ const skipped = [];
+ if (only) for (const id of only) if (!rows.some((r) => r.id === id)) skipped.push({ id, why: "no such read in the cut" });
+ const want = rows.filter((r) => (only ? only.has(r.id) : r.state === "stale"));
+ const pick = [];
+ for (const r of want) {
+ if (r.state === "recorded") skipped.push({ id: r.id, why: "a recorded read is yours: record it again" });
+ else if (r.state === "fresh") skipped.push({ id: r.id, why: "fresh: nothing to re-read" });
+ else if (r.queueable === false) skipped.push({ id: r.id, why: r.why ?? "not re-read here" });
+ else pick.push(r);
+ }
+ const qdir = queueDirFor(o);
+ return withBatches(project.dir, async (batches) => {
+ const steps = await stepsOf(qdir, batches);
+ const busy = new Set(batches.flatMap((b) => b.rows).filter((x) => x.qid && ["waiting", "running"].includes(stateOf(steps.get(x.qid)))).map((x) => x.item));
+ const byItem = new Map();
+ for (const r of pick) {
+ if (busy.has(r.item)) {
+ skipped.push({ id: r.id, why: "its item is queued already" });
+ continue;
+ }
+ byItem.set(r.item, [...(byItem.get(r.item) ?? []), r]);
+ }
+ const made = [];
+ const rowsOut = [];
+ if (o.dryRun) {
+ const plan = [...byItem].sort((a, b) => a[1][0].n - b[1][0].n).map(([item, rs]) => ({ qid: null, item, reads: rs.map((r) => r.id) }));
+ return { batches, result: { batch: null, steps: plan, skipped, dryRun: true } };
+ }
+ for (const [item, rs] of [...byItem].sort((a, b) => a[1][0].n - b[1][0].n)) {
+ const ids = rs.map((r) => r.id);
+ const step = await addStep(qdir, {
+ argv: ["reads", project.id, "reread", "--one", item, "--only", ids.join(",")],
+ label: `re-read ${item}: ${ids.map((id) => id.split("/")[1] ?? "the read").join(", ")} (${project.id})`,
+ target: { project: project.id, take: null }, by: o.by ?? "umtool reads reread", timeoutMin: REREAD_TIMEOUT_MIN,
+ });
+ made.push({ qid: step.qid, item, reads: ids });
+ // What played before (Listen through's "old"): the take; a card's newest reading kept (its key has none now).
+ const cardBefore = (r) => {
+ const k = [...(r.readings ?? [])].sort((a, b) => String(a.createdAt ?? "").localeCompare(String(b.createdAt ?? ""))).at(-1);
+ return k ? { index: null, file: null, key: k.key } : null;
+ };
+ for (const r of rs) rowsOut.push({ read: r.id, item, kind: r.kind, qid: step.qid, before: r.kind === "card" ? cardBefore(r) : r.take ?? null });
+ }
+ if (!made.length) return { batches, result: { batch: null, steps: [], skipped } };
+ const batch = { id: `b${Date.now().toString(36)}`, at: new Date().toISOString(), by: o.by ?? "umtool reads reread", rows: rowsOut };
+ return { batches: [...batches, batch], result: { batch, steps: made, skipped } };
+ }, { dryRun: !!o.dryRun });
+}
+
+/** A bench read's marker with no job yet counts as in flight this long (the post-narration route's own rule). */
+export const BENCH_STARTING_MS = 2 * 60 * 1000;
+
+/**
+ * Whether an editor job has ENDED (done, failed, cancelled): the editor asked (`GET /api/ops/job/<id>`); null when it
+ * cannot be asked (no editor, no token, no answer) -- the caller then falls back on the marker's age.
+ */
+export async function editorJobEnded(jobId, { env = process.env } = {}) {
+ try {
+ const { editorConfig } = await import("./fetchWindows.mjs");
+ const cfg = editorConfig(env);
+ if (!cfg.token) return null;
+ const r = await fetch(`${cfg.url}/api/ops/job/${encodeURIComponent(jobId)}`, { headers: { authorization: `Bearer ${cfg.token}` }, signal: AbortSignal.timeout(5000) });
+ const j = await r.json().catch(() => null);
+ if (!r.ok || !j?.job) return null;
+ return !["queued", "running"].includes(String(j.job.status));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Whether a bench read of post item `e` is in flight -- the take op's marker, by the route's rule: a marker naming a
+ * job is in flight while that job has not ended; one with no job yet, for its first two minutes. A marker whose take
+ * is already kept, or whose job the editor says ended, holds nothing. `jobEnded(jobId)` is editorJobEnded (a test's
+ * stub); when the editor cannot say, the marker counts for BENCH_MARKER_MS.
+ */
+export async function benchReadInFlight(dir, e, { now = Date.now(), jobEnded = editorJobEnded } = {}) {
+ if (e?.type !== "post") return null;
+ const file = path.join(dir, ...takesDirOf(postIdOf(e)).split("/"), ".reading.json");
+ const st = await stat(file).catch(() => null);
+ if (!st) return null;
+ const marker = await readFile(file, "utf8").then(JSON.parse, () => null);
+ const at = Date.parse(String(marker?.at ?? "")) || st.mtimeMs;
+ if (marker?.file && (e.narration?.takes ?? []).some((t) => t?.file === marker.file)) return null;
+ if (!marker?.jobId) return now - at < BENCH_STARTING_MS ? { at: new Date(at).toISOString(), jobId: null } : null;
+ const ended = await jobEnded(String(marker.jobId));
+ if (ended === true) return null;
+ if (ended === null && now - at > BENCH_MARKER_MS) return null;
+ return { at: new Date(at).toISOString(), jobId: marker.jobId };
+}
+
+/**
+ * ONE STEP RUN (`umtool reads <p> reread --one <item> --only <ids>`): the item judged again; its reads still stale
+ * re-read by the bench's own command, in-process. Returns `{ code, argv, reads }` (`argv` null: nothing to do).
+ * `run(argv)` runs a umtool argv (default: the CLI's own dispatch); `tts` / `narrate` the editor's ops as a test hands
+ * them (postsCommand's `tts`, cardNarrationCommand's `narrate`).
+ */
+export async function runOneItem(project, item, ids, { reportsRoot = REPORTS_ROOT, run = null, log = (s) => console.log(s), tts = null, narrate = null, jobEnded = undefined, quiet = null } = {}) {
+ const { rows, ctx } = await projectReads(project, { reportsRoot });
+ const e = ctx.manifest.timeline.find((x) => x?.id === item);
+ if (!e) throw new QueueError(`${item} is not in the cut any more`);
+ const want = new Set(ids ?? []);
+ // Never a read the queue cannot re-read (a piece from a synthesized take: its re-read is that take's, on the bench).
+ const reads = rows.filter((r) => r.item === item && r.queueable !== false && (want.size ? want.has(r.id) : true) && (r.state === "stale" || (want.has(r.id) && r.state === "unpicked") || r.state === "none"));
+ if (!reads.length) {
+ log(`${item}: nothing to re-read now (its reads are fresh, or re-read and waiting for a pick)`);
+ return { code: 0, argv: null, reads: [] };
+ }
+ const inFlight = await benchReadInFlight(project.dir, e, jobEnded ? { jobEnded } : {});
+ if (inFlight) throw new QueueError(`${item}: a read of this post is being made on its bench (since ${inFlight.at}) -- retry when it lands`);
+ const argv = itemRereadArgv(project.id, e, reads);
+ log(`${item}: re-reading ${reads.map((r) => r.id).join(", ")} -- umtool ${argv.join(" ")}`);
+ const exec = run ?? (async (a) => {
+ // `quiet` (`--json`): the command's own words where the caller says (stderr), never into the JSON on stdout.
+ if (a[0] === "posts") return (await import("./postsCli.mjs")).postsCommand(a.slice(1), { root: reportsRoot, ...(tts ? { tts } : {}), ...(quiet ?? {}) });
+ if (a[0] === "narration") return (await import("./cardNarrationCli.mjs")).cardNarrationCommand(a.slice(1), { root: reportsRoot, ...(narrate ? { narrate } : {}), ...(quiet ?? {}) });
+ throw new QueueError(`not a re-read command: ${a.join(" ")}`);
+ });
+ const code = await exec(argv);
+ return { code, argv, reads: reads.map((r) => r.id) };
+}
+
+/**
+ * THE QUEUE AS THE READS PAGE SHOWS IT: `{ rows: [{ read, item, kind, qid, state, error, before, at }], waiting,
+ * counts }` -- the newest batch's rows (and older ones not finished), each with its step's state; `waiting` ONE
+ * sentence when steps wait, saying why (the runner not running, render mode, a bench read in flight, another step
+ * of the queue), else null.
+ */
+export async function queueView(project, o = {}) {
+ const qdir = queueDirFor(o);
+ const batches = await readBatches(project.dir);
+ const steps = await stepsOf(qdir, batches);
+ const last = batches.at(-1) ?? null;
+ const live = batches.filter((b) => b === last || b.rows.some((r) => !TERMINAL.has(steps.get(r.qid)?.state ?? "done")));
+ const rows = live.flatMap((b) => b.rows.map((r) => {
+ const s = steps.get(r.qid);
+ return { ...r, batch: b.id, state: stateOf(s), error: s?.state === "failed" || s?.state === "cancelled" || s?.state === "blocked" ? s.error ?? null : null, at: b.at };
+ }));
+ const counts = Object.fromEntries(["waiting", "running", "done", "failed", "stopped"].map((k) => [k, new Set(rows.filter((r) => r.state === k).map((r) => r.qid)).size]));
+ let waiting = null;
+ if (counts.waiting) waiting = await waitingReason(project, qdir, rows, o);
+ return { rows, waiting, counts, batch: last?.id ?? null };
+}
+
+/** Why the project's steps wait, in one sentence (the app adds its own: its job runner busy). */
+async function waitingReason(project, qdir, rows, o) {
+ const lease = await readLease(qdir).catch(() => null);
+ if (!lease?.live) return "waiting: the umtool app's queue runner is not running (it runs inside the umtool app's server) -- start umtool, and they run";
+ const { renderWaitSentence } = await import("./renderMode.mjs");
+ const render = renderWaitSentence(o.env ?? process.env);
+ if (render) return `waiting: render mode holds the machine -- ${render}`;
+ const all = await listSteps(qdir);
+ const ours = new Set(rows.map((r) => r.qid));
+ const running = all.map((s) => resolveStep(s)).find((s) => s.state === "running");
+ if (running && ours.has(running.qid)) {
+ const { readManifest } = await import("../projects/report.mjs");
+ const m = await readManifest(project.dir);
+ for (const r of rows.filter((x) => x.state === "running")) {
+ const e = m?.timeline?.find((x) => x?.id === r.item);
+ if (e && (await benchReadInFlight(project.dir, e))) return `waiting: a read of ${r.item} is being made on its bench -- the queue goes on when it lands`;
+ }
+ return null;
+ }
+ if (running) return `waiting behind ${running.qid} (${running.label}) -- the queue runs one step at a time`;
+ const first = all.find((s) => s.state === "queued" && !ours.has(s.qid) && s.seq < Math.min(...[...ours].map((q) => all.find((x) => x.qid === q)?.seq ?? Infinity)));
+ if (first) return `waiting behind ${first.qid} (${first.label}) -- the queue runs one step at a time`;
+ return "waiting for its turn: the app starts the next step when its own job runner is free";
+}
+
+/** STOP: every step of the project's batches not started is cancelled; a running one finishes. */
+export async function stopQueue(project, o = {}) {
+ const qdir = queueDirFor(o);
+ const batches = await readBatches(project.dir);
+ const steps = await stepsOf(qdir, batches);
+ const cancelled = [];
+ const running = [];
+ for (const [qid, s] of steps) {
+ if (s.state === "queued" || s.state === "blocked") {
+ await cancelStep(qdir, qid, { by: "umtool reads queue --stop" });
+ cancelled.push(qid);
+ } else if (s.state === "running") running.push(qid);
+ }
+ return { cancelled, running };
+}
+
+/** RETRY one read's step (failed or stopped): it goes back in the queue. */
+export async function retryRead(project, readId, o = {}) {
+ const qdir = queueDirFor(o);
+ const row = (await readBatches(project.dir)).flatMap((b) => b.rows).reverse().find((r) => r.read === readId);
+ if (!row) throw new QueueError(`${readId} was never queued (umtool reads ${project.id} reread --only ${readId})`);
+ try {
+ return await retryStep(qdir, row.qid);
+ } catch (err) {
+ throw new QueueError(`${readId}: ${err instanceof Error ? err.message : String(err)}`);
+ }
+}
+
+/**
+ * PICK (Listen through's Pick, `umtool reads <p> pick`): `which` "new" -- each unpicked read's newer take (reads.mjs
+ * `newTake`) made the one that plays; "old" -- each re-read row of the newest batch back to the take that played
+ * before (a card: its reading before, words and all). `only`: those read ids. ONE structural write, its own undo point.
+ * Returns `{ picked: [{ item, take?, key? }], result }`.
+ */
+export async function pickReads(project, { which = "new", only = null, token = null, reportsRoot = REPORTS_ROOT, dryRun = false } = {}) {
+ if (which !== "new" && which !== "old") throw new QueueError("pick takes --new or --old");
+ const keep = only?.length ? new Set(only) : null;
+ const picks = new Map();
+ if (which === "new") {
+ const { rows } = await projectReads(project, { reportsRoot });
+ for (const r of rows) {
+ if (r.state !== "unpicked" || !r.newTake || (keep && !keep.has(r.id))) continue;
+ const had = picks.get(r.item);
+ if (!had || r.newTake.index > had.take) picks.set(r.item, { item: r.item, take: r.newTake.index });
+ }
+ } else {
+ const last = (await readBatches(project.dir)).at(-1);
+ for (const r of last?.rows ?? []) {
+ if (!r.before || (keep && !keep.has(r.read))) continue;
+ picks.set(r.item, r.before.key ? { item: r.item, key: r.before.key } : { item: r.item, take: r.before.index, file: r.before.takeFile ?? r.before.file });
+ }
+ }
+ if (!picks.size) throw new QueueError(which === "new" ? "no read waits for a pick (no unpicked re-read)" : "no re-read to go back from (the newest batch has none)");
+ if (dryRun) return { picked: [...picks.values()], result: null, dryRun: true };
+ const { cardReadings, readingOfRecord } = await import("./cardNarrationCli.mjs");
+ const cards = new Map();
+ for (const x of picks.values()) {
+ if (!x.key) continue;
+ const rec = (await cardReadings(project.dir, x.item)).find((r) => r.key === x.key);
+ if (!rec) throw new QueueError(`${x.item}: its reading ${x.key.slice(0, 12)} is not kept any more`);
+ cards.set(x.item, { text: rec.text, reading: readingOfRecord(rec) > 0 ? readingOfRecord(rec) : null, tuning: rec.askedTuning ?? null, rec });
+ }
+ // Each card's key as it plays now: a verdict given on it moves with a pick of the same words (keepCardVerdict).
+ const { narrationsOf } = await import("umtool-report-to-video/narration");
+ const { readManifest } = await import("../projects/report.mjs");
+ const keysNow = new Map(narrationsOf((await readManifest(project.dir)) ?? {}).map((n) => [n.id, n.key]));
+ const { cardNarrationIn, manifestToken, postNarrationIn, structuralEdit } = await import("./manifest.mjs");
+ const { withEditNotes } = await import("./edit-guard.mjs");
+ const tok = token ?? (await manifestToken(project.dir));
+ const { result } = await withEditNotes(project, async () => structuralEdit(project.dir, "reads-pick", tok, (m) => {
+ for (const x of picks.values()) {
+ if (x.key) {
+ const { rec: _r, ...patch } = cards.get(x.item);
+ void _r;
+ cardNarrationIn(m, x.item, patch);
+ continue;
+ }
+ const e = m.timeline.find((y) => y?.id === x.item);
+ const takes = e?.narration?.takes ?? [];
+ // The take by its file (an index moves when a take is dropped), else its index.
+ const at = x.file ? takes.findIndex((t) => t?.file === x.file) : x.take;
+ if (!Number.isInteger(at) || at < 0 || !takes[at]) throw new QueueError(`${x.item}: its take ${x.file ?? x.take} is not in its list any more`);
+ postNarrationIn(m, x.item, { pick: at });
+ }
+ return { items: [...picks.keys()] };
+ }, { snapshotEvery: 0 }));
+ // A VERDICT ON THESE WORDS IS KEPT, exactly as `narration --pick` keeps it (cardNarrationCli.mjs keepCardVerdict).
+ const { keepCardVerdict } = await import("./cardNarrationCli.mjs");
+ for (const [id, c] of cards) await keepCardVerdict(project.dir, id, { nowKey: keysNow.get(id) ?? null, rec: c.rec });
+ return { picked: [...picks.values()], result };
+}
+
+/**
+ * The re-read step RUNNING now for one item of a project, or null -- the bench's single-post take op says it instead
+ * of asking a second read of the same post (lane reads-find): `{ qid, label }`.
+ */
+export async function rereadRunningFor(projectId, item, o = {}) {
+ const qdir = queueDirFor(o);
+ for (const s of await listSteps(qdir)) {
+ const r = resolveStep(s);
+ if (r.state !== "running" || r.argv?.[0] !== "reads" || r.argv?.[1] !== projectId) continue;
+ if (r.argv[r.argv.indexOf("--one") + 1] === item) return { qid: r.qid, label: r.label };
+ }
+ return null;
+}
diff --git a/umtool/lib/report/readsQueue.test.mjs b/umtool/lib/report/readsQueue.test.mjs
@@ -0,0 +1,225 @@
+// THE RE-READ QUEUE (lane reads-find, readsQueue.mjs): one step per item in cut order on the durable queue, each the
+// item's bench command (readAgainArgv.mjs: the same argv a bench press runs), run one at a time; a re-read joins
+// UNPICKED; Stop cancels what has not started; state survives a reload (it is on disk); a failed step says why and is
+// retried; a bench read in flight holds a step back. Temp dirs, a stub tts, invented people.
+import "./noLiveEditor.mjs";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { listSteps, queueTick, resolveStep } from "../queue/store.mjs";
+import { projectReads } from "./reads.mjs";
+import { enqueueRereads, pickReads, queueView, readBatches, retryRead, runOneItem, stopQueue } from "./readsQueue.mjs";
+import { itemRereadArgv, readAgainArgv } from "./readAgainArgv.mjs";
+import { postsCommand } from "./postsCli.mjs";
+import { cardNarrationCommand } from "./cardNarrationCli.mjs";
+import { keepCardReading, readManifestOf, readsProject, wavOf } from "./reads.fixtures.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-reads-queue-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+
+/** The fixture with a word changed in each kind: p-1's script, p-2's script and screen line 1, the card. */
+async function changed(name) {
+ const p = await readsProject(ROOT, name);
+ const m = await readManifestOf(p);
+ m.timeline[0].narration.script = m.timeline[0].narration.script.replace("noon", "twelve noon");
+ m.timeline[1].narration.script = m.timeline[1].narration.script.replace("Tuesday", "Wednesday");
+ m.timeline[1].screens[0].saidAs = { 1: "Not this year, they told us." };
+ m.timeline[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));
+ return { ...p, queueDir: path.join(p.root, ".umtool-queue") };
+}
+const o = (p, x = {}) => ({ reportsRoot: p.root, queueDir: p.queueDir, ...x });
+const stubAsk = (asked) => async (body) => {
+ asked.push(body);
+ await wavOf(body.out);
+ return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice, tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3, ...(body.tuning ?? {}) }, reading: body.reading ?? 0 } };
+};
+/** The editor stub for a card: its reading kept beside the build, as narrate-via-editor keeps it. */
+const stubNarrate = (p) => async ({ narrations }) => {
+ for (const n of narrations) await keepCardReading(p.dir, n, { createdAt: new Date().toISOString() });
+ return new Map(narrations.map((n) => [n.id, { seconds: 1.4 }]));
+};
+/** The CLI's own commands, with the stubs: what a step runs in-process. */
+const runner = (p, asked) => async (argv) => {
+ if (argv[0] === "posts") return postsCommand(argv.slice(1), { root: p.root, tts: stubAsk(asked), out: () => {}, err: () => {} });
+ if (argv[0] === "narration") return cardNarrationCommand(argv.slice(1), { root: p.root, narrate: stubNarrate(p), out: () => {}, err: () => {} });
+ throw new Error(argv.join(" "));
+};
+/** The app's runner, in-process: each step's `reads … reread --one` run here; `seen` counts how many run at once. */
+function inProcessExec(p, { asked = [], fail = null, seen = { now: 0, max: 0 } } = {}) {
+ return {
+ busy: () => null,
+ start(step, { onEnd }) {
+ seen.now += 1;
+ seen.max = Math.max(seen.max, seen.now);
+ const item = step.argv[step.argv.indexOf("--one") + 1];
+ const ids = step.argv[step.argv.indexOf("--only") + 1].split(",");
+ void (async () => {
+ try {
+ if (fail?.(item)) throw new Error(`the editor refused ${item}`);
+ const r = await runOneItem(p, item, ids, { reportsRoot: p.root, run: runner(p, asked), log: () => {} });
+ onEnd({ exitCode: r.code, signal: null, cancelled: false, error: null });
+ } catch (err) {
+ onEnd({ exitCode: 1, signal: null, cancelled: false, error: err instanceof Error ? err.message : String(err) });
+ } finally {
+ seen.now -= 1;
+ }
+ })();
+ return { pid: process.pid, jobId: null, cancel: () => {} };
+ },
+ };
+}
+async function drain(p, exec, state = { held: new Map() }) {
+ const until = Date.now() + 90_000;
+ while (Date.now() < until) {
+ await queueTick(p.queueDir, exec, state);
+ const steps = (await listSteps(p.queueDir)).map((s) => resolveStep(s, { owned: new Set(state.held.keys()) }));
+ if (!steps.some((s) => s.state === "queued" || s.state === "running")) return steps;
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ throw new Error("the queue did not drain");
+}
+
+test("RE-READ: one step per item, in cut order, none waiting on another -- each the item's bench command", async () => {
+ const p = await changed("order");
+ const r = await enqueueRereads(p, o(p));
+ assert.deepEqual(r.steps.map((s) => [s.item, s.reads]), [["p-1", ["p-1"]], ["p-2", ["p-2/post", "p-2/screen:s1:1"]], ["c-1", ["c-1"]]]);
+ const steps = await listSteps(p.queueDir);
+ assert.deepEqual(steps.map((s) => s.argv.slice(2).join(" ")), ["reread --one p-1 --only p-1", "reread --one p-2 --only p-2/post,p-2/screen:s1:1", "reread --one c-1 --only c-1"]);
+ assert.ok(steps.every((s) => s.after === null));
+ // Not queued twice while its step waits.
+ assert.deepEqual((await enqueueRereads(p, o(p))).skipped.map((s) => s.why), ["its item is queued already", "its item is queued already", "its item is queued already", "its item is queued already"]);
+ // The words each step runs: the bench's own.
+ const { rows, ctx } = await projectReads(p, { reportsRoot: p.root });
+ const of = (item) => rows.filter((x) => x.item === item && x.state === "stale");
+ const e = (id) => ctx.manifest.timeline.find((x) => x.id === id);
+ assert.deepEqual(itemRereadArgv("p", e("p-1"), of("p-1")), ["posts", "narrate", "p", "p-1", "--take", "--reading", "next", "--no-pick", "--bench-slurs"]);
+ assert.deepEqual(itemRereadArgv("p", e("p-2"), of("p-2")), ["posts", "screen", "p", "p-2", "read", "--tuned", "post=reading:next", "--tuned", "screen:s1:1=reading:next", "--no-pick"]);
+ assert.deepEqual(itemRereadArgv("p", e("c-1"), of("c-1")), ["narration", "p", "c-1", "--read"]);
+ // ONE stale line: exactly the line's Read again (the post-narration route's screen-read op builds the same words).
+ const line = of("p-2").filter((x) => x.role === "screen:s1:1");
+ assert.deepEqual(itemRereadArgv("p", e("p-2"), line), ["posts", "screen", "p", "p-2", "read", ...readAgainArgv({ for: "screen:s1:1", reading: "next", keepPick: true })]);
+});
+
+test("the queue runs to done, ONE step at a time; each re-read joins unpicked; a card's re-read plays; picks are a press", async () => {
+ const p = await changed("run");
+ await enqueueRereads(p, o(p));
+ const asked = [];
+ const seen = { now: 0, max: 0 };
+ const steps = await drain(p, inProcessExec(p, { asked, seen }));
+ assert.deepEqual(steps.map((s) => s.state), ["done", "done", "done"]);
+ assert.equal(seen.max, 1, "never two at once");
+ // p-1: one ask, the bench's (its slur rule; the next reading of new words is 0); p-2: its two changed pieces only.
+ assert.equal(asked.filter((b) => /twelve noon/.test(b.text)).length, 1);
+ assert.equal(asked.some((b) => /Wednesday/.test(b.text)), true);
+ assert.equal(asked.some((b) => /they told us/.test(b.text)), true);
+ // An unchanged line is asked as it was read (its reading, no tuning of its own): the cache's key -- this fixture keeps
+ // no parts cache, so it is asked again here, at the same key.
+ const tolls = asked.filter((b) => /tolls going up/.test(b.text));
+ assert.ok(tolls.every((b) => !b.reading && !b.tuning), JSON.stringify(tolls));
+ const by = Object.fromEntries((await projectReads(p, { reportsRoot: p.root })).rows.map((r) => [r.id, r.state]));
+ assert.deepEqual([by["p-1"], by["p-2/post"], by["p-2/screen:s1:1"], by["c-1"]], ["unpicked", "unpicked", "unpicked", "fresh"]);
+ const m = await readManifestOf(p);
+ assert.equal(m.timeline[0].narration.pick, 0, "never picked by itself");
+ const v = await queueView(p, o(p));
+ assert.deepEqual(v.counts, { waiting: 0, running: 0, done: 3, failed: 0, stopped: 0 });
+ assert.equal(v.waiting, null);
+ // PICK every new read: one undo point; fresh.
+ const picked = await pickReads(p, { which: "new", reportsRoot: p.root });
+ assert.deepEqual(picked.picked.map((x) => x.item), ["p-1", "p-2"]);
+ let after = Object.fromEntries((await projectReads(p, { reportsRoot: p.root })).rows.map((r) => [r.id, r.state]));
+ assert.deepEqual([after["p-1"], after["p-2/post"], after["p-2/screen:s1:1"]], ["fresh", "fresh", "fresh"]);
+ // And back to the old ones (the card's words with its old reading).
+ await pickReads(p, { which: "old", only: ["p-1", "c-1", "p-2/post"], reportsRoot: p.root });
+ const m2 = await readManifestOf(p);
+ assert.equal(m2.timeline[0].narration.pick, 0);
+ assert.equal(m2.timeline[1].narration.pick, 0, "a thread item back to its take (by the take's file, not a part's)");
+ assert.equal(m2.timeline[3].narration.text, "Six months later, the north pier reopened.");
+ after = Object.fromEntries((await projectReads(p, { reportsRoot: p.root })).rows.map((r) => [r.id, r.state]));
+ assert.deepEqual([after["p-1"], after["c-1"]], ["unpicked", "fresh"]);
+});
+
+test("Stop cancels what has not started; the state is on disk (a reload reads it); a failed step says why and is retried", async () => {
+ const p = await changed("stop");
+ await enqueueRereads(p, o(p));
+ // Nothing runs the queue: waiting, and why.
+ let v = await queueView(p, o(p));
+ assert.equal(v.counts.waiting, 3);
+ assert.match(v.waiting, /queue runner is not running/);
+ // One turn of a runner whose first step fails: p-1 failed with its reason; Stop cancels the rest not started.
+ const exec = inProcessExec(p, { fail: (item) => item === "p-1" });
+ const state = { held: new Map() };
+ await queueTick(p.queueDir, exec, state);
+ for (let i = 0; i < 200 && state.held.size; i += 1) await new Promise((r) => setTimeout(r, 20));
+ await queueTick(p.queueDir, { ...exec, busy: () => "a bench press (job-9)" }, state);
+ const stopped = await stopQueue(p, o(p));
+ assert.equal(stopped.cancelled.length, 2);
+ v = await queueView(p, o(p));
+ assert.deepEqual(v.rows.map((r) => [r.read, r.state]), [["p-1", "failed"], ["p-2/post", "stopped"], ["p-2/screen:s1:1", "stopped"], ["c-1", "stopped"]]);
+ // A RELOAD: nothing in memory -- the batch file and the steps say the same.
+ assert.equal((await readBatches(p.dir)).length, 1);
+ assert.deepEqual((await queueView(p, o(p))).rows.map((r) => r.state), v.rows.map((r) => r.state));
+ // Retry the failed one: waiting again, then done.
+ await retryRead(p, "p-1", o(p));
+ assert.equal((await queueView(p, o(p))).rows.find((r) => r.read === "p-1").state, "waiting");
+ await drain(p, inProcessExec(p));
+ assert.equal((await queueView(p, o(p))).rows.find((r) => r.read === "p-1").state, "done");
+});
+
+test("a bench read of the post in flight holds its step back (retryable); a read no longer stale is left alone", async () => {
+ const p = await changed("bench");
+ const marker = path.join(p.dir, "narration", "posts", "1", ".reading.json");
+ await mkdir(path.dirname(marker), { recursive: true });
+ await writeFile(marker, JSON.stringify({ jobId: "job-77", file: "narration/posts/1/take-9.orpheus-tara.wav", at: new Date().toISOString() }));
+ await assert.rejects(runOneItem(p, "p-1", ["p-1"], { reportsRoot: p.root, run: async () => 0, log: () => {} }), /being made on its bench/);
+ await rm(marker);
+ // Fresh again (its script back as read): nothing run.
+ const m = await readManifestOf(p);
+ m.timeline[0].narration.script = m.timeline[0].narration.takes[0].script;
+ await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m, null, 2));
+ let ran = 0;
+ const r = await runOneItem(p, "p-1", ["p-1"], { reportsRoot: p.root, run: async () => (ran += 1, 0), log: () => {} });
+ assert.equal(r.argv, null);
+ assert.equal(ran, 0);
+ void readFile;
+});
+
+// REVIEW 1, SHOULD 9: a Pick on a card keeps its review verdict exactly as `narration --pick` does -- a verdict given on
+// the card as it played, on the same words, moves to the reading picked.
+test("SHOULD 9: reads pick on a card keeps a verdict given on the same words", async () => {
+ const p = await readsProject(ROOT, "verdict");
+ const { narrationsOf } = await import("umtool-report-to-video/narration");
+ const { readNarrationReview, setNarrationReview } = await import("umtool-report-to-video/narration-review");
+ const m = await readManifestOf(p);
+ const n0 = narrationsOf(m).find((x) => x.id === "c-1");
+ await setNarrationReview(p.dir, "c-1", { verdict: "approved", key: n0.key, text: n0.text });
+ // Another reading of the same words kept (reading 1), and a batch whose "before" is it.
+ const n1 = narrationsOf({ ...m, timeline: m.timeline.map((e) => (e.id === "c-1" ? { ...e, narration: { ...e.narration, reading: 1 } } : e)) }).find((x) => x.id === "c-1");
+ await keepCardReading(p.dir, { ...n1, reading: 1 }, { createdAt: "2026-11-03T00:00:00.000Z" });
+ await mkdir(path.join(p.dir, "narration", "reads"), { recursive: true });
+ await writeFile(path.join(p.dir, "narration", "reads", "queue.json"), JSON.stringify({ version: 1, batches: [{ id: "b1", at: "2026-11-03T00:00:00.000Z", rows: [{ read: "c-1", item: "c-1", kind: "card", qid: "q1", before: { index: null, file: null, key: n1.key } }] }] }));
+ await pickReads(p, { which: "old", only: ["c-1"], reportsRoot: p.root });
+ assert.equal((await readManifestOf(p)).timeline[3].narration.reading, 1);
+ const row = (await readNarrationReview(p.dir)).rows["c-1"];
+ assert.deepEqual([row.verdict, row.key], ["approved", n1.key]);
+});
+
+// REVIEW 1, a nit: a bench marker holds the item's step only by the route's rule -- its job not ended, or (no job yet)
+// for two minutes -- never 45 minutes for a press that failed.
+test("a bench marker: in flight while its job runs; not once its job ended; a jobless one only for two minutes", async () => {
+ const { benchReadInFlight } = await import("./readsQueue.mjs");
+ const p = await readsProject(ROOT, "marker");
+ const e = (await readManifestOf(p)).timeline[0];
+ const marker = path.join(p.dir, "narration", "posts", "1", ".reading.json");
+ const put = (o) => writeFile(marker, JSON.stringify(o));
+ await put({ jobId: "job-1", file: "narration/posts/1/take-9.orpheus-tara.wav", at: new Date().toISOString() });
+ assert.ok(await benchReadInFlight(p.dir, e, { jobEnded: async () => false }));
+ assert.equal(await benchReadInFlight(p.dir, e, { jobEnded: async () => true }), null, "its job ended: a failed press holds nothing");
+ await put({ starting: true, at: new Date(Date.now() - 3 * 60 * 1000).toISOString() });
+ assert.equal(await benchReadInFlight(p.dir, e, { jobEnded: async () => false }), null, "no job after two minutes: stale");
+ await put({ starting: true, at: new Date().toISOString() });
+ assert.ok(await benchReadInFlight(p.dir, e, { jobEnded: async () => false }));
+});
diff --git a/umtool/lib/report/readsReplace.mjs b/umtool/lib/report/readsReplace.mjs
@@ -0,0 +1,279 @@
+// REPLACE OVER A VIDEO's READS (lane reads-find; operator ruling 3: an edit changes only what is SPOKEN, never what
+// is shown), in two scopes, each previewed before it is applied and neither synthesizing anything:
+//
+// These reads the spoken text of the matched reads rewritten, in ONE structural write (one undo point,
+// `auto-before-reads-replace`, always its own): a post's script (postNarrationIn, marked
+// for reading as Save script marks it), a screen line's "said as" (`screens[j].saidAs`,
+// created from the line as read when it has none -- the line as shown untouched), a card's
+// narration (cardNarrationIn). A parent, the quoted or a linked post has no spoken-only
+// words: listed, not changed ("said as shown: only Everywhere changes this"); a recorded
+// read is yours and is never replaced.
+// Everywhere, from now on a pronunciation entry (postSay.mjs updateLexicon, `umtool posts say add`'s writer): every
+// read of a post, present and future, says it that way. Whole words only (the lexicon's
+// rule), and never a card's narration (cards are not said through the lexicon).
+//
+// Either way the reads that changed show as stale (reads.mjs); a re-read is a press (readsQueue.mjs).
+//
+// Plain ESM: the CLI runs it under bare node.
+import { LEGACY_EDIT_TEXT, findPattern, matchesIn, projectReads, readsContext, replaceIn } from "./reads.mjs";
+import { AUTO_SNAPSHOT_PREFIX, StructureRefused, cardNarrationIn, manifestToken, postItemIn, postNarrationIn, structuralEdit, undoStructural } from "./manifest.mjs";
+import { screenLineSaid, screensOf } from "umtool-report-to-video/post-screens";
+import { lexiconKey, normalizeLexicon } from "umtool-report-to-video/post-say";
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { createHash } from "node:crypto";
+import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
+import { withNotesLock } from "../annotations/store.mjs";
+
+export const REPLACE_OP = "reads-replace";
+export const UNDO_LABEL = `${AUTO_SNAPSHOT_PREFIX}${REPLACE_OP}`;
+/** Said where Everywhere is offered with Whole word off. */
+export const SAY_WHOLE_WORDS = "Everywhere, from now on matches whole words only (a pronunciation entry): turn Whole word on";
+/** Said for a card a pronunciation entry does not reach. */
+export const SAY_NOT_CARDS = "cards are not said through the lexicon: use These reads for a card";
+
+export class ReplaceError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "ReplaceError";
+ }
+}
+
+const clone = (v) => JSON.parse(JSON.stringify(v));
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+
+/** What each kind's replace does to a read whose spoken text is still its shown text. */
+function createsNote(r) {
+ if (!r.shownSpoken) return null;
+ if (r.kind === "screen") return "creates its said-as (the line as shown is untouched)";
+ return "creates its script from the post's words (the post as shown is untouched)";
+}
+
+/** The writes of a replace, in `m` (inside a write or on a copy): `lines` grouped by item. */
+export function replaceReadsIn(m, lines) {
+ const byItem = new Map();
+ for (const l of lines) byItem.set(l.item, [...(byItem.get(l.item) ?? []), l]);
+ for (const [item, ls] of byItem) {
+ const e = (m.timeline ?? []).find((x) => x?.id === item);
+ if (!e) throw new ReplaceError(`no item ${item} in the cut`);
+ const cardLine = ls.find((l) => l.kind === "card");
+ if (cardLine) {
+ cardNarrationIn(m, item, { text: cardLine.after });
+ continue;
+ }
+ const scriptLine = ls.find((l) => l.kind === "post" || (l.kind === "thread" && l.role === "post"));
+ if (scriptLine) postNarrationIn(m, item, { script: scriptLine.after }, { forReading: true });
+ const lineLines = ls.filter((l) => l.kind === "screen");
+ if (lineLines.length) {
+ const next = clone(screensOf(e));
+ for (const l of lineLines) {
+ const [, id, n] = /^screen:([a-z0-9-]+):(\d+)$/.exec(l.role) ?? [];
+ const sc = next.find((x) => x.id === id);
+ if (!sc) throw new ReplaceError(`${item} has no screen ${id}`);
+ const sa = isObj(sc.saidAs) ? { ...sc.saidAs } : {};
+ // Back to the line as read: no said-as (its own words again); else its said-as.
+ if (l.after.replace(/\s+/g, " ").trim() === screenLineSaid(sc, Number(n)).replace(/\s+/g, " ").trim()) delete sa[n];
+ else sa[n] = l.after;
+ if (Object.keys(sa).length) sc.saidAs = sa;
+ else delete sc.saidAs;
+ }
+ postItemIn(m, item, { screens: next });
+ }
+ }
+ return { items: [...byItem.keys()] };
+}
+
+/**
+ * THESE READS, PREVIEWED: `{ scope: "reads", find, to, lines: [{ id, kind, item, role, before, after, storedAt,
+ * creates }], skipped: [{ id, why }], notes: { <item>: [sentence…] }, refused: { <item>: [error…] }, matches }`.
+ * `only`: the read ids to change (the rest of the matches left as they are).
+ */
+export async function replacePlan(project, from, to, { matchCase = false, word = false, only = null, ctx = null, reportsRoot = undefined } = {}) {
+ if (typeof from !== "string" || !from.trim()) throw new ReplaceError("replace takes the words to find");
+ if (typeof to !== "string") throw new ReplaceError("replace takes what to say instead");
+ const c = ctx ?? (await readsContext(project, reportsRoot ? { reportsRoot } : {}));
+ const { rows } = await projectReads(project, { ctx: c });
+ const re = findPattern(from, { matchCase, word });
+ const keep = only ? new Set(only) : null;
+ const lines = [];
+ const skipped = [];
+ let matches = 0;
+ for (const r of rows) {
+ const hits = matchesIn(r.spoken, re);
+ if (!hits.length || (keep && !keep.has(r.id))) continue;
+ matches += hits.length;
+ if (!r.editable) {
+ skipped.push({ id: r.id, why: r.why ?? "not rewritten here" });
+ continue;
+ }
+ lines.push({ id: r.id, kind: r.kind, item: r.item, role: r.role, before: r.spoken, after: replaceIn(r.spoken, re, to), storedAt: r.storedAt, creates: createsNote(r) });
+ }
+ const notes = {};
+ const say = (item, s) => {
+ notes[item] = [...(notes[item] ?? []), s];
+ };
+ const m = c.manifest;
+ let review = null;
+ for (const item of new Set(lines.map((l) => l.item))) {
+ const e = m.timeline.find((x) => x?.id === item);
+ const row = rows.find((r) => r.item === item);
+ if (e?.type === "post" && e.narration?.approved && lines.some((l) => l.item === item && (l.kind === "post" || l.role === "post"))) say(item, "its approval goes, as a new script takes it away (Save script does the same)");
+ if (row?.legacy) say(item, LEGACY_EDIT_TEXT);
+ if (e?.type === "card") {
+ review ??= await (await import("umtool-report-to-video/narration-review")).readNarrationReview(project.dir).catch(() => null);
+ if (review?.rows?.[item]?.verdict) say(item, `its narration review verdict (${review.rows[item].verdict}) was given on the old words`);
+ }
+ }
+ // What the build would refuse, item by item, on a copy (a said-as saying what a screen masks, …).
+ const refused = {};
+ for (const item of new Set(lines.map((l) => l.item))) {
+ try {
+ replaceReadsIn(clone(m), lines.filter((l) => l.item === item));
+ } catch (err) {
+ refused[item] = err instanceof StructureRefused ? err.errors : [err instanceof Error ? err.message : String(err)];
+ }
+ }
+ return { scope: "reads", find: from, to, matchCase, word, lines, skipped, notes, refused, matches, ctx: c };
+}
+
+/** The replaces made here, newest last: `<project>/narration/reads/replaces.json` -- what an undo checks against. */
+export const REPLACES_FILE = "narration/reads/replaces.json";
+const replacesPath = (dir) => path.join(/* turbopackIgnore: true */ dir, ...REPLACES_FILE.split("/"));
+/** The draft as it is on disk, hashed: what a replace left, compared byte for byte (an undo restores bytes, not times). */
+const draftSha = async (dir) => createHash("sha1").update(await readFile(path.join(/* turbopackIgnore: true */ dir, "video.manifest.json")).catch(() => Buffer.alloc(0))).digest("hex");
+
+/** The records, oldest first: `{ scope: "reads", at, find, to, token, snapshot }` | `{ scope: "say", at, entry, was }`. */
+export async function readReplaces(dir) {
+ try {
+ const j = JSON.parse(await readFile(replacesPath(dir), "utf8"));
+ return Array.isArray(j?.records) ? j.records.filter(isObj) : [];
+ } catch {
+ return [];
+ }
+}
+
+async function withReplaces(dir, fn) {
+ const file = replacesPath(dir);
+ await mkdir(path.dirname(file), { recursive: true });
+ return withNotesLock(file, async () => {
+ const { records, result } = await fn(await readReplaces(dir));
+ const tmp = tmpPathFor(file);
+ await writeFile(tmp, `${JSON.stringify({ version: 1, records: records.slice(-20) }, null, 1)}\n`);
+ await rename(tmp, file);
+ return result;
+ });
+}
+
+/**
+ * THESE READS, APPLIED: the plan's lines in one structural write (its own undo point), against the manifest's token
+ * read BEFORE the plan (a write between the two is refused, never laid over). Refused whole when any item is refused
+ * (the preview says which), or when nothing would change. The manifest's token after it is kept with the replace's
+ * record, and the draft's bytes hashed: Undo the replace is offered only while the draft is still exactly what it left. Returns `{ plan, result }`.
+ */
+export async function applyReplace(project, from, to, o = {}) {
+ const token = o.token ?? (await manifestToken(project.dir));
+ const plan = await replacePlan(project, from, to, o);
+ if (Object.keys(plan.refused).length) throw new ReplaceError(`refused: ${Object.entries(plan.refused).map(([i, errs]) => `${i}: ${errs.join("; ")}`).join(" · ")} -- leave those reads out (--only) or say it another way`);
+ if (!plan.lines.length) throw new ReplaceError(plan.matches ? `nothing to rewrite: every match is in a read These reads does not change (${plan.skipped.map((s) => s.id).join(", ")})` : `"${from}" is in no read's spoken text`);
+ const { withEditNotes } = await import("./edit-guard.mjs");
+ const { result, editNotes } = await withEditNotes(project, async () => structuralEdit(project.dir, REPLACE_OP, token, (m) => replaceReadsIn(m, plan.lines), { snapshotEvery: 0 }));
+ await o.onWritten?.();
+ // The draft hashed only while it is still the replace's own write (its token): a write landing in between (a queue
+ // step in another process) is never hashed in -- the replace is then recorded as one Undo cannot take back.
+ const still = (await manifestToken(project.dir)) === result.token;
+ const sha = still ? await draftSha(project.dir) : null;
+ await withReplaces(project.dir, (records) => ({ records: [...records, { scope: "reads", at: new Date().toISOString(), find: from, to, lines: plan.lines.map((l) => l.id), token: result.token ?? null, sha, snapshot: result.snapshot?.rel ?? null, ...(still ? {} : { undoable: false }) }], result: null }));
+ return { plan, result, editNotes };
+}
+
+/**
+ * Whether the newest replace can be taken back now: `{ scope, available, why }` (null: none was made here). A replace
+ * of These reads only while the draft's token is the one it left (nothing written since -- a re-read landing, a bench
+ * edit) and its undo point is the newest; Everywhere only while the entry is still as it set it.
+ */
+export async function replaceUndoState(project) {
+ const last = (await readReplaces(project.dir)).at(-1);
+ if (!last) return null;
+ if (last.scope === "say") {
+ const { readLexicon } = await import("./postSay.mjs");
+ const now = (await readLexicon(project.dir)).find((x) => lexiconKey(x) === lexiconKey(last.entry));
+ return now && now.say === last.entry.say
+ ? { scope: "say", available: true, why: null, entry: last.entry, was: last.was ?? null }
+ : { scope: "say", available: false, why: `the entry for "${last.entry.word}" changed since (umtool posts say ${project.id} ls)`, entry: last.entry, was: last.was ?? null };
+ }
+ if (last.undoable === false || !last.sha) return { scope: "reads", available: false, why: "the draft changed while the replace was written (another write landed): taking it back could take that back too -- undo from where each was made" };
+ if ((await draftSha(project.dir)) !== last.sha) return { scope: "reads", available: false, why: "the draft changed after the replace (a re-read landed, or another edit): taking the replace back now would take that back too -- undo those from where they were made" };
+ const { listSnapshots } = await import("./snapshots.mjs");
+ const top = (await listSnapshots(project.dir)).find((s) => !s.legacy && s.label?.startsWith(AUTO_SNAPSHOT_PREFIX));
+ if (!top || top.label !== UNDO_LABEL) return { scope: "reads", available: false, why: "its undo point is no longer the newest" };
+ if (last.snapshot && top.rel !== last.snapshot) return { scope: "reads", available: false, why: "its undo point is not the one it made (the newest is another replace's)" };
+ return { scope: "reads", available: true, why: null };
+}
+
+/** Take back the newest replace of These reads: refused, in a sentence, unless replaceUndoState says it may be. */
+export async function undoReplace(project, { token = null } = {}) {
+ // The token the check is made against goes with the restore: a write between the two is refused, never undone.
+ const checked = token ?? (await manifestToken(project.dir));
+ const st = await replaceUndoState(project);
+ if (!st || st.scope !== "reads") throw new ReplaceError("nothing to undo: the newest replace made here is not one of These reads");
+ if (!st.available) throw new ReplaceError(`not undone: ${st.why}`);
+ const { withEditNotes } = await import("./edit-guard.mjs");
+ const { result } = await withEditNotes(project, async () => undoStructural(project.dir, { token: checked }));
+ await withReplaces(project.dir, (records) => ({ records: records.slice(0, -1), result: null }));
+ return result;
+}
+
+/**
+ * EVERYWHERE, FROM NOW ON, PREVIEWED: `{ scope: "say", entry, was, stale: [{ id, kind, item }], cards: [ids],
+ * matches }` -- the entry it adds (or changes: `was` its spoken form before), every read it would make stale, and
+ * the cards it does not reach. Refused with Whole word off.
+ */
+export async function sayOnlyPlan(project, from, to, { matchCase = false, word = true, ctx = null, reportsRoot = undefined } = {}) {
+ if (!word) throw new ReplaceError(SAY_WHOLE_WORDS);
+ if (typeof from !== "string" || !from.trim() || typeof to !== "string" || !to.trim()) throw new ReplaceError("Everywhere takes the words to find and how to say them");
+ const c = ctx ?? (await readsContext(project, reportsRoot ? { reportsRoot } : {}));
+ const before = await projectReads(project, { ctx: c });
+ const entry = { word: from.replace(/\s+/g, " ").trim(), say: to.trim(), ...(matchCase ? { case: true } : {}) };
+ const had = c.lexicon.find((x) => lexiconKey(x) === lexiconKey(entry)) ?? null;
+ const lexicon = normalizeLexicon([...c.lexicon.filter((x) => lexiconKey(x) !== lexiconKey(entry)), entry]);
+ const after = await projectReads(project, { ctx: { ...c, lexicon, red: { ...(c.red ?? {}), say: lexicon } } });
+ const was = new Map(before.rows.map((r) => [r.id, r]));
+ const newly = after.rows.filter((r) => (r.state === "stale" || r.state === "unpicked") && (r.because.includes("words") || r.because.includes("lexicon")) && !(was.get(r.id)?.because ?? []).some((b) => b === "words" || b === "lexicon"));
+ const re = findPattern(from, { matchCase, word: true });
+ const cards = before.rows.filter((r) => r.kind === "card" && matchesIn(r.spoken, re).length).map((r) => r.id);
+ const matches = before.rows.reduce((a, r) => a + matchesIn(r.spoken, re).length, 0);
+ return { scope: "say", entry, was: had ? had.say : null, wasEntry: had ? { ...had } : null, stale: newly.map((r) => ({ id: r.id, kind: r.kind, item: r.item })), cards, matches, ctx: c };
+}
+
+/**
+ * EVERYWHERE, APPLIED: the entry through `posts say add`'s writer (an entry of the same word changes its spoken form).
+ * What it replaced -- the whole entry, its note too -- is kept with the record, so its undo puts that back.
+ * Returns `{ plan, result }`.
+ */
+export async function applySayOnly(project, from, to, o = {}) {
+ const plan = await sayOnlyPlan(project, from, to, o);
+ const { updateLexicon } = await import("./postSay.mjs");
+ const result = await updateLexicon(project.dir, { add: { word: plan.entry.word, say: plan.entry.say, case: plan.entry.case === true, item: null, note: o.note ?? null } });
+ await withReplaces(project.dir, (records) => ({ records: [...records, { scope: "say", at: new Date().toISOString(), entry: { word: result.entry.word, say: result.entry.say, ...(result.entry.case ? { case: true } : {}) }, was: plan.wasEntry }], result: null }));
+ return { plan, result };
+}
+
+/**
+ * EVERYWHERE, TAKEN BACK: the entry it changed back to what it was (its spoken form, its note), or the entry it added
+ * removed -- that one entry, by its identity (word, case, item), never another of the same word. Refused when the
+ * entry changed since.
+ */
+export async function undoSayOnly(project) {
+ const st = await replaceUndoState(project);
+ if (!st || st.scope !== "say") throw new ReplaceError("nothing to take back: the newest replace made here is not an Everywhere");
+ if (!st.available) throw new ReplaceError(`not taken back: ${st.why}`);
+ const { readLexicon, updateLexicon } = await import("./postSay.mjs");
+ let result;
+ if (st.was) result = await updateLexicon(project.dir, { add: { word: st.was.word, say: st.was.say, case: st.was.case === true, item: st.was.item ?? null, note: st.was.note ?? null } });
+ else {
+ const at = (await readLexicon(project.dir)).findIndex((x) => lexiconKey(x) === lexiconKey(st.entry));
+ result = await updateLexicon(project.dir, { remove: at });
+ }
+ await withReplaces(project.dir, (records) => ({ records: records.slice(0, -1), result: null }));
+ return { restored: st.was ?? null, removed: st.was ? null : st.entry, lexicon: result.lexicon };
+}
diff --git a/umtool/lib/report/readsReplace.test.mjs b/umtool/lib/report/readsReplace.test.mjs
@@ -0,0 +1,144 @@
+// REPLACE OVER A VIDEO's READS (lane reads-find, readsReplace.mjs): These reads rewrites the SPOKEN text of each kind
+// through its own writer in one undo point, the shown text untouched (a post's script, a screen line's said-as made
+// when it has none, a card's narration; a context piece and a recorded read listed, never changed); undo restores
+// every line; Everywhere adds a pronunciation entry, previews what it makes stale, never reaches a card, and is whole
+// words only. Neither synthesizes. Temp dirs, invented people.
+import "./noLiveEditor.mjs";
+import assert from "node:assert/strict";
+import { mkdtemp, readdir, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { cardText } from "umtool-report-to-video/post-item";
+import { projectReads } from "./reads.mjs";
+import { ReplaceError, SAY_WHOLE_WORDS, applyReplace, applySayOnly, replacePlan, sayOnlyPlan, undoReplace } from "./readsReplace.mjs";
+import { manifestToken, updatePostNarration } from "./manifest.mjs";
+import { readLexicon } from "./postSay.mjs";
+import { readManifestOf, readsProject } from "./reads.fixtures.mjs";
+import { drawn } from "../../report-to-video/post-reading-pin.fixtures.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-reads-replace-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+const o = (p, x = {}) => ({ reportsRoot: p.root, ...x });
+/** What a manifest SHOWS: every item with its spoken-only fields left out (narration, a screen's saidAs). */
+const shown = (m) => m.timeline.map(({ narration: _n, ...e }) => ({ ...e, ...(Array.isArray(e.screens) ? { screens: e.screens.map(({ saidAs: _s, ...sc }) => sc) } : {}) }));
+const takeFiles = async (p) => (await readdir(path.join(p.dir, "narration", "posts"), { recursive: true })).filter((f) => f.endsWith(".wav")).sort();
+
+test("These reads: a post's script, a screen line (said-as created), a card -- one undo point; shown text and drawn card identical; nothing synthesized", async () => {
+ const p = await readsProject(ROOT, "a");
+ const m0 = await readManifestOf(p);
+ const files0 = await takeFiles(p);
+ const plan = await replacePlan(p, "north", "northern", o(p));
+ assert.deepEqual(plan.lines.map((l) => [l.id, l.creates]), [["p-1", null], ["c-1", null]]);
+ assert.deepEqual(plan.skipped.map((s) => s.id), ["p-3"], "a recorded read is never replaced");
+ // A screen line with no said-as: created from the line as read.
+ const tolls = await replacePlan(p, "tolls", "toll charges", o(p));
+ assert.deepEqual(tolls.lines.map((l) => [l.id, l.before, l.after, l.creates]), [["p-2/screen:s1:0", "Are the tolls going up again?", "Are the toll charges going up again?", "creates its said-as (the line as shown is untouched)"]]);
+ // A context piece: listed, not changed.
+ const bridge = await replacePlan(p, "Bridge works", "The bridge works", o(p));
+ assert.deepEqual(bridge.lines, []);
+ assert.match(bridge.skipped[0].why, /said as shown: only Everywhere changes this/);
+
+ await applyReplace(p, "north", "northern", o(p));
+ await applyReplace(p, "tolls", "toll charges", o(p));
+ const m1 = await readManifestOf(p);
+ assert.match(m1.timeline[0].narration.script, /northern pier/);
+ assert.equal(m1.timeline[0].narration.forReading, true, "marked for reading by the one writer");
+ assert.equal(m1.timeline[1].screens[0].saidAs["0"], "Are the toll charges going up again?");
+ assert.equal(m1.timeline[3].narration.text, "Six months later, the northern pier reopened.");
+ // RULING 3: what is shown is byte-identical, and so is what the cards draw.
+ assert.deepEqual(shown(m1), shown(m0));
+ assert.equal(cardText(m1.timeline[0]), cardText(m0.timeline[0]));
+ for (const k of [0, 1]) assert.deepEqual(drawn(m1.timeline[k]), drawn(m0.timeline[k]), m0.timeline[k].id);
+ assert.deepEqual(await takeFiles(p), files0, "a replace never synthesizes");
+ // The changed reads are stale; the others are not.
+ const by = Object.fromEntries((await projectReads(p, o(p))).rows.map((r) => [r.id, r.state]));
+ assert.deepEqual([by["p-1"], by["p-2/screen:s1:0"], by["c-1"], by["p-2/screen:s1:1"], by["p-3"]], ["stale", "stale", "stale", "fresh", "recorded"]);
+ // Undo takes back the newest replace -- every line of it -- and only a replace.
+ await undoReplace(p);
+ assert.equal("saidAs" in (await readManifestOf(p)).timeline[1].screens[0], false);
+ await undoReplace(p);
+ assert.deepEqual(await readManifestOf(p), m0);
+ await updatePostNarration(p.dir, "p-1", { approved: true }, { token: await manifestToken(p.dir) });
+ await assert.rejects(undoReplace(p), /nothing to undo: the newest replace made here is not one of These reads/);
+});
+
+test("These reads: the preview says what goes (approval), what the build would refuse, and only the ticked reads change", async () => {
+ const p = await readsProject(ROOT, "b");
+ await updatePostNarration(p.dir, "p-1", { approved: true }, { token: await manifestToken(p.dir) });
+ const plan = await replacePlan(p, "north", "northern", o(p));
+ assert.match(plan.notes["p-1"].join(" "), /its approval goes, as a new script takes it away/);
+ // A said-as that says a number the card masks is refused, and the whole write with it.
+ const bad = await replacePlan(p, "this year", "on 5551234567", o(p));
+ assert.ok(bad.refused["p-2"]?.some((x) => /number/.test(x)), JSON.stringify(bad.refused));
+ await assert.rejects(applyReplace(p, "this year", "on 5551234567", o(p)), ReplaceError);
+ // --only: the card alone.
+ await applyReplace(p, "north", "northern", o(p, { only: ["c-1"] }));
+ const m = await readManifestOf(p);
+ assert.match(m.timeline[0].narration.script, /the north pier/);
+ assert.equal(m.timeline[0].narration.approved, true);
+ assert.match(m.timeline[3].narration.text, /northern pier/);
+});
+
+test("Everywhere: a pronunciation entry -- previews the reads it makes stale and the cards it does not reach; whole words only", async () => {
+ const p = await readsProject(ROOT, "say");
+ await assert.rejects(sayOnlyPlan(p, "nort", "x", o(p, { word: false })), (e) => e.message === SAY_WHOLE_WORDS);
+ const plan = await sayOnlyPlan(p, "pier", "peer", o(p));
+ assert.deepEqual(plan.stale.map((s) => s.id), ["p-1"], "the recorded read never; the card is not said through the lexicon");
+ assert.deepEqual(plan.cards, ["c-1"]);
+ const m0 = await readManifestOf(p);
+ await applySayOnly(p, "pier", "peer", o(p));
+ assert.deepEqual(await readLexicon(p.dir), [{ word: "pier", say: "peer" }]);
+ assert.deepEqual(await readManifestOf(p), m0, "the draft is not touched");
+ const row = (await projectReads(p, o(p))).rows.find((r) => r.id === "p-1");
+ assert.deepEqual([row.state, row.because], ["stale", ["lexicon"]]);
+ // The same word again changes what is said for it (the writer's rule): `was` says so.
+ assert.equal((await sayOnlyPlan(p, "pier", "pee-er", o(p))).was, "peer");
+});
+
+// ---------------------------------------------------------------------------
+// REVIEW 1, MUST 2: Undo the replace never takes a later edit back with it. Other writers keep one undo point per op
+// for two minutes, so a write after a replace may leave the replace's undo point the newest: the undo is refused
+// unless the draft is still exactly what the replace left (its token, kept with the replace's record).
+// ---------------------------------------------------------------------------
+
+test("MUST 2: a bench write before the replace, the replace, a re-read landing after it with no undo point of its own -- the undo is refused", async () => {
+ const p = await readsProject(ROOT, "undo-after");
+ const write = async (patch) => updatePostNarration(p.dir, "p-1", patch, { token: await manifestToken(p.dir) });
+ await write({ lead: 0.3 }); // a bench edit: its op's undo point (post-narration)
+ await applyReplace(p, "north", "northern", o(p));
+ const { replaceUndoState } = await import("./readsReplace.mjs");
+ assert.equal((await replaceUndoState(p)).available, true);
+ // A re-read lands: the same op as the bench edit, inside its two minutes -- no undo point of its own.
+ const m = await readManifestOf(p);
+ await write({ addTake: { ...m.timeline[0].narration.takes[0], file: "narration/posts/1/take-2.orpheus-tara.wav", script: m.timeline[0].narration.script }, keepPick: true });
+ const st = await replaceUndoState(p);
+ assert.equal(st.available, false);
+ assert.match(st.why, /the draft changed after the replace/);
+ await assert.rejects(undoReplace(p), /not undone: the draft changed after the replace/);
+ assert.equal((await readManifestOf(p)).timeline[0].narration.takes.length, 2, "the re-read is still there");
+});
+
+// REVIEW 1, SHOULD 4: Everywhere's undo puts back the entry it changed (its spoken form and its note), and removes only
+// the entry it added -- never another of the same word.
+test("SHOULD 4: an Everywhere over an existing entry is taken back to it; with a case and a no-case entry, only its own goes", async () => {
+ const p = await readsProject(ROOT, "say-undo");
+ const { updateLexicon } = await import("./postSay.mjs");
+ const { undoSayOnly } = await import("./readsReplace.mjs");
+ await updateLexicon(p.dir, { add: { word: "pier", say: "peer", note: "the harbour's word" } });
+ const plan = await sayOnlyPlan(p, "pier", "pee-er", o(p));
+ assert.equal(plan.was, "peer");
+ await applySayOnly(p, "pier", "pee-er", o(p));
+ assert.deepEqual(await readLexicon(p.dir), [{ word: "pier", say: "pee-er" }]);
+ await undoSayOnly(p);
+ assert.deepEqual(await readLexicon(p.dir), [{ word: "pier", say: "peer", note: "the harbour's word" }]);
+ // A case entry and a no-case one of the same word: the undo removes only the one Everywhere added.
+ await updateLexicon(p.dir, { add: { word: "Pier", say: "PEER", case: true } });
+ await applySayOnly(p, "north", "nor-th", o(p));
+ await undoSayOnly(p);
+ assert.deepEqual((await readLexicon(p.dir)).map((x) => x.word), ["pier", "Pier"]);
+ await applySayOnly(p, "pier", "pier two", o(p, { matchCase: false }));
+ await undoSayOnly(p);
+ assert.deepEqual(await readLexicon(p.dir), [{ word: "pier", say: "peer", note: "the harbour's word" }, { word: "Pier", say: "PEER", case: true }]);
+});
diff --git a/umtool/lib/report/readsReview2.test.mjs b/umtool/lib/report/readsReview2.test.mjs
@@ -0,0 +1,168 @@
+// REVIEW 2 OF lane/reads-find (N1-N10, and the three questions): each a test, written before its fix. Temp dirs, a stub
+// tts, invented people; noLiveEditor first.
+import "./noLiveEditor.mjs";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { readsPost } from "./readsApi.mjs";
+import { readsCommand } from "./readsCli.mjs";
+import { applyReplace, replaceUndoState, undoReplace } from "./readsReplace.mjs";
+import { runOneItem } from "./readsQueue.mjs";
+import { projectReads } from "./reads.mjs";
+import { manifestToken, updatePostNarration } from "./manifest.mjs";
+import { castDoc, LIVELY, readManifestOf, readsProject, wavOf } from "./reads.fixtures.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-reads-review2-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+delete process.env.UMTOOL_CAST_FILE;
+const ctx = (p) => ({ reportsRoot: p.root, queueDir: path.join(p.root, ".umtool-queue") });
+const stub = async (body) => {
+ await wavOf(body.out);
+ return { jobId: "j", result: { wav: body.out, engine: body.engine, voice: body.voice, tuning: { temperature: 0.55, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3, ...(body.tuning ?? {}) }, reading: body.reading ?? 0 } };
+};
+async function cli(p, args, o = {}) {
+ const lines = [];
+ const code = await readsCommand(["p", ...args], { root: p.root, out: (s) => lines.push(s), err: () => {}, queueDir: ctx(p).queueDir, ...o });
+ return { code, lines, text: lines.join("\n") };
+}
+/** Every file under a dir, its path and contents: what a dry run must leave exactly as it was. */
+async function snapshotOf(dir) {
+ const out = {};
+ for (const f of (await readdir(dir, { recursive: true })).sort()) {
+ const abs = path.join(dir, f);
+ out[f] = await readFile(abs).then((b) => b.toString("base64"), () => "<dir>");
+ }
+ return out;
+}
+
+test("N1: a These-reads preview names its reads (the rows Find counted), as apply does; without them, 400", async () => {
+ const p = await readsProject(ROOT, "n1");
+ const r = await readsPost(p, { op: "preview", scope: "reads", from: "north", to: "northern" }, ctx(p));
+ assert.equal(r.status, 400);
+ const ok = await readsPost(p, { op: "preview", scope: "reads", from: "north", to: "northern", only: ["c-1"] }, ctx(p));
+ assert.deepEqual(ok.json.lines.map((l) => l.id), ["c-1"]);
+});
+
+test("N2: the preview's token goes back with Apply; the draft changed since: 409, nothing written; no token: 400", async () => {
+ const p = await readsProject(ROOT, "n2");
+ const prev = await readsPost(p, { op: "preview", scope: "reads", from: "north", to: "northern", only: ["p-1", "c-1"] }, ctx(p));
+ assert.equal(typeof prev.json.token, "string");
+ assert.equal((await readsPost(p, { op: "replace", scope: "reads", from: "north", to: "northern", only: ["p-1"] }, ctx(p))).status, 400);
+ // A script changes between the preview and Apply.
+ await updatePostNarration(p.dir, "p-1", { script: "The ferry leaves the north pier at one." }, { token: await manifestToken(p.dir) });
+ const m0 = await readManifestOf(p);
+ const r = await readsPost(p, { op: "replace", scope: "reads", from: "north", to: "northern", only: ["p-1"], token: prev.json.token }, ctx(p));
+ assert.equal(r.status, 409);
+ assert.match(r.json.error, /the draft changed since the preview: preview again/);
+ assert.deepEqual(await readManifestOf(p), m0);
+});
+
+test("N3: --only with no value, empty or only commas is refused (never every read)", async () => {
+ const p = await readsProject(ROOT, "n3");
+ await cli(p, ["replace", "north", "northern"]);
+ for (const args of [["reread", "--only"], ["reread", "--only", ""], ["reread", "--only", ","], ["pick", "--new", "--only", ""], ["replace", "a", "b", "--only", ","]]) {
+ const r = await cli(p, [...args, "--json"]);
+ assert.equal(r.code, 2, args.join(" "));
+ assert.match(JSON.parse(r.text).error, /--only names no read/);
+ }
+ assert.equal((await readsPost(p, { op: "reread", only: ["", " "] }, ctx(p))).status, 400);
+});
+
+test("N4: a write landing between the replace and its hash makes it not undoable (said); the undo goes under the token it checked; its snapshot must be the newest", async () => {
+ const p = await readsProject(ROOT, "n4");
+ // A take lands in the gap (a queue step in another process).
+ await applyReplace(p, "north", "northern", { reportsRoot: p.root, onWritten: async () => updatePostNarration(p.dir, "p-2", { lead: 0.3 }, { token: await manifestToken(p.dir) }) });
+ const st = await replaceUndoState(p);
+ assert.equal(st.available, false);
+ assert.match(st.why, /the draft changed while the replace was written/);
+ // A clean replace, then its recorded undo point tampered: refused.
+ const q = await readsProject(ROOT, "n4b");
+ await applyReplace(q, "north", "northern", { reportsRoot: q.root });
+ assert.equal((await replaceUndoState(q)).available, true);
+ const file = path.join(q.dir, "narration", "reads", "replaces.json");
+ const j = JSON.parse(await readFile(file, "utf8"));
+ j.records.at(-1).snapshot = "revisions/not-this-one.manifest.json";
+ await writeFile(file, JSON.stringify(j));
+ assert.match((await replaceUndoState(q)).why, /its undo point is not the one it made/);
+ await assert.rejects(undoReplace(q), /not undone/);
+});
+
+test("N5: a stale read the queue cannot re-read (a piece from a synthesized take) is never re-read by `--one` with no --only", async () => {
+ const { postsCommand } = await import("./postsCli.mjs");
+ const p = await readsProject(ROOT, "n5", { cast: castDoc(LIVELY) });
+ assert.equal(await postsCommand(["narrate", "p", "p-1", "--take", "--thread", "--post-take", "1"], { root: p.root, tts: stub, out: () => {}, err: () => {} }), 0);
+ const row = (await projectReads(p, { reportsRoot: p.root })).rows.find((r) => r.id === "p-1/post");
+ assert.deepEqual([row.state, row.queueable], ["stale", false]);
+ let ran = 0;
+ const r = await runOneItem(p, "p-1", [], { reportsRoot: p.root, run: async () => (ran += 1, 0), log: () => {} });
+ assert.equal(r.argv, null);
+ assert.equal(ran, 0);
+});
+
+test("N6: `reread --one` is the queue step's form: it needs --only and refuses --dry-run, --wait, --stale", async () => {
+ const p = await readsProject(ROOT, "n6");
+ for (const args of [["reread", "--one", "p-1"], ["reread", "--one", "p-1", "--only", "p-1", "--dry-run"], ["reread", "--one", "p-1", "--only", "p-1", "--wait"], ["reread", "--one", "p-1", "--only", "p-1", "--stale"]]) {
+ const r = await cli(p, [...args, "--json"]);
+ assert.equal(r.code, 2, args.join(" "));
+ }
+});
+
+test("N7: every --dry-run writes NOTHING -- replace, undo, reread, pick: the project's files byte for byte", async () => {
+ const p = await readsProject(ROOT, "n7");
+ await cli(p, ["replace", "north", "northern"]);
+ const before = await snapshotOf(p.dir);
+ for (const args of [["replace", "pier", "peer", "--dry-run"], ["replace", "pier", "peer", "--say-only", "--dry-run"], ["undo", "--dry-run"], ["reread", "--dry-run"], ["pick", "--new", "--dry-run"]]) await cli(p, [...args, "--json"]);
+ assert.deepEqual(await snapshotOf(p.dir), before);
+ // And on a project that never queued: no narration/reads/ made.
+ const q = await readsProject(ROOT, "n7b");
+ await updatePostNarration(q.dir, "p-1", { script: "The ferry leaves the north pier at one." }, { token: await manifestToken(q.dir) });
+ await cli(q, ["reread", "--dry-run", "--json"]);
+ await assert.rejects(readdir(path.join(q.dir, "narration", "reads")), /ENOENT/);
+});
+
+test("N8: a subcommand named like an Object property is refused, not looked up", async () => {
+ const p = await readsProject(ROOT, "n8");
+ for (const sub of ["constructor", "toString", "__proto__", "hasOwnProperty"]) {
+ assert.equal((await cli(p, [sub, "--json"])).code, 2, sub);
+ assert.equal((await cli(p, [sub, "--stale", "--json"])).code, 2, `${sub} with a flag`);
+ }
+});
+
+test("N10: a piece from a synthesized take is judged on its words too -- the take's words against the line's now", async () => {
+ const { postsCommand } = await import("./postsCli.mjs");
+ const p = await readsProject(ROOT, "n10");
+ assert.equal(await postsCommand(["narrate", "p", "p-1", "--take", "--thread", "--post-take", "1"], { root: p.root, tts: stub, out: () => {}, err: () => {} }), 0);
+ let row = (await projectReads(p, { reportsRoot: p.root })).rows.find((r) => r.id === "p-1/post");
+ assert.deepEqual([row.state, row.because], ["fresh", []]);
+ await updatePostNarration(p.dir, "p-1", { script: "The ferry leaves the north pier at one." }, { token: await manifestToken(p.dir) });
+ row = (await projectReads(p, { reportsRoot: p.root })).rows.find((r) => r.id === "p-1/post");
+ assert.deepEqual([row.state, row.because], ["stale", ["words"]]);
+});
+
+test("(a) `reread --one --json`: stdout is ONE JSON document -- the inner command's words go to stderr", async () => {
+ const p = await readsProject(ROOT, "qa");
+ await updatePostNarration(p.dir, "p-1", { script: "The ferry leaves the north pier at one." }, { token: await manifestToken(p.dir) });
+ const errs = [];
+ const r = await cli(p, ["reread", "--one", "p-1", "--only", "p-1", "--json"], { tts: stub, err: (s) => errs.push(s) });
+ assert.equal(r.code, 0, r.text);
+ const j = JSON.parse(r.text);
+ assert.equal(j.ok, true);
+ assert.ok(errs.join("\n").includes("p-1"), "the inner command spoke on stderr");
+});
+
+test("(c) a thread take carries no tuningOwn; a piece's own values are read.tuned[role], and tuningStale reads them there", async () => {
+ const { postsCommand } = await import("./postsCli.mjs");
+ const { tuningStale } = await import("umtool-report-to-video/cast");
+ const { resolverFor } = await import("./castProject.mjs");
+ const p = await readsProject(ROOT, "qc", { cast: castDoc(LIVELY) });
+ assert.equal(await postsCommand(["narrate", "p", "p-1", "--take", "--thread", "--tuned", "post=takes:5"], { root: p.root, tts: stub, out: () => {}, err: () => {} }), 0);
+ const t = (await readManifestOf(p)).timeline[0].narration.takes.at(-1);
+ assert.equal("tuningOwn" in t, false);
+ assert.deepEqual(t.read.tuned.post.tuning, { takes: 5 });
+ // The character names 4 takes: the piece owns its 5 -- not stale.
+ const now = { ...LIVELY, takes: 4 };
+ assert.deepEqual(tuningStale(await readManifestOf(p), resolverFor({ cast: castDoc(now) }), { settingTakes: 3 }).filter((r) => r.id === "p-1"), []);
+ void mkdir;
+});
diff --git a/umtool/lib/report/tuneAsk.mjs b/umtool/lib/report/tuneAsk.mjs
@@ -8,7 +8,9 @@
// a PRESS with no character, S3's rule (what differs from the defaults); with one, what differs from the
// character's tuning (all of the sampler when the last read was the line's own) -- nothing changed on
// a character's line asks none of the sampler, so the character's is asked as it is then; the takes
-// when given (S3: a recorded takes is passed back)
+// only when the LINE owns them (lane reads-find, the orchestrator's ruling, 17 Nov 2026: superseding S3's
+// "a recorded takes is passed back") -- the last read's own takes, or a takes typed -- else they are
+// resolved now (the character's, else the editor's setting), never copied from the last read
// a KEEP the sampler as it stands (top k, min p only when not their defaults) and the takes only when typed
//
// Plain ESM, pure.
@@ -25,6 +27,36 @@ export function madeOwnOf(tuning, tuningAsked) {
return TUNE_SAMPLER.some((k) => typeof tuning?.[k] === "number" && tuning[k] !== DEFAULTS[k]);
}
+/**
+ * THE VALUES A READ's LINE OWNED (lane reads-find): its `tuningOwn` (the line's own values as asked, recorded on every
+ * take made since) when it has one; an OLDER take records no ownership field by field, so it reads as owning every
+ * recorded value when `tuningAsked` is true, and none otherwise -- a known limit: an old take that owned only its takes
+ * (recorded "preset") re-reads with the character's or the settings' takes. Null: the line owns none.
+ * @param {{ tuning?: Record<string, number> | null, tuningAsked?: unknown, tuningOwn?: Record<string, number> | null }} [made]
+ */
+export function lineOwnOf(made) {
+ const own = made?.tuningOwn;
+ if (own && typeof own === "object" && !Array.isArray(own)) return Object.keys(own).length ? { ...own } : null;
+ if (made?.tuningAsked === true && made?.tuning && typeof made.tuning === "object") return Object.keys(made.tuning).length ? { ...made.tuning } : null;
+ return null;
+}
+
+/**
+ * The values one PIECE of a thread read owned (`role`): its `read.tuned[role]` (the read's own values for that piece,
+ * postThreadRead.mjs readRecordOf) when the read records the piece there, else lineOwnOf of its part. Null: none.
+ * @param {any} take
+ * @param {string} role
+ */
+export function pieceOwnOf(take, role) {
+ const t = take?.read?.tuned;
+ if (t && typeof t === "object" && t[role] && typeof t[role] === "object") {
+ const own = t[role].tuning;
+ return own && typeof own === "object" && Object.keys(own).length ? { ...own } : null;
+ }
+ const part = (Array.isArray(take?.parts) ? take.parts : []).find((p) => p?.role === role && typeof p?.take !== "string") ?? null;
+ return lineOwnOf(part);
+}
+
/** S3's ask (ReadAgain.tsx tuningAsked): the sampler values off the defaults, and the takes whenever given. */
export function defaultsAskOf(draft) {
const out = {};
@@ -37,18 +69,37 @@ export function defaultsAskOf(draft) {
/**
* The Tune's starting numbers, as its fields hold them (strings): the baseline's sampler (`baseline` null: S3's -- the
- * last read's), and the last read's takes.
- * @param {{ madeWith?: Record<string, number> | null, baseline?: { character: { tuning: Record<string, number> | null } | null, madeOwn: boolean } | null }} o
+ * last read's); the takes the LINE owns (`own`: lineOwnOf's, null none -- or the baseline's `ownTakes`), else the
+ * character's, else empty (the editor's setting): a takes the line does not own is resolved now, never the last read's.
+ * @param {{ madeWith?: Record<string, number> | null, baseline?: { character: { tuning: Record<string, number> | null } | null, madeOwn: boolean, ownTakes?: number | null } | null, own?: Record<string, number> | null }} o
*/
-export function tuneStartOf({ madeWith = null, baseline = null } = {}) {
+export function tuneStartOf({ madeWith = null, baseline = null, own = null } = {}) {
// No character (none now, or one since removed): S3's rule -- the last read's numbers (review 3 #4).
const b = !baseline || baseline.madeOwn || !baseline.character ? madeWith : baseline.character.tuning ?? null;
+ const takes = ownTakesOf(own, baseline) ?? baseline?.character?.tuning?.takes ?? null;
return Object.fromEntries(TTS_TUNING_FIELDS.map((k) => {
- const v = k === "takes" ? madeWith?.takes : b?.[k];
+ const v = k === "takes" ? takes : b?.[k];
return [k, v !== undefined && v !== null ? String(v) : k in DEFAULTS ? String(DEFAULTS[k]) : ""];
}));
}
+/** The takes the line owns: `own`'s, else the baseline's `ownTakes`; null when it owns none. */
+const ownTakesOf = (own, baseline) => {
+ const t = own?.takes ?? baseline?.ownTakes;
+ return typeof t === "number" && Number.isFinite(t) ? t : null;
+};
+
+/**
+ * WHAT A PLAIN PRESS ASKS (lane reads-find: the bench's untouched Read again, and the re-read queue's -- one rule):
+ * the Tune's start, asked as an untouched press asks it. `own` the values the line owned (lineOwnOf).
+ * @param {{ madeWith?: Record<string, number> | null, baseline?: { character: { tuning: Record<string, number> | null } | null, madeOwn: boolean, ownTakes?: number | null } | null, own?: Record<string, number> | null }} o
+ */
+export function plainPressAskOf({ madeWith = null, baseline = null, own = null } = {}) {
+ const b = baseline ? { ...baseline, ownTakes: ownTakesOf(own, baseline) } : baseline;
+ const draft = tuneStartOf({ madeWith, baseline: b, own });
+ return b?.character ? tuneAskOf(draft, b) : defaultsAskOf(draft);
+}
+
/**
* What a press asks as the line's own (null: nothing of its own -- the character's, or the defaults, as they are now).
* @param {Record<string, string>} draft
@@ -62,8 +113,11 @@ export function tuneAskOf(draft, baseline = null) {
const was = baseline.character.tuning?.[k] ?? DEFAULTS[k];
if (v !== null && (baseline.madeOwn || v !== was)) out[k] = v;
}
+ // The takes: the line's own (its last read's, `ownTakes`; or typed other than the character's) -- never the
+ // character's own takes sent back as the line's (they are resolved now; lane reads-find).
const takes = num(draft?.takes);
- if (takes !== null) out.takes = takes;
+ const charTakes = baseline.character.tuning?.takes;
+ if (takes !== null && (takes !== charTakes || takes === baseline.ownTakes)) out.takes = takes;
return Object.keys(out).length ? out : null;
}
@@ -121,6 +175,6 @@ export function unknownBaselineAskOf(draft, { madeOwn = false, dirty = false } =
* @param {{ character: { tuning: Record<string, number> | null } | null, madeOwn: boolean }} baseline
*/
export function characterTuneOf(madeWith, baseline) {
- const b = { ...baseline, madeOwn: false };
+ const b = { ...baseline, madeOwn: false, ownTakes: null };
return { baseline: b, draft: tuneStartOf({ madeWith, baseline: b }) };
}
diff --git a/umtool/lib/report/tuneAsk.test.mjs b/umtool/lib/report/tuneAsk.test.mjs
@@ -4,7 +4,7 @@
// line's own).
import assert from "node:assert/strict";
import { test } from "node:test";
-import { asksSampler, characterTuneOf, defaultsAskOf, keepAskOf, madeOwnOf, sameBaseline, threadTuneMadeOf, tuneAskOf, tuneStartOf, unknownBaselineAskOf } from "./tuneAsk.mjs";
+import { asksSampler, characterTuneOf, defaultsAskOf, keepAskOf, lineOwnOf, madeOwnOf, plainPressAskOf, sameBaseline, threadTuneMadeOf, tuneAskOf, tuneStartOf, unknownBaselineAskOf } from "./tuneAsk.mjs";
const LIVELY = { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 };
const STEADY = { temperature: 0.4, top_p: 0.8 };
@@ -16,17 +16,19 @@ test("review 2 #1: a plain press after a read under the character's Lively asks
const made = { tuning: MADE_LIVELY, tuningAsked: "preset" };
const b = asCharacter(LIVELY, madeOwnOf(made.tuning, made.tuningAsked));
const draft = tuneStartOf({ madeWith: made.tuning, baseline: b });
- assert.deepEqual(tuneAskOf(draft, b), { takes: 3 }, "only the recorded takes (S3's rule): the sampler is the character's");
+ assert.equal(tuneAskOf(draft, b), null, "nothing of its own (lane reads-find): the sampler is the character's, and the takes the line did not own are resolved now, never the last read's");
// The rule before the fix: the last read's numbers, as the line's own.
- assert.deepEqual(defaultsAskOf(tuneStartOf({ madeWith: made.tuning })), { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25, takes: 3 });
+ // (Its takes not owned by the line: not in the start since lane reads-find.)
+ assert.deepEqual(defaultsAskOf(tuneStartOf({ madeWith: made.tuning })), { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 });
// The character is Steady now: the Tune starts there, and a plain press still asks none of the sampler.
const now = asCharacter(STEADY, false);
const d2 = tuneStartOf({ madeWith: made.tuning, baseline: now });
assert.deepEqual([d2.temperature, d2.top_p, d2.repeat_penalty], ["0.4", "0.8", "1.2"]);
- assert.deepEqual(tuneAskOf(d2, now), { takes: 3 });
- // The line's own last read stays its own: its numbers are the baseline, all of the sampler asked.
+ assert.equal(tuneAskOf(d2, now), null, "still nothing of its own: the takes are the character's or the settings', resolved now");
+ // The line's own last read stays its own: its numbers are the baseline, all of the sampler asked -- and its takes,
+ // which it owned (an older take asked true owns every recorded value: lineOwnOf).
const own = asCharacter(STEADY, madeOwnOf({ ...MADE_LIVELY, temperature: 0.9 }, true));
- const d3 = tuneStartOf({ madeWith: { ...MADE_LIVELY, temperature: 0.9 }, baseline: own });
+ const d3 = tuneStartOf({ madeWith: { ...MADE_LIVELY, temperature: 0.9 }, baseline: own, own: lineOwnOf({ tuning: { ...MADE_LIVELY, temperature: 0.9 }, tuningAsked: true }) });
assert.deepEqual(tuneAskOf(d3, own), { temperature: 0.9, top_p: 0.92, top_k: 50, min_p: 0, repeat_penalty: 1.25, takes: 3 });
// Made before `tuningAsked` was recorded: a sampler value off the defaults was the line's own; the defaults were not.
assert.equal(madeOwnOf({ temperature: 0.7 }, undefined), true);
@@ -74,7 +76,7 @@ test("review 3 #1: a draft edited against Lively while the character became Stea
const was = asCharacter(LIVELY, false);
const draft = { ...tuneStartOf({ madeWith: MADE_LIVELY, baseline: was }), top_p: "0.9" };
const a = tuneAskOf(draft, was);
- assert.deepEqual(a, { top_p: 0.9, takes: 3 });
+ assert.deepEqual(a, { top_p: 0.9 }, "the changed value only: the takes the line did not own are not sent");
assert.equal(asksSampler(a), true, "it names a sampler value of its own: the baseline is read again before it is sent");
// Read again: Steady now. It changed under the draft -- nothing is sent (the press is refused, the new baseline said).
const now = asCharacter(STEADY, false);
@@ -82,17 +84,18 @@ test("review 3 #1: a draft edited against Lively while the character became Stea
assert.equal(sameBaseline(asCharacter({ ...LIVELY }, false), was), true);
// Sent as it was, it would have read {temperature 0.4 (Steady's), top_p 0.9} while the Tune showed 0.75.
// Pressed again against Steady, the draft as shown is the line's own: every number that differs from Steady's.
- assert.deepEqual(tuneAskOf(draft, now), { temperature: 0.75, top_p: 0.9, repeat_penalty: 1.25, takes: 3 });
+ assert.deepEqual(tuneAskOf(draft, now), { temperature: 0.75, top_p: 0.9, repeat_penalty: 1.25 });
// An untouched press names no sampler value: sent at once (the character's is asked as it is then).
assert.equal(asksSampler({ takes: 3 }), false);
});
test("review 3 #2: the baseline unknown -- an untouched press asks nothing of its own, an edited one waits", () => {
const draft = tuneStartOf({ madeWith: MADE_LIVELY, baseline: null });
- assert.deepEqual(unknownBaselineAskOf(draft, { madeOwn: false }), { waits: false, ask: { takes: 3 } });
+ assert.deepEqual(unknownBaselineAskOf(draft, { madeOwn: false }), { waits: false, ask: null }, "an untouched press asks nothing of its own: the takes it did not own are resolved now (lane reads-find)");
assert.deepEqual(unknownBaselineAskOf(draft, { madeOwn: false, dirty: true }), { waits: true, ask: null });
// A line whose last read was its own: its numbers again (S3's rule), still its own.
- assert.deepEqual(unknownBaselineAskOf(tuneStartOf({ madeWith: { ...MADE_LIVELY, temperature: 0.9 }, baseline: null }), { madeOwn: true }).ask, { temperature: 0.9, top_p: 0.92, repeat_penalty: 1.25, takes: 3 });
+ const ownMade = { ...MADE_LIVELY, temperature: 0.9 };
+ assert.deepEqual(unknownBaselineAskOf(tuneStartOf({ madeWith: ownMade, baseline: null, own: lineOwnOf({ tuning: ownMade, tuningAsked: true }) }), { madeOwn: true }).ask, { temperature: 0.9, top_p: 0.92, repeat_penalty: 1.25, takes: 3 });
});
test("review 3 #3: Use <character>'s -- a line whose last read was its own goes back to its character: nothing of its own asked", () => {
@@ -101,12 +104,42 @@ test("review 3 #3: Use <character>'s -- a line whose last read was its own goes
assert.ok(asksSampler(tuneAskOf(tuneStartOf({ madeWith: own, baseline: b }), b)), "before: its own numbers, asked as its own");
const back = characterTuneOf(own, b);
assert.deepEqual([back.draft.temperature, back.draft.top_p, back.draft.repeat_penalty], ["0.4", "0.8", "1.2"], "the draft at the character's");
- assert.deepEqual(tuneAskOf(back.draft, back.baseline), { takes: 3 }, "the next press asks only the takes: recorded \"preset\"");
+ assert.equal(tuneAskOf(back.draft, back.baseline), null, "the next press asks nothing of its own -- the takes too are the character's or the settings' now -- and records \"preset\"");
});
test("review 3 #4: no character now, the last read the character's since removed -- the Tune starts from the last read's numbers (S3)", () => {
const none = { character: null, madeOwn: false };
const d = tuneStartOf({ madeWith: MADE_LIVELY, baseline: none });
- assert.deepEqual([d.temperature, d.top_p, d.repeat_penalty, d.takes], ["0.75", "0.92", "1.25", "3"]);
+ assert.deepEqual([d.temperature, d.top_p, d.repeat_penalty, d.takes], ["0.75", "0.92", "1.25", ""], "the sampler the last read's (S3); the takes it did not own empty: the editor's setting");
assert.deepEqual(tuneStartOf({ madeWith: MADE_LIVELY, baseline: none }), tuneStartOf({ madeWith: MADE_LIVELY }), "S3's start, exactly");
});
+
+// ---------------------------------------------------------------------------
+// LINE-OWNED VALUES ONLY (lane reads-find, the orchestrator's ruling 2): a plain press passes back only what the line
+// owned (`tuningOwn`, else an older take's every recorded value when it asked true); the character's or the settings'
+// -- takes included -- are resolved now.
+// ---------------------------------------------------------------------------
+
+test("lineOwnOf: tuningOwn when recorded; an older take asked true owns every recorded value; else none", () => {
+ assert.deepEqual(lineOwnOf({ tuning: MADE_LIVELY, tuningAsked: "preset", tuningOwn: { takes: 5 } }), { takes: 5 });
+ assert.deepEqual(lineOwnOf({ tuning: MADE_LIVELY, tuningAsked: true }), MADE_LIVELY);
+ assert.equal(lineOwnOf({ tuning: MADE_LIVELY, tuningAsked: "preset" }), null, "an old take that owned only its takes reads as owning none (the known limit)");
+ assert.equal(lineOwnOf({ tuning: MADE_LIVELY }), null);
+ assert.equal(lineOwnOf(null), null);
+});
+
+test("a plain press: the character's takes changed -- the old recorded takes are not sent; a line-owned takes survives", () => {
+ // Made under the character's tuning with the editor's 3 takes; the character names 4 takes now.
+ const now = { character: { name: "The Teller", tuning: { ...LIVELY, takes: 4 } }, madeOwn: false };
+ assert.equal(plainPressAskOf({ madeWith: MADE_LIVELY, baseline: now, own: lineOwnOf({ tuning: MADE_LIVELY, tuningAsked: "preset" }) }), null, "the character's 4 is asked as it is now");
+ // The line asked its own 5 takes (tuningOwn): they survive, the sampler is still the character's.
+ assert.deepEqual(plainPressAskOf({ madeWith: { ...MADE_LIVELY, takes: 5 }, baseline: now, own: { takes: 5 } }), { takes: 5 });
+ // Its own takes equal to the character's now are still its own.
+ assert.deepEqual(plainPressAskOf({ madeWith: { ...MADE_LIVELY, takes: 4 }, baseline: now, own: { takes: 4 } }), { takes: 4 });
+ // No character: S3's rule for the sampler; the takes only when owned.
+ assert.equal(plainPressAskOf({ madeWith: { temperature: 0.55, takes: 3 }, baseline: { character: null, madeOwn: false } }), null);
+ assert.deepEqual(plainPressAskOf({ madeWith: { temperature: 0.7, takes: 3 }, baseline: null, own: { temperature: 0.7, takes: 3 } }), { temperature: 0.7, takes: 3 });
+ // The untouched bench press is this same ask (ReadAgain: tuneAskOf of the start, the baseline with ownTakes).
+ const b = { ...now, ownTakes: 5 };
+ assert.deepEqual(tuneAskOf(tuneStartOf({ madeWith: { ...MADE_LIVELY, takes: 5 }, baseline: b, own: { takes: 5 } }), b), plainPressAskOf({ madeWith: { ...MADE_LIVELY, takes: 5 }, baseline: now, own: { takes: 5 } }));
+});
diff --git a/umtool/package.json b/umtool/package.json
@@ -8,7 +8,7 @@
"build": "NEXT_TELEMETRY_DISABLED=1 next build",
"start": "NEXT_TELEMETRY_DISABLED=1 next start --port ${UMTOOL_PORT:-3050}",
"typecheck": "tsc --noEmit",
- "test": "ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/../common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" tsx --test lib/brandIcon.test.ts lib/privacy.test.ts lib/articles/*.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts",
+ "test": "ARCHILYZER_EDITOR_URL=http://127.0.0.1:9 WORKER_TOKEN= UMTOOL_URL=http://127.0.0.1:9 ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/../common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" tsx --test lib/brandIcon.test.ts lib/privacy.test.ts lib/articles/*.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts",
"e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test"
},
"dependencies": {
diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs
@@ -838,11 +838,16 @@ export function madeOf(e, take, role = "post", seen = new Set()) {
const part = parts.find((p) => p?.role === role && typeof p?.take !== "string" && isObj(p?.tuning));
// Where it came from: the piece's own part says so (one asked its explicit defaults has a provenance and no tuning).
const said = parts.find((p) => p?.role === role && typeof p?.take !== "string" && p?.tuningAsked !== undefined);
+ // THE VALUES ITS LINE OWNED (lane reads-find, review 1): a thread piece's `read.tuned[role].tuning` (the read's own
+ // values for it), else the take's `tuningOwn` -- never judged against a character's (a plain press passes them back).
+ const tuned = isObj(take?.read?.tuned) && isObj(take.read.tuned[role]) ? take.read.tuned[role] : null;
+ const own = tuned ? (isObj(tuned.tuning) ? tuned.tuning : null) : role === "post" || !parts.some((p) => p?.role === role) ? (isObj(take?.tuningOwn) ? take.tuningOwn : null) : null;
return {
tuning: part ? part.tuning : isObj(take?.tuning) ? take.tuning : null,
// A thread read's part says where its own tuning came from; else the take does.
asked: said?.tuningAsked ?? part?.tuningAsked ?? take?.tuningAsked,
reading: Number.isInteger(take?.reading) ? take.reading : 0,
+ own,
};
}
@@ -875,6 +880,8 @@ function screenReadsOf(take) {
* where its tuning came from but records a SAMPLER value off the defaults was asked so (S1's flags; its takes are
* never looked at here: they record the editor's setting at the time, which may have changed since);
* a thread read's part that is another take answers as that take does (madeOf);
+ * - a value its line OWNS (the take's `tuningOwn`, a thread piece's `read.tuned[role].tuning`; lane reads-find) is
+ * never compared, its takes included;
* - the tuning it was made with (none recorded: the defaults) differs from the character's: the sampler's five
* values, each a default when unsaid; `takes` ONLY when the character names its takes (a read with none of its own
* records the editor's setting, `settingTakes`); the reading is never compared (a reading is a pick, not a setting).
@@ -899,7 +906,9 @@ export function tuningStale(manifest, resolve, { settingTakes = ORPHEUS_DEFAULT_
if (how.asked === true || (how.asked === undefined && off)) continue;
const wantT = characterTuningNormal(want.tuning);
const wantS = samplerOf(wantT);
- const differs = SAMPLER_FIELDS.some((k) => madeS[k] !== wantS[k]) || (wantT.takes !== undefined && (madeTakes ?? settingTakes) !== wantT.takes);
+ // A value the line OWNS (madeOf's `own`, takes included) is the line's, never the character's: not compared.
+ const owns = (k) => isObj(how.own) && typeof how.own[k] === "number";
+ const differs = SAMPLER_FIELDS.some((k) => !owns(k) && madeS[k] !== wantS[k]) || (!owns("takes") && wantT.takes !== undefined && (madeTakes ?? settingTakes) !== wantT.takes);
if (!differs) continue;
rows.push({
id: e.id, handle: handleKey(r.handle), role: r.role, character: want.character,
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -205,7 +205,9 @@ const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice",
// `tuningAsked` (lane character-tuning): where an Orpheus take's tuning came from -- true (its line's own: the
// command's flags, the bench's Tune), "preset" (its character's: stale when that changes, cast.mjs tuningStale).
// Absent: none was asked (the defaults), or unknown (made before it was recorded).
-const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read", "said", "speedAsked", "screenLine", "tuning", "reading", "forReading", "tuningAsked"]);
+// `tuningOwn` (lane reads-find): the LINE's own values exactly as asked (the flags, the bench's Tune; absent: it owned
+// none) -- what a plain press passes back; every other value is the character's or the settings', resolved anew.
+const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs", "lexicon", "read", "said", "speedAsked", "screenLine", "tuning", "reading", "forReading", "tuningAsked", "tuningOwn"]);
const STEP_KEYS = new Set(["op", "engine", "voice", "pitch", "semitones", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]);
// `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's;
// `engine`: the part's own when it is not the take's (a cast voice that names its engine: postThreadRead.mjs).
@@ -691,6 +693,8 @@ export function validatePostNarration(e) {
if (t.speedAsked !== undefined && t.speedAsked !== true && t.speedAsked !== "item" && t.speedAsked !== "preset") errors.push(`${tw}.speedAsked must be true, "item" or "preset"`);
if (t.tuningAsked !== undefined && t.tuningAsked !== true && t.tuningAsked !== "preset") errors.push(`${tw}.tuningAsked must be true (its line's own tuning) or "preset" (its character's)`);
errors.push(...tuningProblems(t.tuning, t.reading, tw));
+ if (t.tuningOwn !== undefined && (!isObj(t.tuningOwn) || !Object.keys(t.tuningOwn).length)) errors.push(`${tw}.tuningOwn must be the line's own tuning values (or absent: it owned none)`);
+ else if (t.tuningOwn !== undefined) errors.push(...tuningProblems(t.tuningOwn, undefined, `${tw}.tuningOwn`).map((x) => x.replace(`${tw}.tuningOwn.tuning`, `${tw}.tuningOwn`)));
if (t.forReading !== undefined && t.forReading !== true) errors.push(`${tw}.forReading must be true (or absent)`);
if (t.read !== undefined && !(isObj(t.read) && t.read.kind === "thread" && JSON.stringify(t.read).length <= 4000)) errors.push(`${tw}.read must be {kind: "thread", …} (how the thread read was asked for)`);
// A RECORDING OF ONE SCREEN LINE (postScreensCli.mjs `posts screen … record`, post-screens.mjs): the line it was