commit e6a89d54e14926d18112669392ca94b39337a2e7
parent ab3d1cb460938e5d190ab6ea3fb131c9a07470d4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 4 Nov 2026 22:41:25 -0500
umtool: every take render records itself; a durable queue the app runs, step by step
The operator's ruling (4 Nov 2026, after mid-13's render died at exit 1 behind a
grep-filtered shell chain that then printed DONE): umtool does the sequencing and the
tracking, and an agent polls it.
- takes/<id>/render.json + render.log (lib/report/renderRecord.mjs), written by makeTake
whoever started it (a terminal, the Takes page's job, the queue): state running /
waiting (queue-lock said so) / done / failed / cancelled, pid and its start time, stage
and a rough percent from the NDJSON events, on failure the first error line (a bare
"build-video exited 1" is replaced by it) and the log's last 40 lines, on done the mp4
and its measured seconds. Done only with a non-empty mp4: a 0-byte or missing mp4
fails the take before the old preview is replaced. On read, a running record whose
process is gone (pid dead, or reused: /proc start time) reads failed.
- `umtool take status <p> [--id <t>] [--json] [--log] [--tail N]`: exit 0 done, 3
queued/waiting/running, 1 failed/cancelled/blocked/none; a take waiting in the queue
reads queued.
- The durable queue (lib/queue/store.mjs, its design note at the top): steps are a umtool
subcommand's argv, one JSON file each under <reports root>/.umtool-queue/, run by the
umtool APP (instrumentation.ts -> lib/queue/runner.ts, on under `next start`) one at a
time on the app's own job runner (lib/jobs.ts gains Step.logFile -- the full log --,
the exit code and onEnd). --after waits for done; a failure or cancel blocks its chain;
retry puts it back with the steps blocked behind it; a step running when the app died
is failed ("the step's process is gone"), its log kept, never re-run. A lease keeps one
runner per queue dir.
- `umtool queue add|ls|status|wait|log|cancel|retry`, `umtool jobs`.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
13 files changed, 2405 insertions(+), 16 deletions(-)
diff --git a/package.json b/package.json
@@ -24,7 +24,7 @@
"wt": "node scripts/worktree.mjs",
"e2e:sharded": "node scripts/run-sharded-e2e.mjs",
"e2e:all": "node scripts/e2e-all.mjs",
- "test:scripts": "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",
+ "test:scripts": "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",
"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/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -963,6 +963,12 @@ function usage() {
" editor's transcription and download lanes are held; all let go at its end, failure or signal",
" umtool take <project> --id <id> --promote [--anyway] make this the cut: the take's patch applied to the",
" manifest, one undo point (revisions/…-auto-before-promote-take)",
+ " umtool take status <project> [--id <id>] [--json] [--log] [--tail N] the take's render record (every render",
+ " writes takes/<id>/render.json and the full render.log): exit 0 done, 3 queued/waiting/running, 1 failed",
+ " umtool queue add [--after <qid>|last] [--label T] -- <umtool subcommand argv…> a step the umtool APP runs, in",
+ " order, one at a time (it survives the session); prints the qid. ls [--all] | status <qid> | wait <qid>",
+ " [--timeout S] | log <qid> | cancel <qid> | retry <qid> [--json]; status exits 0 done, 3 going, 1 failed",
+ " umtool jobs [--json] every running and recent take render and queue step, across projects, and the app's jobs",
" umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]",
" | ls <project> | relabel <project> <take> <label…> | supersede <project> <take> [--by <take>] [--clear]",
" | delete <project> <take> [--dry-run] [--force] take housekeeping: a label fixed, a take folded away",
@@ -1107,6 +1113,10 @@ const COMMANDS = {
// The take maker (release 33): lib/report/takeCli.mjs.
take: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takeCommand(argv.slice(argv.indexOf("take") + 1))),
takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))),
+ // The durable queue and every render's record (4 Nov 2026): lib/queue/cli.mjs.
+ queue: async () =>
+ process.exit(await (await import("../lib/queue/cli.mjs")).queueCommand(argv.slice(argv.indexOf("queue") + 1), { commands: Object.keys(COMMANDS) })),
+ jobs: async () => process.exit(await (await import("../lib/queue/cli.mjs")).jobsCommand(argv.slice(argv.indexOf("jobs") + 1))),
// Render mode (2026-10-30): lib/report/renderMode.mjs.
"render-mode": async () => process.exit(await (await import("../lib/report/renderMode.mjs")).renderModeCommand(argv.slice(argv.indexOf("render-mode") + 1))),
// The render pool (report-to-video render-pool.mjs): lib/report/poolCli.mjs.
diff --git a/umtool/instrumentation.ts b/umtool/instrumentation.ts
@@ -0,0 +1,23 @@
+// Next.js instrumentation hook: register() runs once when the server starts.
+// umtool arms ONE thing here, the durable queue's runner (lib/queue/runner.ts),
+// so the steps an agent queued (`umtool queue add`) run in the app -- the live
+// unit -- and survive the session that queued them. A step that was running
+// when the last process died is marked failed with its log, never re-run.
+//
+// Skipped on the Edge runtime (the runner is Node-only; every import is lazy
+// for that reason), when the process boots idle (ARCHILYZER_IDLE_BOOT, as the
+// editor's runners are), and unless queueRunnerEnabled says so: on under `next
+// start`, off under `next dev` unless UMTOOL_QUEUE_RUNNER=1.
+import { isIdleBoot } from "yt-dlp-transcript-common/lib/idleBoot";
+
+export async function register() {
+ if (process.env.NEXT_RUNTIME !== "nodejs") return;
+ if (isIdleBoot()) return;
+ try {
+ const { queueRunnerEnabled, startQueueRunner } = await import("./lib/queue/runner");
+ if (queueRunnerEnabled(process.env)) startQueueRunner();
+ } catch (e) {
+ // A runner that cannot arm must not keep the app from serving; the queue's pages say it is not running.
+ console.error(`umtool: the queue runner did not start: ${e instanceof Error ? e.message : String(e)}`);
+ }
+}
diff --git a/umtool/lib/jobs.ts b/umtool/lib/jobs.ts
@@ -1,4 +1,5 @@
import { spawn } from "node:child_process";
+import { createWriteStream, type WriteStream } from "node:fs";
import { ENV_DENY, type Step } from "./trim";
// ---------------------------------------------------------------------------
@@ -46,6 +47,10 @@ export type Job = {
/** Set by cancel(); the running step notices and kills its group. */
cancelling: boolean;
error: string | null;
+ /** The last step's exit code (null: killed by a signal, or it never started). */
+ exitCode: number | null;
+ /** The signal that ended the last step, if one did. */
+ signal: string | null;
};
/** Kept in memory, like lib/mix.ts: a job that does not survive a restart is a
@@ -107,6 +112,27 @@ function push(job: Job, line: string, ndjson = false) {
function runStep(job: Job, step: Step): Promise<void> {
return new Promise((resolve, reject) => {
push(job, `$ ${step.argv.join(" ")}`);
+ // The full log (Step.logFile): every chunk as it came, nothing clamped.
+ let file: WriteStream | null = null;
+ if (step.logFile) {
+ try {
+ file = createWriteStream(/* turbopackIgnore: true */ step.logFile, { flags: "a" });
+ file.on("error", () => {
+ file = null;
+ });
+ file.write(`$ ${step.argv.join(" ")}\n`);
+ } catch {
+ file = null;
+ }
+ }
+ const tee = (b: Buffer | string) => {
+ file?.write(b);
+ };
+ const closeFile = (line?: string) => {
+ if (line) file?.write(line);
+ file?.end();
+ file = null;
+ };
const denied = Object.keys(step.env).filter((k) => ENV_DENY.includes(k));
if (denied.length) push(job, ` (recipe sets ${denied.join(", ")} — by design)`);
@@ -127,6 +153,7 @@ function runStep(job: Job, step: Step): Promise<void> {
const stop = (why: string) => {
push(job, ` ** ${why}`);
+ tee(`** ${why}\n`);
killGroup(child.pid);
};
@@ -150,14 +177,24 @@ function runStep(job: Job, step: Step): Promise<void> {
clearInterval(cancelTimer);
};
- child.stdout.on("data", (b: Buffer) => push(job, b.toString(), step.ndjson));
- child.stderr.on("data", (b: Buffer) => push(job, b.toString()));
+ child.stdout.on("data", (b: Buffer) => {
+ tee(b);
+ push(job, b.toString(), step.ndjson);
+ });
+ child.stderr.on("data", (b: Buffer) => {
+ tee(b);
+ push(job, b.toString());
+ });
child.on("error", (e) => {
done();
+ closeFile(`** ${e.message}\n`);
reject(e);
});
- child.on("close", (code) => {
+ child.on("close", (code, signal) => {
done();
+ job.exitCode = code;
+ job.signal = signal ?? null;
+ closeFile(`** exit ${code === null ? `by ${signal ?? "a signal"}` : code}\n`);
if (job.cancelling) reject(new Error("cancelled"));
else if (code === 0) resolve();
else reject(new Error(`${step.argv[0]} exited ${code}`));
@@ -196,7 +233,16 @@ function killGroup(pid: number | undefined) {
export function startJob(
kind: string,
steps: Step[],
- { project = null, onDone }: { project?: string | null; onDone?: (job: Job) => unknown } = {},
+ {
+ project = null,
+ onDone,
+ onEnd,
+ }: {
+ project?: string | null;
+ onDone?: (job: Job) => unknown;
+ /** Runs once the job has ended, whatever its state (the durable queue records it: lib/queue/). */
+ onEnd?: (job: Job) => unknown;
+ } = {},
): Job {
const running = runningJob();
if (running) throw new Error(`a job is already running (${running.id})`);
@@ -216,6 +262,8 @@ export function startJob(
pids: [],
cancelling: false,
error: null,
+ exitCode: null,
+ signal: null,
};
jobs.set(job.id, job);
reg.current = job;
@@ -239,6 +287,13 @@ export function startJob(
job.endedAt = Date.now();
if (reg.current === job) reg.current = null;
}
+ if (onEnd) {
+ try {
+ await onEnd(job);
+ } catch {
+ /* the job has ended either way */
+ }
+ }
if (job.state === "done" && onDone) {
try {
await onDone(job);
@@ -279,6 +334,7 @@ export function jobView(job: Job, since = 0, sinceEvent = 0) {
stepIndex: job.stepIndex,
steps: job.steps.map((s) => ({ label: s.label, argv: s.argv, cwd: s.cwd, env: s.env })),
error: job.error,
+ exitCode: job.exitCode,
log: job.log.slice(Math.max(0, since)),
next: job.log.length,
events: job.events.slice(Math.max(0, sinceEvent)),
diff --git a/umtool/lib/queue/cli.mjs b/umtool/lib/queue/cli.mjs
@@ -0,0 +1,405 @@
+// `umtool queue …` and `umtool jobs` (lib/queue/store.mjs is the queue): what
+// an agent calls instead of writing a shell chain. Queue the steps, then poll:
+//
+// umtool queue add [--after <qid>|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>
+// umtool queue ls [--all] [--json]
+// umtool queue status <qid> [--json] exit 0 done · 3 queued/running · 1 failed/blocked/cancelled
+// umtool queue wait <qid> [--timeout <s>] the same exit, after up to <s> seconds (default 90)
+// umtool queue log <qid> [--tail N] its full log
+// umtool queue cancel <qid> | retry <qid> [--json]
+// umtool jobs [--json] every running and recent render and step, across projects
+//
+// Plain ESM: the CLI runs it under bare node.
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { readRenderRecord, recordLines, renderPointerFile } from "../report/renderRecord.mjs";
+import {
+ addStep,
+ cancelStep,
+ getStep,
+ isQid,
+ listSteps,
+ logFileOf,
+ logTail,
+ queueDirOf,
+ readLease,
+ resolveStep,
+ retryStep,
+ stepExitCode,
+ TERMINAL,
+} from "./store.mjs";
+
+export const QUEUE_USAGE = [
+ "usage: umtool queue add [--after <qid>|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>",
+ " a step: the argv of a umtool command (no shell: one word per argument), run by the umtool app",
+ " (its systemd unit) one at a time, in order. --after waits for that step to be DONE; if it fails",
+ " or is cancelled this one is BLOCKED (`retry` the failed one and both go back). Prints the qid",
+ " (q<N>) on stdout. --timeout: the step's time limit (default 720 minutes)",
+ " umtool queue ls [--all] [--json] the steps (default: not finished, or finished in the last 24 h)",
+ " and whether the app's runner is up",
+ " umtool queue status <qid> [--json] one step: state, exit code, error, log path.",
+ " EXIT 0 done · 3 queued or running · 1 failed, blocked or cancelled",
+ " umtool queue wait <qid> [--timeout <s>] wait up to <s> seconds (default 90) for it to finish; the same exits",
+ " umtool queue log <qid> [--tail N] its full log (the latest attempt's)",
+ " umtool queue cancel <qid> [--json] a queued/blocked step at once; a running one is stopped (its process group)",
+ " umtool queue retry <qid> [--json] a failed or cancelled step back in the queue, with the steps blocked behind it",
+ "",
+ "A running step whose app died reads FAILED (\"the step's process is gone\"), its log kept: it is never re-run on its",
+ "own. A take render's own record is `umtool take status <project> --id <take>`.",
+].join("\n");
+
+export const JOBS_USAGE = [
+ "usage: umtool jobs [--json] every running and recent take render (takes/<id>/render.json, read through the queue",
+ " dir's renders/ pointers), every queue step not finished or finished in the last 24 h, and the",
+ " umtool app's own jobs (GET /api/jobs at --url / UMTOOL_URL, when it answers)",
+].join("\n");
+
+class CliError extends Error {}
+
+const DAY_MS = 86_400_000;
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+function parse(args, valued) {
+ const dash = args.indexOf("--");
+ const head = dash === -1 ? args : args.slice(0, dash);
+ const rest = dash === -1 ? null : args.slice(dash + 1);
+ const flags = {};
+ const positional = [];
+ for (let i = 0; i < head.length; i += 1) {
+ const a = head[i];
+ if (a.startsWith("--")) {
+ if (valued.has(a)) {
+ if (i + 1 >= head.length) throw new CliError(`${a} needs a value`);
+ flags[a] = head[++i];
+ } else flags[a] = "";
+ } else positional.push(a);
+ }
+ return { flags, positional, rest, has: (n) => n in flags, one: (n) => flags[n] };
+}
+
+/** The umtool app's base URL (buildRun.mjs's rule). */
+const appBase = (url, env = process.env) => String(url || env.UMTOOL_URL || "http://localhost:3050").replace(/\/+$/, "");
+
+async function askApp(base, route, fetchImpl, timeoutMs = 1500) {
+ try {
+ const res = await fetchImpl(`${base}${route}`, { signal: AbortSignal.timeout(timeoutMs) });
+ if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
+ return { ok: true, json: await res.json() };
+ } catch (e) {
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
+ }
+}
+
+/**
+ * Which project and take a step works on, when its argv says: `take <p> --id <t>`,
+ * `takes <sub> <p> [<t>]`, or any command whose first word after it is a project.
+ */
+export async function targetOf(argv, root) {
+ const [cmd, ...rest] = argv;
+ // umtool's commands take the project first (`takes` after its subcommand).
+ const word = cmd === "takes" ? rest[1] : rest[0];
+ let project = null;
+ if (word && !word.startsWith("-")) {
+ const r = await resolveProject(word, root).catch(() => ({}));
+ if (r?.project) project = r.project.id;
+ }
+ let take = null;
+ if (cmd === "take") {
+ const i = rest.indexOf("--id");
+ take = i >= 0 ? rest[i + 1] ?? null : null;
+ } else if (cmd === "takes" && ["pick", "cancel", "relabel", "delete", "supersede", "fork"].includes(rest[0] ?? "")) take = rest[2] ?? null;
+ return project || take ? { project, take } : null;
+}
+
+const fmtTime = (iso) => (iso ? String(iso).slice(0, 19).replace("T", " ") : "—");
+
+/** One line of a step, for `ls` and `jobs`. */
+export function stepLine(s) {
+ const tail =
+ s.state === "blocked" || s.state === "failed" || s.state === "cancelled"
+ ? ` — ${s.error ?? ""}`
+ : s.state === "running"
+ ? ` (since ${fmtTime(s.startedAt).slice(11)}, pid ${s.pid ?? "?"})`
+ : s.state === "done"
+ ? ` (${fmtTime(s.endedAt).slice(11)})`
+ : s.after
+ ? ` (after ${s.after})`
+ : "";
+ return `${s.qid.padEnd(6)} ${s.state.toUpperCase().padEnd(9)} ${s.label}${tail}`;
+}
+
+function stepDetail(s, dir) {
+ const out = [stepLine(s)];
+ out.push(` argv: umtool ${s.argv.map((a) => (/[\s"'$]/.test(a) ? JSON.stringify(a) : a)).join(" ")}`);
+ if (s.after) out.push(` after: ${s.after}`);
+ out.push(` queued ${fmtTime(s.createdAt)}${s.startedAt ? ` · started ${fmtTime(s.startedAt)}` : ""}${s.endedAt ? ` · ended ${fmtTime(s.endedAt)}` : ""}${s.exitCode != null ? ` · exit ${s.exitCode}` : ""}${s.attempts > 1 ? ` · attempt ${s.attempts}` : ""}`);
+ if (s.error) out.push(` error: ${s.error}`);
+ if (s.target?.take && s.target?.project) out.push(` its take's record: umtool take status ${s.target.project} --id ${s.target.take}`);
+ out.push(` log: ${logFileOf(dir, s.qid)}`);
+ return out;
+}
+
+/** The runner line: is the app running the queue? */
+function runnerLine(lease) {
+ if (lease?.live) return `runner: the umtool app (pid ${lease.pid}${lease.host ? ` on ${lease.host}` : ""}, since ${fmtTime(lease.since)})`;
+ return "runner: NONE — nothing runs until the umtool app is up (archilyzer-umtool.service; `archilyzer service restart --apps umtool`)";
+}
+
+/**
+ * `umtool queue …`
+ * @param {string[]} args everything after `queue`
+ * @param {{ reportsRoot?: string, commands?: string[], log?: (s: string) => void, err?: (s: string) => void,
+ * fetchImpl?: typeof fetch, cwd?: string, env?: Record<string, string | undefined>, pollMs?: number }} [opts]
+ * @returns {Promise<number>}
+ */
+export async function queueCommand(args, { reportsRoot = REPORTS_ROOT, commands = null, log = console.log, err = console.error, fetchImpl = fetch, cwd = process.cwd(), env = process.env, pollMs = 2000 } = {}) {
+ try {
+ const p = parse(args, new Set(["--after", "--label", "--timeout", "--tail", "--url"]));
+ const [sub, qid] = p.positional;
+ const dir = queueDirOf({ reportsRoot, env });
+ const json = p.has("--json");
+ if (!sub || p.has("--help")) {
+ log(QUEUE_USAGE);
+ return sub ? 0 : 2;
+ }
+ if (sub === "add") {
+ const argv = p.rest ?? [];
+ if (!argv.length) throw new CliError("umtool queue add [--after <qid>] [--label T] -- <umtool subcommand argv…> (the `--` and then the command)");
+ if (argv[0] === "umtool") throw new CliError("give the subcommand, not `umtool` itself: `-- take <project> --id <t> …`");
+ if (argv[0] === "queue") throw new CliError("a queue step cannot queue steps");
+ if (commands && !commands.includes(argv[0])) throw new CliError(`"${argv[0]}" is not a umtool command (\`umtool help\`)`);
+ const after = p.one("--after") ?? null;
+ if (after !== null && after !== "last" && !isQid(after)) throw new CliError(`--after takes a qid (q<N>) or "last", not "${after}"`);
+ const target = await targetOf(argv, reportsRoot);
+ const step = await addStep(dir, {
+ argv,
+ label: p.one("--label") ?? null,
+ after,
+ cwd,
+ target,
+ by: env.USER ? `umtool queue add (${env.USER})` : "umtool queue add",
+ timeoutMin: p.has("--timeout") ? Number(p.one("--timeout")) : undefined,
+ });
+ const lease = await readLease(dir);
+ if (json) log(JSON.stringify({ ok: true, step, runner: lease }, null, 2));
+ else {
+ log(step.qid);
+ err(`${step.qid} queued: ${step.label}${step.after ? ` (after ${step.after})` : ""}`);
+ err(` poll: umtool queue status ${step.qid} (exit 0 done, 3 still going, 1 failed)`);
+ if (!lease?.live) err(` ${runnerLine(lease)}`);
+ }
+ return 0;
+ }
+ if (sub === "ls") {
+ const lease = await readLease(dir);
+ const all = (await listSteps(dir)).map((s) => resolveStep(s));
+ const cutoff = Date.now() - DAY_MS;
+ const steps = p.has("--all") ? all : all.filter((s) => !TERMINAL.has(s.state) || Date.parse(s.endedAt ?? s.createdAt) > cutoff);
+ if (json) log(JSON.stringify({ dir, runner: lease, steps }, null, 2));
+ else {
+ log(runnerLine(lease));
+ if (!steps.length) log(all.length ? "no step finished in the last 24 h (--all lists every one)" : "the queue is empty");
+ for (const s of steps) log(stepLine(s));
+ }
+ return 0;
+ }
+ if (sub === "status" || sub === "wait" || sub === "log" || sub === "cancel" || sub === "retry") {
+ if (!isQid(qid)) throw new CliError(`umtool queue ${sub} <qid> (q<N>: \`umtool queue ls\`)`);
+ if (sub === "cancel") {
+ const r = await cancelStep(dir, qid);
+ if (json) log(JSON.stringify({ ok: true, ...r }, null, 2));
+ else log(r.said);
+ return 0;
+ }
+ if (sub === "retry") {
+ const r = await retryStep(dir, qid);
+ if (json) log(JSON.stringify({ ok: true, ...r }, null, 2));
+ else log(r.said);
+ return 0;
+ }
+ const first = await getStep(dir, qid);
+ if (!first) throw new CliError(`no step ${qid} (\`umtool queue ls --all\`)`);
+ if (sub === "log") {
+ const file = logFileOf(dir, qid);
+ if (p.has("--tail")) {
+ const n = Math.max(1, Number(p.one("--tail")) || 40);
+ for (const l of (await logTail(file, 1024 * 1024)).slice(-n)) log(l);
+ } else {
+ const text = await readFile(file, "utf8").catch(() => null);
+ if (text === null) {
+ err(`${qid} has no log yet (${first.state})`);
+ return 1;
+ }
+ log(text.replace(/\n$/, ""));
+ }
+ return 0;
+ }
+ let step = resolveStep(first);
+ if (sub === "wait") {
+ const limit = Math.max(1, Number(p.one("--timeout") ?? 90) || 90) * 1000;
+ const until = Date.now() + limit;
+ while (stepExitCode(step.state) === 3 && Date.now() < until) {
+ await sleep(Math.min(pollMs, Math.max(50, until - Date.now())));
+ const s = await getStep(dir, qid);
+ if (s) step = resolveStep(s);
+ }
+ }
+ const code = stepExitCode(step.state);
+ if (json) log(JSON.stringify({ ...step, exit: code, log: logFileOf(dir, qid) }, null, 2));
+ else for (const l of stepDetail(step, dir)) log(l);
+ return code;
+ }
+ throw new CliError(`unknown: queue ${sub}\n\n${QUEUE_USAGE}`);
+ } catch (e) {
+ err(e instanceof Error ? e.message : String(e));
+ return e instanceof CliError ? 2 : 1;
+ }
+}
+
+/**
+ * The recent take renders, through the pointers in the queue dir's renders/.
+ * @param {string} dir the queue dir
+ * @param {{ days?: number, limit?: number }} [o]
+ */
+export async function recentRenders(dir, { days = 7, limit = 30 } = {}) {
+ const names = await readdir(path.join(dir, "renders")).catch(() => []);
+ const ptrs = [];
+ for (const n of names) {
+ if (!n.endsWith(".json")) continue;
+ const ptr = await readFile(path.join(dir, "renders", n), "utf8").then(JSON.parse, () => null);
+ if (ptr?.projectDir && ptr?.take) ptrs.push(ptr);
+ }
+ const cutoff = Date.now() - days * DAY_MS;
+ const out = [];
+ for (const ptr of ptrs.sort((a, b) => String(b.startedAt).localeCompare(String(a.startedAt))).slice(0, limit * 2)) {
+ const rec = await readRenderRecord(path.join(ptr.projectDir, "takes", ptr.take));
+ if (!rec) continue;
+ const live = rec.state === "running" || rec.state === "waiting";
+ if (!live && Date.parse(rec.endedAt ?? rec.startedAt) < cutoff) continue;
+ out.push({ ...rec, project: rec.project ?? ptr.project, projectDir: ptr.projectDir, logPath: path.join(ptr.projectDir, "takes", ptr.take, rec.log ?? "render.log") });
+ if (out.length >= limit) break;
+ }
+ return out;
+}
+
+/**
+ * `umtool jobs`
+ * @param {string[]} args
+ * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, fetchImpl?: typeof fetch, env?: Record<string, string | undefined> }} [opts]
+ */
+export async function jobsCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, fetchImpl = fetch, env = process.env } = {}) {
+ try {
+ const p = parse(args, new Set(["--url"]));
+ if (p.has("--help")) {
+ log(JOBS_USAGE);
+ return 0;
+ }
+ const dir = queueDirOf({ reportsRoot, env });
+ const [lease, all, renders, app] = await Promise.all([
+ readLease(dir),
+ listSteps(dir),
+ recentRenders(dir),
+ askApp(appBase(p.one("--url"), env), "/api/jobs?n=20", fetchImpl),
+ ]);
+ const cutoff = Date.now() - DAY_MS;
+ const steps = all.map((s) => resolveStep(s)).filter((s) => !TERMINAL.has(s.state) || Date.parse(s.endedAt ?? s.createdAt) > cutoff);
+ const appJobs = app.ok ? /** @type {any} */ (app.json)?.jobs ?? [] : null;
+ if (p.has("--json")) {
+ log(JSON.stringify({ queue: { dir, runner: lease, steps }, renders, app: app.ok ? { jobs: appJobs } : { error: app.error } }, null, 2));
+ return 0;
+ }
+ log("QUEUE");
+ log(` ${runnerLine(lease)}`);
+ if (!steps.length) log(" no step queued, running or finished in the last 24 h");
+ for (const s of [...steps].reverse()) log(` ${stepLine(s)}`);
+ log("TAKE RENDERS");
+ if (!renders.length) log(" none recorded in the last 7 days");
+ for (const r of renders) for (const [i, l] of recordLines(r, { tail: 0 }).entries()) log(` ${i ? " " : ""}${l}`);
+ log("THE APP'S JOBS");
+ if (!appJobs) log(` the umtool app did not answer (${app.error})`);
+ else if (!appJobs.length) log(" none");
+ else for (const j of appJobs) log(` ${String(j.state).toUpperCase().padEnd(9)} ${j.label}${j.error ? ` — ${j.error}` : ""}`);
+ return 0;
+ } catch (e) {
+ err(e instanceof Error ? e.message : String(e));
+ return 1;
+ }
+}
+
+/**
+ * `umtool take status <project> [--id <take>] [--json] [--log] [--tail N]`: the
+ * take's render record (renderRecord.mjs), or -- when no render of it runs --
+ * the queue step waiting to render it (`queued`). Without --id: every take of
+ * the project that has a record, newest first, and the exit of the newest.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ take: string | null, json: boolean, showLog: boolean, tail: number | null, reportsRoot?: string, env?: Record<string, string | undefined>,
+ * log: (s: string) => void, err: (s: string) => void }} o
+ */
+export async function takeStatus(project, { take, json, showLog, tail, reportsRoot = REPORTS_ROOT, env = process.env, log, err }) {
+ const { statusExitCode } = await import("../report/renderRecord.mjs");
+ const takesRoot = path.join(project.dir, "takes");
+ const dir = queueDirOf({ reportsRoot, env });
+ const steps = (await listSteps(dir)).map((s) => resolveStep(s)).filter((s) => s.target?.project === project.id && s.target?.take);
+ const ids = take ? [take] : (await readdir(takesRoot).catch(() => [])).filter((n) => !n.startsWith("."));
+ const rows = [];
+ for (const id of ids) {
+ const rec = await readRenderRecord(path.join(takesRoot, id));
+ const pending = steps.filter((s) => s.target.take === id && (s.state === "queued" || s.state === "blocked")).at(-1) ?? null;
+ const recLive = rec && (rec.state === "running" || rec.state === "waiting");
+ let row;
+ if (pending && !recLive && (!rec || Date.parse(pending.createdAt) > Date.parse(rec.startedAt))) {
+ // Waiting in the queue: the step is the newest word on this take.
+ row = {
+ project: project.id,
+ take: id,
+ state: pending.state === "blocked" ? "blocked" : "queued",
+ queue: { qid: pending.qid, state: pending.state, after: pending.after, error: pending.error },
+ error: pending.state === "blocked" ? pending.error : null,
+ previous: rec,
+ };
+ row.exit = pending.state === "blocked" ? 1 : 3;
+ } else if (rec) {
+ row = { ...rec, exit: statusExitCode(rec.state) };
+ } else if (take) {
+ // No record: a take made before records (take.json built, its preview there) reads done from take.json.
+ const doc = await readFile(path.join(takesRoot, id, "take.json"), "utf8").then(JSON.parse, () => null);
+ if (doc?.builtAt && !doc.draft) row = { project: project.id, take: id, state: "done", recorded: false, builtAt: doc.builtAt, seconds: doc.seconds ?? null, mp4: doc.preview ?? "preview.mp4", exit: 0 };
+ else row = { project: project.id, take: id, state: "none", error: doc?.draft ? "a draft: never rendered" : `no render of take ${id} is recorded`, exit: 1 };
+ }
+ if (row) rows.push(row);
+ }
+ rows.sort((a, b) => String(b.startedAt ?? b.queue?.qid ?? "").localeCompare(String(a.startedAt ?? a.queue?.qid ?? "")));
+ if (!rows.length) {
+ if (json) log(JSON.stringify({ project: project.id, takes: [] }, null, 2));
+ else err(`${project.id}: no take render is recorded`);
+ return 1;
+ }
+ const code = rows[0].exit;
+ if (json) {
+ log(JSON.stringify(take ? { ...rows[0], logPath: path.join(takesRoot, take, "render.log") } : { project: project.id, takes: rows }, null, 2));
+ return code;
+ }
+ for (const r of rows) {
+ if (r.queue) {
+ log(`${project.id} take ${r.take}: ${r.state.toUpperCase()} in the queue as ${r.queue.qid}${r.queue.after ? ` (after ${r.queue.after})` : ""}${r.error ? ` — ${r.error}` : ""}`);
+ log(` poll: umtool queue status ${r.queue.qid}`);
+ continue;
+ }
+ if (r.recorded === false || r.state === "none") {
+ log(`${project.id} take ${r.take}: ${r.state.toUpperCase()}${r.recorded === false ? ` (made ${fmtTime(r.builtAt)}, before renders recorded themselves)` : ` — ${r.error}`}`);
+ continue;
+ }
+ for (const l of recordLines(r, { logPath: path.join(takesRoot, r.take, r.log ?? "render.log"), tail: take ? (tail ?? 12) : 0 })) log(l);
+ }
+ if (showLog && take) {
+ const file = path.join(takesRoot, take, "render.log");
+ const lines = tail ? (await logTail(file, 1024 * 1024)).slice(-tail) : (await readFile(file, "utf8").catch(() => "")).split("\n");
+ log("--- render.log");
+ for (const l of lines) log(l);
+ }
+ return code;
+}
+
+export { renderPointerFile };
diff --git a/umtool/lib/queue/runner.ts b/umtool/lib/queue/runner.ts
@@ -0,0 +1,166 @@
+import path from "node:path";
+import { cancelJob, runningJob, startJob } from "@/lib/jobs";
+import { REPORTS_ROOT } from "@/lib/paths.mjs";
+import { projectRef } from "@/lib/projects";
+import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
+import { readRenderRecord } from "@/lib/report/renderRecord.mjs";
+import { acquireLease, pruneSteps, queueDirOf, queueTick } from "./store.mjs";
+
+// ---------------------------------------------------------------------------
+// THE QUEUE'S RUNNER, in the umtool app (lib/queue/store.mjs says what the
+// queue is). Armed by instrumentation.ts at boot, so the live unit
+// (archilyzer-umtool.service) runs the steps whoever queued them, and keeps
+// running them across an AI session's end, an app restart or a ship.
+//
+// Every 2 s, one turn (queueTick): take or renew the lease (runner.json -- one
+// runner per queue dir, machine-wide), mark a running step whose process is
+// gone failed (the app that ran it died: never re-run), block what waits on a
+// failure, and start the next ready step as a job on the app's own runner
+// (lib/jobs.ts). So a step shows in the rail's Running list and /settings/system
+// like any job, a Takes-page job and a step never run at once (a page job asked
+// for while a step runs is a 409 naming it; a step waits while a page job runs),
+// and a step gets the runner's process-group kill and its time limit (the step's
+// `timeoutMin`, 12 h by default). Its FULL log is the job's Step.logFile.
+//
+// On by default only under `next start` (NODE_ENV=production: the live unit,
+// the e2e suite's own app over its fixture); `next dev` in a worktree runs
+// nothing unless UMTOOL_QUEUE_RUNNER=1. UMTOOL_QUEUE_RUNNER=0 turns it off.
+// ARCHILYZER_IDLE_BOOT=1 boots without it (instrumentation.ts).
+// ---------------------------------------------------------------------------
+
+export const QUEUE_TICK_MS = 2000;
+const PRUNE_EVERY_MS = 60 * 60 * 1000;
+
+type Held = { cancelling: boolean; cancel: () => void };
+type RunnerState = {
+ dir: string;
+ held: Map<string, Held>;
+ timer: ReturnType<typeof setInterval> | null;
+ ticking: boolean;
+ holding: boolean;
+ lastTickAt: number | null;
+ lastError: string | null;
+ lastPruneAt: number;
+ waiting: string | null;
+};
+
+const g = globalThis as typeof globalThis & { __umtoolQueueRunner?: RunnerState };
+
+/** Whether this process runs the queue (see the top of the file). */
+export function queueRunnerEnabled(env: Record<string, string | undefined> = process.env): boolean {
+ const v = (env.UMTOOL_QUEUE_RUNNER ?? "").trim();
+ if (v === "0" || v === "false" || v === "off") return false;
+ if (v === "1" || v === "true" || v === "on") return true;
+ return env.NODE_ENV === "production";
+}
+
+export const queueDir = () => queueDirOf({ reportsRoot: REPORTS_ROOT });
+
+const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
+
+type QueueStep = { qid: string; label: string; argv: string[]; cwd: string; timeoutMin: number; startedAt: string | null; target?: { project: string | null; take: string | null } | null };
+
+/** A failed take step's error, from the take's own render record when it is this attempt's. */
+async function describe(step: QueueStep): Promise<string | null> {
+ const t = step.target;
+ if (!t?.project || !t.take) return null;
+ const project = await projectRef(t.project);
+ if (!project) return null;
+ const rec = await readRenderRecord(path.join(/* turbopackIgnore: true */ project.dir, "takes", t.take));
+ if (!rec || (rec.state !== "failed" && rec.state !== "cancelled") || !rec.error) return null;
+ if (step.startedAt && String(rec.startedAt) < step.startedAt) return null;
+ return `take ${t.take}: ${rec.error}`;
+}
+
+const exec = {
+ busy: () => {
+ const j = runningJob();
+ return j ? `${j.kind} (${j.id})` : null;
+ },
+ start: (step: QueueStep, { logFile, onEnd }: { logFile: string; onEnd: (end: { exitCode: number | null; signal: string | null; cancelled: boolean; error: string | null }) => void }) => {
+ const job = startJob(
+ `queue ${step.qid}: ${step.label}`,
+ [
+ {
+ label: step.label,
+ argv: [process.execPath, umtoolCli(), ...step.argv],
+ cwd: step.cwd,
+ env: {},
+ timeoutMs: Math.max(1, step.timeoutMin) * 60_000,
+ logFile,
+ },
+ ],
+ {
+ project: step.target?.project ?? null,
+ onEnd: (j) => onEnd({ exitCode: j.exitCode, signal: j.signal, cancelled: j.cancelling, error: j.error }),
+ },
+ );
+ return { pid: job.pids[0] ?? null, jobId: job.id, cancel: () => void cancelJob(job.id) };
+ },
+ describe,
+};
+
+async function tick(st: RunnerState) {
+ if (st.ticking) return;
+ st.ticking = true;
+ try {
+ st.holding = await acquireLease(st.dir);
+ if (!st.holding) return;
+ const r = await queueTick(st.dir, exec, { held: st.held });
+ st.waiting = r.waiting;
+ if (Date.now() - st.lastPruneAt > PRUNE_EVERY_MS) {
+ st.lastPruneAt = Date.now();
+ await pruneSteps(st.dir).catch(() => []);
+ }
+ st.lastError = null;
+ } catch (e) {
+ st.lastError = e instanceof Error ? e.message : String(e);
+ } finally {
+ st.lastTickAt = Date.now();
+ st.ticking = false;
+ }
+}
+
+/** Arm the runner (idempotent: one per process). */
+export function startQueueRunner({ intervalMs = QUEUE_TICK_MS }: { intervalMs?: number } = {}): RunnerState {
+ const have = g.__umtoolQueueRunner;
+ if (have?.timer) return have;
+ const st: RunnerState = have ?? {
+ dir: queueDir(),
+ held: new Map(),
+ timer: null,
+ ticking: false,
+ holding: false,
+ lastTickAt: null,
+ lastError: null,
+ lastPruneAt: 0,
+ waiting: null,
+ };
+ g.__umtoolQueueRunner = st;
+ void tick(st);
+ st.timer = setInterval(() => void tick(st), intervalMs);
+ // No signal handler of its own (one would keep the process from exiting on
+ // SIGTERM): the lease names this pid, and a dead pid's lease is free.
+ st.timer.unref?.();
+ return st;
+}
+
+/** Ask for a turn now (after an add, a cancel, a retry from the page). */
+export function kickQueue() {
+ const st = g.__umtoolQueueRunner;
+ if (st?.timer) void tick(st);
+}
+
+/** What the page and GET /api/queue say about this process's runner. */
+export function queueRunnerStatus() {
+ const st = g.__umtoolQueueRunner;
+ return {
+ enabled: queueRunnerEnabled(),
+ armed: !!st?.timer,
+ holding: st?.holding ?? false,
+ running: st ? [...st.held.keys()] : [],
+ lastTickAt: st?.lastTickAt ?? null,
+ lastError: st?.lastError ?? null,
+ waiting: st?.waiting ?? null,
+ };
+}
diff --git a/umtool/lib/queue/store.mjs b/umtool/lib/queue/store.mjs
@@ -0,0 +1,593 @@
+// THE DURABLE QUEUE (operator, 4 Nov 2026: "it'd be better to have Archilyzer
+// or umtool handle it and you simply poll them"; "we want the plain apps to do
+// as much heavy lifting as possible so cheaper models can more easily do these
+// tasks without having to improvise shell scripts and instead call real tools").
+//
+// DESIGN NOTE (lane/run-queue, slice A of the apps-do-the-work plan)
+//
+// What it replaces: `until grep -q DONE …; do sleep; done` chains that ran
+// `umtool take … | grep | tail` and printed DONE whatever the exit code. A
+// step here is a umtool subcommand's ARGV (never a shell string), stored as
+// one JSON file; the umtool APP runs the steps, one at a time, so the queue
+// outlives the AI session that filled it, and an app restart or a ship.
+//
+// <queue dir>/ UMTOOL_QUEUE_DIR, else <reports root>/.umtool-queue
+// seq the last qid's number
+// steps/<qid>.json one step (below), written atomically
+// logs/<qid>.log its latest attempt's FULL log (lib/jobs.ts Step.logFile)
+// logs/<qid>.<n>.log attempt n's, kept when it is retried
+// runner.json the runner's lease: { pid, pidStart, host, since, beat }
+// renders/<project>~<take>.json pointers to take render records (renderRecord.mjs), for `umtool jobs`
+// .lock read-modify-write of steps/ (O_EXCL, its pid inside; a dead holder's is broken)
+//
+// step: { qid, seq, label, argv, cwd, after, target: { project, take } | null,
+// state, createdAt, by, startedAt, endedAt, exitCode, signal, pid, pidStart,
+// host, runnerPid, jobId, attempts, error, blockedBy, cancelRequested, timeoutMin }
+//
+// state queued waits for its turn (and for `after`, when it names a step)
+// running the app's runner started it (its pid is the step's process)
+// done it exited 0
+// failed a non-zero exit or a signal -- or the app died while it ran: a
+// running step the runner does not hold and whose process is gone
+// reads, and is then written, failed ("the step's process is gone").
+// It is NEVER re-run on its own: `umtool queue retry <qid>` does that.
+// blocked `after` names a step that failed, was cancelled or is blocked;
+// `blockedBy` and `error` say which and why. A retry of that step
+// puts this one back in the queue.
+// cancelled `umtool queue cancel` (a running one is stopped: its process group
+// TERM then KILL, by lib/jobs.ts)
+//
+// ORDER: the oldest queued step whose `after` is done (or that names none) runs
+// next, and only when nothing else of the queue runs AND the app's own job
+// runner is idle (lib/jobs.ts: one job at a time, so a step and a Takes-page
+// job never interleave in one out/). A step's heavy work still goes through
+// the machine's heavy slot and render mode, by itself (a take's render does).
+// "after" is explicit: a step added without it does not wait for the one
+// before, and a failure blocks only the steps that named it (directly or
+// through a blocked step).
+//
+// The pure parts (planQueue, resolveStep) are tested alone; the runner loop
+// is queueTick, with the executor injected (lib/queue/runner.ts gives it the
+// app's job runner; the tests a plain spawn).
+//
+// Plain ESM: the CLI runs it under bare node.
+import { closeSync, openSync, writeSync } from "node:fs";
+import { mkdir, open, readdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { firstErrorLine, procStartTime, processAlive, queueDirFor } from "../report/renderRecord.mjs";
+
+export const STEP_STATES = Object.freeze(["queued", "running", "done", "failed", "blocked", "cancelled"]);
+export const TERMINAL = new Set(["done", "failed", "cancelled"]);
+/** A queue step's default time limit (minutes): a whole cut's render runs hours. */
+export const DEFAULT_TIMEOUT_MIN = 12 * 60;
+/** How stale a lease's heartbeat may be on another host before it is taken (ms). */
+export const LEASE_STALE_MS = 60_000;
+/** Terminal steps older than this are pruned by the runner, with their logs (days). */
+export const KEEP_DAYS = 30;
+
+export const QID = /^q[1-9][0-9]{0,8}$/;
+export const isQid = (v) => typeof v === "string" && QID.test(v);
+
+/**
+ * The queue's directory.
+ * @param {{ reportsRoot: string, env?: Record<string, string | undefined> }} o
+ */
+export const queueDirOf = ({ reportsRoot, env = process.env }) => queueDirFor(reportsRoot, env);
+
+const stepsDir = (dir) => path.join(dir, "steps");
+export const stepFile = (dir, qid) => path.join(stepsDir(dir), `${qid}.json`);
+export const logFileOf = (dir, qid, attempt = null) => path.join(dir, "logs", attempt ? `${qid}.${attempt}.log` : `${qid}.log`);
+const leaseFile = (dir) => path.join(dir, "runner.json");
+
+let tmpSeq = 0;
+async function writeJson(file, doc) {
+ tmpSeq += 1;
+ const tmp = `${file}.${process.pid}.${tmpSeq}.tmp`;
+ await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
+ await rename(tmp, file);
+}
+const readJson = (file) => readFile(/* turbopackIgnore: true */ file, "utf8").then((t) => JSON.parse(t), () => null);
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Run `fn` holding the queue's lock (`.lock`, O_EXCL with the holder's pid).
+ * A lock whose holder is gone, or older than 30 s, is broken.
+ * @template T
+ * @param {string} dir
+ * @param {() => Promise<T>} fn
+ * @returns {Promise<T>}
+ */
+export async function withQueueLock(dir, fn, { timeoutMs = 15_000 } = {}) {
+ await mkdir(stepsDir(dir), { recursive: true });
+ await mkdir(path.join(dir, "logs"), { recursive: true });
+ const file = path.join(dir, ".lock");
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ try {
+ const fd = openSync(/* turbopackIgnore: true */ file, "wx");
+ writeSync(fd, `${process.pid} ${os.hostname()} ${Date.now()}\n`);
+ closeSync(fd);
+ break;
+ } catch (err) {
+ if (/** @type {NodeJS.ErrnoException} */ (err).code !== "EEXIST") throw err;
+ const text = await readFile(/* turbopackIgnore: true */ file, "utf8").catch(() => "");
+ const [pid, host, at] = text.trim().split(" ");
+ const stale = (host === os.hostname() && !processAlive(Number(pid))) || (Number(at) > 0 && Date.now() - Number(at) > 30_000) || !text;
+ if (stale) {
+ await unlink(file).catch(() => {});
+ continue;
+ }
+ if (Date.now() > deadline) throw new Error(`the queue is locked by pid ${pid} (${file})`);
+ await sleep(25 + Math.random() * 50);
+ }
+ }
+ try {
+ return await fn();
+ } finally {
+ await unlink(file).catch(() => {});
+ }
+}
+
+/** Every step, oldest first. */
+export async function listSteps(dir) {
+ const names = await readdir(stepsDir(dir)).catch(() => []);
+ const steps = [];
+ for (const n of names) {
+ if (!n.endsWith(".json")) continue;
+ const s = await readJson(path.join(stepsDir(dir), n));
+ if (s && isQid(s.qid) && STEP_STATES.includes(s.state)) steps.push(s);
+ }
+ return steps.sort((a, b) => a.seq - b.seq);
+}
+
+export const getStep = (dir, qid) => (isQid(qid) ? readJson(stepFile(dir, qid)) : Promise.resolve(null));
+const putStep = (dir, step) => writeJson(stepFile(dir, step.qid), step);
+
+/**
+ * A step as it reads NOW: running on this host, not held by the reader's
+ * runner (`owned`), its process gone -> failed. Pure but for `alive`.
+ *
+ * @param {Record<string, any>} step
+ * @param {{ host?: string, alive?: (pid: number, start?: number | null) => boolean, owned?: Set<string> }} [o]
+ */
+export function resolveStep(step, { host = os.hostname(), alive = processAlive, owned = new Set() } = {}) {
+ if (step.state !== "running" || owned.has(step.qid)) return step;
+ if (step.host && step.host !== host) return step;
+ if (step.pid && alive(Number(step.pid), step.pidStart ?? null)) return step;
+ // Marked running a moment ago, its pid not written yet, by a runner that is alive: running.
+ if (!step.pid && step.runnerPid && alive(Number(step.runnerPid)) && Date.now() - Date.parse(step.startedAt ?? 0) < 30_000) return step;
+ // A step marked running whose process never started (the app died between the
+ // two writes) has no pid: gone too.
+ return { ...step, state: "failed", gone: true, error: goneError(step) };
+}
+
+const goneError = (step) =>
+ `the step's process is gone${step.pid ? ` (pid ${step.pid})` : ""} — the umtool app stopped or restarted while it ran; ` +
+ `nothing re-ran it. Its log is kept: \`umtool queue log ${step.qid}\`; \`umtool queue retry ${step.qid}\` runs it again`;
+
+/** `umtool queue status`'s exit code: 0 done, 3 queued or running, 1 failed, blocked or cancelled. */
+export function stepExitCode(state) {
+ if (state === "done") return 0;
+ if (state === "queued" || state === "running") return 3;
+ return 1;
+}
+
+/**
+ * Pure: what the queue should do now.
+ * - `block`: queued steps whose `after` failed, was cancelled or is blocked (in
+ * seq order, so a chain blocks in one pass), each with its reason
+ * - `start`: the step to start, or null (a step runs; none is ready)
+ *
+ * @param {Array<Record<string, any>>} steps resolved (resolveStep)
+ * @returns {{ start: Record<string, any> | null, block: Array<{ qid: string, blockedBy: string, error: string }>, running: Record<string, any> | null }}
+ */
+export function planQueue(steps) {
+ const byId = new Map(steps.map((s) => [s.qid, { ...s }]));
+ const block = [];
+ for (const s of [...byId.values()].sort((a, b) => a.seq - b.seq)) {
+ if (s.state !== "queued" || !s.after) continue;
+ const dep = byId.get(s.after);
+ if (!dep) {
+ s.state = "blocked";
+ const error = `it waits on ${s.after}, which is not in the queue`;
+ block.push({ qid: s.qid, blockedBy: s.after, error });
+ continue;
+ }
+ if (dep.state === "failed" || dep.state === "cancelled" || dep.state === "blocked") {
+ s.state = "blocked";
+ const why = dep.state === "blocked" ? `is blocked (${dep.blockedBy ? `by ${dep.blockedBy}` : "upstream"})` : dep.state === "cancelled" ? "was cancelled" : "failed";
+ const error = `it waits on ${dep.qid}, which ${why} — \`umtool queue retry ${dep.qid}\` puts both back`;
+ s.blockedBy = dep.qid;
+ block.push({ qid: s.qid, blockedBy: dep.qid, error });
+ }
+ }
+ const all = [...byId.values()].sort((a, b) => a.seq - b.seq);
+ const running = all.find((s) => s.state === "running") ?? null;
+ if (running) return { start: null, block, running };
+ const start = all.find((s) => s.state === "queued" && (!s.after || byId.get(s.after)?.state === "done")) ?? null;
+ return { start, block, running: null };
+}
+
+/**
+ * Add a step.
+ *
+ * @param {string} dir
+ * @param {{ argv: string[], label?: string | null, after?: string | null, cwd?: string, by?: string,
+ * target?: { project: string | null, take: string | null } | null, timeoutMin?: number, now?: () => Date }} o
+ * `after`: a qid, or "last" (the newest step in the queue now).
+ */
+export async function addStep(dir, o) {
+ if (!Array.isArray(o.argv) || !o.argv.length || o.argv.some((a) => typeof a !== "string")) throw new Error("a step is a umtool subcommand's argv: `umtool queue add -- take <project> --id <t> …`");
+ const now = o.now ?? (() => new Date());
+ return withQueueLock(dir, async () => {
+ let after = o.after ?? null;
+ const steps = await listSteps(dir);
+ if (after === "last") {
+ after = steps.length ? steps[steps.length - 1].qid : null;
+ if (!after) throw new Error("--after last: the queue is empty");
+ }
+ if (after !== null && !steps.some((s) => s.qid === after)) throw new Error(`--after ${after}: no such step (\`umtool queue ls --all\`)`);
+ const seqFile = path.join(dir, "seq");
+ const last = Number((await readFile(/* turbopackIgnore: true */ seqFile, "utf8").catch(() => "0")).trim()) || 0;
+ const seq = Math.max(last, ...steps.map((s) => s.seq)) + 1;
+ await writeFile(/* turbopackIgnore: true */ seqFile, `${seq}\n`, "utf8");
+ const step = {
+ qid: `q${seq}`,
+ seq,
+ label: o.label?.trim() || labelOf(o.argv),
+ argv: o.argv,
+ cwd: o.cwd ?? process.cwd(),
+ after,
+ target: o.target ?? null,
+ state: "queued",
+ createdAt: now().toISOString(),
+ by: o.by ?? "umtool queue add",
+ startedAt: null,
+ endedAt: null,
+ exitCode: null,
+ signal: null,
+ pid: null,
+ pidStart: null,
+ host: null,
+ runnerPid: null,
+ jobId: null,
+ attempts: 0,
+ error: null,
+ blockedBy: null,
+ cancelRequested: null,
+ timeoutMin: Number(o.timeoutMin) > 0 ? Number(o.timeoutMin) : DEFAULT_TIMEOUT_MIN,
+ };
+ await putStep(dir, step);
+ return step;
+ });
+}
+
+/** A step's default label: its argv, shortened. */
+const labelOf = (argv) => {
+ const text = argv.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(" ");
+ return text.length > 100 ? `${text.slice(0, 99)}…` : text;
+};
+
+/** The steps that wait on `qid`, directly or through each other (seq order). */
+function dependentsOf(steps, qid) {
+ const out = [];
+ const seen = new Set([qid]);
+ let grew = true;
+ while (grew) {
+ grew = false;
+ for (const s of steps) {
+ if (!seen.has(s.qid) && s.after && seen.has(s.after)) {
+ seen.add(s.qid);
+ out.push(s);
+ grew = true;
+ }
+ }
+ }
+ return out.sort((a, b) => a.seq - b.seq);
+}
+
+/**
+ * Cancel a step: a queued or blocked one at once; a running one is asked (the
+ * runner stops its process group and writes cancelled). Its dependents block.
+ * @returns {Promise<{ step: Record<string, any>, said: string }>}
+ */
+export async function cancelStep(dir, qid, { by = "umtool queue cancel", now = () => new Date() } = {}) {
+ return withQueueLock(dir, async () => {
+ const step = await getStep(dir, qid);
+ if (!step) throw new Error(`no step ${qid}`);
+ if (TERMINAL.has(step.state)) throw new Error(`${qid} is ${step.state} already`);
+ if (step.state === "running") {
+ step.cancelRequested = { at: now().toISOString(), by };
+ await putStep(dir, step);
+ return { step, said: `${qid}: asked to stop (the runner stops its process group; it reads cancelled once it has)` };
+ }
+ step.state = "cancelled";
+ step.endedAt = now().toISOString();
+ step.error = `cancelled by ${by}`;
+ await putStep(dir, step);
+ await blockDependents(dir, step);
+ return { step, said: `${qid}: cancelled` };
+ });
+}
+
+async function blockDependents(dir, step) {
+ const steps = await listSteps(dir);
+ for (const d of dependentsOf(steps, step.qid)) {
+ if (d.state !== "queued") continue;
+ d.state = "blocked";
+ d.blockedBy = d.after;
+ d.error = d.after === step.qid
+ ? `it waits on ${step.qid}, which ${step.state === "cancelled" ? "was cancelled" : step.state} — \`umtool queue retry ${step.qid}\` puts both back`
+ : `it waits on ${d.after}, which is blocked (by ${step.qid})`;
+ await putStep(dir, d);
+ }
+}
+
+/**
+ * Retry: a failed or cancelled step goes back in the queue (its log kept as
+ * logs/<qid>.<attempt>.log), and every step blocked behind it with it. A
+ * blocked step goes back only when what it waits on is not failed itself.
+ * @returns {Promise<{ step: Record<string, any>, requeued: string[], said: string }>}
+ */
+export async function retryStep(dir, qid) {
+ return withQueueLock(dir, async () => {
+ const steps = await listSteps(dir);
+ const step = steps.find((s) => s.qid === qid);
+ if (!step) throw new Error(`no step ${qid}`);
+ const resolved = resolveStep(step);
+ if (resolved.state === "queued" || resolved.state === "running") throw new Error(`${qid} is ${resolved.state}: nothing to retry`);
+ if (resolved.state === "done") throw new Error(`${qid} is done: add it again (\`umtool queue add\`) to run it again`);
+ if (resolved.state === "blocked") {
+ const dep = steps.find((s) => s.qid === step.after);
+ const depState = dep ? resolveStep(dep).state : null;
+ if (depState && depState !== "done" && depState !== "queued" && depState !== "running") {
+ throw new Error(`${qid} waits on ${step.after}, which is ${depState}: retry ${step.after} (it puts ${qid} back too)`);
+ }
+ }
+ const requeued = [];
+ const requeue = async (s) => {
+ const was = resolveStep(s);
+ if (was.state === "failed" || was.state === "cancelled") {
+ const logs = path.join(dir, "logs");
+ await rename(logFileOf(dir, s.qid), path.join(logs, `${s.qid}.${s.attempts || 1}.log`)).catch(() => {});
+ }
+ Object.assign(s, { state: "queued", error: null, blockedBy: null, cancelRequested: null, exitCode: null, signal: null, pid: null, pidStart: null, endedAt: null, startedAt: null, jobId: null });
+ await putStep(dir, s);
+ requeued.push(s.qid);
+ };
+ await requeue(step);
+ for (const d of dependentsOf(steps, qid)) if (d.state === "blocked") await requeue(d);
+ return { step, requeued, said: `${requeued.join(", ")} back in the queue` };
+ });
+}
+
+/** Mark a step started (the runner, holding the lock). */
+async function markStarted(dir, step, { pid, runnerPid, jobId, now }) {
+ Object.assign(step, {
+ state: "running",
+ startedAt: now().toISOString(),
+ endedAt: null,
+ pid: pid ?? null,
+ pidStart: pid ? procStartTime(pid) : null,
+ host: os.hostname(),
+ runnerPid,
+ jobId: jobId ?? null,
+ attempts: (step.attempts ?? 0) + 1,
+ error: null,
+ });
+ await putStep(dir, step);
+}
+
+/** The last ~64 KB of a log, as lines. */
+export async function logTail(file, maxBytes = 64 * 1024) {
+ try {
+ const st = await stat(/* turbopackIgnore: true */ file);
+ const fh = await open(/* turbopackIgnore: true */ file, "r");
+ try {
+ const len = Math.min(st.size, maxBytes);
+ const buf = Buffer.alloc(len);
+ await fh.read(buf, 0, len, st.size - len);
+ const lines = buf.toString("utf8").split("\n");
+ if (st.size > maxBytes) lines.shift();
+ return lines.filter((l) => l.trim());
+ } finally {
+ await fh.close();
+ }
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Pure: the step's end state from how its process ended. A failed step's
+ * error is the LAST line of its log that reads as an error (a umtool command
+ * says why it stopped last), else its last line, with the exit after it.
+ * @param {{ exitCode: number | null, signal?: string | null, cancelled?: boolean, error?: string | null }} end
+ * @param {string[]} tail the log's last lines
+ */
+export function endOf(end, tail) {
+ if (end.cancelled) return { state: "cancelled", error: "cancelled — its process group was stopped" };
+ if (end.exitCode === 0) return { state: "done", error: null };
+ const how = end.exitCode === null ? `killed${end.signal ? ` by ${end.signal}` : ""}` : `exit ${end.exitCode}`;
+ const lines = tail.filter((l) => !/^\*\* (exit |killed after|cancelled)/.test(l) && !/^[$#] /.test(l));
+ const said = firstErrorLine([...lines].reverse()) ?? lines[lines.length - 1] ?? null;
+ return { state: "failed", error: said ? `${said} (${how})` : `it ended with ${how}` };
+}
+
+/**
+ * Take the runner's lease, or renew it. False when another live process holds it.
+ * @param {string} dir
+ */
+export async function acquireLease(dir, { pid = process.pid, host = os.hostname(), now = () => new Date(), alive = processAlive, url = null } = {}) {
+ await mkdir(dir, { recursive: true });
+ const cur = await readJson(leaseFile(dir));
+ const mine = cur && Number(cur.pid) === pid && cur.host === host;
+ if (cur && !mine) {
+ const live = cur.host === host ? alive(Number(cur.pid), cur.pidStart ?? null) : now().getTime() - Date.parse(cur.beat ?? 0) < LEASE_STALE_MS;
+ if (live) return false;
+ }
+ const at = now().toISOString();
+ await writeJson(leaseFile(dir), { pid, pidStart: procStartTime(pid), host, since: mine ? cur.since : at, beat: at, ...(url ? { url } : {}) });
+ return true;
+}
+
+/** The runner's lease as it reads: `{ live, pid, host, since, beat }` or null. */
+export async function readLease(dir, { host = os.hostname(), alive = processAlive, now = () => new Date() } = {}) {
+ const cur = await readJson(leaseFile(dir));
+ if (!cur) return null;
+ const live = cur.host === host ? alive(Number(cur.pid), cur.pidStart ?? null) : now().getTime() - Date.parse(cur.beat ?? 0) < LEASE_STALE_MS;
+ return { ...cur, live };
+}
+
+/** Let the lease go (the runner, stopping). */
+export async function releaseLease(dir, { pid = process.pid } = {}) {
+ const cur = await readJson(leaseFile(dir));
+ if (cur && Number(cur.pid) === pid) await unlink(leaseFile(dir)).catch(() => {});
+}
+
+/**
+ * One turn of the runner. The executor:
+ * busy() a reason the app cannot start a step now (its job runner is busy), or null
+ * start(step, { logFile, onEnd }) -> { pid, jobId, cancel() }; onEnd({ exitCode, signal, cancelled, error })
+ * describe?(step) a better error for a failed step (a take's render record's), or null
+ *
+ * `held`: the runner's own map qid -> handle, kept between turns.
+ *
+ * @param {string} dir
+ * @param {{ busy: () => string | null, start: (step: any, o: { logFile: string, onEnd: (end: any) => void }) => { pid: number | null, jobId?: string | null, cancel: () => void },
+ * describe?: (step: any) => Promise<string | null> }} exec
+ * @param {{ held: Map<string, any>, now?: () => Date, runnerPid?: number, alive?: (pid: number, start?: number | null) => boolean,
+ * onChange?: () => void }} state
+ * @returns {Promise<{ started: string | null, recovered: string[], blocked: string[], waiting: string | null }>}
+ */
+export async function queueTick(dir, exec, state) {
+ const now = state.now ?? (() => new Date());
+ const runnerPid = state.runnerPid ?? process.pid;
+ const alive = state.alive ?? processAlive;
+ const out = { started: null, recovered: [], blocked: [], waiting: null };
+ /** @type {any} */
+ let toStart = null;
+ await withQueueLock(dir, async () => {
+ const steps = await listSteps(dir);
+ const owned = new Set(state.held.keys());
+ // Recovery: a running step this runner does not hold, its process gone, is failed -- never re-run.
+ for (const s of steps) {
+ const r = resolveStep(s, { owned, alive });
+ if (r !== s && r.state === "failed") {
+ Object.assign(s, { state: "failed", endedAt: now().toISOString(), error: r.error, exitCode: null });
+ await putStep(dir, s);
+ await appendLog(dir, s.qid, `** ${r.error}`);
+ out.recovered.push(s.qid);
+ }
+ }
+ // A cancel asked of a step this runner holds.
+ for (const s of steps) {
+ if (s.state === "running" && s.cancelRequested && state.held.has(s.qid)) {
+ const h = state.held.get(s.qid);
+ if (!h.cancelling) {
+ h.cancelling = true;
+ h.cancel();
+ }
+ }
+ }
+ const plan = planQueue(steps);
+ for (const b of plan.block) {
+ const s = steps.find((x) => x.qid === b.qid);
+ if (!s) continue;
+ Object.assign(s, { state: "blocked", blockedBy: b.blockedBy, error: b.error });
+ await putStep(dir, s);
+ out.blocked.push(s.qid);
+ }
+ if (plan.running || state.held.size || !plan.start) return;
+ const busy = exec.busy();
+ if (busy) {
+ out.waiting = `${plan.start.qid} waits for the app's runner: ${busy}`;
+ return;
+ }
+ toStart = plan.start;
+ // Marked running BEFORE it is started, so a crash between the two reads failed (gone), never queued again.
+ await markStarted(dir, toStart, { pid: null, runnerPid, jobId: null, now });
+ });
+ if (!toStart) return out;
+ const step = toStart;
+ const logFile = logFileOf(dir, step.qid);
+ await appendLog(dir, step.qid, `# queue ${step.qid} attempt ${step.attempts}: ${step.label}\n# started ${step.startedAt} by the umtool app (pid ${runnerPid}), cwd ${step.cwd}\n# argv: umtool ${step.argv.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(" ")}`);
+ const handle = { cancelling: false, cancel: () => {} };
+ state.held.set(step.qid, handle);
+ let started;
+ try {
+ started = exec.start(step, {
+ logFile,
+ onEnd: (end) => {
+ void finishStep(dir, step.qid, end, exec, state).catch(() => {});
+ },
+ });
+ } catch (e) {
+ state.held.delete(step.qid);
+ await finishStep(dir, step.qid, { exitCode: null, error: e instanceof Error ? e.message : String(e) }, exec, state, { notStarted: true });
+ return out;
+ }
+ handle.cancel = started.cancel;
+ await withQueueLock(dir, async () => {
+ const s = await getStep(dir, step.qid);
+ if (!s || s.state !== "running") return;
+ s.pid = started.pid ?? null;
+ s.pidStart = started.pid ? procStartTime(started.pid) : null;
+ s.jobId = started.jobId ?? null;
+ await putStep(dir, s);
+ });
+ out.started = step.qid;
+ state.onChange?.();
+ return out;
+}
+
+async function appendLog(dir, qid, text) {
+ await mkdir(path.join(dir, "logs"), { recursive: true });
+ const fh = await open(/* turbopackIgnore: true */ logFileOf(dir, qid), "a");
+ try {
+ await fh.write(text.endsWith("\n") ? text : `${text}\n`);
+ } finally {
+ await fh.close();
+ }
+}
+
+async function finishStep(dir, qid, end, exec, state, { notStarted = false } = {}) {
+ const now = state.now ?? (() => new Date());
+ const tail = await logTail(logFileOf(dir, qid));
+ await withQueueLock(dir, async () => {
+ const s = await getStep(dir, qid);
+ if (!s) return;
+ const r = endOf({ ...end, cancelled: !!end.cancelled || (!!s.cancelRequested && end.exitCode !== 0) }, tail);
+ let error = notStarted ? `it could not be started: ${end.error}` : r.error;
+ if (r.state === "failed" && exec.describe) {
+ const better = await exec.describe(s).catch(() => null);
+ if (better) error = `${better} (${end.exitCode === null ? "killed" : `exit ${end.exitCode}`})`;
+ }
+ Object.assign(s, { state: r.state, endedAt: now().toISOString(), exitCode: end.exitCode ?? null, signal: end.signal ?? null, error });
+ await putStep(dir, s);
+ if (r.state !== "done") await blockDependents(dir, s);
+ });
+ state.held.delete(qid);
+ state.onChange?.();
+}
+
+/**
+ * Prune terminal steps (and their logs) older than `days`. Blocked steps whose
+ * reason went with them are kept: they still say why.
+ */
+export async function pruneSteps(dir, { days = KEEP_DAYS, now = () => new Date() } = {}) {
+ const cutoff = now().getTime() - days * 86_400_000;
+ const removed = [];
+ await withQueueLock(dir, async () => {
+ for (const s of await listSteps(dir)) {
+ if (!TERMINAL.has(s.state) || !s.endedAt || Date.parse(s.endedAt) > cutoff) continue;
+ await rm(stepFile(dir, s.qid), { force: true });
+ const logs = await readdir(path.join(dir, "logs")).catch(() => []);
+ for (const n of logs) if (n === `${s.qid}.log` || n.startsWith(`${s.qid}.`)) await rm(path.join(dir, "logs", n), { force: true });
+ removed.push(s.qid);
+ }
+ });
+ return removed;
+}
diff --git a/umtool/lib/queue/store.test.mjs b/umtool/lib/queue/store.test.mjs
@@ -0,0 +1,311 @@
+// lib/queue/store.mjs: the durable queue -- order, `after`, blocking, cancel,
+// retry, and what an app that died mid-step leaves (failed, never re-run). The
+// runner turn (queueTick) runs real processes through a plain spawn executor
+// here; the app gives it lib/jobs.ts.
+import assert from "node:assert/strict";
+import { spawn, spawnSync } from "node:child_process";
+import { createWriteStream } from "node:fs";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { test } from "node:test";
+import {
+ acquireLease,
+ addStep,
+ cancelStep,
+ endOf,
+ getStep,
+ listSteps,
+ logFileOf,
+ planQueue,
+ queueTick,
+ readLease,
+ resolveStep,
+ retryStep,
+ stepExitCode,
+ stepFile,
+} from "./store.mjs";
+import { queueCommand, takeStatus } from "./cli.mjs";
+
+const tmp = () => mkdtemp(path.join(os.tmpdir(), "umtool-queue-"));
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/** The tests' executor: each step's argv is `node -e <script>`, its output to the log file. */
+function spawnExec({ busy = () => null } = {}) {
+ return {
+ busy,
+ start(step, { logFile, onEnd }) {
+ const out = createWriteStream(logFile, { flags: "a" });
+ const child = spawn(process.execPath, ["-e", step.argv[1] ?? ""], { cwd: step.cwd, stdio: ["ignore", "pipe", "pipe"], detached: true });
+ child.stdout.pipe(out, { end: false });
+ child.stderr.pipe(out, { end: false });
+ let cancelled = false;
+ child.on("close", (code, signal) => {
+ out.end(() => onEnd({ exitCode: code, signal, cancelled, error: null }));
+ });
+ return {
+ pid: child.pid,
+ jobId: null,
+ cancel: () => {
+ cancelled = true;
+ try {
+ process.kill(-(child.pid ?? 0), "SIGTERM");
+ } catch {
+ /* gone */
+ }
+ },
+ };
+ },
+ };
+}
+
+/** Run turns until no step is queued or running (or the deadline). */
+async function drain(dir, exec, state, { ms = 15_000 } = {}) {
+ const until = Date.now() + ms;
+ for (;;) {
+ await queueTick(dir, exec, state);
+ const steps = (await listSteps(dir)).map((s) => resolveStep(s, { owned: new Set(state.held.keys()) }));
+ if (!steps.some((s) => s.state === "queued" || s.state === "running")) return steps;
+ if (Date.now() > until) throw new Error(`still going: ${steps.map((s) => `${s.qid}=${s.state}`).join(" ")}`);
+ await sleep(40);
+ }
+}
+
+const js = (code) => ["node-e", code];
+
+test("planQueue: the oldest ready step; after waits for done; a failure blocks its chain", () => {
+ const s = (qid, state, after = null) => ({ qid, seq: Number(qid.slice(1)), state, after });
+ assert.equal(planQueue([s("q1", "queued"), s("q2", "queued")]).start?.qid, "q1");
+ assert.equal(planQueue([s("q1", "running"), s("q2", "queued")]).start, null, "one at a time");
+ assert.equal(planQueue([s("q1", "queued"), s("q2", "queued", "q1")]).start?.qid, "q1");
+ assert.equal(planQueue([s("q1", "done"), s("q2", "queued", "q1")]).start?.qid, "q2");
+ // q3 does not wait on q2: it runs while q2 waits for q1... q1 runs first, by order.
+ assert.equal(planQueue([s("q1", "failed"), s("q2", "queued", "q1"), s("q3", "queued")]).start?.qid, "q3");
+ const p = planQueue([s("q1", "failed"), s("q2", "queued", "q1"), s("q3", "queued", "q2"), s("q4", "queued")]);
+ assert.deepEqual(p.block.map((b) => [b.qid, b.blockedBy]), [["q2", "q1"], ["q3", "q2"]]);
+ assert.match(p.block[0].error, /q1, which failed/);
+ assert.match(p.block[1].error, /q2, which is blocked/);
+ assert.equal(p.start?.qid, "q4");
+ assert.match(planQueue([s("q1", "cancelled"), s("q2", "queued", "q1")]).block[0].error, /was cancelled/);
+});
+
+test("exit codes: 0 done, 3 queued/running, 1 failed/blocked/cancelled", () => {
+ assert.equal(stepExitCode("done"), 0);
+ assert.equal(stepExitCode("queued"), 3);
+ assert.equal(stepExitCode("running"), 3);
+ for (const s of ["failed", "blocked", "cancelled"]) assert.equal(stepExitCode(s), 1);
+});
+
+test("endOf: done on exit 0, failed with the last error line otherwise, cancelled", () => {
+ assert.deepEqual(endOf({ exitCode: 0 }, []), { state: "done", error: null });
+ const f = endOf({ exitCode: 1 }, ["$ node umtool take …", "take t1: render", "no project matches \"nope\"", "** exit 1"]);
+ assert.equal(f.state, "failed");
+ assert.equal(f.error, 'no project matches "nope" (exit 1)');
+ assert.equal(endOf({ exitCode: null, signal: "SIGKILL" }, []).error, "it ended with killed by SIGKILL");
+ assert.equal(endOf({ exitCode: 143, cancelled: true }, []).state, "cancelled");
+});
+
+test("the runner runs steps in order, one at a time, with --after; a failure blocks its chain; logs are full", async () => {
+ const dir = await tmp();
+ try {
+ const trace = path.join(dir, "trace.txt");
+ const w = (tag, code = 0) => js(`require("fs").appendFileSync(${JSON.stringify(trace)}, "${tag}+"); setTimeout(() => { require("fs").appendFileSync(${JSON.stringify(trace)}, "${tag}-"); ${code ? `console.error("Error: ${tag} broke"); process.exit(${code})` : `console.log("${tag} ok")`} }, 60)`);
+ const q1 = await addStep(dir, { argv: w("a"), label: "a" });
+ const q2 = await addStep(dir, { argv: w("b", 2), label: "b", after: q1.qid });
+ const q3 = await addStep(dir, { argv: w("c"), label: "c", after: q2.qid });
+ const q4 = await addStep(dir, { argv: w("d"), label: "d", after: "last" });
+ assert.equal(q4.after, q3.qid, "--after last is the newest step");
+ const q5 = await addStep(dir, { argv: w("e"), label: "e" });
+ const state = { held: new Map() };
+ const steps = await drain(dir, spawnExec(), state);
+ const by = Object.fromEntries(steps.map((s) => [s.qid, s]));
+ assert.equal(by[q1.qid].state, "done");
+ assert.equal(by[q1.qid].exitCode, 0);
+ assert.equal(by[q2.qid].state, "failed");
+ assert.equal(by[q2.qid].exitCode, 2);
+ assert.equal(by[q2.qid].error, "Error: b broke (exit 2)");
+ assert.equal(by[q3.qid].state, "blocked");
+ assert.equal(by[q3.qid].blockedBy, q2.qid);
+ assert.match(by[q3.qid].error, new RegExp(`${q2.qid}, which failed`));
+ assert.equal(by[q4.qid].state, "blocked");
+ assert.equal(by[q4.qid].blockedBy, q3.qid);
+ assert.equal(by[q5.qid].state, "done");
+ // One at a time: every step ended before the next began.
+ assert.equal(await readFile(trace, "utf8"), "a+a-b+b-e+e-");
+ const log = await readFile(logFileOf(dir, q2.qid), "utf8");
+ assert.match(log, /# queue q2 attempt 1: b/);
+ assert.match(log, /Error: b broke/);
+
+ // Retry the failed one: it and the chain blocked behind it go back.
+ const r = await retryStep(dir, q2.qid);
+ assert.deepEqual(r.requeued, [q2.qid, q3.qid, q4.qid]);
+ assert.equal((await getStep(dir, q2.qid))?.state, "queued");
+ // Its first attempt's log is kept beside the new one.
+ assert.match(await readFile(logFileOf(dir, q2.qid, 1), "utf8"), /b broke/);
+ // A blocked one cannot be retried on its own while what it waits on is failed.
+ await writeFile(stepFile(dir, q2.qid), JSON.stringify({ ...(await getStep(dir, q2.qid)), state: "failed" }));
+ await writeFile(stepFile(dir, q3.qid), JSON.stringify({ ...(await getStep(dir, q3.qid)), state: "blocked", blockedBy: q2.qid }));
+ await assert.rejects(retryStep(dir, q3.qid), new RegExp(`retry ${q2.qid}`));
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("no step starts while the app's own job runner is busy", async () => {
+ const dir = await tmp();
+ try {
+ await addStep(dir, { argv: js("0"), label: "x" });
+ const state = { held: new Map() };
+ const r = await queueTick(dir, spawnExec({ busy: () => "build demo (job-1)" }), state);
+ assert.equal(r.started, null);
+ assert.match(r.waiting ?? "", /waits for the app's runner: build demo/);
+ assert.equal((await listSteps(dir))[0].state, "queued");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("cancel: a queued step at once (its dependents block); a running one is stopped", async () => {
+ const dir = await tmp();
+ try {
+ const a = await addStep(dir, { argv: js("setTimeout(() => {}, 20000)"), label: "long" });
+ const b = await addStep(dir, { argv: js("0"), label: "after long", after: a.qid });
+ const c = await addStep(dir, { argv: js("0"), label: "c" });
+ const d = await addStep(dir, { argv: js("0"), label: "after c", after: c.qid });
+ await cancelStep(dir, c.qid);
+ assert.equal((await getStep(dir, c.qid))?.state, "cancelled");
+ assert.equal((await getStep(dir, d.qid))?.state, "blocked");
+ const state = { held: new Map() };
+ const exec = spawnExec();
+ await queueTick(dir, exec, state);
+ assert.equal((await getStep(dir, a.qid))?.state, "running");
+ const said = await cancelStep(dir, a.qid);
+ assert.match(said.said, /asked to stop/);
+ const steps = await drain(dir, exec, state);
+ const by = Object.fromEntries(steps.map((s) => [s.qid, s]));
+ assert.equal(by[a.qid].state, "cancelled");
+ assert.equal(by[b.qid].state, "blocked");
+ await assert.rejects(cancelStep(dir, a.qid), /cancelled already/);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("restart recovery: a running step whose process is gone is failed with its log, never re-run", async () => {
+ const dir = await tmp();
+ try {
+ const a = await addStep(dir, { argv: js("0"), label: "was running" });
+ const b = await addStep(dir, { argv: js("0"), label: "after it", after: a.qid });
+ const dead = Number(spawnSync(process.execPath, ["-e", "process.stdout.write(String(process.pid))"], { encoding: "utf8" }).stdout);
+ // What a dead app left: a, running, its pid gone; and its log.
+ await writeFile(stepFile(dir, a.qid), JSON.stringify({ ...(await getStep(dir, a.qid)), state: "running", pid: dead, pidStart: null, host: os.hostname(), runnerPid: dead, startedAt: new Date().toISOString(), attempts: 1 }));
+ await writeFile(logFileOf(dir, a.qid), "half a render\n");
+ // A reader with no runner already says failed.
+ const read = resolveStep(/** @type {any} */ (await getStep(dir, a.qid)));
+ assert.equal(read.state, "failed");
+ assert.match(read.error, /process is gone/);
+ let ran = 0;
+ const exec = { ...spawnExec(), start: (...args) => (ran += 1, spawnExec().start(...args)) };
+ const state = { held: new Map() };
+ const r = await queueTick(dir, exec, state);
+ assert.deepEqual(r.recovered, [a.qid]);
+ const after = await getStep(dir, a.qid);
+ assert.equal(after?.state, "failed");
+ assert.match(after?.error ?? "", /the umtool app stopped or restarted while it ran; nothing re-ran it/);
+ assert.equal((await getStep(dir, b.qid))?.state, "blocked");
+ assert.equal(ran, 0, "nothing re-ran");
+ const log = await readFile(logFileOf(dir, a.qid), "utf8");
+ assert.match(log, /half a render/);
+ assert.match(log, /process is gone/);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("the lease: one runner per queue dir; a dead holder's lease is taken", async () => {
+ const dir = await tmp();
+ try {
+ assert.equal(await acquireLease(dir, { pid: 111, alive: () => true }), true);
+ assert.equal(await acquireLease(dir, { pid: 222, alive: () => true }), false, "held by a live 111");
+ assert.equal(await acquireLease(dir, { pid: 111, alive: () => true }), true, "renewed by its holder");
+ assert.equal(await acquireLease(dir, { pid: 222, alive: () => false }), true, "111 is gone");
+ assert.equal((await readLease(dir, { alive: () => true }))?.pid, 222);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("the CLI: add prints the qid, status exits 3/0/1, wait, log, a step that is not a command is refused", async () => {
+ const root = await tmp();
+ try {
+ const lines = [];
+ const errs = [];
+ const run = (args) => queueCommand(args, { reportsRoot: root, commands: ["ls", "take", "takes"], log: (l) => lines.push(l), err: (l) => errs.push(l), fetchImpl: /** @type {any} */ (async () => { throw new Error("no app"); }), env: {}, pollMs: 20 });
+ assert.equal(await run(["add", "--", "nope"]), 2);
+ assert.match(errs.at(-1) ?? "", /not a umtool command/);
+ assert.equal(await run(["add", "--", "queue", "ls"]), 2);
+ assert.equal(await run(["add", "--label", "list", "--", "ls", "--json"]), 0);
+ assert.equal(lines.at(-1), "q1");
+ assert.equal(await run(["status", "q1"]), 3);
+ assert.equal(await run(["add", "--after", "q9", "--", "ls"]), 1);
+ assert.match(errs.at(-1) ?? "", /no such step/);
+ // The runner (here, a turn of ours) runs it.
+ const dir = path.join(root, ".umtool-queue");
+ const exec = { busy: () => null, start: (step, o) => spawnExec().start({ ...step, argv: ["node-e", "console.log('listed')"] }, o) };
+ await drain(dir, exec, { held: new Map() });
+ assert.equal(await run(["status", "q1"]), 0);
+ assert.equal(await run(["wait", "q1", "--timeout", "1"]), 0);
+ lines.length = 0;
+ assert.equal(await run(["log", "q1"]), 0);
+ assert.match(lines.join("\n"), /listed/);
+ lines.length = 0;
+ assert.equal(await run(["status", "q1", "--json"]), 0);
+ const j = JSON.parse(lines.join("\n"));
+ assert.equal(j.state, "done");
+ assert.equal(j.exit, 0);
+ // wait on a step that never runs: exit 3 at the timeout.
+ await run(["add", "--", "ls"]);
+ const t0 = Date.now();
+ assert.equal(await run(["wait", "q2", "--timeout", "1"]), 3);
+ assert.ok(Date.now() - t0 >= 900);
+ assert.equal(await run(["cancel", "q2"]), 0);
+ assert.equal(await run(["status", "q2"]), 1);
+ assert.equal(await run(["retry", "q2"]), 0);
+ assert.equal(await run(["status", "q2"]), 3);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("take status: queued from the queue, then the render record's state and exit", async () => {
+ const root = await tmp();
+ try {
+ const projectDir = path.join(root, "demo");
+ const { mkdir } = await import("node:fs/promises");
+ await mkdir(path.join(projectDir, "takes", "t1"), { recursive: true });
+ await writeFile(path.join(projectDir, "video.manifest.json"), JSON.stringify({ slug: "demo", timeline: [] }));
+ const lines = [];
+ const errs = [];
+ const status = (take = "t1") => takeStatus({ id: "demo", dir: projectDir }, { take, json: true, showLog: false, tail: null, reportsRoot: root, env: {}, log: (l) => lines.push(l), err: (l) => errs.push(l) });
+ // Nothing yet.
+ assert.equal(await status(), 1);
+ // Queued.
+ const dir = path.join(root, ".umtool-queue");
+ await addStep(dir, { argv: ["take", "demo", "--id", "t1", "--full"], target: { project: "demo", take: "t1" } });
+ lines.length = 0;
+ assert.equal(await status(), 3);
+ assert.equal(JSON.parse(lines.join("\n")).state, "queued");
+ // Its render recorded failed (newer than the step): failed, exit 1.
+ const { openRenderRecord } = await import("../report/renderRecord.mjs");
+ await sleep(5);
+ await (await openRenderRecord(path.join(projectDir, "takes", "t1"), { take: "t1", project: "demo" })).fail(new Error("1 entry could not be cut: m09: no source on disk"));
+ lines.length = 0;
+ assert.equal(await status(), 1);
+ const j = JSON.parse(lines.join("\n"));
+ assert.equal(j.state, "failed");
+ assert.match(j.error, /m09: no source on disk/);
+ assert.match(j.logPath, /takes\/t1\/render\.log$/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/renderRecord.mjs b/umtool/lib/report/renderRecord.mjs
@@ -0,0 +1,498 @@
+// EVERY RENDER RECORDS ITSELF (operator, 4 Nov 2026, after mid-13's render
+// died at exit 1 behind a grep-filtered shell chain, and the next chain read
+// its unconditional "DONE" as success): a take's render writes its own record,
+// whoever started it -- a terminal, the Takes page's job, the durable queue
+// (lib/queue/) -- so a failure is never only in a scrollback somebody filtered.
+//
+// takes/<id>/render.json the LAST run's record, written atomically (tmp + rename)
+// takes/<id>/render.log that run's log, FULL and unfiltered: every line the
+// take maker said, every line build-video and
+// queue-lock wrote, every NDJSON event as it came
+//
+// The record:
+//
+// { version: 1, project, take, label, state, pid, pidStart, host, argv,
+// startedAt, updatedAt, endedAt, exitCode,
+// stage, percent, entries: { done, of }, from the build's NDJSON events
+// error, message, tail, on failed: the first error line
+// (or the thrown message), the
+// message itself, the log's last 40 lines
+// log: "render.log",
+// mp4, mp4Bytes, seconds } on done: the take's preview and
+// its measured length (ffprobe)
+//
+// state running the take process is setting up or rendering
+// waiting its render waits at the machine's heavy slot (queue-lock said so)
+// done exit 0 AND a non-empty mp4 -- never otherwise
+// failed anything else: a thrown error, a non-zero exit, an mp4 that is
+// missing or 0 bytes, or (on read) a "running" whose process is gone
+// cancelled stopped by `umtool takes cancel` / the Takes page's Cancel
+// ("queued" is not written here: a take step waiting in the durable queue is the
+// queue's, and `umtool take status` reads it from there.)
+//
+// ON READ (readRenderRecord), never trusted as written: a record that says
+// running or waiting on THIS host whose pid is gone -- or is another process now
+// (its start time, /proc/<pid>/stat, differs) -- reads failed, "the render
+// process is gone"; a done whose mp4 is missing or empty reads failed too.
+//
+// Who writes it: makeTake (takeMaker.mjs), once the take's directory exists; a
+// refused rebuild of a take that exists records the refusal. A take whose first
+// render is refused before its directory is made leaves no directory (as before)
+// and so no record: the command's exit code and stderr say why.
+//
+// Beside it, for `umtool jobs` (lib/queue/cli.mjs): a pointer per take in the
+// queue dir's renders/ (`<project>~<take>.json`, overwritten per run), written
+// only for a project under the reports root -- a temp project in a test writes
+// none.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { createWriteStream, readFileSync } from "node:fs";
+import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+export const RENDER_FILE = "render.json";
+export const RENDER_LOG = "render.log";
+export const RENDER_STATES = Object.freeze(["queued", "waiting", "running", "done", "failed", "cancelled"]);
+/** How many of the log's last lines a failed record carries. */
+export const TAIL_LINES = 40;
+/** The least time between two progress writes of the record (ms); a change of state writes at once. */
+export const WRITE_EVERY_MS = 1000;
+
+/**
+ * `umtool take status`'s exit code for a state: 0 done, 3 still going
+ * (queued, waiting, running), 1 anything else (failed, cancelled, none).
+ * @param {string | null | undefined} state
+ */
+export function statusExitCode(state) {
+ if (state === "done") return 0;
+ if (state === "queued" || state === "waiting" || state === "running") return 3;
+ return 1;
+}
+
+/**
+ * A process's start time (clock ticks since boot, /proc/<pid>/stat field 22),
+ * or null where there is no /proc (or no such process). With the pid it names
+ * ONE process: a pid reused after a crash has another start time.
+ * @param {number} pid
+ */
+export function procStartTime(pid) {
+ if (!Number.isInteger(pid) || pid <= 0) return null;
+ try {
+ const text = readFileSync(/* turbopackIgnore: true */ `/proc/${pid}/stat`, "utf8");
+ // The command name (field 2) is in parentheses and may hold spaces: split after the last ')'.
+ const rest = text.slice(text.lastIndexOf(")") + 2).split(" ");
+ const v = Number(rest[19]);
+ return Number.isFinite(v) ? v : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Is the process this record names alive here? `start` (procStartTime when it
+ * was written) must still match when both sides know it.
+ * @param {number} pid
+ * @param {number | null | undefined} [start]
+ */
+export function processAlive(pid, start = null) {
+ if (!Number.isInteger(pid) || pid <= 0) return false;
+ try {
+ process.kill(pid, 0);
+ } catch (err) {
+ if (/** @type {NodeJS.ErrnoException} */ (err)?.code !== "EPERM") return false;
+ }
+ if (start == null) return true;
+ const now = procStartTime(pid);
+ return now == null || now === start;
+}
+
+const ERROR_LINE = /\b(error|errors|failed|fatal|refused|cannot|can't|could not|not found|no such|ENOENT|EACCES|Traceback|exited \d+|killed|out of memory|OOM)\b|^\s*\*\*/i;
+/** A thrown message that names no cause: the exit code alone. */
+const BARE_EXIT = /^(build-video|node|\S+) exited \d+$/;
+
+/**
+ * The first line of a log that reads as an error (not a JSON event), or null.
+ * @param {string[]} lines
+ */
+export function firstErrorLine(lines) {
+ for (const l of lines) {
+ const t = String(l).trim();
+ if (!t || t.startsWith("{")) continue;
+ if (ERROR_LINE.test(t)) return t.length > 400 ? `${t.slice(0, 400)}…` : t;
+ }
+ return null;
+}
+
+/**
+ * The record's `error`: the thrown message when it names a cause; when it is a
+ * bare "build-video exited 1", the first error line of the log, with the exit after it.
+ * @param {string} message
+ * @param {string[]} lines
+ */
+export function errorOf(message, lines) {
+ const first = firstErrorLine(lines);
+ if (!BARE_EXIT.test(message.trim())) return message;
+ return first && !first.includes(message) ? `${first} — ${message}` : message;
+}
+
+/**
+ * The stage and a rough percent from one of build-video's NDJSON events (its
+ * protocol: start, card, clip, fetch, snap, segment, entry-failed, concat,
+ * chapters, youtube, chrome, narrate, note, done) and the take maker's own
+ * (`take`, phase render/done/failed). Rough on purpose: segments are 5-60 %,
+ * the deck's chrome 60-85, the concat 90, the chapters and youtube file 95.
+ *
+ * @param {Record<string, any>} ev
+ * @param {{ stage: string | null, percent: number | null, entries: { done: number, of: number | null } }} prev
+ */
+export function progressOf(ev, prev) {
+ const entries = { ...prev.entries };
+ let stage = prev.stage;
+ let percent = prev.percent;
+ const bump = (p) => {
+ percent = Math.max(percent ?? 0, Math.min(99, Math.round(p)));
+ };
+ switch (ev?.ev) {
+ case "take":
+ if (ev.phase === "render") {
+ stage = "render";
+ bump(1);
+ }
+ break;
+ case "start":
+ stage = "cutting";
+ entries.of = Number.isFinite(Number(ev.entries)) ? Number(ev.entries) : entries.of;
+ bump(3);
+ break;
+ case "fetch":
+ case "clip":
+ case "card":
+ case "snap":
+ case "pieces":
+ case "narrate":
+ stage = "cutting";
+ break;
+ case "segment":
+ stage = "cutting";
+ entries.done += 1;
+ if (entries.of) bump(5 + (55 * Math.min(entries.done, entries.of)) / entries.of);
+ break;
+ case "chrome":
+ stage = `chrome ${ev.phase ?? ""}`.trim();
+ bump(ev.phase === "render" ? 70 : ev.phase === "overlay" ? 85 : 62);
+ break;
+ case "concat":
+ stage = "concat";
+ bump(90);
+ break;
+ case "chapters":
+ case "youtube":
+ stage = "finishing";
+ bump(95);
+ break;
+ case "done":
+ stage = "muxed";
+ bump(99);
+ break;
+ default:
+ break;
+ }
+ return { stage, percent, entries };
+}
+
+/** A line of queue-lock (scripts/queue-lock.mjs) that says the render waits at the heavy slot's door. */
+export const WAITING_LINE = /^(queue-lock|heavy):.*\b(waiting|held for a render)\b/i;
+/** A line that says it was let in. */
+const ADMITTED_LINE = /^(queue-lock|heavy):.*\b(admitted|acquired|going on)\b/i;
+
+let tmpSeq = 0;
+async function writeAtomic(file, doc) {
+ tmpSeq += 1;
+ const tmp = `${file}.${process.pid}.${tmpSeq}.tmp`;
+ await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
+ await rename(tmp, file);
+}
+
+/**
+ * The queue dir (lib/queue/store.mjs queueDirOf) without importing the queue:
+ * UMTOOL_QUEUE_DIR, else `<reports root>/.umtool-queue`.
+ * @param {string} reportsRoot
+ * @param {Record<string, string | undefined>} [env]
+ */
+export const queueDirFor = (reportsRoot, env = process.env) => path.resolve(env.UMTOOL_QUEUE_DIR || path.join(reportsRoot, ".umtool-queue"));
+
+/** The pointer file of a project's take in the queue dir's renders/. */
+export const renderPointerFile = (queueDir, project, take) => path.join(queueDir, "renders", `${encodeURIComponent(project)}~${take}.json`);
+
+/**
+ * The project's id when its directory is under the reports root, else null.
+ * @param {string} projectDir
+ * @param {string} reportsRoot
+ */
+export function projectIdUnder(projectDir, reportsRoot) {
+ const rel = path.relative(path.resolve(reportsRoot), path.resolve(projectDir));
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null;
+ return rel.split(path.sep).join("/");
+}
+
+/**
+ * Open the record of a run of take `take` in `takeDir` (which exists): writes
+ * `running` and truncates render.log. Returns the recorder the take maker feeds.
+ *
+ * @param {string} takeDir
+ * @param {{ take: string, projectDir?: string, project?: string | null, label?: string | null, argv?: string[],
+ * reportsRoot?: string | null, env?: Record<string, string | undefined>, now?: () => Date, pid?: number, host?: string,
+ * writeEveryMs?: number, earlier?: string[] }} o
+ * `earlier`: lines said before the directory existed (written to the log first).
+ */
+export async function openRenderRecord(takeDir, o) {
+ const now = o.now ?? (() => new Date());
+ const pid = o.pid ?? process.pid;
+ const file = path.join(takeDir, RENDER_FILE);
+ const logPath = path.join(takeDir, RENDER_LOG);
+ const project = o.project ?? (o.projectDir && o.reportsRoot ? projectIdUnder(o.projectDir, o.reportsRoot) : null) ?? (o.projectDir ? path.basename(o.projectDir) : null);
+ const startedAt = now().toISOString();
+ /** @type {Record<string, any>} */
+ const doc = {
+ version: 1,
+ project,
+ take: o.take,
+ label: o.label ?? null,
+ state: "running",
+ pid,
+ pidStart: procStartTime(pid),
+ host: o.host ?? os.hostname(),
+ argv: o.argv ?? process.argv.slice(2),
+ startedAt,
+ updatedAt: startedAt,
+ endedAt: null,
+ exitCode: null,
+ stage: "setting up",
+ percent: 0,
+ entries: { done: 0, of: null },
+ error: null,
+ message: null,
+ tail: [],
+ log: RENDER_LOG,
+ mp4: null,
+ mp4Bytes: null,
+ seconds: null,
+ };
+ const lines = [];
+ const pushTail = (l) => {
+ lines.push(l);
+ if (lines.length > 4000) lines.splice(0, lines.length - 4000);
+ };
+ const log = createWriteStream(/* turbopackIgnore: true */ logPath, { flags: "w" });
+ let logOk = true;
+ log.on("error", () => {
+ logOk = false;
+ });
+ const writeLog = (s) => {
+ if (logOk) log.write(s.endsWith("\n") ? s : `${s}\n`);
+ };
+ writeLog(`# umtool take ${doc.argv.join(" ")}`);
+ writeLog(`# pid ${pid} on ${doc.host}, ${startedAt}`);
+ for (const l of o.earlier ?? []) {
+ writeLog(l);
+ pushTail(l);
+ }
+
+ // Writes are chained (one at a time) and progress is throttled; a state change writes at once.
+ let chain = Promise.resolve();
+ let timer = null;
+ let ended = false;
+ const every = o.writeEveryMs ?? WRITE_EVERY_MS;
+ const write = () => {
+ doc.updatedAt = now().toISOString();
+ const snap = JSON.parse(JSON.stringify(doc));
+ chain = chain.then(() => writeAtomic(file, snap)).catch(() => {});
+ return chain;
+ };
+ const soon = () => {
+ if (timer || ended) return;
+ timer = setTimeout(() => {
+ timer = null;
+ if (!ended) void write();
+ }, every);
+ timer.unref?.();
+ };
+ await write();
+
+ // The pointer `umtool jobs` lists renders by (best effort: a render never fails for it).
+ const root = o.reportsRoot ?? null;
+ if (root && o.projectDir && projectIdUnder(o.projectDir, root)) {
+ const ptr = renderPointerFile(queueDirFor(root, o.env), /** @type {string} */ (projectIdUnder(o.projectDir, root)), o.take);
+ await mkdir(path.dirname(ptr), { recursive: true })
+ .then(() => writeAtomic(ptr, { project: projectIdUnder(o.projectDir ?? "", root), projectDir: path.resolve(o.projectDir ?? ""), take: o.take, startedAt, pid }))
+ .catch(() => {});
+ }
+
+ let built = false;
+ const finish = async () => {
+ ended = true;
+ if (timer) clearTimeout(timer);
+ timer = null;
+ doc.endedAt = now().toISOString();
+ await write();
+ await new Promise((r) => {
+ if (!logOk) return r(undefined);
+ log.end(() => r(undefined));
+ });
+ };
+
+ return {
+ file,
+ logFile: logPath,
+ get state() {
+ return doc.state;
+ },
+ /** One line of prose, as the take maker or the render said it. */
+ line(l) {
+ const s = String(l);
+ writeLog(s);
+ for (const part of s.split("\n")) {
+ if (!part.trim()) continue;
+ pushTail(part);
+ if (ended) continue;
+ if (!built && doc.state === "running" && WAITING_LINE.test(part)) {
+ doc.state = "waiting";
+ doc.stage = "waiting for the heavy slot";
+ void write();
+ } else if (doc.state === "waiting" && ADMITTED_LINE.test(part)) {
+ doc.state = "running";
+ doc.stage = "render";
+ void write();
+ }
+ }
+ },
+ /** One NDJSON event (build-video's or the take maker's). */
+ event(ev) {
+ writeLog(JSON.stringify(ev));
+ if (ended) return;
+ if (ev?.ev !== "take") built = true;
+ const p = progressOf(ev, doc);
+ doc.stage = p.stage;
+ doc.percent = p.percent;
+ doc.entries = p.entries;
+ if (doc.state === "waiting" && ev?.ev !== "take") {
+ doc.state = "running";
+ void write();
+ } else soon();
+ },
+ /**
+ * The render is done: `mp4` must be a non-empty file, or the record says failed.
+ * @param {{ mp4: string, seconds?: number | null }} r
+ */
+ async done({ mp4, seconds = null }) {
+ if (ended) return doc;
+ const st = await stat(/* turbopackIgnore: true */ mp4).catch(() => null);
+ doc.mp4 = path.relative(takeDir, mp4) || path.basename(mp4);
+ doc.mp4Bytes = st?.size ?? null;
+ if (!st || !st.isFile() || st.size === 0) {
+ doc.state = "failed";
+ doc.exitCode = 1;
+ doc.message = !st ? `the render recorded no mp4: ${mp4} is not there` : `the render's mp4 is empty (0 bytes): ${mp4}`;
+ doc.error = doc.message;
+ doc.tail = lines.slice(-TAIL_LINES);
+ } else {
+ doc.state = "done";
+ doc.exitCode = 0;
+ doc.stage = "done";
+ doc.percent = 100;
+ doc.seconds = typeof seconds === "number" && Number.isFinite(seconds) ? seconds : null;
+ if (doc.seconds === null) writeLog("# ffprobe could not measure the mp4: seconds is null");
+ }
+ writeLog(`# ${doc.state}${doc.state === "done" ? ` — ${doc.mp4} (${doc.mp4Bytes} bytes${doc.seconds != null ? `, ${doc.seconds} s` : ""})` : ` — ${doc.error}`}`);
+ await finish();
+ return doc;
+ },
+ /**
+ * The run failed (or was cancelled).
+ * @param {unknown} err
+ * @param {{ cancelled?: boolean, exitCode?: number }} [o2]
+ */
+ async fail(err, { cancelled = false, exitCode = 1 } = {}) {
+ if (ended) return doc;
+ const message = err instanceof Error ? err.message : String(err);
+ doc.state = cancelled ? "cancelled" : "failed";
+ doc.exitCode = exitCode;
+ doc.message = message;
+ doc.error = cancelled ? message : errorOf(message, lines);
+ doc.tail = lines.slice(-TAIL_LINES);
+ writeLog(`# ${doc.state} — ${doc.error}`);
+ await finish();
+ return doc;
+ },
+ /** Wait for the writes so far (tests). */
+ flush: () => chain,
+ };
+}
+
+/**
+ * A record as written, read back and resolved -- or null when there is none.
+ *
+ * @param {string} takeDir
+ * @param {{ host?: string, alive?: (pid: number, start?: number | null) => boolean }} [opts]
+ * @returns {Promise<Record<string, any> | null>}
+ */
+export async function readRenderRecord(takeDir, opts = {}) {
+ let raw;
+ try {
+ raw = JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(takeDir, RENDER_FILE), "utf8"));
+ } catch {
+ return null;
+ }
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || !RENDER_STATES.includes(raw.state)) return null;
+ const mp4Abs = raw.mp4 ? path.resolve(takeDir, raw.mp4) : null;
+ const mp4 = raw.state === "done" && mp4Abs ? await stat(/* turbopackIgnore: true */ mp4Abs).catch(() => null) : null;
+ return resolveRecord(raw, { ...opts, mp4: mp4 ? { size: mp4.size, isFile: mp4.isFile() } : null, takeDir });
+}
+
+/**
+ * Pure: what a record written as `raw` says now. A running/waiting record on
+ * this host whose process is gone reads failed; a done whose mp4 is missing or
+ * empty reads failed.
+ *
+ * @param {Record<string, any>} raw
+ * @param {{ host?: string, alive?: (pid: number, start?: number | null) => boolean, mp4?: { size: number, isFile: boolean } | null, takeDir?: string }} [o]
+ * @returns {Record<string, any>}
+ */
+export function resolveRecord(raw, { host = os.hostname(), alive = processAlive, mp4 = null, takeDir = "" } = {}) {
+ /** @type {Record<string, any>} */
+ const rec = { ...raw, gone: false };
+ const logRel = takeDir ? path.join(path.basename(takeDir), raw.log ?? RENDER_LOG) : raw.log ?? RENDER_LOG;
+ if ((raw.state === "running" || raw.state === "waiting") && (!raw.host || raw.host === host) && !alive(Number(raw.pid), raw.pidStart ?? null)) {
+ rec.state = "failed";
+ rec.gone = true;
+ rec.message = `the render process is gone (pid ${raw.pid}) — it stopped without recording an end: killed, out of memory, or the machine restarted`;
+ rec.error = `${rec.message}; its log: takes/${logRel}`;
+ } else if (raw.state === "done" && (!mp4 || !mp4.isFile || mp4.size === 0)) {
+ rec.state = "failed";
+ rec.message = !mp4 ? `done was recorded, but its mp4 (${raw.mp4 ?? "none named"}) is not there` : `done was recorded, but its mp4 (${raw.mp4}) is empty (0 bytes)`;
+ rec.error = rec.message;
+ }
+ rec.exit = statusExitCode(rec.state);
+ return rec;
+}
+
+/**
+ * The record as lines, for `umtool take status` and `umtool jobs`.
+ * @param {Record<string, any>} rec resolved
+ * @param {{ logPath?: string | null, tail?: number }} [o]
+ */
+export function recordLines(rec, { logPath = null, tail = 12 } = {}) {
+ const out = [];
+ const when = rec.endedAt ? `${String(rec.startedAt).slice(0, 19).replace("T", " ")} → ${String(rec.endedAt).slice(11, 19)}` : `since ${String(rec.startedAt).slice(0, 19).replace("T", " ")}`;
+ const progress = rec.state === "running" || rec.state === "waiting" ? ` — ${rec.stage ?? "?"}${rec.percent != null ? ` ${rec.percent}%` : ""}${rec.entries?.of ? ` (${rec.entries.done}/${rec.entries.of} segments)` : ""}` : "";
+ out.push(`${rec.project ?? "?"} take ${rec.take}: ${rec.state.toUpperCase()}${progress} (${when}, pid ${rec.pid}${rec.exitCode != null ? `, exit ${rec.exitCode}` : ""})`);
+ if (rec.state === "done") out.push(` mp4: takes/${rec.take}/${rec.mp4} (${rec.mp4Bytes} bytes${rec.seconds != null ? `, ${rec.seconds} s` : ", length not measured"})`);
+ if (rec.error) out.push(` error: ${rec.error}`);
+ if ((rec.state === "failed" || rec.state === "cancelled") && Array.isArray(rec.tail) && rec.tail.length && tail > 0) {
+ out.push(` the log's last ${Math.min(tail, rec.tail.length)} lines:`);
+ for (const l of rec.tail.slice(-tail)) out.push(` ${l}`);
+ }
+ if (logPath) out.push(` log: ${logPath}`);
+ return out;
+}
diff --git a/umtool/lib/report/renderRecord.test.mjs b/umtool/lib/report/renderRecord.test.mjs
@@ -0,0 +1,251 @@
+// renderRecord.mjs: every take render records itself -- done only with exit 0
+// and a non-empty mp4; failed with the first error line and the log's tail; a
+// "running" whose process is gone reads failed. And makeTake writes it.
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { test } from "node:test";
+import {
+ errorOf,
+ firstErrorLine,
+ openRenderRecord,
+ progressOf,
+ readRenderRecord,
+ resolveRecord,
+ RENDER_FILE,
+ RENDER_LOG,
+ renderPointerFile,
+ statusExitCode,
+} from "./renderRecord.mjs";
+import { makeTake } from "./takeMaker.mjs";
+
+const tmp = () => mkdtemp(path.join(os.tmpdir(), "render-record-"));
+const readRec = async (dir) => JSON.parse(await readFile(path.join(dir, RENDER_FILE), "utf8"));
+
+test("statusExitCode: 0 done, 3 still going, 1 anything else", () => {
+ assert.equal(statusExitCode("done"), 0);
+ for (const s of ["queued", "waiting", "running"]) assert.equal(statusExitCode(s), 3);
+ for (const s of ["failed", "cancelled", "blocked", "none", null]) assert.equal(statusExitCode(s), 1);
+});
+
+test("the first error line, and a bare `exited 1` replaced by it", () => {
+ const lines = ['{"ev":"start"}', "chrome render: 120 frames", "Error: hyperframes could not open the page", "build-video exited 1"];
+ assert.equal(firstErrorLine(lines), "Error: hyperframes could not open the page");
+ assert.equal(errorOf("build-video exited 1", lines), "Error: hyperframes could not open the page — build-video exited 1");
+ // A message that names its cause is kept as it is.
+ assert.equal(errorOf("2 entries could not be cut: m01: no source", lines), "2 entries could not be cut: m01: no source");
+ assert.equal(errorOf("build-video exited 1", ["all fine"]), "build-video exited 1");
+});
+
+test("progress: segments 5-60 %, chrome, concat, done", () => {
+ let p = { stage: null, percent: null, entries: { done: 0, of: null } };
+ p = progressOf({ ev: "start", entries: 4 }, p);
+ assert.equal(p.entries.of, 4);
+ p = progressOf({ ev: "segment", id: "m01" }, p);
+ p = progressOf({ ev: "segment", id: "m02" }, p);
+ assert.equal(p.stage, "cutting");
+ assert.equal(p.percent, 33);
+ p = progressOf({ ev: "chrome", phase: "render" }, p);
+ assert.equal(p.stage, "chrome render");
+ assert.equal(p.percent, 70);
+ p = progressOf({ ev: "concat", n: 4 }, p);
+ assert.equal(p.percent, 90);
+});
+
+test("done: exit 0 and a non-empty mp4, measured; the log is full", async () => {
+ const dir = await tmp();
+ try {
+ const rec = await openRenderRecord(dir, { take: "t1", project: "demo", argv: ["take", "demo", "--id", "t1"], earlier: ["said before the dir existed"] });
+ assert.equal((await readRec(dir)).state, "running");
+ rec.line("queue-lock: waiting for the heavy slot — held by e2e");
+ await rec.flush();
+ assert.equal((await readRec(dir)).state, "waiting");
+ rec.event({ ev: "start", entries: 2 });
+ rec.event({ ev: "segment", id: "m01" });
+ await rec.flush();
+ assert.equal((await readRec(dir)).state, "running");
+ await writeFile(path.join(dir, "preview.mp4"), "not empty");
+ const doc = await rec.done({ mp4: path.join(dir, "preview.mp4"), seconds: 12.5 });
+ assert.equal(doc.state, "done");
+ const on = await readRec(dir);
+ assert.equal(on.state, "done");
+ assert.equal(on.exitCode, 0);
+ assert.equal(on.mp4, "preview.mp4");
+ assert.equal(on.mp4Bytes, 9);
+ assert.equal(on.seconds, 12.5);
+ assert.equal(on.percent, 100);
+ const log = await readFile(path.join(dir, RENDER_LOG), "utf8");
+ assert.match(log, /said before the dir existed/);
+ assert.match(log, /queue-lock: waiting/);
+ assert.match(log, /"ev":"segment"/);
+ const read = await readRenderRecord(dir);
+ assert.equal(read?.state, "done");
+ assert.equal(read?.exit, 0);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("a zero-length mp4 is failed, never done; a missing one too", async () => {
+ const dir = await tmp();
+ try {
+ const rec = await openRenderRecord(dir, { take: "t1" });
+ await writeFile(path.join(dir, "preview.mp4"), "");
+ const doc = await rec.done({ mp4: path.join(dir, "preview.mp4"), seconds: 0 });
+ assert.equal(doc.state, "failed");
+ assert.match(doc.error, /empty \(0 bytes\)/);
+ const r2 = await openRenderRecord(dir, { take: "t1" });
+ const d2 = await r2.done({ mp4: path.join(dir, "nope.mp4") });
+ assert.equal(d2.state, "failed");
+ assert.match(d2.error, /not there/);
+ assert.equal(d2.exitCode, 1);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("failed: the first error line, the log's last 40 lines, exit 1", async () => {
+ const dir = await tmp();
+ try {
+ const rec = await openRenderRecord(dir, { take: "t1" });
+ for (let i = 0; i < 60; i += 1) rec.line(`frame ${i}`);
+ rec.line("ffmpeg: Error while decoding stream #0:0: Invalid data found");
+ rec.line("tail line");
+ const doc = await rec.fail(new Error("build-video exited 1"));
+ assert.equal(doc.state, "failed");
+ assert.equal(doc.exitCode, 1);
+ assert.equal(doc.message, "build-video exited 1");
+ assert.equal(doc.error, "ffmpeg: Error while decoding stream #0:0: Invalid data found — build-video exited 1");
+ assert.equal(doc.tail.length, 40);
+ assert.equal(doc.tail.at(-1), "tail line");
+ const read = await readRenderRecord(dir);
+ assert.equal(read?.exit, 1);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("a running record whose pid is dead reads failed: the render process is gone", async () => {
+ const raw = { state: "running", pid: 999999, pidStart: 1, host: os.hostname(), take: "t1", log: "render.log" };
+ const r = resolveRecord(raw, { alive: () => false, takeDir: "/x/takes/t1" });
+ assert.equal(r.state, "failed");
+ assert.equal(r.gone, true);
+ assert.match(r.error, /the render process is gone \(pid 999999\)/);
+ assert.match(r.error, /takes\/t1\/render\.log/);
+ assert.equal(r.exit, 1);
+ // Alive: still running. Another host: trusted as written.
+ assert.equal(resolveRecord(raw, { alive: () => true }).state, "running");
+ assert.equal(resolveRecord({ ...raw, host: "elsewhere" }, { alive: () => false }).state, "running");
+ // waiting too
+ assert.equal(resolveRecord({ ...raw, state: "waiting" }, { alive: () => false }).state, "failed");
+ // A done whose mp4 went away.
+ assert.equal(resolveRecord({ state: "done", mp4: "preview.mp4" }, { mp4: null }).state, "failed");
+ assert.equal(resolveRecord({ state: "done", mp4: "preview.mp4" }, { mp4: { size: 0, isFile: true } }).state, "failed");
+ assert.equal(resolveRecord({ state: "done", mp4: "preview.mp4" }, { mp4: { size: 10, isFile: true } }).state, "done");
+});
+
+test("a record written by a real pid that then died reads failed", async () => {
+ const dir = await tmp();
+ try {
+ const { spawnSync } = await import("node:child_process");
+ const dead = spawnSync(process.execPath, ["-e", "process.stdout.write(String(process.pid))"], { encoding: "utf8" });
+ const pid = Number(dead.stdout);
+ await openRenderRecord(dir, { take: "t1", pid });
+ const r = await readRenderRecord(dir);
+ assert.equal(r?.state, "failed");
+ assert.equal(r?.gone, true);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+// ---- makeTake writes the record -----------------------------------------------
+
+async function project() {
+ const root = await tmp();
+ const dir = path.join(root, "demo");
+ await mkdir(dir, { recursive: true });
+ const manifest = { slug: "demo", title: "Demo", render: {}, timeline: [{ type: "clip", id: "m01", video: "v1", start: 1, end: 3 }] };
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest, null, 2));
+ return { root, dir };
+}
+
+const okRender = async (job) => {
+ job.emit({ ev: "start", entries: 1 });
+ job.log("stderr: chrome render 10 frames");
+ job.emit({ ev: "segment", id: "m01" });
+ const file = path.join(job.outDir, `${job.slug}.mp4`);
+ await mkdir(job.outDir, { recursive: true });
+ await writeFile(file, "an mp4");
+ return { file };
+};
+
+test("makeTake: a made take records done, with its mp4 and seconds; a pointer for `umtool jobs` under the reports root", async () => {
+ const { root, dir } = await project();
+ try {
+ const r = await makeTake(dir, { id: "t1", label: "One", window: "full" }, { render: okRender, probe: async () => 2.5, pruneAfter: false, reportsRoot: root, projectId: "demo" });
+ assert.equal(r.skipped, false);
+ const rec = await readRenderRecord(path.join(dir, "takes", "t1"));
+ assert.equal(rec?.state, "done");
+ assert.equal(rec?.seconds, 2.5);
+ assert.equal(rec?.mp4, "preview.mp4");
+ assert.equal(rec?.project, "demo");
+ const log = await readFile(path.join(dir, "takes", "t1", RENDER_LOG), "utf8");
+ assert.match(log, /stderr: chrome render 10 frames/);
+ const ptr = renderPointerFile(path.join(root, ".umtool-queue"), "demo", "t1");
+ assert.ok(existsSync(ptr), "the pointer is written");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("makeTake: a render that throws records failed (the error and the tail); a 0-byte mp4 fails the take and keeps the old one", async () => {
+ const { root, dir } = await project();
+ try {
+ const bad = async (job) => {
+ job.log("Error: the chrome capture crashed");
+ throw new Error("build-video exited 1");
+ };
+ await assert.rejects(makeTake(dir, { id: "t1", label: "One", window: "full" }, { render: bad, pruneAfter: false, reportsRoot: null }), /exited 1/);
+ const rec = await readRenderRecord(path.join(dir, "takes", "t1"));
+ assert.equal(rec?.state, "failed");
+ assert.equal(rec?.error, "Error: the chrome capture crashed — build-video exited 1");
+ assert.ok(rec?.tail.some((l) => /chrome capture crashed/.test(l)));
+ assert.equal(existsSync(path.join(root, ".umtool-queue")), false, "no pointer outside a reports root");
+
+ await makeTake(dir, { id: "t2", label: "Two", window: "full" }, { render: okRender, probe: async () => 1, pruneAfter: false, reportsRoot: null });
+ const before = await readFile(path.join(dir, "takes", "t2", "preview.mp4"), "utf8");
+ const empty = async (job) => {
+ const file = path.join(job.outDir, `${job.slug}.mp4`);
+ await writeFile(file, "");
+ return { file };
+ };
+ await assert.rejects(makeTake(dir, { id: "t2", label: "Two", window: "full" }, { render: empty, force: true, pruneAfter: false, reportsRoot: null }), /empty \(0 bytes\)/);
+ assert.equal((await readRenderRecord(path.join(dir, "takes", "t2")))?.state, "failed");
+ assert.equal(await readFile(path.join(dir, "takes", "t2", "preview.mp4"), "utf8"), before, "the old take is whole");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("makeTake: a skipped take writes no record; a refused first render leaves no directory", async () => {
+ const { root, dir } = await project();
+ try {
+ await makeTake(dir, { id: "t1", label: "One", window: "full" }, { render: okRender, probe: async () => 1, pruneAfter: false, reportsRoot: null });
+ const first = await readRec(path.join(dir, "takes", "t1"));
+ const r = await makeTake(dir, { id: "t1", label: "One", window: "full" }, { render: okRender, pruneAfter: false, reportsRoot: null });
+ assert.equal(r.skipped, true);
+ assert.deepEqual(await readRec(path.join(dir, "takes", "t1")), first, "the record of the last real run stays");
+ await assert.rejects(makeTake(dir, { id: "t3", label: "x", style: "nope", window: "full" }, { render: okRender, styles: {}, pruneAfter: false, reportsRoot: null }), /unknown style/);
+ assert.equal(existsSync(path.join(dir, "takes", "t3")), false);
+ // A refused REBUILD of a take that exists is recorded.
+ await assert.rejects(makeTake(dir, { id: "t1", label: "One", style: "nope", window: "full" }, { render: okRender, styles: {}, force: true, pruneAfter: false, reportsRoot: null }), /unknown style/);
+ const refused = await readRenderRecord(path.join(dir, "takes", "t1"));
+ assert.equal(refused?.state, "failed");
+ assert.match(refused?.error ?? "", /unknown style/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs
@@ -49,6 +49,11 @@ export const TAKE_USAGE = [
" umtool take <project> --id <id> --label L [--patch F | …] --draft (or --no-render) the take RECORDED,",
" nothing rendered: it can be walked (/projects/<p>/takes/<id>/walk, `umtool walk <p> --take <id>`)",
" and its clips edited into its patch; `umtool take <p> --id <id> --full` renders it later",
+ " umtool take status <project> [--id <id>] [--json] [--log] [--tail N] the take's render RECORD",
+ " (takes/<id>/render.json, written by every render whoever started it): state, stage, percent,",
+ " the error and the log's last lines, the full log (takes/<id>/render.log); a take waiting in the",
+ " queue (`umtool queue`) reads queued. EXIT 0 done · 3 queued, waiting or running · 1 failed,",
+ " cancelled, blocked or none. Without --id every take with a record, the newest's exit",
" umtool take <project> --id <id> --promote [--anyway] [--json] make this the cut: the take's manifest",
" (its patch applied to the project's manifest now) over the project's -- one undo point",
" (revisions/…-auto-before-promote-take; `umtool timeline <p> undo` takes it back)",
@@ -115,7 +120,7 @@ export const UNCENSORED_PATCH = Object.freeze({ render: { posts: { slurs: { on:
function parse(args) {
const valued = new Set([
"--id", "--label", "--group", "--kind", "--summary", "--style", "--patch", "--patch-json", "--set", "--effect",
- "--at", "--dur", "--recipe", "--only", "--progress", "--from", "--by", "--name",
+ "--at", "--dur", "--recipe", "--only", "--progress", "--from", "--by", "--name", "--tail",
]);
/** @type {Record<string, string[]>} */
const flags = {};
@@ -236,6 +241,13 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
log(TAKE_USAGE);
return p.has("--help") ? 0 : 2;
}
+ // `umtool take status <project> [--id <t>]` (lib/queue/cli.mjs takeStatus): the render record.
+ if (p.positional[0] === "status" && p.positional.length >= 2) {
+ const project = await pickProject(p.positional[1], reportsRoot);
+ const { takeStatus } = await import("../queue/cli.mjs");
+ const tail = p.has("--tail") ? Math.max(1, Number(p.one("--tail")) || 40) : null;
+ return await takeStatus(project, { take: p.one("--id") ?? null, json: p.has("--json"), showLog: p.has("--log"), tail, reportsRoot, log, err });
+ }
const project = await pickProject(p.positional[0], reportsRoot);
const out = reporter(p, log, err);
const id = p.one("--id");
@@ -301,6 +313,9 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
keepFrames: p.has("--keep-frames"),
emit: out.emit,
log: out.log,
+ projectId: project.id,
+ argv: ["take", ...args],
+ reportsRoot,
...(deps ?? (await realDeps())),
});
const r = await withTakePriority(
@@ -548,6 +563,9 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con
only,
emit: out.emit,
log: out.log,
+ projectId: project.id,
+ argv: ["takes", ...args],
+ reportsRoot,
...(deps ?? (await realDeps())),
}),
);
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -53,6 +53,7 @@ import { cutSlurState } from "umtool-report-to-video/post-slurs";
import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-report-to-video/montage-rulings";
import { markKeepFrames } from "umtool-report-to-video/prune-frames";
import { PIPELINE_DIR, RENDER_BUDGET, UMTOOL_DIR } from "./driver.mjs";
+import { REPORTS_ROOT } from "../paths.mjs";
import { replaceManifest } from "./manifest.mjs";
import { incorrectClips, incorrectWhy } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
@@ -502,6 +503,41 @@ export async function linkSharedOut(projectDir, takeOut) {
export async function makeTake(projectDir, rawSpec, opts = {}) {
const prune = await import("./takePrune.mjs");
const cancel = await import("./takeCancel.mjs");
+ // EVERY RENDER RECORDS ITSELF (renderRecord.mjs): takes/<id>/render.json and
+ // the full render.log, opened once the take's directory exists. What is said
+ // before then is kept and written first. `opts.record: false` keeps none.
+ const recordMod = opts.record === false ? null : await import("./renderRecord.mjs");
+ const id = typeof rawSpec?.id === "string" && isTakeId(rawSpec.id) ? rawSpec.id : null;
+ /** @type {any} */
+ let rec = null;
+ /** @type {string[]} */
+ const earlier = [];
+ const baseLog = opts.log ?? (() => {});
+ const baseEmit = opts.emit ?? (() => {});
+ const log = (line) => {
+ if (rec) rec.line(line);
+ else if (recordMod) earlier.push(String(line));
+ baseLog(line);
+ };
+ const emit = (ev) => {
+ if (rec) rec.event(ev);
+ baseEmit(ev);
+ };
+ const label = typeof rawSpec?.label === "string" ? rawSpec.label : null;
+ const openRecord = async (takeDir) => {
+ if (!recordMod || !id || rec) return;
+ rec = await recordMod
+ .openRenderRecord(takeDir, {
+ take: id,
+ projectDir,
+ project: opts.projectId ?? null,
+ label,
+ argv: opts.argv,
+ reportsRoot: opts.reportsRoot === undefined ? REPORTS_ROOT : opts.reportsRoot,
+ earlier,
+ })
+ .catch(() => null);
+ };
let lockFile = null;
// CANCEL (takeCancel.mjs): while the take holds its build lock it answers a
// cancel request -- its render stopped, the take marked cancelled.
@@ -510,25 +546,33 @@ export async function makeTake(projectDir, rawSpec, opts = {}) {
let asked = null;
let stopWatch = null;
let rebuild = false;
- const label = typeof rawSpec?.label === "string" ? rawSpec.label : null;
- const onTakeDir = async (takeDir, id) => {
- lockFile = await prune.writeBuildLock(takeDir, { take: id, from: opts.from ?? null, ...(label ? { label } : {}) }).catch(() => null);
+ const onTakeDir = async (takeDir, tid) => {
+ await openRecord(takeDir);
+ lockFile = await prune.writeBuildLock(takeDir, { take: tid, from: opts.from ?? null, ...(label ? { label } : {}) }).catch(() => null);
rebuild = await stat(path.join(takeDir, TAKE_FILE)).then(() => true, () => false);
stopWatch = cancel.watchCancel(takeDir, (req) => {
asked = req;
- (opts.log ?? (() => {}))(`${id}: cancel asked${req?.by ? ` by ${req.by}` : ""} — stopping the render`);
+ log(`${tid}: cancel asked${req?.by ? ` by ${req.by}` : ""} — stopping the render`);
abort.abort();
});
};
let r;
try {
- r = await makeTakeLocked(projectDir, rawSpec, { ...opts, onTakeDir, signal: abort.signal });
+ r = await makeTakeLocked(projectDir, rawSpec, { ...opts, log, emit, onTakeDir, signal: abort.signal });
} catch (e) {
- if (abort.signal.aborted && typeof rawSpec?.id === "string") {
+ // A refusal before the take's directory was made: recorded only for a take that exists (a rebuild).
+ if (!rec && id && recordMod) {
+ const dir = path.join(takesDirOf(projectDir), id);
+ if (await stat(path.join(dir, TAKE_FILE)).then(() => true, () => false)) await openRecord(dir);
+ }
+ if (abort.signal.aborted && id) {
const by = String(asked?.by ?? "");
- await cancel.markCancelled(projectDir, rawSpec.id, { by, label, rebuild }).catch(() => {});
- throw new cancel.TakeCancelled(rawSpec.id, by);
+ await cancel.markCancelled(projectDir, id, { by, label, rebuild }).catch(() => {});
+ const err = new cancel.TakeCancelled(id, by);
+ await rec?.fail(err, { cancelled: true });
+ throw err;
}
+ await rec?.fail(e);
throw e;
} finally {
stopWatch?.();
@@ -538,10 +582,12 @@ export async function makeTake(projectDir, rawSpec, opts = {}) {
if (!r.skipped) {
const dir = path.join(takesDirOf(projectDir), r.id);
await Promise.all([unlink(path.join(dir, cancel.CANCEL_FILE)).catch(() => {}), unlink(path.join(dir, cancel.CANCELLED_FILE)).catch(() => {})]);
+ // done only with a non-empty mp4 (the record says failed otherwise, and so does this).
+ const doc = await rec?.done({ mp4: path.join(dir, PREVIEW), seconds: r.take?.seconds ?? null });
+ if (doc && doc.state !== "done") throw new Error(doc.error ?? `take ${r.id}: the render left no mp4`);
}
if (!r.skipped && opts.pruneAfter !== false) {
- const log = opts.log ?? (() => {});
- await prune.pruneAfterBuild(projectDir, { built: r.id, log: (line) => log(`${r.id}: ${line}`) });
+ await prune.pruneAfterBuild(projectDir, { built: r.id, log: (line) => baseLog(`${r.id}: ${line}`) });
}
return r;
}
@@ -708,6 +754,11 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
}
const renderSeconds = Math.round((clock() - (firstEventAt ?? renderStart)) / 100) / 10;
+ // A render that "succeeded" without a picture is a failure, never a take
+ // (renderRecord.mjs): checked before the old preview is replaced.
+ const made = await stat(file).catch(() => null);
+ if (!made || !made.isFile()) throw new Error(`${spec.id}: the render exited 0 but wrote no mp4 (${file} is not there)`);
+ if (made.size === 0) throw new Error(`${spec.id}: the render exited 0 but its mp4 is empty (0 bytes): ${file}`);
await moveFile(file, preview);
await keepBuildName(preview, file, (line) => log(`${spec.id}: ${line}`));
await rename(nextManifest, path.join(takeDir, MANIFEST));
diff --git a/umtool/lib/trim.ts b/umtool/lib/trim.ts
@@ -196,6 +196,13 @@ export type Step = {
timeoutMs?: number;
/** Lines matching this are progress events, not log noise. */
ndjson?: boolean;
+ /**
+ * Every byte the step writes, appended to this file as it comes -- FULL and
+ * unfiltered, beside the rolling in-memory log (lib/jobs.ts keeps the last
+ * 400 lines). The durable queue's steps (lib/queue/) set it, so a step's log
+ * outlives the app that ran it.
+ */
+ logFile?: string;
};
/** Env keys a request may never set. The recipe owns both, for the reason above. */