// 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
// reread --one - --only ` -- 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
pick`); a card's re-read is what the card says now, so it plays.
//
// /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, 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/`); 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 reread --one - --only `): 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}`;
// ONLY this project's own steps are read (its batches'): never the whole queue store, which holds every old step
// of every project (the regression of 17 Nov 2026). What else the queue runs is the runner's to say (the route adds
// its own reason: what it waits for).
if (rows.some((x) => x.state === "running")) {
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;
}
return "waiting for its turn: the queue runs one step at a time, when the app's job runner is free (umtool queue ls: what is ahead)";
}
/** 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
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 }`. Only this project's own batches'
* steps are read, never the whole queue store.
* @param {{ id: string, dir: string }} project
* @param {string} item
*/
export async function rereadRunningFor(project, item, o = {}) {
const qdir = queueDirFor(o);
const rows = (await readBatches(project.dir)).flatMap((b) => b.rows).filter((r) => r.item === item && r.qid);
for (const qid of new Set(rows.map((r) => r.qid))) {
const s = await getStep(qdir, qid);
if (s && resolveStep(s).state === "running") return { qid, label: s.label };
}
return null;
}