// 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 })); });