Archilyzer · Source

archilyzer

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

commit 75d0be65ea31c02c4ce70304b9cda72e62147453
parent ef616e425832c2125dce13afdca5077135e2fd15
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 23:21:30 -0500

Merge lane/run-queue: every take render records itself (render.json + the full render.log: state, stage, percent, exit code, error, mp4) and umtool runs a durable queue -- umtool queue add [--after <qid>|last] -- <umtool args>, queue status|wait|log|retry|cancel --json, take status <p> --id <t> --json, umtool jobs; the /jobs page and the Takes panel show each render's state and error (operator, 4 Nov: "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")

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Meditor/CHANGELOG.md | 1+
Mpackage.json | 2+-
Aumtool/app/api/queue/log/route.ts | 18++++++++++++++++++
Aumtool/app/api/queue/route.ts | 40++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/takes/render/route.ts | 30++++++++++++++++++++++++++++++
Aumtool/app/jobs/page.tsx | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 10++++++++++
Mumtool/components/projects/TakeVariants.tsx | 24+++++++++++++++++++++++-
Mumtool/components/projects/TakesBench.tsx | 9+++++++++
Mumtool/components/projects/TakesPage.tsx | 28++++++++++++++++++++++++++--
Aumtool/components/queue/LiveRefresh.tsx | 19+++++++++++++++++++
Aumtool/components/queue/QueuePanel.tsx | 151++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/queue/RenderRecord.tsx | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/shell/RunningList.tsx | 5++++-
Mumtool/docs/cli.md | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/knobs.md | 16++++++++++++++++
Mumtool/docs/report-video.md | 13+++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 15+++++++++++++++
Aumtool/e2e/run-queue.spec.ts | 143+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/instrumentation.ts | 23+++++++++++++++++++++++
Mumtool/lib/hrefs.ts | 15+++++++++++++++
Mumtool/lib/jobs.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/lib/queue/cli.mjs | 413+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/queue/runner.ts | 166+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/queue/store.mjs | 596+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/queue/store.test.mjs | 324+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/queue/view.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/renderRecord.mjs | 498+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/renderRecord.test.mjs | 251+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeCancel.mjs | 21+++++++++++++++------
Mumtool/lib/report/takeCli.mjs | 20+++++++++++++++++++-
Mumtool/lib/report/takeMaker.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/lib/trim.ts | 7+++++++
33 files changed, 3239 insertions(+), 26 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **Every umtool take render records itself, and umtool runs a queue of steps in order.** A render that died at exit 1 behind a filtered shell chain left no trace (`take.json` kept `builtAt: null`, no log), and the next chain read the chain's own DONE as success. Now every render, whoever starts it, writes `takes/<id>/render.json` (running, waiting at the heavy slot, done, failed or cancelled; its stage; on failure the first error line and the log's last 40 lines; on done the mp4 and its seconds) and the full `takes/<id>/render.log`; done needs exit 0 and a non-empty mp4, and a record whose process is gone reads failed. `umtool take status <p> --id <t>` exits 0 done, 3 still going, 1 failed. `umtool queue add [--after <qid>] -- <command…>` queues a umtool command that the umtool app runs, one step at a time, surviving the session, a restart or a ship: a failure blocks what waits on it, `retry` puts both back, a step that was running when the app died is failed with its log and never re-run. `umtool queue ls|status|wait|log|cancel|retry` and `umtool jobs` poll them; `/jobs` (the rail's *Running*) and the Takes page show the queue and the records, with the error and the log. umtool/docs/cli.md, "Queue and poll instead of scripting". - **A small fix to a report-video take re-renders in minutes, not half an hour.** A take renders hard cuts, and its final picture was one overlay pass over the whole cut on every take -- 12.6 of mid-6's 30 minutes, 26 of mid-7's 60 -- however small the change. The pass is now in keyed chunks, one segment's run each: `umtool take … --from <take>` re-encodes only the chunks of the post it touched, and a post that grew or shrank moves the chunks after it without changing them (the deck's frames after it are the same frames, later). The deck is drawn only where a chunk to encode reads it, so a take `--from` a pruned one no longer captures the whole deck again (12,347 captures, ~3 minutes on mid-7), and the cut's sound is keyed by each segment's audio, so a caption or a knob that moves no word keeps it. The picture is now frame-exact: the old pass laid each next segment at the longer of its picture and its sound, the footage up to 0.3 s behind the deck by the end of the cut. - **A recorded take can be cleaned up, or given a stock synthetic voice, by the editor.** umtool's derived takes (`umtool posts narrate <p> <item> --derive <n> --op enhance|convert`, the post bench's **run AI on take #n**) said "not installed": the editor had no voice ops. It now has two, each a job on a new `voice` queue, its engine run behind the machine's heavy slot with a declared memory estimate: `pnpm ops voice-enhance` (denoise, soften the room, level — DeepFilterNet 3, or RNNoise through ffmpeg with nothing to install) and `pnpm ops voice-convert` (the timing and pitch contour kept, the timbre swapped — OpenVoice v2's converter or Seed-VC). The result is a 48 kHz mono WAV exactly as long as the take, so a derived take lines up with its source; a take recorded part by part is processed part by part. A conversion lands only on a STOCK voice of our own TTS engines (`zac`, `orpheus:leah`, `kokoro:am_michael`): a file or a recording is refused as a target, whatever it holds. The engines are installed by `archilyzer voice setup --engine <id>`, which says what it downloads and how big first; `settings.voice` picks the defaults (SETTINGS.md); OPERATING.md, "Enhance or convert a recorded take". - **X post captures keep the post's context: what it quotes and what it answers.** A post video drew a reply ("you called me a Leftist…") with nothing it answered, because the archive row named no parent, no quote and no links. `capture-posts` on an X channel now reads, off the page it already loads, the post it answers (the archive's in-reply-to id, else the post directly above it) and the post it quotes — author, display name, check, date, words and media links — into the post's `capture.json` as `context`, with no extra page load (`"context": false` turns it off). `"contextOnly": true` loads one page per post for that alone (and the avatars it shows) and writes nothing else: `pnpm ops capture-posts --json '{"slug":"<x-channel>","ids":["<post id>", …],"contextOnly":true}' --wait`. Not verified against live X yet; the first run is the check. Needs a restart of the editor. 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/app/api/queue/log/route.ts b/umtool/app/api/queue/log/route.ts @@ -0,0 +1,18 @@ +import { readFile } from "node:fs/promises"; +import { queueDir } from "@/lib/queue/runner"; +import { isQid, logFileOf } from "@/lib/queue/store.mjs"; + +export const dynamic = "force-dynamic"; + +// GET ?qid=<qid>[&attempt=<n>] a queue step's FULL log, as text (what +// `umtool queue log <qid>` prints). The path is built from the qid alone. +export async function GET(request: Request) { + const url = new URL(request.url); + const qid = url.searchParams.get("qid"); + if (!isQid(qid)) return new Response("?qid=<qid>", { status: 400 }); + const n = url.searchParams.get("attempt"); + const attempt = n && /^[1-9][0-9]{0,3}$/.test(n) ? Number(n) : null; + const text = await readFile(/* turbopackIgnore: true */ logFileOf(queueDir(), qid, attempt), "utf8").catch(() => null); + if (text === null) return new Response(`no log for ${qid}${attempt ? ` attempt ${attempt}` : ""} (yet)`, { status: 404, headers: { "content-type": "text/plain; charset=utf-8" } }); + return new Response(text, { headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } }); +} diff --git a/umtool/app/api/queue/route.ts b/umtool/app/api/queue/route.ts @@ -0,0 +1,40 @@ +import { kickQueue } from "@/lib/queue/runner"; +import { cancelStep, isQid, retryStep } from "@/lib/queue/store.mjs"; +import { queueDir } from "@/lib/queue/runner"; +import { queueView } from "@/lib/queue/view"; + +export const dynamic = "force-dynamic"; + +// THE DURABLE QUEUE (lib/queue/store.mjs), for /jobs and the Takes panel. +// +// GET [?project=<id>][&all=1] { dir, runner, steps }: the runner (is the app +// running the queue, and since when) and the +// steps, newest first (not finished, or finished +// in the last day; all=1 every one) +// POST ?cancel=<qid> | ?retry=<qid> what `umtool queue cancel|retry` do +// +// Steps are ADDED from a terminal (`umtool queue add -- <argv…>`), never here: +// a step is a command line, and a page that took one would run whatever it was +// sent. +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const view = await queueView({ project: url.searchParams.get("project"), all: url.searchParams.get("all") === "1" }); + return Response.json(view, { headers: noStore }); +} + +export async function POST(request: Request) { + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + const retry = url.searchParams.get("retry"); + const qid = cancel ?? retry; + if (!isQid(qid)) return Response.json({ error: "?cancel=<qid> or ?retry=<qid>" }, { status: 400 }); + try { + const r = cancel ? await cancelStep(queueDir(), qid, { by: "the umtool app (/jobs)" }) : await retryStep(queueDir(), qid); + kickQueue(); + return Response.json({ ok: true, said: r.said }, { headers: noStore }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); + } +} diff --git a/umtool/app/api/report/takes/render/route.ts b/umtool/app/api/report/takes/render/route.ts @@ -0,0 +1,30 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { projectRef } from "@/lib/projects"; +import { RENDER_LOG } from "@/lib/report/renderRecord.mjs"; +import { isTakeId } from "@/lib/report/takes.mjs"; +import { takeRender } from "@/lib/queue/view"; + +export const dynamic = "force-dynamic"; + +// A TAKE'S RENDER RECORD (lib/report/renderRecord.mjs), what `umtool take +// status` reads: +// +// GET ?project=<id>&take=<id> the record, resolved (a running one whose +// process is gone reads failed), or 404 +// GET ?project=<id>&take=<id>&log=1 takes/<id>/render.log, FULL, as text +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const take = url.searchParams.get("take"); + if (!isTakeId(take)) return Response.json({ error: "not a take id" }, { status: 400 }); + if (url.searchParams.get("log") === "1") { + const text = await readFile(/* turbopackIgnore: true */ path.join(project.dir, "takes", take, RENDER_LOG), "utf8").catch(() => null); + if (text === null) return new Response(`take ${take} has no render log`, { status: 404, headers: { "content-type": "text/plain; charset=utf-8" } }); + return new Response(text, { headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } }); + } + const rec = await takeRender(project.dir, take); + if (!rec) return Response.json({ error: `take ${take} has no render record` }, { status: 404 }); + return Response.json(rec, { headers: { "cache-control": "no-store" } }); +} diff --git a/umtool/app/jobs/page.tsx b/umtool/app/jobs/page.tsx @@ -0,0 +1,51 @@ +import type { Metadata } from "next"; +import AppShell from "@/components/shell/AppShell"; +import LiveRefresh from "@/components/queue/LiveRefresh"; +import QueuePanel from "@/components/queue/QueuePanel"; +import RenderRecord from "@/components/queue/RenderRecord"; +import { ActivityPanel } from "@/components/system/Status"; +import { Panel } from "@/components/ui/panel"; +import { listActivity, runningActivity } from "@/lib/activity"; +import { queueView, rendersView } from "@/lib/queue/view"; + +export const dynamic = "force-dynamic"; +export const metadata: Metadata = { title: "Jobs · umtool" }; + +// JOBS (4 Nov 2026, "the apps do the work"): what `umtool jobs` prints, on a +// page -- the durable queue (lib/queue/: each step, its state, its error, its +// full log, Cancel and Retry), every recent take render's own record (takes/ +// <id>/render.json, whoever started it: a terminal, the Takes page, the queue), +// and the app's in-memory jobs. Read from disk on every request; refreshed +// while something runs, silent when nothing does. + +export default async function JobsPage() { + const [queue, renders] = await Promise.all([queueView(), rendersView()]); + const running = runningActivity(); + const recent = listActivity(12); + const live = renders.some((r) => r.state === "running" || r.state === "waiting"); + return ( + <div className="flex h-full flex-col"> + <AppShell active="jobs" crumbs={[{ label: "Jobs" }]} /> + <LiveRefresh live={live} /> + <main className="deck-main flex-1 space-y-3 p-4" data-jobs-page=""> + <Panel title="Queue" data-panel="queue" aside={<span className="text-muted-2">{queue.steps.length} step{queue.steps.length === 1 ? "" : "s"} · umtool queue ls</span>}> + <QueuePanel initial={{ runner: queue.runner, steps: queue.steps }} emptyText="Nothing queued, running or finished in the last day." /> + </Panel> + <Panel title="Take renders" data-panel="renders" aside={<span className="text-muted-2">the last 7 days · umtool take status</span>}> + {renders.length === 0 ? ( + <p className="m-0 text-[12px] text-[var(--color-dim)]" data-renders-empty=""> + No take render recorded in the last 7 days. + </p> + ) : ( + <div className="space-y-1.5"> + {renders.map((r) => ( + <RenderRecord key={`${r.project}:${r.take}`} project={r.project ?? ""} rec={r} showProject compact={r.state === "done"} /> + ))} + </div> + )} + </Panel> + <ActivityPanel running={running} recent={recent} /> + </main> + </div> + ); +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -965,6 +965,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", @@ -1115,6 +1121,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/components/projects/TakeVariants.tsx b/umtool/components/projects/TakeVariants.tsx @@ -4,6 +4,8 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; import { useState } from "react"; import DeletePlan from "@/components/DeletePlan"; +import RenderRecord from "@/components/queue/RenderRecord"; +import type { RenderView } from "@/lib/queue/view"; import { buttonVariants } from "@/components/ui/button"; import { takesCompareHref, takesHref } from "@/lib/hrefs"; @@ -19,6 +21,8 @@ export type CompareOption = { ref: string; label: string }; export type WorkDirs = { rendering: Array<{ id: string; label: string | null; pid: number | null; startedAt: string | null; from: string | null }>; cancelled: Array<{ id: string; label: string | null; at: string; by: string }>; + /** First renders that failed: their own record says so (lib/report/renderRecord.mjs). */ + failed?: Array<{ id: string; label: string | null; record: RenderView }>; }; const sm = buttonVariants({ size: "sm" }); @@ -184,7 +188,8 @@ export function TakeWorkDirs({ project, dirs, ready }: { project: string; dirs: const router = useRouter(); const [show, setShow] = useState(false); const [said, setSaid] = useState<CancelSaid | null>(null); - if (!dirs.rendering.length && !dirs.cancelled.length && !said) return null; + const failed = dirs.failed ?? []; + if (!dirs.rendering.length && !dirs.cancelled.length && !failed.length && !said) return null; return ( <section data-take-workdirs="" className="space-y-1.5 text-[12px]"> <CancelSaidLine said={said} /> @@ -203,6 +208,23 @@ export function TakeWorkDirs({ project, dirs, ready }: { project: string; dirs: </span> </div> ))} + {failed.map((f) => ( + // A first render that failed: never a take, its error and its log in the open (not folded). + <div key={f.id} data-take-failed={f.id} className="space-y-1"> + <div className="flex flex-wrap items-center gap-2"> + <span className="micro text-reject-text">first render failed</span> + <span className="font-mono">{f.id}</span> + {f.label && <span className="text-text-2">{f.label}</span>} + <span className="text-[11px] text-[var(--color-dim)]"> + never finished: no take · <code className="font-mono">umtool take status {project} --id {f.id}</code> + </span> + <span className="ml-auto"> + <DeletePlan label={`Delete take ${f.id}`} subject={`the failed take ${f.id}`} endpoint="/api/report/takes/delete" body={{ project, take: f.id }} onDone={() => router.refresh()} /> + </span> + </div> + <RenderRecord project={project} rec={f.record} /> + </div> + ))} {dirs.cancelled.length > 0 && ( <p className="m-0 text-[11px] text-[var(--color-dim)]" data-cancelled-count={dirs.cancelled.length}> {dirs.cancelled.length} cancelled render{dirs.cancelled.length === 1 ? "" : "s"} {show ? "shown" : "folded away"} ·{" "} diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -11,6 +11,8 @@ import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { fmtAgo, fmtBytes } from "@/lib/format"; import { playHref, takeWalkHref } from "@/lib/hrefs"; +import RenderRecord from "@/components/queue/RenderRecord"; +import type { RenderView } from "@/lib/queue/view"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; import { startTakeJob } from "./NewTakePanel"; import TakeActions from "./TakeActions"; @@ -59,6 +61,12 @@ export type Take = { latest?: boolean; /** Its last render was cancelled (takes/<id>/cancelled.json, lib/report/takeCancel.mjs): the take kept is the one before. */ cancelled?: { at: string; by: string } | null; + /** + * Its render record (lib/report/renderRecord.mjs) when it says more than the + * take does: a render running now, or a last render that failed or was + * cancelled after this take was built (the take kept is the one before). + */ + render?: RenderView | null; }; /** A take's work files, as `GET /api/report/takes/prune` measures them (lib/report/takePrune.mjs). */ @@ -763,6 +771,7 @@ function TakeCard({ </button> </div> {t.summary && <p className="text-[12px] text-[var(--color-text)]">{t.summary}</p>} + {t.render && <RenderRecord project={project} rec={t.render} compact />} {t.changes.length > 0 && ( <ul className="list-disc pl-4 text-[11px] text-[var(--color-dim)]"> {t.changes.map((c, i) => ( diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx @@ -18,6 +18,9 @@ import { readCancelled, takeWorkDirs } from "@/lib/report/takeCancel.mjs"; import { variantFamily } from "@/lib/report/variantFork.mjs"; import { REPORTS_ROOT } from "@/lib/paths.mjs"; import { TakeWorkDirs, type CompareOption } from "./TakeVariants"; +import QueuePanel from "@/components/queue/QueuePanel"; +import LiveRefresh from "@/components/queue/LiveRefresh"; +import { queueView, takeRender } from "@/lib/queue/view"; // `/browse/<project>/takes` -- alternative renders of one part of the cut, // watched side by side and judged like / maybe / no. @@ -49,10 +52,13 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { const working = await readWorkingCut(project.dir, { manifestText, resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }).catch(() => null); // Cancel, fork, compare (UI notes item 19): first renders in progress or cancelled, each take's // last-render-cancelled mark, and every take of the project and its variants (variantFork.mjs). - const [workDirs, cancelledMarks, family] = await Promise.all([ + // Every render records itself (lib/report/renderRecord.mjs), and the queue holds what waits to run (lib/queue/). + const [workDirs, cancelledMarks, family, renders, queue] = await Promise.all([ takeWorkDirs(project.dir), Promise.all((listing.takes as Take[]).map(async (t) => [t.id, await readCancelled(project.dir, t.id)] as const)).then((xs) => new Map(xs)), variantFamily(project, { root: REPORTS_ROOT }).catch(() => ({ parent: project.id, members: [] })), + Promise.all((listing.takes as Take[]).map(async (t) => [t.id, await takeRender(project.dir, t.id)] as const)).then((xs) => new Map(xs)), + queueView({ project: project.id }), ]); const compareOptions: CompareOption[] = family.members.flatMap((m) => (m.takes as Array<{ id: string; label: string; draft?: boolean }>).map((t) => ({ @@ -66,7 +72,12 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { const c = cancelledMarks.get(t.id); // A cancel after the take was last built (a rebuild stopped): the take kept is the one from before. const cancelled = c && (!t.builtAt || c.at > t.builtAt) ? { at: String(c.at), by: String(c.by ?? "") } : null; - return { ...t, stale: t.baseHash ? t.baseHash !== current : null, holds: holds.get(t.id) ?? [], latest: t.id === working?.latest?.id, cancelled }; + // The record, when it says more than the take: rendering now, or a later render that did not make it. + const rec = renders.get(t.id) ?? null; + const live = rec && (rec.state === "running" || rec.state === "waiting"); + const later = rec && (rec.state === "failed" || rec.state === "cancelled") && (!t.builtAt || rec.startedAt > t.builtAt); + const render = live || later ? rec : null; + return { ...t, stale: t.baseHash ? t.baseHash !== current : null, holds: holds.get(t.id) ?? [], latest: t.id === working?.latest?.id, cancelled, render }; }); const byId = new Map(takes.map((t) => [t.id, t])); const panel = @@ -80,6 +91,15 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { /> ) : null; const judged = takes.filter((t) => verdicts[t.id]?.verdict).length; + // The project's queue steps (lib/queue/): shown when it has any. + const liveRenders = [...renders.values()].some((r) => r && (r.state === "running" || r.state === "waiting")); + const queuePanel = + queue.steps.length > 0 ? ( + <section data-takes-queue="" className="space-y-1"> + <h2 className="micro m-0">Queue — {project.id}</h2> + <QueuePanel initial={{ runner: queue.runner, steps: queue.steps }} project={project.id} /> + </section> + ) : null; // The piece this view belongs to: the article's when an article claims the project (P4a-2). const back = await pieceHrefOfProject(project.id, { tab: "cut" }); @@ -113,7 +133,9 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { > {takes.length === 0 ? ( <BenchBody workClassName="space-y-4"> + <LiveRefresh live={liveRenders} /> {panel} + {queuePanel} <TakeWorkDirs project={project.id} dirs={workDirs} ready /> <p data-takes-empty="" className="text-[12px] text-[var(--color-dim)]"> No takes yet.{" "} @@ -165,7 +187,9 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { )} </p> )} + <LiveRefresh live={liveRenders} /> {panel} + {queuePanel} </> } > diff --git a/umtool/components/queue/LiveRefresh.tsx b/umtool/components/queue/LiveRefresh.tsx @@ -0,0 +1,19 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect } from "react"; + +// Refresh the server-rendered page every `ms` while `live` (a render records +// itself as it goes: its stage and percent move on disk). An idle page makes no +// requests at all, as NowLive's rule says. +export default function LiveRefresh({ live, ms = 4000 }: { live: boolean; ms?: number }) { + const router = useRouter(); + useEffect(() => { + if (!live) return; + const t = setInterval(() => { + if (document.visibilityState !== "hidden") router.refresh(); + }, ms); + return () => clearInterval(t); + }, [live, ms, router]); + return null; +} diff --git a/umtool/components/queue/QueuePanel.tsx b/umtool/components/queue/QueuePanel.tsx @@ -0,0 +1,151 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect, useRef, useState } from "react"; +import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; +import { queueLogHref } from "@/lib/hrefs"; +import type { RunnerView, StepView } from "@/lib/queue/view"; + +// THE DURABLE QUEUE (lib/queue/store.mjs), as a list: the runner (is the umtool +// app running it), then each step -- its qid, state, label, what it waits on, +// its error, its full log, and Cancel / Retry. Steps are added from a terminal +// (`umtool queue add -- <argv…>`), never here. +// +// Polls GET /api/queue every 3 s ONLY while a step is queued or running (an +// idle page makes no requests), and asks the page to refresh when a step +// finishes, so the render records beside it catch up. + +export const QUEUE_POLL_MS = 3000; + +const TONE: Record<StepView["state"], BadgeVariants["variant"]> = { + queued: "info", + running: "meter", + done: "on", + failed: "blocking", + blocked: "open", + cancelled: "state", +}; + +type View = { runner: RunnerView; steps: StepView[] }; + +const clock = (iso: string | null) => (iso ? iso.slice(11, 16) : ""); + +export default function QueuePanel({ initial, project = null, emptyText = "Nothing queued." }: { initial: View; project?: string | null; emptyText?: string }) { + const router = useRouter(); + const [view, setView] = useState<View>(initial); + const [said, setSaid] = useState<{ text: string; ok: boolean } | null>(null); + const [ready, setReady] = useState(false); + const inflight = useRef(false); + const current = useRef(view); + current.current = view; + useEffect(() => setReady(true), []); + useEffect(() => setView(initial), [initial]); + + const live = view.steps.some((s) => s.state === "queued" || s.state === "running"); + useEffect(() => { + if (!live) return; + const t = setInterval(async () => { + if (inflight.current || document.visibilityState === "hidden") return; + inflight.current = true; + try { + const r = await fetch(`/api/queue${project ? `?${new URLSearchParams({ project })}` : ""}`, { cache: "no-store" }); + if (!r.ok) return; + const next = (await r.json()) as View; + const moved = current.current.steps.some((s) => (s.state === "running" || s.state === "queued") && next.steps.find((n) => n.qid === s.qid)?.state !== s.state); + setView(next); + if (moved) router.refresh(); + } catch { + /* the next tick asks again */ + } finally { + inflight.current = false; + } + }, QUEUE_POLL_MS); + return () => clearInterval(t); + }, [live, project, router]); + + const act = async (op: "cancel" | "retry", qid: string) => { + const r = await fetch(`/api/queue?${new URLSearchParams({ [op]: qid })}`, { method: "POST", cache: "no-store" }); + const j = (await r.json().catch(() => ({}))) as { said?: string; error?: string }; + setSaid({ text: j.said ?? j.error ?? `HTTP ${r.status}`, ok: r.ok }); + const v = await fetch(`/api/queue${project ? `?${new URLSearchParams({ project })}` : ""}`, { cache: "no-store" }).then((x) => (x.ok ? x.json() : null)).catch(() => null); + if (v) setView(v as View); + router.refresh(); + }; + + const runner = view.runner; + return ( + <div className="space-y-1.5" data-queue="" data-queue-project={project ?? ""}> + <p className="m-0 text-[11.5px] text-text-2" data-queue-runner={runner.live ? "live" : "none"}> + {runner.live ? ( + <> + Run by the umtool app (pid {runner.pid}) one step at a time. + {runner.waiting ? <span className="text-[var(--color-dim)]"> {runner.waiting}.</span> : null} + </> + ) : ( + <span className="text-reject-text">No runner: nothing in the queue runs until the umtool app is up (archilyzer-umtool.service).</span> + )}{" "} + <span className="text-[var(--color-dim)]"> + Add steps from a terminal: <code className="font-mono">umtool queue add -- &lt;command…&gt;</code> + </span> + </p> + {said && ( + <p className={`m-0 text-[11.5px] ${said.ok ? "text-text-2" : "text-reject-text"}`} data-queue-said=""> + {said.text} + </p> + )} + {view.steps.length === 0 ? ( + <p className="m-0 text-[12px] text-[var(--color-dim)]" data-queue-empty=""> + {emptyText} + </p> + ) : ( + <ul className="m-0 list-none space-y-1 p-0"> + {view.steps.map((s) => ( + <li + key={s.qid} + data-queue-step={s.qid} + data-queue-state={s.state} + className={`space-y-0.5 rounded border px-2.5 py-1.5 text-[11.5px] ${s.state === "failed" || s.state === "blocked" ? "border-[var(--color-bad)]" : "border-seam"} bg-[var(--color-panel)]`} + > + <div className="flex flex-wrap items-baseline gap-2"> + <span className="font-mono text-text">{s.qid}</span> + <span className={badgeVariants({ variant: TONE[s.state], size: "sm" })}>{s.state}</span> + <span className="min-w-0 truncate" title={`umtool ${s.argv.join(" ")}`} data-queue-label=""> + {s.label} + </span> + {s.after && <span className="text-[11px] text-[var(--color-dim)]">after {s.after}</span>} + <span className="num text-[11px] text-[var(--color-dim)]" suppressHydrationWarning> + {s.startedAt ? `${clock(s.startedAt)}${s.endedAt ? `→${clock(s.endedAt)}` : ""}` : `queued ${clock(s.createdAt)}`} + {s.exitCode != null ? ` · exit ${s.exitCode}` : ""} + {s.attempts > 1 ? ` · attempt ${s.attempts}` : ""} + </span> + <span className="ml-auto inline-flex items-center gap-1.5"> + {s.startedAt && ( + <a href={queueLogHref(s.qid)} target="_blank" rel="noreferrer" className="ink-link text-[11px]" data-queue-log=""> + log + </a> + )} + {(s.state === "queued" || s.state === "blocked" || (s.state === "running" && !s.cancelRequested)) && ( + <button type="button" disabled={!ready} data-action="queue-cancel" className={buttonVariants({ variant: "outline", size: "sm" })} onClick={() => void act("cancel", s.qid)}> + Cancel + </button> + )} + {(s.state === "failed" || s.state === "cancelled") && ( + <button type="button" disabled={!ready} data-action="queue-retry" className={buttonVariants({ variant: "outline", size: "sm" })} onClick={() => void act("retry", s.qid)}> + Retry + </button> + )} + </span> + </div> + {s.error && ( + <p className="m-0 font-mono text-[11px] text-reject-text" data-queue-error=""> + {s.error} + </p> + )} + </li> + ))} + </ul> + )} + </div> + ); +} diff --git a/umtool/components/queue/RenderRecord.tsx b/umtool/components/queue/RenderRecord.tsx @@ -0,0 +1,86 @@ +import Link from "next/link"; +import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; +import { takeRenderLogHref, takesHref } from "@/lib/hrefs"; +import type { RenderView } from "@/lib/queue/view"; + +// A take's render RECORD (lib/report/renderRecord.mjs: takes/<id>/render.json, +// written by every render whoever started it), as one block: its state, its +// stage and percent while it runs, and when it failed the error, the log's +// last lines (folded) and the full log. Server-safe: no hooks. Used by the +// Takes panel (a take's card, a first render that failed) and /jobs. + +const TONE: Record<RenderView["state"], BadgeVariants["variant"]> = { + queued: "info", + waiting: "meter", + running: "meter", + done: "on", + failed: "blocking", + cancelled: "state", +}; + +const clock = (iso: string | null) => (iso ? iso.slice(0, 16).replace("T", " ") : ""); + +export default function RenderRecord({ + project, + rec, + showProject = false, + compact = false, +}: { + project: string; + rec: RenderView; + /** /jobs: the project's takes page, linked. */ + showProject?: boolean; + /** A take's card: one line, the tail folded. */ + compact?: boolean; +}) { + const live = rec.state === "running" || rec.state === "waiting"; + const bad = rec.state === "failed" || rec.state === "cancelled"; + return ( + <div + data-render-record={rec.take} + data-render-project={project} + data-render-state={rec.state} + className={`space-y-1 rounded border px-2.5 py-1.5 text-[11.5px] ${bad ? "border-[var(--color-bad)]" : "border-seam"} bg-[var(--color-panel)]`} + > + <div className="flex flex-wrap items-baseline gap-2"> + <span className={badgeVariants({ variant: TONE[rec.state], size: "sm" })} data-render-state-badge=""> + {rec.state === "failed" ? "render failed" : rec.state === "cancelled" ? "render cancelled" : `render ${rec.state}`} + </span> + {showProject && ( + <Link href={takesHref(project)} prefetch={false} className="ink-link font-mono"> + {project} + </Link> + )} + <span className="font-mono">{rec.take}</span> + {rec.label && !compact && <span className="text-text-2">{rec.label}</span>} + {live && ( + <span className="text-text-2" data-render-stage=""> + {rec.stage ?? "…"} + {rec.percent != null ? ` · ${rec.percent}%` : ""} + {rec.entries?.of ? ` · ${rec.entries.done}/${rec.entries.of} segments` : ""} + </span> + )} + <span className="num text-[11px] text-[var(--color-dim)]" suppressHydrationWarning> + {clock(rec.startedAt)} + {rec.endedAt ? ` → ${rec.endedAt.slice(11, 16)}` : ""} + {rec.exitCode != null ? ` · exit ${rec.exitCode}` : ""} + {rec.state === "done" && rec.seconds != null ? ` · ${rec.seconds.toFixed(1)} s` : ""} + </span> + <a href={takeRenderLogHref(project, rec.take)} target="_blank" rel="noreferrer" className="ink-link ml-auto text-[11px]" data-render-log=""> + log + </a> + </div> + {rec.error && ( + <p className="m-0 font-mono text-[11px] text-reject-text" data-render-error=""> + {rec.error} + </p> + )} + {bad && rec.tail?.length > 0 && ( + <details data-render-tail="" open={!compact}> + <summary className="cursor-pointer text-[11px] text-[var(--color-dim)]">the log&rsquo;s last {Math.min(rec.tail.length, 40)} lines</summary> + <pre className="m-0 mt-1 max-h-56 overflow-auto whitespace-pre-wrap break-all rounded bg-panel-2 p-1.5 text-[10.5px] leading-snug">{rec.tail.slice(-40).join("\n")}</pre> + </details> + )} + </div> + ); +} diff --git a/umtool/components/shell/RunningList.tsx b/umtool/components/shell/RunningList.tsx @@ -4,6 +4,7 @@ import Link from "next/link"; import { useEffect, useRef, useState } from "react"; import type { ActivityItem, RunningView } from "@/lib/activity-types"; import { JobProgressBar, JobProgressText } from "@/components/ui/job-progress"; +import { jobsHref } from "@/lib/hrefs"; // --------------------------------------------------------------------------- // The rail's foot (canvas `.running`): what is running, umtool's own and the @@ -120,7 +121,9 @@ export default function RunningList({ initial }: { initial: RunningView }) { > <h2 className="micro flex justify-between px-5 pb-2"> <span> - Running{" "} + <Link href={jobsHref()} prefetch={false} className="text-inherit no-underline hover:text-text" data-rail-jobs="" title="Jobs: the queue, every take render's record, the app's jobs"> + Running + </Link>{" "} <span className="font-mono normal-case tracking-normal text-meter" data-running-count={view.running}> {view.running} </span> diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -112,6 +112,10 @@ Inbox cannot disagree about what is wrong with one. | `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post-json:<json>\|post-json:@<file> [--id ID]` | **a post item made by hand** — a post no archive holds (one kept only as a picture): `{post: "<channel>/<postId>", author, handle, date, text, media: ["posts-media/…"], parents?, quoted?, subjects?, redact?}`, its media measured, its id `p-<postId>` unless `--id`; refused in the build's words (**exit 1**). Its avatar: `posts avatar <project> <handle> <file>` | | `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) | | `preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\|none> <project>` | the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`): a render block a manifest stands on (`"preset": "<name>"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build ([knobs.md](knobs.md#look-presets)) | +| `take status <project> [--id <take>] [--json] [--log] [--tail N]` | a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare "exited 1") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A "running" whose process is gone reads **failed** ("the render process is gone"); a done whose mp4 is missing or 0 bytes reads **failed**. **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 ([queue and poll](#queue-and-poll-instead-of-scripting)) | +| `queue add [--after <qid>\|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>` | a **step** of the durable queue: the argv of a umtool command, one word per argument (no shell), stored under `<reports root>/.umtool-queue/` and run by the **umtool app** (its systemd unit), one step at a time, in order — so it survives the session that queued it, an app restart and a ship. Prints the qid (`q<N>`) alone on stdout. `--after` waits for that step to be **done**; when it fails or is cancelled this one is **blocked** (and so is whatever waits on it). `--timeout`: the step's limit (default 720 minutes). A step does not start while the app's own job runner is busy (a Takes-page job), and a heavy step still takes the machine's heavy slot and render mode by itself | +| `queue ls [--all] [--json]` · `queue status <qid> [--json]` · `queue wait <qid> [--timeout <s>]` · `queue log <qid> [--tail N]` · `queue cancel <qid>` · `queue retry <qid>` | the queue: `ls` the runner (is the app running it) and the steps not finished or finished in the last 24 h; `status` one step (**exit 0 done · 3 queued or running · 1 failed, blocked or cancelled**); `wait` the same after up to `<s>` seconds (default 90); `log` its FULL log (`logs/<qid>.log`; earlier attempts kept as `<qid>.<n>.log`); `cancel` a queued or blocked step at once, a running one stopped (its process group); `retry` a failed or cancelled step back in the queue with every step blocked behind it. A step that was running when the app died reads **failed** ("the step's process is gone"), its log kept — it is never re-run on its own | +| `jobs [--json]` | every running and recent **take render** across projects (their records), 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). The page is **/jobs** (the rail's *Running* links it) | A project argument is an exact id, a directory, or a **unique** basename. Two projects answering to one name is reported, never resolved by picking one. @@ -144,8 +148,54 @@ from its cwd to `pnpm-workspace.yaml`. | `UMTOOL_BENCH_PREP` | unset = a fetch that lands and a write that moves or adds a clip queue the bench's prep (`prep`); `0` queues nothing (the triggers, `umtool prep` and the Cut tab's button; `prep --wait` still runs) | | `UMTOOL_PRUNE_KEEP`, `UMTOOL_PRUNE_DAYS` | the prune policy's newest-per-group (2) and age (`3d`) when neither `takes/prune.json` nor the command line says (`prune`) | | `UMTOOL_PRUNE_AFTER_BUILD` | unset = a take that is made prunes its project's takes by the policy after; `0` does not | +| `UMTOOL_QUEUE_DIR` | `<REPORTS_DIR>/.umtool-queue`: the durable queue's steps, logs, the runner's lease and the render pointers `jobs` reads ([queue and poll](#queue-and-poll-instead-of-scripting)) | +| `UMTOOL_QUEUE_RUNNER` | unset = the app runs the queue under `next start` (the live unit, the e2e suite's app) and not under `next dev`; `1` runs it anyway, `0` never. One runner per queue dir (its lease, `runner.json`) | | `UMTOOL_DISK_GUARD`, `UMTOOL_DISK_GUARD_GB`, `UMTOOL_DISK_FLOOR_GB` | before a render: under 30 GiB free it prunes every project's takes by policy, under 10 GiB it refuses the render; `UMTOOL_DISK_GUARD=0` turns it off | +## Queue and poll instead of scripting + +**Do not write a shell chain** (`umtool take … | grep | tail; echo DONE`, `until grep -q DONE …`). +mid-13's render died at exit 1 behind exactly that: the grep filtered the error away, the chain +printed DONE anyway, and the next chain read it as success. umtool records every render and runs +a queue; queue the steps, then poll umtool. + +```sh +# 1. Queue the steps (each prints its qid on stdout; the umtool app runs them, in order, one at a time). +q1=$(node umtool/bin/umtool.mjs queue add --label "render mid-14" -- take emberparadox/mr-obvious --id mid-14 --full --priority) +q2=$(node umtool/bin/umtool.mjs queue add --after "$q1" --label "list the takes" -- takes ls emberparadox/mr-obvious) + +# 2. Poll. Exit 0 = done, 3 = still queued or running, 1 = failed / blocked / cancelled. +node umtool/bin/umtool.mjs queue status "$q1" --json # one look: state, exitCode, error, log +node umtool/bin/umtool.mjs queue wait "$q1" --timeout 90 # or wait up to 90 s for it, same exits + +# 3. The render's own record (whoever started it -- the queue, the Takes page or a terminal). +node umtool/bin/umtool.mjs take status emberparadox/mr-obvious --id mid-14 --json +# .state .stage .percent .error .tail (the log's last 40 lines) .mp4 .seconds +node umtool/bin/umtool.mjs take status emberparadox/mr-obvious --id mid-14 --log --tail 80 + +# 4. Everything at once, across projects. +node umtool/bin/umtool.mjs jobs +``` + +- **`--after <qid>` means "when that one is DONE"**. If it fails (or is cancelled), every step + waiting on it is `blocked`, with the reason in `error`. Fix the cause, then + `umtool queue retry <qid>`: the failed step and everything blocked behind it go back in order. +- A step without `--after` does not wait for the step before it: it runs in its turn regardless. + `--after last` waits for the newest step in the queue. +- **Exit codes are the contract**: read the exit (or `.exit` in `--json`), never a word in the + output. A take's render is `done` only when it exited 0 AND wrote a non-empty mp4; a record + that says running while its process is gone reads `failed` ("the render process is gone"). +- A step that was running when the app stopped (a restart, a ship) is `failed` with its log — + never re-run silently. `umtool queue retry <qid>` runs it again. +- The runner is the umtool app. `umtool queue ls` says `runner: NONE` when the app is down: + the steps wait, nothing runs. +- `umtool queue log <qid>` is a step's full log; `take status … --log` is a render's + (`takes/<take>/render.log`). Both are the unfiltered output, nothing grepped. +- Heavy steps (renders) still take the machine's heavy slot and render mode by themselves: + `--priority` on the take, as by hand. Do not wrap a queued step in `pnpm heavy --`. +- The page is **/jobs** (the queue with Cancel and Retry, the take renders, the app's jobs); the + Takes page shows a take's render record and the project's queue. + ## `check` is the one to run before every build ``` diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1146,6 +1146,22 @@ clip); **not anchored** (written before anchors). Every write and undo is append | clamp a clipped beat; remove or re-point an orphan; anchor a beat that has been looked at | the beat's **Clamp to …**, **Remove the beat**, **Re-point**, **Looked at — anchor to <take>** (an edit or a confirm in the walk re-anchors too) | `trailer-beats <p> --reel R clamp <n>` · `repoint <n> <clip>` · `remove <n>` · `anchor [<n>…] --take <t>` · `--take <t>` on any edit | `{op: "set", index, patch, take}` · `{op: "anchor", only?, take}` | | what changed, when, against which take | -- | `trailer-beats <p> --reel R history [--json]` | `promo/<name>-beats.history.json` | +## Queue a chain of renders, then poll (no shell scripts) + +Every take render writes its own record, whoever started it: `takes/<take>/render.json` (its +state, stage, percent, the error and the log's last lines, the mp4 and its seconds) and the FULL +`takes/<take>/render.log`. A chain of steps — render this, then that, then pick — is the durable +queue the umtool app runs, not a shell loop. [cli.md](cli.md#queue-and-poll-instead-of-scripting) +has the walk-through; in short: + +| | From a terminal | In umtool | Route | +|---|---|---|---| +| queue a step (a umtool command's argv) | `umtool queue add [--after <qid>\|last] [--label T] -- <argv…>` → prints `q<N>` | — (a step is a command line: added from a terminal only) | — | +| one step: state, exit, error, log | `umtool queue status <qid> [--json]` (exit 0 done · 3 going · 1 failed/blocked/cancelled) · `queue wait <qid> --timeout 90` · `queue log <qid>` | **/jobs** → Queue, a step's **log** | `GET /api/queue` · `GET /api/queue/log?qid=` | +| cancel / retry | `umtool queue cancel <qid>` · `umtool queue retry <qid>` (with the steps blocked behind it) | **Cancel** / **Retry** on the step | `POST /api/queue?cancel=<qid>` · `?retry=<qid>` | +| a take's render record | `umtool take status <p> --id <take> [--json] [--log] [--tail N]` (exit 0 done · 3 queued/waiting/running · 1 failed) | the take's card (a render running now, or a later one that failed), **first render failed** above the takes, the project's **Queue** | `GET /api/report/takes/render?project=&take=` (`&log=1` the full log) | +| everything, across projects | `umtool jobs [--json]` | **/jobs** (the rail's *Running*) | `GET /api/queue`, `GET /api/jobs` | + ## Takes: relabel, supersede, cancel, delete, fork as variant, compare | | In umtool | From a terminal | Route | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1993,8 +1993,21 @@ umtool take <project> --id uncensored --label "Uncensored" --set render.blur=off umtool takes make <project> --recipe takes/recipe.json # or --all-styles umtool takes styles umtool takes pick <project> flash [--anyway] +umtool take status <project> --id flash [--json] # its render record: exit 0 done, 3 going, 1 failed +umtool queue add --after q3 -- take <project> --id crisp --set render.crf=34 --full # after q3 is done ``` +**Every render records itself** (`lib/report/renderRecord.mjs`), whoever started it — this page, +a terminal or the queue: `takes/<id>/render.json` (running, waiting at the heavy slot, done, +failed or cancelled; its stage and a rough percent; on failure the first error line and the log's +last 40 lines; on done the mp4 and its measured seconds) and the FULL `takes/<id>/render.log`. +`done` needs exit 0 and a non-empty mp4: a render that exits 0 with no picture, or an empty +one, fails the take before the old preview is replaced. A record that says running while its +process is gone reads failed. The take's card shows a render running now, or a later one that +failed (the take kept is the one before); a first render that failed is listed above the takes +with its error, its log and Delete. A chain of renders is the durable queue +([cli.md](cli.md#queue-and-poll-instead-of-scripting)), not a shell loop. + A take (`lib/report/takeMaker.mjs`): 1. reads the project's `video.manifest.json`, applies the style's patch diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -2287,6 +2287,21 @@ copyFileSync( path.join(TAKES_MAKE, "out", "clips-raw", "vid1_0.00-9.00.mp4"), ); +// queue-fixture: the durable queue and every render's own record (run-queue.spec.ts, 4 Nov +// 2026). One clip, its window cached (a take of it renders); no takes/ yet. The spec queues a +// take that renders, one that cannot (a clip nothing on disk covers) after it, and a step +// after that -- run by THIS suite's app over the fixture's own queue dir (.umtool-queue). +{ + const dir = writeProject( + "queue-fixture", + manifest("queue-fixture", "The Queue Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "clip", id: "m01", video: "vid1", start: 3, end: 6, cite: 3, section: 0, lock: true, quote: "and because" }, + ]), + ); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4")); +} + // -- THE VIDEO-NOTES AND TIMELINE FIXTURES ------------------------------------ // // video-notes-fixture is a GENERATED manifest (`generatedBy`) with a built cut diff --git a/umtool/e2e/run-queue.spec.ts b/umtool/e2e/run-queue.spec.ts @@ -0,0 +1,143 @@ +import { test, expect } from "@playwright/test"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// The apps do the work (operator, 4 Nov 2026): every take render records +// itself, and a durable queue the umtool app runs puts steps in order. +// +// umtool queue add -- take <p> --id good … q1, renders (the fixture's stubs) +// umtool queue add --after q1 -- take <p> --id broken --full --patch-json … +// q2, a clip nothing on disk covers: fails +// umtool queue add --after q2 -- takes ls <p> q3, blocked by q2's failure +// +// run by THIS suite's app (lib/queue/runner.ts, on under `next start`) over the +// fixture's own queue dir. Then the record (`umtool take status`), the Takes +// panel (the failed first render with its error and its log; the project's +// queue) and /jobs (the queue, the renders), and Cancel on the blocked step. +// +// Fixture: queue-fixture (make-fixture.mjs), which this spec WRITES (takes/). +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/queue-fixture"; + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +function cli(args: string[], base: string) { + const r = spawnSync("node", ["bin/umtool.mjs", ...args], { + cwd: path.join(HERE, ".."), + encoding: "utf8", + env: { ...process.env, REPORTS_DIR: FIXTURE, CHANNELS_DIR: path.join(FIXTURE, "channels"), UMTOOL_CACHE_DIR: path.join(FIXTURE, "cache"), UMTOOL_MEDIA_DIR: "", UMTOOL_URL: base }, + }); + return { code: r.status, out: r.stdout, err: r.stderr }; +} + +/** Poll `umtool queue status <qid>` until it is not 3 (still going). */ +async function settle(qid: string, base: string, ms = 180_000) { + const until = Date.now() + ms; + for (;;) { + const r = cli(["queue", "status", qid, "--json"], base); + if (r.code !== 3) return { code: r.code, step: JSON.parse(r.out) as { state: string; error: string | null; exitCode: number | null } }; + if (Date.now() > until) throw new Error(`${qid} still going after ${ms} ms: ${r.out}`); + await sleep(1000); + } +} + +test("a queued chain runs in order in the app; the failed render records itself; the Takes panel and /jobs show it", async ({ page, baseURL }) => { + test.setTimeout(300_000); + const base = String(baseURL); + + // The app runs the queue. + const ls = cli(["queue", "ls", "--json"], base); + expect(ls.code).toBe(0); + expect((JSON.parse(ls.out) as { runner: { live: boolean } | null }).runner?.live).toBe(true); + + const add = (args: string[]) => { + const r = cli(["queue", "add", ...args], base); + expect(r.code, r.err).toBe(0); + return r.out.trim(); + }; + const q1 = add(["--label", "the good take", "--", "take", PROJECT, "--id", "good", "--label", "Good"]); + const patch = JSON.stringify({ timeline: [{ type: "clip", id: "m09", video: "vid9", start: 1, end: 2, cite: 1, section: 0, lock: true, quote: "nothing here" }] }); + const q2 = add(["--after", q1, "--label", "the broken take", "--", "take", PROJECT, "--id", "broken", "--label", "Broken", "--full", "--patch-json", patch]); + const q3 = add(["--after", "last", "--", "takes", "ls", PROJECT]); + expect([q1, q2, q3]).toEqual([expect.stringMatching(/^q\d+$/), expect.stringMatching(/^q\d+$/), expect.stringMatching(/^q\d+$/)]); + + // While q2 waits, its take reads queued. + const early = cli(["take", "status", PROJECT, "--id", "broken", "--json"], base); + expect([3, 1]).toContain(early.code); // queued (3) -- or, on a fast machine, already failed (1) + + const s1 = await settle(q1, base); + expect(s1.code).toBe(0); + expect(s1.step.state).toBe("done"); + const s2 = await settle(q2, base); + expect(s2.code).toBe(1); + expect(s2.step.state).toBe("failed"); + expect(s2.step.error).toMatch(/take broken: /); + const s3 = await settle(q3, base, 20_000); + expect(s3.code).toBe(1); + expect(s3.step.state).toBe("blocked"); + expect(s3.step.error).toContain(`${q2}, which failed`); + + // The records, as a cheaper model polls them. + const good = cli(["take", "status", PROJECT, "--id", "good", "--json"], base); + expect(good.code).toBe(0); + const goodRec = JSON.parse(good.out) as { state: string; mp4: string; mp4Bytes: number }; + expect(goodRec.state).toBe("done"); + expect(goodRec.mp4).toBe("preview.mp4"); + expect(goodRec.mp4Bytes).toBeGreaterThan(0); + const broken = cli(["take", "status", PROJECT, "--id", "broken", "--json"], base); + expect(broken.code).toBe(1); + const rec = JSON.parse(broken.out) as { state: string; error: string; tail: string[]; exitCode: number }; + expect(rec.state).toBe("failed"); + expect(rec.exitCode).toBe(1); + expect(rec.error).toMatch(/m09/); + expect(rec.tail.length).toBeGreaterThan(0); + + // The Takes panel: the failed first render, in the open, with its error and its log; the project's queue. + await page.goto(urls.takesHref(PROJECT)); + const failed = page.locator("[data-take-failed='broken']"); + await expect(failed).toBeVisible(); + await expect(failed.locator("[data-render-state='failed'] [data-render-error]")).toContainText("m09"); + const logHref = await failed.locator("[data-render-log]").getAttribute("href"); + const log = await page.request.get(String(logHref)); + expect(log.status()).toBe(200); + expect(await log.text()).toMatch(/# failed — .*m09/); + await expect(page.locator("[data-take='good']")).toBeVisible(); + const queue = page.locator("[data-takes-queue]"); + await expect(queue.locator(`[data-queue-step='${q1}']`)).toHaveAttribute("data-queue-state", "done"); + await expect(queue.locator(`[data-queue-step='${q2}']`)).toHaveAttribute("data-queue-state", "failed"); + await expect(queue.locator(`[data-queue-step='${q2}'] [data-queue-error]`)).toContainText("take broken"); + await expect(queue.locator(`[data-queue-step='${q3}']`)).toHaveAttribute("data-queue-state", "blocked"); + const stepLog = await page.request.get(String(await queue.locator(`[data-queue-step='${q2}'] [data-queue-log]`).getAttribute("href"))); + expect(stepLog.status()).toBe(200); + expect(await stepLog.text()).toContain(`# queue ${q2} attempt 1: the broken take`); + + // /jobs: the queue and the renders, across projects; the rail's Running links it (the Takes page is a bench: no rail). + await page.goto("/"); + await page.locator("[data-rail-jobs]").click(); + await expect(page).toHaveURL(/\/jobs$/); + await expect(page.locator("[data-queue-runner='live']")).toBeVisible(); + await expect(page.locator(`[data-panel='queue'] [data-queue-step='${q2}']`)).toHaveAttribute("data-queue-state", "failed"); + await expect(page.locator(`[data-panel='renders'] [data-render-record='broken']`)).toHaveAttribute("data-render-state", "failed"); + await expect(page.locator(`[data-panel='renders'] [data-render-record='broken'] [data-render-error]`)).toContainText("m09"); + await expect(page.locator(`[data-panel='renders'] [data-render-record='good']`)).toHaveAttribute("data-render-state", "done"); + + // Cancel the blocked step from the page: cancelled, and the CLI agrees. + await page.locator(`[data-panel='queue'] [data-queue-step='${q3}'] [data-action='queue-cancel']`).click(); + await expect(page.locator(`[data-panel='queue'] [data-queue-step='${q3}']`)).toHaveAttribute("data-queue-state", "cancelled"); + const after = cli(["queue", "status", q3, "--json"], base); + expect(after.code).toBe(1); + expect((JSON.parse(after.out) as { state: string }).state).toBe("cancelled"); + + // `umtool jobs` lists them all. + const jobs = cli(["jobs", "--json"], base); + expect(jobs.code).toBe(0); + const j = JSON.parse(jobs.out) as { queue: { steps: { qid: string }[] }; renders: { take: string; state: string }[] }; + expect(j.queue.steps.map((s) => s.qid)).toEqual(expect.arrayContaining([q1, q2, q3])); + expect(j.renders.find((r) => r.take === "broken")?.state).toBe("failed"); +}); 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/hrefs.ts b/umtool/lib/hrefs.ts @@ -187,6 +187,21 @@ export function settingsHref(): string { return "/settings"; } +/** Jobs: the durable queue (lib/queue/), the take renders' records, and the app's own jobs. */ +export function jobsHref(): string { + return "/jobs"; +} + +/** A queue step's full log, as text (GET /api/queue/log). */ +export function queueLogHref(qid: string, attempt: number | null = null): string { + return withQuery("/api/queue/log", { qid, ...(attempt ? { attempt: String(attempt) } : {}) }); +} + +/** A take render's full log, takes/<take>/render.log, as text (GET /api/report/takes/render). */ +export function takeRenderLogHref(project: string, take: string): string { + return withQuery("/api/report/takes/render", { project, take, log: "1" }); +} + /** Settings: the machine -- tools, disk, index, sources, deliverables, recent jobs. */ export function systemHref(): string { return "/settings/system"; 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,413 @@ +// `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)); + // The newest queue step that renders this take, and whether the record is of its run or older. + const step = steps.filter((s) => s.target.take === id).at(-1) ?? null; + const stepAt = step ? Date.parse(step.startedAt ?? step.createdAt) : NaN; + const recIsOlder = !rec || Date.parse(rec.startedAt) < stepAt; + const recLive = rec && (rec.state === "running" || rec.state === "waiting"); + let row; + const fromStep = (state, exit, error = null) => ({ + project: project.id, + take: id, + state, + queue: { qid: step.qid, state: step.state, after: step.after, error: step.error }, + error, + previous: rec, + exit, + }); + // A step still to run renders this take again, whatever an earlier run recorded (a render live now speaks for itself). + if (step && !recLive && step.state === "queued") row = fromStep("queued", 3); + else if (step && !recLive && step.state === "blocked") row = fromStep("blocked", 1, step.error); + // Started, its take process not yet writing its own record (a second of setup): running, never the last run's word. + else if (step && recIsOlder && step.state === "running") row = { ...fromStep("running", 3), stage: "starting" }; + // Ended without a record of its own (refused before the take's directory existed): the step says why. + else if (step && recIsOlder && (step.state === "failed" || step.state === "cancelled")) row = fromStep(step.state, 1, step.error); + 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 | null; 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 ?? UMTOOL_DIR, + 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,596 @@ +// 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}$/; +/** @param {unknown} v @returns {v is string} */ +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`); +/** @param {string} dir @param {string} qid @param {number | null} [attempt] */ +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, + // Where it was queued from (relative paths in its argv resolve there); the runner's own dir when unsaid. + cwd: o.cwd ?? null, + 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,324 @@ +// 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"); + // The runner starts it; its take process has not written its record yet: running (never an older run's word). + const { openRenderRecord } = await import("../report/renderRecord.mjs"); + const step = /** @type {any} */ (await getStep(dir, "q1")); + await writeFile(stepFile(dir, "q1"), JSON.stringify({ ...step, state: "running", startedAt: new Date().toISOString(), pid: process.pid, host: os.hostname() })); + lines.length = 0; + assert.equal(await status(), 3); + assert.equal(JSON.parse(lines.join("\n")).stage, "starting"); + // Its render recorded failed (this attempt's record): failed, exit 1. + 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$/); + // A later step that failed with no record of its own (refused before the take's directory): the step's error. + const q2 = await addStep(dir, { argv: ["take", "demo", "--id", "t1"], target: { project: "demo", take: "t1" } }); + await sleep(5); + await writeFile(stepFile(dir, q2.qid), JSON.stringify({ ...q2, state: "failed", startedAt: new Date().toISOString(), endedAt: new Date().toISOString(), exitCode: 2, error: "--id <id>: the take's directory name (exit 2)" })); + lines.length = 0; + assert.equal(await status(), 1); + assert.match(JSON.parse(lines.join("\n")).error, /--id <id>/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/queue/view.ts b/umtool/lib/queue/view.ts @@ -0,0 +1,85 @@ +import path from "node:path"; +import { readRenderRecord } from "@/lib/report/renderRecord.mjs"; +import { recentRenders } from "./cli.mjs"; +import { queueDir, queueRunnerStatus } from "./runner"; +import { listSteps, readLease, resolveStep, TERMINAL } from "./store.mjs"; + +// --------------------------------------------------------------------------- +// What the pages show of the queue and the render records (/jobs, the Takes +// panel, GET /api/queue): read from the queue dir and the takes' own +// render.json, resolved as the CLI resolves them (a running step or render +// whose process is gone reads failed). SERVER ONLY. +// --------------------------------------------------------------------------- + +export type StepView = { + qid: string; + label: string; + argv: string[]; + state: "queued" | "running" | "done" | "failed" | "blocked" | "cancelled"; + after: string | null; + target: { project: string | null; take: string | null } | null; + createdAt: string; + startedAt: string | null; + endedAt: string | null; + exitCode: number | null; + error: string | null; + blockedBy: string | null; + attempts: number; + cancelRequested: { at: string; by: string } | null; +}; + +export type RenderView = { + project: string | null; + take: string; + label: string | null; + state: "queued" | "waiting" | "running" | "done" | "failed" | "cancelled"; + startedAt: string; + endedAt: string | null; + exitCode: number | null; + stage: string | null; + percent: number | null; + entries?: { done: number; of: number | null }; + error: string | null; + tail: string[]; + mp4: string | null; + seconds: number | null; + pid: number; + gone?: boolean; +}; + +export type RunnerView = { live: boolean; pid: number | null; since: string | null; here: boolean; waiting: string | null; lastError: string | null }; + +const DAY_MS = 86_400_000; + +/** The queue: the runner, and the steps (not finished, or finished in the last day; `all` every one). */ +export async function queueView({ project = null, all = false }: { project?: string | null; all?: boolean } = {}) { + const dir = queueDir(); + const status = queueRunnerStatus(); + const owned = new Set(status.running); + const [lease, raw] = await Promise.all([readLease(dir), listSteps(dir)]); + const cutoff = Date.now() - DAY_MS; + const steps = (raw as StepView[]) + .map((s) => resolveStep(s, { owned }) as StepView) + .filter((s) => all || !TERMINAL.has(s.state) || Date.parse(s.endedAt ?? s.createdAt) > cutoff) + .filter((s) => !project || s.target?.project === project) + .reverse(); + const runner: RunnerView = { + live: !!lease?.live, + pid: lease?.pid ?? null, + since: lease?.since ?? null, + here: !!lease?.live && lease.pid === process.pid, + waiting: status.waiting, + lastError: status.lastError, + }; + return { dir, runner, steps }; +} + +/** The recent take renders across projects (the queue dir's pointers). */ +export async function rendersView(): Promise<RenderView[]> { + return (await recentRenders(queueDir())) as unknown as RenderView[]; +} + +/** One take's render record, resolved, or null. */ +export async function takeRender(projectDir: string, take: string): Promise<RenderView | null> { + return (await readRenderRecord(path.join(/* turbopackIgnore: true */ projectDir, "takes", take))) as RenderView | null; +} 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/takeCancel.mjs b/umtool/lib/report/takeCancel.mjs @@ -134,19 +134,23 @@ export async function readCancelled(projectDir, takeId) { /** * The take directories that are not (or not yet) takes: a first render in - * progress (a live build lock, no take.json) and a first render cancelled - * (cancelled.json, no take.json). What the Takes page lists beside the takes: - * the first with Cancel, the second folded away with Delete. + * progress (a live build lock, no take.json), a first render cancelled + * (cancelled.json, no take.json) and a first render that FAILED (its own + * record, renderRecord.mjs, says failed -- or says running and its process is + * gone). What the Takes page lists beside the takes: the first with Cancel, + * the second folded away with Delete, the third in the open with its error. * * @param {string} projectDir * @param {{ host?: string, alive?: (pid: number) => boolean }} [opts] - * @returns {Promise<{ rendering: Array<{ id: string, label: string | null, pid: number | null, startedAt: string | null, from: string | null }>, cancelled: Array<{ id: string, label: string | null, at: string, by: string }> }>} + * @returns {Promise<{ rendering: Array<{ id: string, label: string | null, pid: number | null, startedAt: string | null, from: string | null }>, cancelled: Array<{ id: string, label: string | null, at: string, by: string }>, failed: Array<{ id: string, label: string | null, record: any }> }>} */ export async function takeWorkDirs(projectDir, opts = {}) { const root = takesDirOf(projectDir); const names = await readdir(root).catch(() => []); const rendering = []; const cancelled = []; + const failed = []; + const { readRenderRecord } = await import("./renderRecord.mjs"); for (const id of names.sort()) { if (!isTakeId(id)) continue; const dir = path.join(root, id); @@ -158,9 +162,14 @@ export async function takeWorkDirs(projectDir, opts = {}) { continue; } const c = await readCancelled(projectDir, id); - if (c) cancelled.push({ id, label: c.label ?? null, at: c.at, by: c.by ?? "" }); + if (c) { + cancelled.push({ id, label: c.label ?? null, at: c.at, by: c.by ?? "" }); + continue; + } + const rec = await readRenderRecord(dir); + if (rec && rec.state === "failed") failed.push({ id, label: rec.label ?? null, record: rec }); } - return { rendering, cancelled }; + return { rendering, cancelled, failed }; } const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); 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. */