commit d7294ce608809aba7a808fbd9aad507ca8365e44
parent a07a830a4c96e2220fb9f564df115f4294f3e61b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 11:00:06 -0400
umtool: the pipeline chain over an article's iteration, the parent seed and the dedupe (release 27 S7)
lib/report/chain.mjs plans the chain — current, windows, prepare, posts,
manifest, voices, video, podcast, attach, dedupe — as lib/jobs.ts steps, one
process each (`node --import tsx lib/report/chain-run.mjs step <id> <n>
<step>`), resuming at the first step the iteration has not recorded done
(planChain, chainStart, chainSteps). chainWindows asks the editor for every
cited window padded to the cut's fetchPad and the citation's own pad, so one
fetch serves the evidence clips and the cut. No secret rides in a step.
lib/report/chain-run.mjs executes one: makeCurrent; the editor's
fetch-windows and capture-posts through `pnpm ops`; `reports prepare --article
--only`; to-manifest into `<projectsRoot>/<id>/i<n>/` with the lineage's sweep
origin, seeded from the parent's project; narrate-via-editor; build-video
--skip-fetch and verify-build; build-podcast; attach-video, the iteration
recorded as the article's video, reports check; dedupe. Each records itself in
the iteration's steps (`chain:<step>`) through the registry.
lib/report/iterations.mjs: seedFromParent (narration by id, else heading;
voices hard-linked) and dedupeMedia (segments and voices only, the files no
tool writes in place). `umtool chain <article> <n> [--from] [--dry] [--final]`.
The S0 kit's derive.ts and regenerate.ts get Turbopack's opt-out on their
module-relative paths (the next-build-trace scan reaches common/testing).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 1250 insertions(+), 9 deletions(-)
diff --git a/common/testing/draft/derive.ts b/common/testing/draft/derive.ts
@@ -8,7 +8,7 @@ import { sweepToReport } from "../../lib/report/convertSweep";
import { reportToManifest, type PostOf } from "../../lib/report/convertManifest";
import { cuesOf, ORIGIN, POSTS } from "./corpus.mjs";
-const HERE = path.dirname(fileURLToPath(import.meta.url));
+const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url));
export const SWEEPS = ["basic", "quotes-in-claims", "multi-quote", "posts-only", "paragraphs", "inexact"] as const;
export type SweepName = (typeof SWEEPS)[number];
@@ -16,7 +16,7 @@ export type SweepName = (typeof SWEEPS)[number];
// The sweeps whose report and manifest are committed.
export const DERIVED = ["basic", "posts-only", "paragraphs"] as const satisfies readonly SweepName[];
-export const readSweep = (name: SweepName) => readFile(path.join(HERE, "sweeps", `${name}.md`), "utf8");
+export const readSweep = (name: SweepName) => readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ HERE, "sweeps", `${name}.md`), "utf8");
export const postOf: PostOf = async (channel, id) => {
const p = POSTS.find((x) => x.channelSlug === channel && x.id === id);
diff --git a/common/testing/draft/regenerate.ts b/common/testing/draft/regenerate.ts
@@ -8,13 +8,13 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { DERIVED, deriveFixture } from "./derive";
-const HERE = path.dirname(fileURLToPath(import.meta.url));
+const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url));
for (const name of DERIVED) {
const { report, manifest } = await deriveFixture(name);
- await mkdir(path.join(HERE, "reports"), { recursive: true });
- await mkdir(path.join(HERE, "manifests"), { recursive: true });
- await writeFile(path.join(HERE, "reports", `${name}.report.json`), JSON.stringify(report, null, 2) + "\n");
- await writeFile(path.join(HERE, "manifests", `${name}.video.manifest.json`), JSON.stringify(manifest, null, 2) + "\n");
+ await mkdir(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ HERE, "reports"), { recursive: true });
+ await mkdir(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ HERE, "manifests"), { recursive: true });
+ await writeFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ HERE, "reports", `${name}.report.json`), JSON.stringify(report, null, 2) + "\n");
+ await writeFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ HERE, "manifests", `${name}.video.manifest.json`), JSON.stringify(manifest, null, 2) + "\n");
console.log(`wrote ${name}`);
}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -23,6 +23,9 @@
// [--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]
+// umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]
+// an iteration's pipeline: current, windows, prepare, posts, manifest,
+// voices, video, podcast, attach, dedupe (resumes at the first step not done)
// umtool index [--rebuild] [--prune] [--since MS] [--json]
// umtool new <slug> [--kind report-video] [--from <report.md>|<share URL>|<channel>/<id>]
// [--site-origin URL] [--seed chapters] [--brand archilyzer-media]
@@ -66,12 +69,14 @@ 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 { CHAIN_STEP_NAMES, planChain } from "../lib/report/chain.mjs";
+import { spawn } from "node:child_process";
import { openIndex, signRecord } from "../lib/projects/index-db.mjs";
import { pipelineProcessesFor } from "../lib/report/busy.mjs";
import { probeTools } from "../lib/tools.mjs";
import { notesCommand } from "../lib/annotations/cli.mjs";
import { scaffoldReportVideo } from "../lib/projects/scaffold.mjs";
-import { CACHE_DIR, INDEX_DIR, MEDIA_ROOT, MEDIA_TIERED, OLD_CACHE_DIR } from "../lib/paths.mjs";
+import { ARTICLES_DIR, CACHE_DIR, INDEX_DIR, MEDIA_ROOT, MEDIA_TIERED, OLD_CACHE_DIR } from "../lib/paths.mjs";
import {
deliverablesState,
measureTree,
@@ -690,6 +695,9 @@ 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]",
+ " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]",
+ ` 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>/)",
" umtool index [--rebuild] [--prune] [--since MS] [--json]",
" umtool new <slug> [--from <report.md>|<share URL>|<channel>/<id>] [--site-origin URL] [--seed chapters]",
" [--brand archilyzer-media] render.brand: the report-to-video brand preset",
@@ -719,6 +727,7 @@ const COMMANDS = {
window: cmdWindow,
corrections: cmdCorrections,
build: cmdBuild,
+ chain: cmdChain,
index: cmdIndex,
new: cmdNew,
show: cmdShow,
@@ -924,6 +933,60 @@ async function cmdBuild() {
}
}
+/**
+ * `umtool chain <article> <n>` — an iteration's pipeline (lib/report/chain.mjs),
+ * the same steps the app runs as a job, here one after another in the
+ * foreground, each a process whose output is this one's. Resumes at the first
+ * step the iteration has not recorded done; `--from` names one; `--dry`
+ * prints the steps and runs nothing. Stops at the first step that fails.
+ */
+async function cmdChain() {
+ const article = positional[0];
+ const n = Number(positional[1]);
+ if (!article || !Number.isInteger(n) || n < 1) {
+ die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]");
+ }
+ let plan;
+ try {
+ plan = planChain({
+ articlesDir: ARTICLES_DIR,
+ article,
+ n,
+ from: val("--from") ?? null,
+ ...(val("--projects-root") ? { projectsRoot: path.resolve(val("--projects-root")) } : {}),
+ ...(val("--site-origin") ? { siteOrigin: val("--site-origin") } : {}),
+ final: has("--final"),
+ });
+ } catch (err) {
+ die(err.message);
+ }
+ const { start, steps } = plan;
+ if (json && has("--dry")) return out({ article, n, start, steps });
+ if (steps.length === 0) {
+ console.log(`${article} i${n}: every step of the chain is done (--from <step> runs one again)`);
+ return;
+ }
+ console.log(`# ${article} i${n} — the chain from "${start}"`);
+ for (const s of steps) {
+ console.log(`# ${s.label}`);
+ if (has("--dry")) console.log(`(cd ${s.cwd} && ${s.argv.join(" ")})\n`);
+ }
+ if (has("--dry")) return;
+ for (const s of steps) {
+ console.log(`\n== ${s.label}`);
+ const code = await new Promise((resolve) => {
+ const child = spawn(s.argv[0], s.argv.slice(1), { cwd: s.cwd, env: { ...process.env, ...s.env }, stdio: "inherit" });
+ child.on("error", () => resolve(1));
+ child.on("exit", (c, sig) => resolve(sig ? 1 : (c ?? 1)));
+ });
+ if (code !== 0) {
+ console.error(`chain: stopped at "${s.label}" (exit ${code}); run \`umtool chain ${article} ${n}\` again to resume there`);
+ process.exit(1);
+ }
+ }
+ console.log(`\n${article} i${n}: the chain is done`);
+}
+
async function cmdIndex() {
const ix = await openIndex();
if (!ix.ok) {
diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs
@@ -0,0 +1,366 @@
+// THE CHAIN'S EXECUTOR (release 27 S7): one step of ./chain.mjs, run as its
+// own process —
+//
+// node --import tsx umtool/lib/report/chain-run.mjs step <article> <n> <step>
+// [--projects-root <dir>] [--site-origin <url>] [--final]
+//
+// — under tsx, because the article registry, the iterations store and the
+// reports CLIs it calls are common's TypeScript. The Next app never imports
+// this file (it imports ./chain.mjs, which plans). Each step records itself in
+// the iteration's `steps` as `chain:<step>` (running → done | failed |
+// cancelled, minutes, one line) and exits 0 when it is done.
+//
+// Every fetch, capture and voice is the EDITOR's (no yt-dlp, gallery-dl or
+// TTS here): `pnpm ops fetch-windows` / `capture-posts` and
+// narrate-via-editor.mjs, with the editor's URL and token read from the
+// environment or the editor's env files at run time — never put in a step.
+
+import { spawn } from "node:child_process";
+import { copyFile, mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { articleDir, articleFile } from "yt-dlp-transcript-common/lib/report/registry";
+import {
+ lineage,
+ makeCurrent,
+ projectOf,
+ readIteration,
+ readIterationFile,
+ recordIterationStep,
+ setCurrentVideo,
+ updateIteration,
+} from "yt-dlp-transcript-common/lib/report/iterations";
+import { articleReportStore } from "yt-dlp-transcript-common/lib/report/store";
+import { readStoreMediaIndex } from "yt-dlp-transcript-common/publish/reportMedia";
+import { isArticleProblem } from "yt-dlp-transcript-common/publish/reportHost";
+import { main as prepareMain } from "yt-dlp-transcript-common/bin/reports-prepare";
+import { toManifestMain } from "yt-dlp-transcript-common/bin/reports-convert";
+import { attachVideoMain } from "yt-dlp-transcript-common/bin/reports-attach-video";
+import { checkMain } from "yt-dlp-transcript-common/bin/reports-check";
+import { CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainTask, chainWindows, originFromSweep } from "./chain.mjs";
+import { PIPELINE_DIR } from "./driver.mjs";
+import { dedupeMedia, seedFromParent } from "./iterations.mjs";
+
+const OPS = path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs");
+const SCREENSHOT_MISSING = /no captured screenshot/;
+
+/** A step that ends early with a reason: failed, with that line. */
+class StepFailed extends Error {}
+
+const exists = async (p) => !!(await stat(p).catch(() => null));
+
+/** Run a command, its output into this process's, its exit code back. */
+function run(argv, { cwd = REPO_ROOT, env = process.env } = {}) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(argv[0], argv.slice(1), { cwd, env, stdio: "inherit" });
+ child.on("error", reject);
+ child.on("exit", (code, signal) => resolve(signal ? 128 + 15 : (code ?? 1)));
+ });
+}
+
+/**
+ * This process's environment with the editor's URL and token filled in, as
+ * `pnpm ops` fills its own (scripts/archilyzer-ops.mjs loadEditorEnv: the
+ * environment, else the editor's env files). The values are never printed.
+ * Imported at run time by path: the ops client is a CLI, not a module the
+ * app's scan set should follow.
+ */
+async function editorEnv() {
+ const { loadEditorEnv } = await import(pathToFileURL(OPS).href);
+ const env = { ...process.env };
+ loadEditorEnv(env);
+ return env;
+}
+
+// The ops client fills the editor's URL and token itself.
+const ops = (action, args) => run([process.execPath, OPS, action, ...args, "--wait"]);
+
+/** The article's own problems in the prepared media index, and the post screenshots among them. */
+async function ownProblems(paths, article) {
+ const index = await readStoreMediaIndex(articleReportStore(paths));
+ const own = (index?.problems ?? []).filter((p) => isArticleProblem(p, article));
+ const shots = own.filter((p) => p.kind === "missing-media" && SCREENSHOT_MISSING.test(p.message) && p.moment);
+ return { own, shots, rest: own.filter((p) => !shots.includes(p)) };
+}
+
+const describe = (problems) =>
+ problems
+ .slice(0, 3)
+ .map((p) => `${p.kind}: ${p.moment ?? p.report ?? ""} ${p.message}`.trim())
+ .join("; ") + (problems.length > 3 ? `; and ${problems.length - 3} more` : "");
+
+// ─── The steps: each answers its one line, or throws StepFailed ───
+
+const STEPS = {
+ async current(ctx) {
+ const { report, current } = await makeCurrent(ctx.article, ctx.n, ctx.paths);
+ await mkdir(ctx.project, { recursive: true });
+ if (ctx.iteration.projectDir !== ctx.project) await updateIteration(ctx.article, ctx.n, { projectDir: ctx.project }, ctx.paths);
+ return `the article is i${ctx.n}${current.reportFrom !== ctx.n ? ` (the report of i${current.reportFrom})` : ""}: “${report.title}”`;
+ },
+
+ async windows(ctx) {
+ const report = JSON.parse(await readFile(articleFile(ctx.paths, ctx.article), "utf8"));
+ const body = chainWindows(report, { pad: CHAIN_WINDOW_PAD, requestedBy: `umtool chain ${ctx.article} i${ctx.n}` });
+ if (body.items.length === 0) return "no clip windows cited";
+ await mkdir(ctx.project, { recursive: true });
+ const file = path.join(ctx.project, "windows.json");
+ await writeJson(file, body);
+ const code = await ops("fetch-windows", ["--file", file]);
+ if (code !== 0) throw new StepFailed(`the editor's fetch-windows ended ${code} (a re-run fetches only what is missing)`);
+ return `${body.items.length} window(s) on disk`;
+ },
+
+ async prepare(ctx) {
+ const code = await prepareMain({ article: ctx.article, only: true });
+ if (code === 0) return "the evidence media is complete; the article is exported";
+ const { own, shots, rest } = await ownProblems(ctx.paths, ctx.article);
+ if (own.length > 0 && rest.length === 0) return `${shots.length} post screenshot(s) to capture (the next step)`;
+ throw new StepFailed(rest.length ? describe(rest) : `reports prepare ended ${code}`);
+ },
+
+ async posts(ctx) {
+ const { shots, rest } = await ownProblems(ctx.paths, ctx.article);
+ if (rest.length > 0) throw new StepFailed(`prepare has this article's other problems first: ${describe(rest)}`);
+ if (shots.length === 0) return "no post screenshot to capture";
+ const bySlug = new Map();
+ for (const p of shots) {
+ const [slug, id] = String(p.moment).split("/");
+ if (!slug || !id) continue;
+ bySlug.set(slug, [...new Set([...(bySlug.get(slug) ?? []), id])]);
+ }
+ for (const [slug, ids] of bySlug) {
+ console.log(`chain: capturing ${ids.length} post screenshot(s) of ${slug} (the editor, paced)`);
+ const code = await ops("capture-posts", ["--json", JSON.stringify({ slug, ids, media: false })]);
+ if (code !== 0) throw new StepFailed(`the editor's capture-posts for ${slug} ended ${code}`);
+ }
+ const code = await prepareMain({ article: ctx.article, only: true });
+ if (code !== 0) {
+ const again = await ownProblems(ctx.paths, ctx.article);
+ throw new StepFailed(again.own.length ? describe(again.own) : `reports prepare ended ${code}`);
+ }
+ return `${shots.length} post screenshot(s) captured; the evidence media is complete`;
+ },
+
+ async manifest(ctx) {
+ const file = path.join(ctx.project, "video.manifest.json");
+ await mkdir(ctx.project, { recursive: true });
+ if (await exists(file)) return "the project's manifest is kept (delete it to start the cut over)";
+ const input = articleFile(ctx.paths, ctx.article);
+ const siteOrigin = ctx.siteOrigin ?? (await sweepOrigin(ctx));
+ const code = await toManifestMain({
+ input,
+ out: file,
+ channelsDir: ctx.paths.channelsDir,
+ ...(siteOrigin ? { siteOrigin } : {}),
+ });
+ if (code !== 0) throw new StepFailed(`reports to-manifest ended ${code}`);
+ // What the cut reads beside its manifest: the report, and any still it shows.
+ await copyFile(input, path.join(ctx.project, "report.json"));
+ const manifest = JSON.parse(await readFile(file, "utf8"));
+ let stills = 0;
+ for (const e of manifest.timeline ?? []) {
+ if (e?.type !== "image" || typeof e.src !== "string" || path.isAbsolute(e.src) || e.src.split(/[\\/]/).includes("..")) continue;
+ const src = path.join(articleDir(ctx.paths, ctx.article), e.src);
+ if (!(await exists(src))) continue;
+ await mkdir(path.dirname(path.join(ctx.project, e.src)), { recursive: true });
+ await copyFile(src, path.join(ctx.project, e.src));
+ stills += 1;
+ }
+ let seeded = "";
+ const parentN = ctx.iteration.parent;
+ if (parentN !== null) {
+ const parent = await readIteration(ctx.article, parentN, ctx.paths);
+ const parentProject = parent?.projectDir ?? projectOf(ctx.projectsRoot, ctx.article, parentN);
+ if (await exists(path.join(parentProject, "video.manifest.json"))) {
+ const r = await seedFromParent(parentProject, ctx.project);
+ seeded = `; from i${parentN}: ${r.carried} narration(s) carried, ${r.linked} voice file(s) linked`;
+ }
+ }
+ return `${(manifest.timeline ?? []).length} timeline entries${stills ? `, ${stills} still(s)` : ""}${siteOrigin ? "" : " — no site origin: set provenance.siteOrigin before the QR codes render"}${seeded}`;
+ },
+
+ async voices(ctx) {
+ const file = path.join(ctx.project, "video.manifest.json");
+ const manifest = JSON.parse(await readFile(file, "utf8"));
+ const narrated = (manifest.timeline ?? []).filter((e) => e?.type === "card" && e.narration?.text).length;
+ if (narrated === 0) return "no narration to voice";
+ const code = await run(
+ [process.execPath, path.join(PIPELINE_DIR, "narrate-via-editor.mjs"), file, "--out", path.join(ctx.project, "out"), "--progress", "ndjson"],
+ { cwd: PIPELINE_DIR, env: await editorEnv() },
+ );
+ if (code !== 0) throw new StepFailed(`narrate-via-editor ended ${code}`);
+ return `${narrated} card(s) voiced`;
+ },
+
+ async video(ctx) {
+ const file = path.join(ctx.project, "video.manifest.json");
+ const out = path.join(ctx.project, "out");
+ const argv = [process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), file, "--out", out, "--progress", "ndjson", "--continue-on-error", "--skip-fetch"];
+ if (!ctx.final) argv.push("--no-xfade");
+ const code = await run(argv, { cwd: PIPELINE_DIR });
+ if (code !== 0) throw new StepFailed(`build-video ended ${code}`);
+ const verify = [process.execPath, path.join(PIPELINE_DIR, "verify-build.mjs"), file, "--out", out];
+ if (!ctx.final) verify.push("--no-xfade");
+ const v = await run(verify, { cwd: PIPELINE_DIR });
+ if (v !== 0) throw new StepFailed(`verify-build ended ${v}: the cut is not what the manifest says`);
+ return `${ctx.final ? "final (crossfaded)" : "fast (hard cuts)"} cut built and verified`;
+ },
+
+ async podcast(ctx) {
+ const file = path.join(ctx.project, "video.manifest.json");
+ const code = await run(
+ [process.execPath, path.join(PIPELINE_DIR, "build-podcast.mjs"), file, "--out", path.join(ctx.project, "out"), "--progress", "ndjson"],
+ { cwd: PIPELINE_DIR },
+ );
+ if (code !== 0) throw new StepFailed(`build-podcast ended ${code}`);
+ return "podcast built";
+ },
+
+ async attach(ctx) {
+ const manifest = JSON.parse(await readFile(path.join(ctx.project, "video.manifest.json"), "utf8"));
+ const video = path.join(ctx.project, "out", `${manifest.slug ?? ctx.article}.mp4`);
+ if (!(await exists(video))) throw new StepFailed(`no cut at ${video}: build the video first`);
+ const code = await attachVideoMain({ article: ctx.article, video });
+ if (code !== 0) throw new StepFailed(`reports attach-video ended ${code}`);
+ await setCurrentVideo(ctx.article, ctx.n, ctx.paths);
+ const check = await checkMain({ article: ctx.article, paths: ctx.paths });
+ await updateIteration(
+ ctx.article,
+ ctx.n,
+ (cur) => ({
+ checks: [...(cur.checks ?? []).filter((c) => c.name !== "reports check"), { name: "reports check", ok: check === 0, ...(check === 0 ? {} : { detail: `exit ${check}` }) }],
+ }),
+ ctx.paths,
+ );
+ if (check !== 0) throw new StepFailed(`attached, but reports check --article ${ctx.article} ended ${check}`);
+ return `the article's video is i${ctx.n}'s; reports check passes`;
+ },
+
+ async dedupe(ctx) {
+ const r = await dedupeMedia(path.join(ctx.projectsRoot, ctx.article));
+ return `${r.links} file(s) linked, ${(r.freedBytes / 1e6).toFixed(1)} MB freed`;
+ },
+};
+
+async function writeJson(file, value) {
+ const tmp = `${file}.tmp-${process.pid}`;
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`);
+ await rename(tmp, file);
+}
+
+// The archive the sweep's moment links name — the QR codes' origin: the
+// newest sweep.md in the iteration's lineage that names one.
+async function sweepOrigin(ctx) {
+ const line = await lineage(ctx.article, ctx.n, ctx.paths).catch(() => [ctx.n]);
+ for (const n of [...line].reverse()) {
+ const origin = originFromSweep(await readIterationFile(ctx.article, n, "sweep.md", ctx.paths));
+ if (origin) return origin;
+ }
+ return undefined;
+}
+
+/**
+ * Run one step of an iteration's chain, recorded in its `steps`.
+ * @returns {Promise<number>} the exit code: 0 done, 1 failed, 2 refused
+ */
+export async function runChainStep(article, n, name, opts = {}) {
+ if (!CHAIN_STEP_NAMES.includes(name)) {
+ console.error(`chain: no step "${name}" (${CHAIN_STEP_NAMES.join(", ")})`);
+ return 2;
+ }
+ const paths = opts.paths ?? getPaths();
+ const iteration = await readIteration(article, n, paths).catch((err) => {
+ console.error(`chain: ${err.message}`);
+ return undefined;
+ });
+ if (iteration === undefined) return 2;
+ if (!iteration) {
+ console.error(`chain: "${article}" has no iteration i${n}`);
+ return 2;
+ }
+ if (iteration.status !== "done") {
+ console.error(`chain: "${article}" i${n} is ${iteration.status} — the chain runs over a done iteration`);
+ return 2;
+ }
+ const projectsRoot = opts.projectsRoot ?? DEFAULT_PROJECTS_ROOT;
+ const ctx = {
+ article,
+ n,
+ paths,
+ iteration,
+ projectsRoot,
+ project: projectOf(projectsRoot, article, n),
+ siteOrigin: opts.siteOrigin,
+ final: opts.final === true,
+ };
+ const task = chainTask(name);
+ const startedAt = new Date();
+ const record = (status, detail) =>
+ recordIterationStep(
+ article,
+ n,
+ {
+ task,
+ status,
+ startedAt: startedAt.toISOString(),
+ ...(status === "running" ? {} : { endedAt: new Date().toISOString(), minutes: Number(((Date.now() - startedAt.getTime()) / 60_000).toFixed(2)) }),
+ ...(detail ? { detail } : {}),
+ },
+ paths,
+ );
+ await record("running");
+ // A cancel (the job runner's SIGTERM to the step's process group) is recorded, best effort.
+ const onTerm = () => {
+ record("cancelled", "cancelled").finally(() => process.exit(143));
+ };
+ process.once("SIGTERM", onTerm);
+ console.log(`chain: ${article} i${n} — ${name}`);
+ try {
+ const detail = await STEPS[name](ctx);
+ await record("done", detail);
+ console.log(`chain: ${name} done — ${detail}`);
+ return 0;
+ } catch (err) {
+ const detail = err instanceof StepFailed ? err.message : `${err?.name ?? "Error"}: ${err?.message ?? String(err)}`;
+ await record("failed", detail).catch(() => {});
+ console.error(`chain: ${name} failed — ${detail}`);
+ return 1;
+ } finally {
+ process.removeListener("SIGTERM", onTerm);
+ }
+}
+
+function parseArgs(argv) {
+ const [cmd, article, n, name, ...rest] = argv;
+ const flag = (k) => {
+ const i = rest.indexOf(k);
+ return i >= 0 ? rest[i + 1] : undefined;
+ };
+ return {
+ cmd,
+ article,
+ n: Number(n),
+ name,
+ projectsRoot: flag("--projects-root"),
+ siteOrigin: flag("--site-origin"),
+ final: rest.includes("--final"),
+ };
+}
+
+const isMain = !!process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
+if (isMain) {
+ const a = parseArgs(process.argv.slice(2));
+ if (a.cmd !== "step" || !a.article || !Number.isInteger(a.n) || !a.name) {
+ console.error("usage: node --import tsx chain-run.mjs step <article> <n> <step> [--projects-root <dir>] [--site-origin <url>] [--final]");
+ process.exit(2);
+ }
+ runChainStep(a.article, a.n, a.name, a).then(
+ (code) => process.exit(code),
+ (err) => {
+ console.error(`chain: ${err?.message ?? err}`);
+ process.exit(1);
+ },
+ );
+}
diff --git a/umtool/lib/report/chain-run.test.mjs b/umtool/lib/report/chain-run.test.mjs
@@ -0,0 +1,158 @@
+// The chain's executor (release 27 S7), run as the job runner runs it — one
+// process a step under tsx — over a temp article store and synthetic
+// fixtures: the steps that need no editor (current, windows with nothing to
+// fetch, manifest seeded from the parent, dedupe), each recorded in the
+// iteration; and its refusals.
+//
+// Run with: node --test umtool/lib/report/chain-run.test.mjs
+
+import assert from "node:assert/strict";
+import test, { after } from "node:test";
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { CHAIN_RUN, REPO_ROOT } from "./chain.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const KIT = path.join(HERE, "..", "..", "..", "common", "testing", "draft");
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "umtool-chain-run-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const TRANSCRIPTS = path.join(ROOT, "transcripts");
+const ARTICLES = path.join(TRANSCRIPTS, "reports");
+const PROJECTS = path.join(ROOT, "projects");
+const ENV = {
+ ...process.env,
+ TRANSCRIPTS_DIR: TRANSCRIPTS,
+ SITES_DIR: path.join(TRANSCRIPTS, "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ // Never the live editor.
+ ARCHILYZER_EDITOR_URL: "http://127.0.0.1:9",
+ WORKER_TOKEN: "",
+};
+delete ENV.ARTICLES_DIR;
+
+const put = (file, data) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, typeof data === "string" || Buffer.isBuffer(data) ? data : `${JSON.stringify(data, null, 2)}\n`);
+};
+const json = (file) => JSON.parse(readFileSync(file, "utf8"));
+const NOW = "2026-10-13T12:00:00.000Z";
+const iteration = (n, over = {}) => ({
+ format: "archilyzer-iteration",
+ version: 1,
+ article: "synth-basic",
+ n,
+ kind: "sweep",
+ model: "qwen3:8b",
+ parent: null,
+ copyOf: null,
+ question: "What does the baker say?",
+ status: "done",
+ usage: {},
+ steps: [],
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...over,
+});
+
+const basic = json(path.join(KIT, "reports", "basic.report.json"));
+const iter = (n) => path.join(ARTICLES, "synth-basic", "iterations", String(n));
+put(ENV.SETTINGS_FILE, {});
+put(path.join(iter(1), "iteration.json"), iteration(1));
+put(path.join(iter(1), "report.json"), basic);
+put(path.join(iter(1), "sweep.md"), readFileSync(path.join(KIT, "sweeps", "basic.md"), "utf8"));
+put(path.join(iter(2), "iteration.json"), iteration(2, { kind: "revise-report", parent: 1, feedback: "Say it plainer.", question: undefined }));
+put(path.join(iter(2), "report.json"), { ...basic, title: "What the baker says, plainer" });
+put(path.join(iter(3), "iteration.json"), iteration(3, { status: "queued" }));
+// i1's video project: a narrated title card and its voice.
+const parentProject = path.join(PROJECTS, "synth-basic", "i1");
+const parentManifest = json(path.join(KIT, "manifests", "basic.video.manifest.json"));
+parentManifest.timeline[0] = { ...parentManifest.timeline[0], seconds: "auto", narration: { text: "What the baker says." } };
+put(path.join(parentProject, "video.manifest.json"), parentManifest);
+put(path.join(parentProject, "out", "narration", "voice1.wav"), Buffer.alloc(300, 2));
+
+function step(n, name, ...extra) {
+ const r = spawnSync(process.execPath, ["--import", "tsx", CHAIN_RUN, "step", "synth-basic", String(n), name, "--projects-root", PROJECTS, ...extra], {
+ cwd: REPO_ROOT,
+ env: ENV,
+ encoding: "utf8",
+ timeout: 120_000,
+ });
+ return { code: r.status, out: `${r.stdout}\n${r.stderr}` };
+}
+
+const recorded = (n) => Object.fromEntries(json(path.join(iter(n), "iteration.json")).steps.map((s) => [s.task, s]));
+
+test("current: the iteration becomes the article, its project recorded", () => {
+ const r = step(2, "current");
+ assert.equal(r.code, 0, r.out);
+ assert.equal(json(path.join(ARTICLES, "synth-basic", "report.json")).title, "What the baker says, plainer");
+ const it = json(path.join(iter(2), "iteration.json"));
+ assert.equal(it.projectDir, path.join(PROJECTS, "synth-basic", "i2"));
+ const s = recorded(2)["chain:current"];
+ assert.equal(s.status, "done");
+ assert.match(s.detail, /the article is i2: “What the baker says, plainer”/);
+ assert.equal(typeof s.minutes, "number");
+ assert.equal(json(path.join(ARTICLES, "synth-basic", "iterations", "current.json")).report, 2);
+});
+
+test("windows: the cited windows are asked of the editor — and its failure fails the step, recorded", () => {
+ // The editor here is a closed port: the step fails, says why, and the plan is on disk.
+ const r = step(2, "windows");
+ assert.equal(r.code, 1, r.out);
+ const body = json(path.join(PROJECTS, "synth-basic", "i2", "windows.json"));
+ assert.ok(body.items.length > 0);
+ assert.ok(body.items.every((i) => i.pad === 3 && i.clipId.startsWith("synth-basic#")));
+ assert.equal(body.requestedBy, "umtool chain synth-basic i2");
+ const s = recorded(2)["chain:windows"];
+ assert.equal(s.status, "failed");
+ assert.match(s.detail, /fetch-windows ended/);
+});
+
+test("manifest: to-manifest into the project, its origin from the lineage's sweep, narration and voices seeded from the parent", () => {
+ const r = step(2, "manifest");
+ assert.equal(r.code, 0, r.out);
+ const project = path.join(PROJECTS, "synth-basic", "i2");
+ const m = json(path.join(project, "video.manifest.json"));
+ assert.equal(m.timeline[0].heading, "What the baker says, plainer");
+ assert.equal(m.timeline[0].foot, "");
+ assert.equal(m.timeline[0].narration?.text, "What the baker says.");
+ assert.equal(m.provenance.siteOrigin, "https://synth.example");
+ assert.ok(existsSync(path.join(project, "report.json")));
+ assert.equal(
+ statSync(path.join(project, "out", "narration", "voice1.wav")).ino,
+ statSync(path.join(parentProject, "out", "narration", "voice1.wav")).ino,
+ );
+ assert.match(recorded(2)["chain:manifest"].detail, /from i1: 1 narration\(s\) carried, 1 voice file\(s\) linked/);
+ // Run again: the manifest is kept, never made over an edited one.
+ const again = step(2, "manifest");
+ assert.equal(again.code, 0, again.out);
+ assert.match(recorded(2)["chain:manifest"].detail, /kept/);
+});
+
+test("dedupe: the article's projects share identical segments", () => {
+ const seg = Buffer.alloc(70 * 1024, 5);
+ put(path.join(PROJECTS, "synth-basic", "i1", "out", "sourced", "segments", "c01.mp4"), seg);
+ put(path.join(PROJECTS, "synth-basic", "i2", "out", "sourced", "segments", "c01.mp4"), seg);
+ const r = step(2, "dedupe");
+ assert.equal(r.code, 0, r.out);
+ assert.match(recorded(2)["chain:dedupe"].detail, /^1 file\(s\) linked/);
+});
+
+test("refusals: a queued iteration, an unknown step, no such iteration", () => {
+ const queued = step(3, "current");
+ assert.equal(queued.code, 2);
+ assert.match(queued.out, /i3 is queued — the chain runs over a done iteration/);
+ const nope = step(2, "nope");
+ assert.equal(nope.code, 2);
+ assert.match(nope.out, /no step "nope"/);
+ const none = step(9, "current");
+ assert.equal(none.code, 2);
+ assert.match(none.out, /has no iteration i9/);
+});
diff --git a/umtool/lib/report/chain.mjs b/umtool/lib/report/chain.mjs
@@ -0,0 +1,213 @@
+// THE PIPELINE CHAIN over an article's iteration (release 27 S7;
+// plans/release-27.md "Shape"): the code steps that take an iteration's
+// report to an article with its evidence media, a video and a podcast.
+//
+// current make the iteration current (the article's report.json)
+// windows the editor fetches every cited clip window, padded to the
+// video build's fetchPad, so one fetch serves both the article's
+// evidence clips and the cut
+// prepare `reports prepare --article <id> --only`
+// posts the editor captures THIS article's missing post screenshots,
+// then prepare again
+// manifest `reports to-manifest` into the iteration's project
+// (`<projectsRoot>/<id>/i<n>/`), seeded from the parent's
+// project — narration carried, voices linked
+// voices the editor's TTS speaks the narration (narrate-via-editor)
+// video build-video, from the windows the editor fetched (--skip-fetch)
+// podcast build-podcast
+// attach `reports attach-video --article`, the iteration recorded as the
+// article's video, then `reports check --article`
+// dedupe hard-link identical segments and voices across the article's
+// projects (./iterations.mjs)
+//
+// Each step is ONE PROCESS — `node --import tsx chain-run.mjs step <id> <n>
+// <step>` — so lib/jobs.ts runs the chain as a job like any other (detached
+// process group, cancel, per-step timeout), and `umtool chain` runs the same
+// argv from a terminal. A step records itself in the iteration's `steps`
+// (`chain:<step>`: running, then done or failed, with its minutes and a line)
+// through the article registry; a chain started again resumes at the first
+// step not done, or `--from` names one.
+//
+// This module PLANS (plain node: no TypeScript, nothing of common's), so the
+// Next app may import it; ./chain-run.mjs EXECUTES.
+
+import { existsSync, readFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { UMTOOL_DIR } from "./driver.mjs";
+
+export const CHAIN_STEPS = [
+ { name: "current", label: "make the iteration current", timeoutMs: 2 * 60_000 },
+ { name: "windows", label: "fetch the cited clip windows (editor)", timeoutMs: 6 * 60 * 60_000 },
+ { name: "prepare", label: "prepare the article's evidence media", timeoutMs: 60 * 60_000 },
+ { name: "posts", label: "capture the article's post screenshots (editor)", timeoutMs: 3 * 60 * 60_000 },
+ { name: "manifest", label: "make the video manifest, seeded from the parent", timeoutMs: 5 * 60_000 },
+ { name: "voices", label: "voice the narration (editor TTS)", timeoutMs: 3 * 60 * 60_000, ndjson: true },
+ { name: "video", label: "build the video", timeoutMs: 4 * 60 * 60_000, ndjson: true },
+ { name: "podcast", label: "build the podcast", timeoutMs: 30 * 60_000, ndjson: true },
+ { name: "attach", label: "attach the video to the article", timeoutMs: 30 * 60_000 },
+ { name: "dedupe", label: "share identical segments and voices", timeoutMs: 15 * 60_000 },
+];
+export const CHAIN_STEP_NAMES = CHAIN_STEPS.map((s) => s.name);
+
+// How a step is named in the iteration's `steps`.
+export const chainTask = (name) => `chain:${name}`;
+
+// The video build's starter fetchPad (common/lib/report/convertManifest.ts
+// STARTER_RENDER): the windows are fetched this wide so the cut finds them.
+export const CHAIN_WINDOW_PAD = 3;
+
+// Until S6's `settings.generation.projectsRoot`: off the corpus disk (D1).
+export const DEFAULT_PROJECTS_ROOT = path.join(/* turbopackIgnore: true */ os.homedir(), "reports", "articles");
+
+// From driver.mjs's package root, which is found from the module (or, under
+// the Next server, the cwd) — never this module's URL alone.
+/** The checkout this module is in. */
+export const REPO_ROOT = path.dirname(/* turbopackIgnore: true */ UMTOOL_DIR);
+/** The executor every step runs. */
+export const CHAIN_RUN = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "lib", "report", "chain-run.mjs");
+
+const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+
+/** `<projectsRoot>/<id>/i<n>/` (common/lib/report/iterations.ts projectOf). */
+export function chainProject(projectsRoot, article, n) {
+ if (!ID_RE.test(article)) throw new Error(`"${article}" is not an article id`);
+ if (!Number.isInteger(n) || n < 1) throw new Error(`${n} is not an iteration number`);
+ return path.join(/* turbopackIgnore: true */ projectsRoot, article, `i${n}`);
+}
+
+/**
+ * Where a chain starts: `from` when given, else the first step the iteration
+ * has not recorded done (`done`: the step names recorded done), else nothing
+ * (the whole chain is done: null).
+ */
+export function chainStart({ from = null, done = [] } = {}) {
+ if (from !== null && from !== undefined) {
+ if (!CHAIN_STEP_NAMES.includes(from)) throw new Error(`--from must be one of ${CHAIN_STEP_NAMES.join(", ")}`);
+ return from;
+ }
+ const finished = new Set(done);
+ return CHAIN_STEP_NAMES.find((s) => !finished.has(s)) ?? null;
+}
+
+/** The step names an iteration.json records done, from its `steps`. */
+export function doneSteps(iteration) {
+ const out = [];
+ for (const s of iteration?.steps ?? []) {
+ if (typeof s?.task !== "string" || !s.task.startsWith("chain:")) continue;
+ const name = s.task.slice("chain:".length);
+ if (s.status === "done") out.push(name);
+ }
+ return out;
+}
+
+/** An iteration's iteration.json as it is on disk, read only, or null. */
+export function readIterationRecord(articlesDir, article, n) {
+ const file = path.join(/* turbopackIgnore: true */ articlesDir, article, "iterations", String(n), "iteration.json");
+ if (!existsSync(/* turbopackIgnore: true */ file)) return null;
+ try {
+ return JSON.parse(readFileSync(/* turbopackIgnore: true */ file, "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The chain's steps for lib/jobs.ts (and `umtool chain`), from `start`
+ * (chainStart) to the end. No secret rides in a step: the executor reads the
+ * editor's URL and token itself (jobView shows a step's env to the browser).
+ *
+ * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string }} o
+ * @returns {import("../trim").Step[]}
+ */
+export function chainSteps(o) {
+ const projectsRoot = o.projectsRoot ?? DEFAULT_PROJECTS_ROOT;
+ chainProject(projectsRoot, o.article, o.n);
+ const start = o.start === undefined ? CHAIN_STEP_NAMES[0] : o.start;
+ if (start === null) return [];
+ const at = CHAIN_STEP_NAMES.indexOf(start);
+ if (at < 0) throw new Error(`no chain step "${start}"`);
+ const extra = [
+ "--projects-root",
+ projectsRoot,
+ ...(o.siteOrigin ? ["--site-origin", o.siteOrigin] : []),
+ ...(o.final ? ["--final"] : []),
+ ];
+ return CHAIN_STEPS.slice(at).map((s, i) => ({
+ label: `${at + i + 1}/${CHAIN_STEPS.length} ${s.label}`,
+ cwd: REPO_ROOT,
+ env: {},
+ argv: [o.node ?? process.execPath, "--import", "tsx", CHAIN_RUN, "step", o.article, String(o.n), s.name, ...extra],
+ timeoutMs: s.timeoutMs,
+ ...(s.ndjson ? { ndjson: true } : {}),
+ }));
+}
+
+/**
+ * The chain to run for an iteration as it is on disk — what `umtool chain`
+ * and the app's job both start from: its record (read only), where it starts
+ * (resume, or `from`) and the steps. Throws for no such iteration, an
+ * iteration not done, or an unknown `from`. `steps` is empty when every step
+ * is done.
+ *
+ * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean }} o
+ */
+export function planChain(o) {
+ const record = readIterationRecord(o.articlesDir, o.article, o.n);
+ if (!record) throw new Error(`"${o.article}" has no iteration i${o.n} under ${o.articlesDir}`);
+ if (record.status !== "done") throw new Error(`${o.article} i${o.n} is ${record.status}: the chain runs over a done iteration`);
+ const start = chainStart({ from: o.from ?? null, done: doneSteps(record) });
+ const steps = chainSteps({
+ article: o.article,
+ n: o.n,
+ start,
+ ...(o.projectsRoot ? { projectsRoot: o.projectsRoot } : {}),
+ ...(o.siteOrigin ? { siteOrigin: o.siteOrigin } : {}),
+ final: o.final === true,
+ });
+ return { record, start, steps };
+}
+
+const floor2 = (x) => Math.floor(x * 100 + 1e-6) / 100;
+const ceil2 = (x) => Math.ceil(x * 100 - 1e-6) / 100;
+
+/**
+ * The clip windows a report cites, as the body of the editor's fetch-windows
+ * (one per distinct moment): each the cited span widened by `pad` (the cut's
+ * fetchPad) and by the citation's own pad (its evidence clip's), clamped at 0
+ * and rounded outward to the hundredth — `from`/`to` ARE the window; `pad`
+ * rides along as provenance.
+ */
+export function chainWindows(report, { pad = CHAIN_WINDOW_PAD, requestedBy = "umtool chain" } = {}) {
+ const items = [];
+ const byMoment = new Map();
+ for (const [cid, c] of Object.entries(report?.citations ?? {})) {
+ if (c?.kind !== "video" && c?.kind !== "audio") continue;
+ if (typeof c.start !== "number" || typeof c.end !== "number") continue;
+ const before = Math.max(pad, c.pad?.before ?? 0);
+ const after = Math.max(pad, c.pad?.after ?? 0);
+ const from = floor2(Math.max(0, c.start - before));
+ const to = ceil2(c.end + after);
+ const key = `${c.channel}/${c.id}`;
+ const same = (byMoment.get(key) ?? []).find((w) => w.from <= from && w.to >= to);
+ if (same) continue;
+ const item = {
+ slug: c.channel,
+ id: c.id,
+ from,
+ to,
+ clipId: `${report.id}#${cid}`,
+ reason: `article ${report.id} ${cid}`,
+ pad,
+ };
+ items.push(item);
+ byMoment.set(key, [...(byMoment.get(key) ?? []), item]);
+ }
+ return { items, requestedBy };
+}
+
+/** The archive origin a sweep's moment links name (`https://host/?v=…`), or null. */
+export function originFromSweep(text) {
+ const m = /(https?:\/\/[^/\s)"']+)\/?\?v=/.exec(String(text ?? ""));
+ return m ? m[1] : null;
+}
diff --git a/umtool/lib/report/chain.test.mjs b/umtool/lib/report/chain.test.mjs
@@ -0,0 +1,138 @@
+// The pipeline chain's plan (release 27 S7): its steps for the job runner,
+// where it resumes, the windows it asks the editor for, and `umtool chain
+// --dry`. Plain node, temp dirs only.
+//
+// Run with: node --test umtool/lib/report/chain.test.mjs
+
+import assert from "node:assert/strict";
+import test, { after } from "node:test";
+import { execFileSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import {
+ CHAIN_RUN,
+ CHAIN_STEP_NAMES,
+ REPO_ROOT,
+ chainProject,
+ chainStart,
+ chainSteps,
+ chainWindows,
+ doneSteps,
+ originFromSweep,
+} from "./chain.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "umtool-chain-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+test("the steps, in order, each one process of the executor under tsx, from the checkout", () => {
+ assert.deepEqual(CHAIN_STEP_NAMES, ["current", "windows", "prepare", "posts", "manifest", "voices", "video", "podcast", "attach", "dedupe"]);
+ assert.equal(REPO_ROOT, path.resolve(HERE, "..", "..", ".."));
+ assert.equal(CHAIN_RUN, path.join(HERE, "chain-run.mjs"));
+ const steps = chainSteps({ article: "my-article", n: 3, projectsRoot: "/p", node: "node" });
+ assert.equal(steps.length, 10);
+ assert.equal(steps[0].label, "1/10 make the iteration current");
+ assert.deepEqual(steps[0].argv, ["node", "--import", "tsx", CHAIN_RUN, "step", "my-article", "3", "current", "--projects-root", "/p"]);
+ assert.ok(steps.every((s) => s.cwd === REPO_ROOT && Object.keys(s.env).length === 0), "no secret rides in a step");
+ assert.ok(steps.every((s) => s.timeoutMs > 0));
+ assert.deepEqual(steps.filter((s) => s.ndjson).map((s) => s.argv[7]), ["voices", "video", "podcast"]);
+ const late = chainSteps({ article: "my-article", n: 3, projectsRoot: "/p", start: "video", final: true, siteOrigin: "https://a.example", node: "node" });
+ assert.deepEqual(late.map((s) => s.argv[7]), ["video", "podcast", "attach", "dedupe"]);
+ assert.equal(late[0].label, "7/10 build the video");
+ assert.deepEqual(late[0].argv.slice(8), ["--projects-root", "/p", "--site-origin", "https://a.example", "--final"]);
+ assert.deepEqual(chainSteps({ article: "a", n: 1, start: null }), []);
+ assert.throws(() => chainSteps({ article: "Bad", n: 1 }), /not an article id/);
+ assert.throws(() => chainSteps({ article: "a", n: 0 }), /not an iteration number/);
+ assert.throws(() => chainSteps({ article: "a", n: 1, start: "nope" }), /no chain step/);
+ assert.equal(chainProject("/p", "a", 2), path.join("/p", "a", "i2"));
+});
+
+test("resume: the first step not recorded done; --from names one; all done is nothing", () => {
+ const it = {
+ steps: [
+ { task: "narrate", status: "done" },
+ { task: "chain:current", status: "done" },
+ { task: "chain:windows", status: "done" },
+ { task: "chain:prepare", status: "failed" },
+ ],
+ };
+ assert.deepEqual(doneSteps(it), ["current", "windows"]);
+ assert.equal(chainStart({ done: doneSteps(it) }), "prepare");
+ assert.equal(chainStart({ done: [] }), "current");
+ assert.equal(chainStart({ done: CHAIN_STEP_NAMES }), null);
+ assert.equal(chainStart({ from: "manifest", done: CHAIN_STEP_NAMES }), "manifest");
+ assert.throws(() => chainStart({ from: "nope" }), /--from must be one of/);
+});
+
+test("chainWindows: each cited moment padded to the cut's fetchPad and the citation's own pad, rounded outward, once", () => {
+ const report = {
+ id: "art",
+ citations: {
+ c1: { kind: "video", channel: "synth-kitchen", id: "v1", start: 10.004, end: 20.001, quote: "a" },
+ // Inside c1's window: no second window.
+ c2: { kind: "video", channel: "synth-kitchen", id: "v1", start: 12, end: 18, quote: "b" },
+ // Its own pad is wider than the fetchPad after.
+ c3: { kind: "audio", channel: "synth-other", id: "a1", start: 1, end: 5, pad: { after: 8 }, quote: "c" },
+ p1: { kind: "post", channel: "synth-posts", id: "9", quote: "d" },
+ s1: { kind: "source", source: "s", quote: "e" },
+ },
+ };
+ const body = chainWindows(report, { requestedBy: "test" });
+ assert.equal(body.requestedBy, "test");
+ assert.deepEqual(body.items, [
+ { slug: "synth-kitchen", id: "v1", from: 7, to: 23.01, clipId: "art#c1", reason: "article art c1", pad: 3 },
+ { slug: "synth-other", id: "a1", from: 0, to: 13, clipId: "art#c3", reason: "article art c3", pad: 3 },
+ ]);
+ assert.deepEqual(chainWindows({ id: "x", citations: {} }).items, []);
+});
+
+test("originFromSweep: the archive a sweep's moment links name", () => {
+ assert.equal(originFromSweep("see [it](https://synth.example/?v=synth-kitchen%2Fv1&t=5)"), "https://synth.example");
+ assert.equal(originFromSweep("[x](http://localhost:8768/?v=a%2Fb)"), "http://localhost:8768");
+ assert.equal(originFromSweep("no links"), null);
+ assert.equal(originFromSweep(null), null);
+});
+
+test("umtool chain --dry: the plan, resuming where the iteration left off; refusals", () => {
+ const articles = path.join(ROOT, "reports");
+ const dir = path.join(articles, "art", "iterations", "2");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ path.join(dir, "iteration.json"),
+ JSON.stringify({ n: 2, status: "done", steps: [{ task: "chain:current", status: "done" }, { task: "chain:windows", status: "done" }] }),
+ );
+ const umtool = path.join(HERE, "..", "..", "bin", "umtool.mjs");
+ const env = { ...process.env, ARTICLES_DIR: articles };
+ const run = (...args) => execFileSync(process.execPath, [umtool, "chain", ...args], { env, encoding: "utf8", cwd: ROOT });
+ const plan = JSON.parse(run("art", "2", "--dry", "--json", "--projects-root", path.join(ROOT, "projects")));
+ assert.equal(plan.start, "prepare");
+ assert.deepEqual(plan.steps.map((s) => s.argv[7]), ["prepare", "posts", "manifest", "voices", "video", "podcast", "attach", "dedupe"]);
+ assert.ok(plan.steps.every((s) => s.argv.includes(path.join(ROOT, "projects"))));
+ const text = run("art", "2", "--dry", "--from", "video");
+ assert.match(text, /# art i2 — the chain from "video"/);
+ assert.match(text, /\(cd .* && .*chain-run\.mjs step art 2 video/);
+ assert.throws(() => run("art", "9", "--dry"), (e) => /has no iteration i9/.test(String(e.stderr)));
+ assert.throws(() => run("art", "2", "--dry", "--from", "nope"), (e) => /--from must be one of/.test(String(e.stderr)));
+});
+
+test("planChain: the record, the resume point and the steps; a queued iteration is refused", async () => {
+ const { planChain } = await import("./chain.mjs");
+ const articles = path.join(ROOT, "plan-reports");
+ const put = (n, record) => {
+ const dir = path.join(articles, "art", "iterations", String(n));
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, "iteration.json"), JSON.stringify(record));
+ };
+ put(1, { n: 1, status: "done", steps: [] });
+ put(2, { n: 2, status: "queued", steps: [] });
+ put(3, { n: 3, status: "done", steps: ["current", "windows", "prepare", "posts", "manifest", "voices", "video", "podcast", "attach", "dedupe"].map((s) => ({ task: `chain:${s}`, status: "done" })) });
+ const plan = planChain({ articlesDir: articles, article: "art", n: 1, projectsRoot: "/p" });
+ assert.equal(plan.start, "current");
+ assert.equal(plan.steps.length, 10);
+ assert.deepEqual(planChain({ articlesDir: articles, article: "art", n: 3 }).steps, []);
+ assert.equal(planChain({ articlesDir: articles, article: "art", n: 3, from: "attach" }).steps.length, 2);
+ assert.throws(() => planChain({ articlesDir: articles, article: "art", n: 2 }), /i2 is queued/);
+ assert.throws(() => planChain({ articlesDir: articles, article: "art", n: 7 }), /has no iteration i7/);
+});
diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs
@@ -26,7 +26,7 @@ import { fileURLToPath } from "node:url";
*/
function packageRoot() {
try {
- const dir = path.resolve(/* turbopackIgnore: true */ path.dirname(fileURLToPath(import.meta.url)), "..", "..");
+ const dir = path.resolve(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)), "..", "..");
if (existsSync(path.join(/* turbopackIgnore: true */ dir, "report-to-video", "build-video.mjs"))) return dir;
} catch {
// Not a file: URL (a bundle): the cwd, below.
diff --git a/umtool/lib/report/iterations.mjs b/umtool/lib/report/iterations.mjs
@@ -0,0 +1,192 @@
+// An article's iterations, on the video side (release 27 S7): what a new
+// iteration's video project keeps from its parent's, and the bytes the
+// projects of one article share.
+//
+// A project is `<projectsRoot>/<articleId>/i<n>/` (common/lib/report/
+// iterations.ts projectOf, D1): video.manifest.json and out/. Two things here,
+// ported from the stopgap (~/reports/local-reports seed_version.py and
+// dedupe_media.py):
+//
+// seedFromParent a card of the new manifest with no narration takes its
+// parent card's (matched by id, else by heading), and the
+// parent's synthesized voices are hard-linked in, so
+// narrate-via-editor finds them kept and no voice is made
+// again; a card whose words changed gets new audio
+// dedupeMedia byte-identical files across the projects are made one
+// file (hard links) — ONLY the files the tools never write
+// in place, so a later build of one iteration can never
+// write through a link into another's: a segment
+// (`out/<variant>/segments/*.mp4`; build-video unlinks a
+// linked segment before it rebuilds it, detachSegmentFiles)
+// and a voice (`out/narration/*.{wav,json}`, named by the
+// content key of the words and the voice, never rewritten)
+//
+// Plain node: no TypeScript, no Next. Server-only (node:fs).
+
+import { createHash } from "node:crypto";
+import { createReadStream } from "node:fs";
+import { link, lstat, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+export const MANIFEST_NAME = "video.manifest.json";
+// Below this a segment is not worth a hash (a voice always is: it is small
+// and there are many).
+export const DEDUPE_MIN_BYTES = 64 * 1024;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const headKey = (c) => String(c?.heading ?? "").trim().toLowerCase();
+
+async function readJson(file) {
+ return JSON.parse(await readFile(file, "utf8"));
+}
+
+// Replace `file` whole: a temp beside it, then a rename.
+async function writeJsonAtomic(file, value) {
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`);
+ await rename(tmp, file);
+}
+
+/**
+ * Carry what a new iteration's video project can keep from its parent's.
+ *
+ * @param {string} parentDir the parent iteration's project (its manifest and out/)
+ * @param {string} newDir the new project, its manifest freshly made
+ * @returns {Promise<{ carried: number, linked: number }>}
+ */
+export async function seedFromParent(parentDir, newDir) {
+ const parent = await readJson(path.join(parentDir, MANIFEST_NAME));
+ const manifestFile = path.join(newDir, MANIFEST_NAME);
+ const next = await readJson(manifestFile);
+ const narrated = (parent.timeline ?? []).filter((c) => c?.type === "card" && isObj(c.narration) && c.narration.text);
+ const byId = new Map(narrated.map((c) => [c.id, c]));
+ const byHead = new Map();
+ for (const c of narrated) if (headKey(c) && !byHead.has(headKey(c))) byHead.set(headKey(c), c);
+ let carried = 0;
+ for (const c of next.timeline ?? []) {
+ if (c?.type !== "card" || (isObj(c.narration) && c.narration.text)) continue;
+ const src = byId.get(c.id) ?? (headKey(c) ? byHead.get(headKey(c)) : undefined);
+ if (!src) continue;
+ c.narration = { ...src.narration };
+ // A narrated card is timed by its voice.
+ if (src.seconds === "auto") c.seconds = "auto";
+ carried += 1;
+ }
+ if (carried > 0) await writeJsonAtomic(manifestFile, next);
+
+ let linked = 0;
+ const from = path.join(parentDir, "out", "narration");
+ const to = path.join(newDir, "out", "narration");
+ let names = [];
+ try {
+ names = await readdir(from);
+ } catch {
+ names = [];
+ }
+ const voices = names.filter((f) => f.endsWith(".wav") || f.endsWith(".json"));
+ if (voices.length > 0) await mkdir(to, { recursive: true });
+ for (const f of voices) {
+ const src = path.join(from, f);
+ const dst = path.join(to, f);
+ if (!(await lstat(src).catch(() => null))?.isFile()) continue;
+ if (await lstat(dst).catch(() => null)) continue;
+ await link(src, dst);
+ linked += 1;
+ }
+ return { carried, linked };
+}
+
+// Every file dedupe may link under one project: its segments and its voices.
+async function candidates(projectDir) {
+ const out = [];
+ const outDir = path.join(projectDir, "out");
+ const files = async (dir, test) => {
+ let names = [];
+ try {
+ names = await readdir(dir);
+ } catch {
+ return;
+ }
+ for (const f of names) {
+ if (!test(f)) continue;
+ const p = path.join(dir, f);
+ const st = await lstat(p).catch(() => null);
+ if (st?.isFile()) out.push(p);
+ }
+ };
+ let variants = [];
+ try {
+ variants = (await readdir(outDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
+ } catch {
+ variants = [];
+ }
+ for (const v of variants) {
+ if (v === "narration") continue;
+ await files(path.join(outDir, v, "segments"), (f) => f.endsWith(".mp4"));
+ }
+ await files(path.join(outDir, "narration"), (f) => f.endsWith(".wav") || f.endsWith(".json"));
+ return out;
+}
+
+function sha256(file) {
+ return new Promise((resolve, reject) => {
+ const h = createHash("sha256");
+ createReadStream(file)
+ .on("error", reject)
+ .on("data", (b) => h.update(b))
+ .on("end", () => resolve(h.digest("hex")));
+ });
+}
+
+/**
+ * Hard-link byte-identical segments and voices across the projects under
+ * `root` (each subdirectory a project: an article's `i1/`, `i2/`, …). Same
+ * filesystem only. A file already one with its twin is left as it is.
+ *
+ * @param {string} root
+ * @param {{ dry?: boolean }} [opts]
+ * @returns {Promise<{ links: number, freedBytes: number }>}
+ */
+export async function dedupeMedia(root, { dry = false } = {}) {
+ let projects = [];
+ try {
+ projects = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
+ } catch {
+ return { links: 0, freedBytes: 0 };
+ }
+ const bySize = new Map();
+ for (const p of projects) {
+ for (const file of await candidates(path.join(root, p))) {
+ const st = await stat(file);
+ if (st.size < DEDUPE_MIN_BYTES && !file.endsWith(".wav")) continue;
+ const key = `${st.dev}:${st.size}`;
+ if (!bySize.has(key)) bySize.set(key, []);
+ bySize.get(key).push(file);
+ }
+ }
+ let links = 0;
+ let freedBytes = 0;
+ for (const [key, files] of bySize) {
+ if (files.length < 2) continue;
+ const size = Number(key.split(":")[1]);
+ const keep = new Map();
+ for (const file of files) {
+ const digest = await sha256(file);
+ const first = keep.get(digest);
+ if (!first) {
+ keep.set(digest, file);
+ continue;
+ }
+ if ((await stat(first)).ino === (await stat(file)).ino) continue;
+ if (!dry) {
+ const tmp = `${file}.dedupe-tmp`;
+ await rm(tmp, { force: true });
+ await link(first, tmp);
+ await rename(tmp, file);
+ }
+ links += 1;
+ freedBytes += size;
+ }
+ }
+ return { links, freedBytes };
+}
diff --git a/umtool/lib/report/iterations.test.mjs b/umtool/lib/report/iterations.test.mjs
@@ -0,0 +1,111 @@
+// The video side of an article's iterations (release 27 S7): the parent
+// seed and the dedupe. Temp dirs only.
+//
+// Run with: node --test umtool/lib/report/iterations.test.mjs
+
+import assert from "node:assert/strict";
+import test, { after } from "node:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, existsSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { DEDUPE_MIN_BYTES, dedupeMedia, seedFromParent } from "./iterations.mjs";
+
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "umtool-iterations-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const put = (file, data) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, typeof data === "string" || Buffer.isBuffer(data) ? data : `${JSON.stringify(data, null, 2)}\n`);
+};
+const json = (file) => JSON.parse(readFileSync(file, "utf8"));
+const ino = (file) => statSync(file).ino;
+
+const card = (id, heading, narration) => ({
+ type: "card",
+ id,
+ style: "chapter",
+ seconds: narration ? "auto" : 3.5,
+ heading,
+ ...(narration ? { narration: { text: narration } } : {}),
+});
+
+test("seedFromParent: narration carried by id, else by heading; voices linked; a card with its own words kept", async () => {
+ const dir = path.join(ROOT, "seed");
+ const parent = path.join(dir, "i1");
+ const child = path.join(dir, "i2");
+ put(path.join(parent, "video.manifest.json"), {
+ timeline: [card("title", "The title", "Opening words."), card("s1", "The shop", "About the shop."), card("s2", "Gone", "A card the child lost.")],
+ });
+ put(path.join(parent, "out", "narration", "abc.wav"), Buffer.alloc(100, 1));
+ put(path.join(parent, "out", "narration", "abc.json"), { key: "abc" });
+ put(path.join(parent, "out", "narration", "notes.txt"), "not a voice");
+ put(path.join(child, "video.manifest.json"), {
+ timeline: [
+ card("title", "The title"),
+ // Renumbered, same heading.
+ card("s9", "THE SHOP "),
+ card("s3", "New section", "Its own words."),
+ { type: "clip", id: "c01", channel: "synth-kitchen", video: "v1", start: 1, end: 2 },
+ ],
+ });
+ // A voice the child already has is not replaced.
+ put(path.join(child, "out", "narration", "abc.json"), { key: "mine" });
+ const r = await seedFromParent(parent, child);
+ assert.deepEqual(r, { carried: 2, linked: 1 });
+ const m = json(path.join(child, "video.manifest.json"));
+ assert.deepEqual(m.timeline.map((e) => e.narration?.text ?? null), ["Opening words.", "About the shop.", "Its own words.", null]);
+ assert.equal(m.timeline[1].seconds, "auto");
+ assert.equal(ino(path.join(child, "out", "narration", "abc.wav")), ino(path.join(parent, "out", "narration", "abc.wav")));
+ assert.deepEqual(json(path.join(child, "out", "narration", "abc.json")), { key: "mine" });
+ assert.equal(existsSync(path.join(child, "out", "narration", "notes.txt")), false);
+});
+
+test("seedFromParent: a parent with no voices and nothing to carry writes nothing", async () => {
+ const dir = path.join(ROOT, "seed-empty");
+ put(path.join(dir, "i1", "video.manifest.json"), { timeline: [card("s1", "One")] });
+ put(path.join(dir, "i2", "video.manifest.json"), { timeline: [card("s1", "One")] });
+ const before = readFileSync(path.join(dir, "i2", "video.manifest.json"), "utf8");
+ assert.deepEqual(await seedFromParent(path.join(dir, "i1"), path.join(dir, "i2")), { carried: 0, linked: 0 });
+ assert.equal(readFileSync(path.join(dir, "i2", "video.manifest.json"), "utf8"), before);
+});
+
+test("dedupeMedia: identical segments and voices become one file; nothing else is touched; a dry run links nothing", async () => {
+ const root = path.join(ROOT, "dedupe", "my-article");
+ const seg = Buffer.alloc(DEDUPE_MIN_BYTES + 10, 7);
+ const other = Buffer.alloc(DEDUPE_MIN_BYTES + 10, 8);
+ const voice = Buffer.alloc(200, 3);
+ put(path.join(root, "i1", "out", "sourced", "segments", "c01.mp4"), seg);
+ put(path.join(root, "i2", "out", "sourced", "segments", "c01.mp4"), seg);
+ put(path.join(root, "i3", "out", "sourced", "segments", "c01.mp4"), other);
+ put(path.join(root, "i2", "out", "full", "segments", "c02.mp4"), seg);
+ put(path.join(root, "i1", "out", "narration", "k.wav"), voice);
+ put(path.join(root, "i2", "out", "narration", "k.wav"), voice);
+ // Small segments, the final cut and anything outside the two places are never linked.
+ put(path.join(root, "i1", "out", "sourced", "segments", "tiny.mp4"), "x");
+ put(path.join(root, "i2", "out", "sourced", "segments", "tiny.mp4"), "x");
+ put(path.join(root, "i1", "out", "sourced", "my-article.mp4"), seg);
+ put(path.join(root, "i2", "out", "sourced", "my-article.mp4"), seg);
+ put(path.join(root, "i1", "video.manifest.json"), seg);
+ put(path.join(root, "i2", "video.manifest.json"), seg);
+
+ const dry = await dedupeMedia(root, { dry: true });
+ assert.deepEqual(dry, { links: 3, freedBytes: 2 * seg.length + voice.length });
+ assert.notEqual(ino(path.join(root, "i2", "out", "sourced", "segments", "c01.mp4")), ino(path.join(root, "i1", "out", "sourced", "segments", "c01.mp4")));
+
+ const done = await dedupeMedia(root);
+ assert.deepEqual(done, dry);
+ const a = ino(path.join(root, "i1", "out", "sourced", "segments", "c01.mp4"));
+ assert.equal(ino(path.join(root, "i2", "out", "sourced", "segments", "c01.mp4")), a);
+ assert.equal(ino(path.join(root, "i2", "out", "full", "segments", "c02.mp4")), a);
+ assert.notEqual(ino(path.join(root, "i3", "out", "sourced", "segments", "c01.mp4")), a);
+ assert.equal(ino(path.join(root, "i2", "out", "narration", "k.wav")), ino(path.join(root, "i1", "out", "narration", "k.wav")));
+ assert.notEqual(ino(path.join(root, "i2", "out", "sourced", "segments", "tiny.mp4")), ino(path.join(root, "i1", "out", "sourced", "segments", "tiny.mp4")));
+ assert.notEqual(ino(path.join(root, "i2", "out", "sourced", "my-article.mp4")), ino(path.join(root, "i1", "out", "sourced", "my-article.mp4")));
+ assert.notEqual(ino(path.join(root, "i2", "video.manifest.json")), ino(path.join(root, "i1", "video.manifest.json")));
+ // Run again: already one file, nothing to do.
+ assert.deepEqual(await dedupeMedia(root), { links: 0, freedBytes: 0 });
+ // No temp left behind.
+ assert.equal(existsSync(path.join(root, "i2", "out", "narration", "k.wav.dedupe-tmp")), false);
+ // A root that is not there is nothing to do.
+ assert.deepEqual(await dedupeMedia(path.join(ROOT, "nowhere")), { links: 0, freedBytes: 0 });
+});