commit ddef84dd012e93a99454665c1d174ed6907b9b9b
parent 11d213c1db2b49e207f563c03ada665fb05e4265
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 19 Oct 2026 12:26:32 -0400
umtool: `umtool build <project> --run` — the app's build job over HTTP, followed, Ctrl-C cancels
lib/report/buildRun.mjs runBuildOverHttp: POST /api/report/build on --url / UMTOOL_URL / localhost:3050
(?replace=1 with --replace), the log polled as it grows, SIGINT posts ?cancel=; exit 1 unless done.
Without --run the command prints the chain as before. buildRun.test.mjs: 3 tests against a fake app.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
3 files changed, 180 insertions(+), 1 deletion(-)
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -25,6 +25,7 @@
// [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent
// umtool corrections <project> what the report got wrong, as markdown for the next pass
// umtool build <project> [--preset preview|fast|final] [--only ID] [--dry]
+// [--run [--url URL] [--replace]] run it as the app's job, follow it, Ctrl-C cancels
// umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]
// [--draft-all [--model M] [--deck]]
// an iteration's pipeline: current, windows, prepare, posts, manifest,
@@ -88,6 +89,7 @@ import { updateClip, updateStorage } from "../lib/report/manifest.mjs";
import { withEditNotes } from "../lib/report/edit-guard.mjs";
import { hms } from "umtool-report-to-video/attribution";
import { buildSteps, checkSourcesSteps, PRESETS } from "../lib/report/driver.mjs";
+import { runBuildOverHttp, umtoolBase } from "../lib/report/buildRun.mjs";
import { CHAIN_STEP_NAMES, chainStepsOf, planChain } from "../lib/report/chain.mjs";
import { spawn } from "node:child_process";
import { openIndex, signRecord } from "../lib/projects/index-db.mjs";
@@ -698,6 +700,8 @@ function usage() {
" an empty value (--title '') deletes the field",
" umtool corrections <project> what the report got wrong + the walk's coverage",
" umtool build <project> [--preset preview|fast|final] [--only ID]",
+ " --run: the app's build job (UMTOOL_URL, else http://localhost:3050; --url), followed here;",
+ " Ctrl-C cancels it; --replace stamps a newer deliverable aside",
" umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]",
` an article iteration's pipeline, one step a process: ${CHAIN_STEP_NAMES.join(", ")}`,
" (resumes at the first step not done; --dry prints it; the project is <root>/<article>/i<n>/)",
@@ -1002,7 +1006,33 @@ async function cmdBuild() {
clipCount,
});
- if (json) return out({ project: p.id, preset, steps });
+ if (json && !has("--run")) return out({ project: p.id, preset, steps });
+
+ // --run (release 36): the app runs the chain -- its job runner owns the
+ // cancellation, the timeouts and the process-group kill -- and this follows it.
+ if (has("--run")) {
+ const base = umtoolBase(val("--url"));
+ let cancel = null;
+ let stopping = false;
+ process.on("SIGINT", async () => {
+ if (stopping || !cancel) process.exit(130);
+ stopping = true;
+ console.error("\ncancelling the build job (Ctrl-C again to leave it running)…");
+ const ok = await cancel().catch(() => false);
+ console.error(ok ? "cancel requested; waiting for the job to stop" : "the job did not take the cancel");
+ });
+ const r = await runBuildOverHttp({
+ base, project: p.id, preset, only: val("--only") ?? null, skipFetch: has("--skip-fetch"), replace: has("--replace"),
+ token: process.env.WORKER_TOKEN ?? null,
+ log: (l) => (json ? null : console.log(l)),
+ onJob: (c) => {
+ cancel = c;
+ },
+ });
+ if (json) out(r);
+ if (r.state === "done") return;
+ die(r.needsReplace ? `${r.error} (--replace)` : `build ${r.state}${r.error ? `: ${r.error}` : ""}`, 1);
+ }
// Print, never run. The app runs the chain through lib/jobs.ts, which owns the
// cancellation, the timeouts and the process-group kill; a second runner here
diff --git a/umtool/lib/report/buildRun.mjs b/umtool/lib/report/buildRun.mjs
@@ -0,0 +1,63 @@
+// `umtool build <project> --run` (release 36 lane C): the build chain as the
+// project page runs it -- a job on the running umtool app's runner (POST
+// /api/report/build), followed from the terminal (its log, polled), cancelled
+// on Ctrl-C (POST ?cancel=<job>). The app owns the steps, the timeouts, the
+// process-group kill and the heavy slot; this only asks and watches. Without
+// `--run` the command prints the chain, as before.
+//
+// Plain ESM: the CLI runs under bare node.
+
+/** Where the app answers: `--url`, else UMTOOL_URL, else the local default. */
+export const umtoolBase = (url, env = process.env) => String(url || env.UMTOOL_URL || "http://localhost:3050").replace(/\/+$/, "");
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Start the build and follow it to the end.
+ *
+ * @param {{ base: string, project: string, preset?: string, only?: string | null, skipFetch?: boolean,
+ * replace?: boolean, token?: string | null, pollMs?: number, fetchImpl?: typeof fetch,
+ * log?: (line: string) => void, onJob?: (cancel: () => Promise<boolean>) => void }} o
+ * @returns {Promise<{ state: string, job: string | null, error: string | null, needsReplace?: boolean }>}
+ */
+export async function runBuildOverHttp({
+ base, project, preset = "fast", only = null, skipFetch = false, replace = false, token = null,
+ pollMs = 1500, fetchImpl = fetch, log = (l) => console.log(l), onJob = () => {},
+}) {
+ const headers = { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) };
+ const call = async (method, route, body) => {
+ try {
+ const res = await fetchImpl(`${base}${route}`, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });
+ return { status: res.status, json: await res.json().catch(() => ({})) };
+ } catch (err) {
+ return { status: 0, json: { error: `umtool at ${base} did not answer: ${err?.message ?? err}` } };
+ }
+ };
+ const started = await call("POST", `/api/report/build${replace ? "?replace=1" : ""}`, { project, preset, ...(only ? { only } : {}), ...(skipFetch ? { skipFetch: true } : {}) });
+ if (started.status !== 200 || !started.json?.job?.id) {
+ const j = started.json ?? {};
+ return { state: "refused", job: null, error: String(j.error ?? `HTTP ${started.status}`), ...(j.needsReplace ? { needsReplace: true } : {}) };
+ }
+ const id = started.json.job.id;
+ log(`job ${id}: ${started.json.job.kind ?? "build"}`);
+ for (const s of started.json.steps ?? []) log(` step: ${s.label}`);
+ onJob(async () => (await call("POST", `/api/report/build?cancel=${encodeURIComponent(id)}`)).json?.cancelled === true);
+ let since = 0;
+ let sinceEvent = 0;
+ let misses = 0;
+ for (;;) {
+ const r = await call("GET", `/api/report/build?job=${encodeURIComponent(id)}&since=${since}&sinceEvent=${sinceEvent}`);
+ if (r.status !== 200) {
+ misses += 1;
+ if (misses >= 40) return { state: "lost", job: id, error: String(r.json?.error ?? `HTTP ${r.status}`) };
+ await sleep(pollMs);
+ continue;
+ }
+ misses = 0;
+ for (const line of r.json.log ?? []) log(line);
+ since = Number.isFinite(r.json.next) ? r.json.next : since + (r.json.log?.length ?? 0);
+ if (Number.isFinite(r.json.nextEvent)) sinceEvent = r.json.nextEvent;
+ if (r.json.state !== "running") return { state: r.json.state, job: id, error: r.json.error ?? null };
+ await sleep(pollMs);
+ }
+}
diff --git a/umtool/lib/report/buildRun.test.mjs b/umtool/lib/report/buildRun.test.mjs
@@ -0,0 +1,86 @@
+// `umtool build --run` (release 36 lane C): the build route as the CLI asks
+// it -- started, followed (the log as it grows), cancelled, refused -- against
+// a fake app on a local port. Synthetic.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import http from "node:http";
+import test from "node:test";
+
+import { runBuildOverHttp, umtoolBase } from "./buildRun.mjs";
+
+/** A fake umtool: the build route's POST, GET ?job= and ?cancel=. */
+async function fakeApp(handler) {
+ const seen = [];
+ const server = http.createServer(async (req, res) => {
+ let body = "";
+ for await (const c of req) body += c;
+ const url = new URL(req.url, "http://x");
+ seen.push({ method: req.method, path: url.pathname, query: Object.fromEntries(url.searchParams), body: body ? JSON.parse(body) : null, auth: req.headers.authorization ?? null });
+ const [status, json] = handler(seen.at(-1), seen);
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(json));
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const base = `http://127.0.0.1:${server.address().port}`;
+ return { base, seen, close: () => new Promise((r) => server.close(r)) };
+}
+
+test("umtoolBase: --url, else UMTOOL_URL, else the local default; no trailing slash", () => {
+ assert.equal(umtoolBase("http://h:1/", {}), "http://h:1");
+ assert.equal(umtoolBase(undefined, { UMTOOL_URL: "http://u:2//" }), "http://u:2");
+ assert.equal(umtoolBase(undefined, {}), "http://localhost:3050");
+});
+
+test("runBuildOverHttp: starts the job, prints its log as it grows, ends with its state", async () => {
+ let polls = 0;
+ const app = await fakeApp((r) => {
+ if (r.method === "POST" && !r.query.cancel) return [200, { ok: true, job: { id: "j1", kind: "build reports/x (fast)" }, steps: [{ label: "check" }, { label: "build" }] }];
+ if (r.method === "GET") {
+ polls += 1;
+ const log = ["line 1", "line 2", "line 3"];
+ const since = Number(r.query.since);
+ return polls < 3
+ ? [200, { state: "running", log: log.slice(since, polls), next: polls, nextEvent: polls * 2, error: null }]
+ : [200, { state: "done", log: log.slice(since), next: 3, nextEvent: 6, error: null }];
+ }
+ return [404, {}];
+ });
+ try {
+ const lines = [];
+ const r = await runBuildOverHttp({ base: app.base, project: "reports/x", preset: "final", only: null, token: "tok", pollMs: 5, log: (l) => lines.push(l) });
+ assert.deepEqual(r, { state: "done", job: "j1", error: null });
+ assert.deepEqual(lines, ["job j1: build reports/x (fast)", " step: check", " step: build", "line 1", "line 2", "line 3"]);
+ assert.deepEqual(app.seen[0].body, { project: "reports/x", preset: "final" });
+ assert.equal(app.seen[0].auth, "Bearer tok");
+ // Each poll asks only for what it has not seen.
+ assert.deepEqual(app.seen.slice(1).map((s) => [s.query.since, s.query.sinceEvent]), [["0", "0"], ["1", "2"], ["2", "4"]]);
+ } finally {
+ await app.close();
+ }
+});
+
+test("runBuildOverHttp: a newer deliverable is refused until --replace; a running job is named; Ctrl-C cancels", async () => {
+ const app = await fakeApp((r) => {
+ if (r.method === "POST" && r.query.cancel) return [200, { cancelled: true }];
+ if (r.method === "POST" && r.query.replace !== "1") return [409, { error: "x.mp4 is newer than the manifest", needsReplace: true }];
+ if (r.method === "POST") return [200, { ok: true, job: { id: "j2", kind: "build" } }];
+ return [200, { state: "failed", log: ["** cancel requested"], next: 1, error: "cancelled" }];
+ });
+ try {
+ const refused = await runBuildOverHttp({ base: app.base, project: "reports/x", log: () => {} });
+ assert.deepEqual(refused, { state: "refused", job: null, error: "x.mp4 is newer than the manifest", needsReplace: true });
+ let cancel = null;
+ const r = await runBuildOverHttp({ base: app.base, project: "reports/x", replace: true, skipFetch: true, only: "c1", pollMs: 5, log: () => {}, onJob: (c) => (cancel = c) });
+ assert.equal(r.state, "failed");
+ assert.equal(r.error, "cancelled");
+ assert.deepEqual(app.seen[1].body, { project: "reports/x", preset: "fast", only: "c1", skipFetch: true });
+ assert.equal(await cancel(), true);
+ assert.equal(app.seen.at(-1).query.cancel, "j2");
+ } finally {
+ await app.close();
+ }
+ const gone = await runBuildOverHttp({ base: "http://127.0.0.1:9", project: "p", log: () => {} });
+ assert.equal(gone.state, "refused");
+ assert.match(gone.error, /did not answer/);
+});