Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 700c9746a68a388968b7383bb3f7d8394277a4e1
parent e5c5c0873da10597842fe7543dfd3ea3b5ff2e8a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 17 Nov 2026 15:48:15 -0500

the re-read queue: one press queues a video's stale reads on the durable queue, each the bench's own command

readsQueue.mjs: one step per item in cut order on lib/queue's durable queue (the umtool app runs it,
one step at a time, only while its own job runner is idle; it survives a reload and a restart), none
waiting on another. A step is `umtool reads <p> reread --one <item> --only <ids>`: it judges the
item again and runs in-process the command the item's bench button runs (readAgainArgv.mjs, shared
with the post-narration route's screen-read and thread-read ops): a post's take with the bench's
ask (--bench-slurs), one stale piece exactly as its line's Read again (--for … --reading next), several
as --tuned role=reading:next, a card's own reading. The tuning asked is each read's plain press
(reads.mjs `ask`: only what the line owned). Re-reads join unpicked. A bench read of the post in
flight holds its step back (retryable). Stop cancels what has not started; a failed step keeps
its reason and is retried; the Reads page's state is the batch file and the steps, so a reload
reads the same. queueView says in one sentence why steps wait (the runner not running, render mode,
a bench read in flight, another step of the queue).

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mumtool/app/api/report/post-narration/route.ts | 29+++--------------------------
Aumtool/lib/report/readAgainArgv.mjs | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/reads.fixtures.mjs | 9++++++---
Mumtool/lib/report/reads.mjs | 24++++++++++++++++++++----
Aumtool/lib/report/readsQueue.mjs | 243+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/readsQueue.test.mjs | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 536 insertions(+), 33 deletions(-)

diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -20,6 +20,7 @@ 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 { askBody, benchSlurVoice, postTakeAskOf } 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 { characterById, recordedPresetOf, shownNameOf } from "umtool-report-to-video/cast"; @@ -629,32 +630,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/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.fixtures.mjs b/umtool/lib/report/reads.fixtures.mjs @@ -9,6 +9,7 @@ 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."; @@ -49,8 +50,8 @@ export function recordedPost() { export const card = () => ({ type: "card", id: "c-1", seconds: "auto", heading: "Later", narration: { text: CARD_TEXT, engine: "orpheus", voice: "leo" } }); /** - * The project: `<root>/<name>/p`, the cast beside it in `<root>/<name>/.umtool/cast.json`, the takes' files on disk - * and the card's reading kept in out/narration/. Returns `{ id, dir, root }`. + * 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); @@ -61,9 +62,11 @@ export async function readsProject(root, name, { cast = castDoc(), timeline = nu 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 n of narrationsOf(manifest)) await keepCardReading(dir, n); - return { id: name, dir, root: top }; + return { id: "p", dir, root: top }; } /** A card's reading kept beside the build (narration-store.mjs's shape): its record and its sound. */ diff --git a/umtool/lib/report/reads.mjs b/umtool/lib/report/reads.mjs @@ -16,6 +16,8 @@ // editable whether These reads can rewrite it (a parent, the quoted or a linked post has no spoken-only words: // "said as shown: only Everywhere changes this"; a recorded read is yours) // take the take that plays: `{ index, file, key, reading, tuning, tunedBy: "line" | "character" | null }` +// 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: @@ -40,6 +42,7 @@ import { parseScreenRole, saidAsOf, screenLineSaid, screensOf } from "umtool-rep 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"]); @@ -76,6 +79,18 @@ export function threadOptsOfRead(read, takes = []) { /** 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, file: t.file ?? null, key: null, reading: Number.isInteger(t.reading) ? t.reading : 0, tuning: isObj(t.tuning) ? t.tuning : null, tunedBy: tunedByOf(t), ...extra } : null); @@ -136,7 +151,7 @@ async function postRows(ctx, m, vs, e, n) { const spoken = str(n0.script) || shownDraftOf(e); if (!norm(spoken)) return []; const want = vs.resolve(e, "post", e.handle ?? null, null); - return [{ ...base, id: readIdOf(e.id), kind: "post", role: null, character: characterRow(vs, want?.character), voice: want ? `${want.engine}:${want.voice}` : null, spoken, said: spokenRead(spoken, e, ctx.red, slur).text, storedAt: str(n0.script) ? "narration.script" : null, shownSpoken: !str(n0.script), editable: true, why: null, take: null, newTake: null, state: "none", because: [] }]; + 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; @@ -146,7 +161,7 @@ async function postRows(ctx, m, vs, e, n) { ...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, + 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 = []; @@ -170,7 +185,7 @@ async function threadRows(ctx, m, vs, e, take, base) { } catch (err) { // The read as it was asked cannot be made now (a take it named is gone, a line changed under a recording): one row // that says so -- stale, re-made from the bench. - return [{ ...base, id: readIdOf(e.id, "post"), kind: "thread", role: "post", character: null, voice: str(take.voice) || null, spoken: str(e.narration?.script), said: null, storedAt: "narration.script", shownSpoken: false, editable: true, why: null, take: takeView(take), newTake: null, state: "stale", because: ["words"], error: err instanceof Error ? err.message : String(err) }]; + 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(" "); @@ -192,6 +207,7 @@ async function threadRows(ctx, m, vs, e, take, base) { voice: `${pc.engine ?? take.engine ?? "?"}:${pc.voice ?? "?"}`, spoken: sc ? (as ?? screenLineSaid(screen, sc.n)) : str(pc.written), said: pc.text, storedAt, shownSpoken: own ? !str(e.narration?.script) : sc ? as === null : true, editable: editable && !pc.take, why: pc.take ? "read from a take (a recording): record it again" : editable ? null : SAID_AS_SHOWN, take: takeView(take, part ? { reading: Number.isInteger(part.reading) ? part.reading : 0, tuning: isObj(part.tuning) ? part.tuning : null, tunedBy: tunedByOf(part) ?? tunedByOf(take) } : {}), newTake: null, + 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) { rows.push({ ...row, state: "recorded", because: [] }); @@ -216,7 +232,7 @@ function cardRows(ctx, n, at) { id: readIdOf(n.id), kind: "card", item: n.id, role: null, n: at, character: null, voice: `${n.engine}:${n.voice}`, spoken: n.text, said: n.text, storedAt: "narration.text", shownSpoken: false, editable: true, why: null, legacy: false, take: plays ? { index: null, file: null, key: plays.key, reading: Number.isInteger(plays.askedReading) ? plays.askedReading : plays.reading ?? 0, tuning: plays.askedTuning ?? null, tunedBy: "line" } : null, - newTake: null, state, because: state === "stale" ? [same ? "settings" : "words"] : [], + 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 })), }]; } diff --git a/umtool/lib/report/readsQueue.mjs b/umtool/lib/report/readsQueue.mjs @@ -0,0 +1,243 @@ +// 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) { + const file = batchPath(dir); + await mkdir(path.dirname(file), { recursive: true }); + return withNotesLock(file, async () => { + const { batches, result } = await fn(await readBatches(dir)); + 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 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 = []; + 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 }); + for (const r of rs) rowsOut.push({ read: r.id, item, kind: r.kind, qid: step.qid, before: 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 } }; + }); +} + +/** Whether a bench read of post item `e` is in flight (the take op's marker, young and naming a job not yet kept). */ +export async function benchReadInFlight(dir, e, { now = Date.now() } = {}) { + 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 (now - at > BENCH_MARKER_MS) return null; + if (marker?.file && (e.narration?.takes ?? []).some((t) => t?.file === marker.file)) return null; + return { at: new Date(at).toISOString(), jobId: marker?.jobId ?? null }; +} + +/** + * 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 } = {}) { + 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 ?? []); + const reads = rows.filter((r) => r.item === item && (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); + 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) => { + if (a[0] === "posts") return (await import("./postsCli.mjs")).postsCommand(a.slice(1), { root: reportsRoot, ...(tts ? { tts } : {}) }); + if (a[0] === "narration") return (await import("./cardNarrationCli.mjs")).cardNarrationCommand(a.slice(1), { root: reportsRoot, ...(narrate ? { narrate } : {}) }); + 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})`); + return retryStep(qdir, row.qid); +} diff --git a/umtool/lib/report/readsQueue.test.mjs b/umtool/lib/report/readsQueue.test.mjs @@ -0,0 +1,175 @@ +// 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, 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); +}); + +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; +});