commit 48b14021ce99f08f6b7ecb07450914c83cfb5d7c
parent d9712d0d682f0ccd3515d6aa820fa9391ffd1bda
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 11:22:35 -0400
Merge r27/iterations-chain: release 27 S4 (iterations store) and S7 (pipeline chain, owed bugs)
# Conflicts:
# plans/release-27.md
Diffstat:
35 files changed, 2963 insertions(+), 65 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -29,11 +29,12 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer build all` | `[--skip-archives]` | alias: publish index + publish build all --runner auto (containers when an engine answers, else serially on the host) |
| `archilyzer build hub` | | compose:hub + INSTANCE\_MODE=hub next build into export/out — a raw build, unstamped; to deploy the hub build it with `publish hub` |
| `archilyzer build homepage` | `[--no-source] [--private]` | compose + source publish + next build in homepage/ (reads the index as it stands), then the public build's audit (no private article, moment or X post); --no-source removes the published source instead; --private builds every published article into homepage/out-private instead (serve it with `pnpm --filter homepage start:private`; never deployed) |
-| `archilyzer reports prepare` | `<id> \| --article <articleId>` | cut every clip and copy every post capture the site's published reports cite into its report-media cache, before its build, then export the reports as files (reports export) when nothing is missing (exit 1 when a citation lacks media or an export fails; default id: SITE\_ID); --article: the articles' cache (transcripts/reports/), every published article plus that one |
+| `archilyzer reports prepare` | `<id> \| --article <articleId> [--only]` | cut every clip and copy every post capture the site's published reports cite into its report-media cache, before its build, then export the reports as files (reports export) when nothing is missing (exit 1 when a citation lacks media or an export fails; default id: SITE\_ID); --article: the articles' cache (transcripts/reports/), every published article plus that one; --only: that article answers for the run — its problems fail it, another article's are warnings, and only it is exported |
| `archilyzer reports export` | `<id> [--report <reportId>] \| --article <articleId>` | \[--formats html,pdf,md,slides,slides-pdf,zip\] \[--allow-missing-media\] write the site's published reports as files (report.html, report.pdf, report.md, slides.html, slides.pdf, evidence-pack.zip) into its report-exports staging, where compose publishes them from (exit 1 on a problem; a PDF skipped for want of a browser is a note; default id: SITE\_ID); --article: one article (transcripts/reports/), published or a draft |
| `archilyzer reports check` | `<id> [--reports <a,b>] \| --article <articleId>` | \[--allow-missing-media\] what compose would say about the site's reports, with no build: each report validated, every cited quote checked against its record, every cited moment's prepared media present and current, the report video under the publish limit (exit 1 with the list; --reports checks those, drafts included; default id: SITE\_ID); --article: one article (transcripts/reports/), published or a draft, as the homepage's compose would |
| `archilyzer reports verify-quotes` | `<report.json> \| --article <articleId>` | \[--json\] every video, audio and post quote of one report against its record with compose's own check: the best score and track, and the en-orig track's score where the record has one — a quote that matches a served `en` rewrite and not en-orig is reported (exit 1 when any quote drifted) |
| `archilyzer reports attach-video` | `<report.json> <video> \| --article <articleId> <video>` | \[--poster <image>\] \[--caption <line>\] the report's video: remuxed (an H.264 mp4 under the limit) or encoded to fit the 24 MiB publish limit, written beside report.json as video.mp4 with a poster (given, kept, or a frame of the video), and `video` set in report.json (an article's through the article registry) |
+| `archilyzer reports iterations` | `<articleId> [--json]` | an article's iterations (transcripts/reports/<id>/iterations/): each one's kind, model, status, cost, lineage and what it revised or copied, the current article and current video marked (exit 1 when an iteration.json is unsound; 2 for no such article) |
| `archilyzer reports move-to-articles` | `[--keep <site>/<id>,…] [--drafts] [--apply]` | ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply *(passthrough)* |
| `archilyzer reports convert` | `<sweep\|ask\|manifest> <in> --out <report.json> [--channels-dir <dir>] [--id <id>] [--title <title>]` | a /sweep report (markdown), an /ask answer or a report-to-video manifest as a report.json, written only when it validates (--channels-dir: widen spans from the cues, find posts' channels) |
| `archilyzer reports to-manifest` | `<report.json> --out <manifest.json> [--channels-dir <dir>] [--site-origin <url>]` | a starter report-to-video manifest from a report (a chapter card per section, a claim's still and clips stamped with its verdict, its posts) |
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -269,13 +269,19 @@ export const COMMANDS: Command[] = [
{
path: ["reports", "prepare"],
usage:
- "<id> | --article <articleId> cut every clip and copy every post capture the site's published reports cite into its report-media cache, before its build, then export the reports as files (reports export) when nothing is missing (exit 1 when a citation lacks media or an export fails; default id: SITE_ID); --article: the articles' cache (transcripts/reports/), every published article plus that one",
- flags: { article: "string" },
+ "<id> | --article <articleId> [--only] cut every clip and copy every post capture the site's published reports cite into its report-media cache, before its build, then export the reports as files (reports export) when nothing is missing (exit 1 when a citation lacks media or an export fails; default id: SITE_ID); --article: the articles' cache (transcripts/reports/), every published article plus that one; --only: that article answers for the run — its problems fail it, another article's are warnings, and only it is exported",
+ flags: { article: "string", only: "boolean" },
maxPositionals: 1,
run: async ({ positionals, flags, env }) => {
const article = articleFrom(positionals, flags, "reports prepare");
if (article === null) return 2;
- if (article) return (await import("./reports-prepare")).main({ article, signal: interrupted() });
+ if (flags.only === true && !article) {
+ console.error("reports prepare: --only answers for one article: give --article <id>");
+ return 2;
+ }
+ if (article) {
+ return (await import("./reports-prepare")).main({ article, only: flags.only === true, signal: interrupted() });
+ }
const siteId = siteIdFrom(positionals, env, "reports prepare");
if (!siteId) return 2;
return (await import("./reports-prepare")).main({ siteId, signal: interrupted() });
@@ -377,6 +383,21 @@ export const COMMANDS: Command[] = [
});
},
},
+ {
+ path: ["reports", "iterations"],
+ usage:
+ "<articleId> [--json] an article's iterations (transcripts/reports/<id>/iterations/): each one's kind, model, status, cost, lineage and what it revised or copied, the current article and current video marked (exit 1 when an iteration.json is unsound; 2 for no such article)",
+ flags: { json: "boolean" },
+ maxPositionals: 1,
+ run: async ({ positionals, flags }) => {
+ const [article] = positionals;
+ if (!article) {
+ console.error("reports iterations: give <articleId>");
+ return 2;
+ }
+ return (await import("./reports-iterations")).iterationsMain({ article, json: flags.json === true });
+ },
+ },
script(["reports", "move-to-articles"], "move-reports-to-articles.ts",
"[--keep <site>/<id>,…] [--drafts] [--apply] ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply"),
{
diff --git a/common/bin/compose-homepage.test.ts b/common/bin/compose-homepage.test.ts
@@ -7,7 +7,7 @@
import { after, test } from "node:test";
import assert from "node:assert/strict";
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -30,6 +30,7 @@ const { getPaths } = await import("../lib/paths");
const { buildIndex } = await import("../controller/buildIndex");
const { articleDir, configureArticle } = await import("../lib/report/registry");
const { main, channelSiteUrlOf } = await import("./compose-homepage");
+const { createIteration, updateIteration, writeIterationFile } = await import("../lib/report/iterations");
const { REPORT_MEDIA_FORMAT, REPORT_MEDIA_VERSION } = await import("../publish/reportMedia");
const paths = getPaths();
@@ -137,3 +138,38 @@ test("channelSiteUrlOf: the first listed site with a public URL; none for a chan
assert.equal(of("y"), undefined);
assert.equal(of("z"), undefined);
});
+
+// Every file under `dir`, relative.
+function filesUnder(dir: string): string[] {
+ const out: string[] = [];
+ const walk = (d: string, rel: string) => {
+ for (const e of readdirSync(d, { withFileTypes: true })) {
+ const r = rel ? `${rel}/${e.name}` : e.name;
+ if (e.isDirectory()) walk(path.join(d, e.name), r);
+ else out.push(r);
+ }
+ };
+ if (existsSync(dir)) walk(dir, "");
+ return out;
+}
+
+test("iterations are never published: a public article's iterations and an article in the making stay off the homepage (release 27 S4)", async () => {
+ const MARK = "ITERATION-ONLY-WORDS-7f3a";
+ await createIteration("open", { kind: "sweep", model: "qwen3:8b", question: `${MARK}?` }, paths);
+ await writeIterationFile("open", 1, "report.json", article("open", { title: `${MARK} title` }), paths);
+ await writeIterationFile("open", 1, "sweep.md", `# ${MARK}\n`, paths);
+ await writeIterationFile("open", 1, "turns.jsonl", `${JSON.stringify({ role: "user", content: MARK })}\n`, paths);
+ await updateIteration("open", 1, { status: "done" }, paths);
+ await createIteration("in-the-making", { kind: "sweep", model: "qwen3:8b", question: `${MARK}?` }, paths);
+ await writeIterationFile("in-the-making", 1, "report.json", article("in-the-making", { title: MARK }), paths);
+ for (const audience of ["public", "private"] as const) {
+ await quietly(() => main({ paths, audience }));
+ const files = filesUnder(PUBLIC);
+ assert.ok(files.length > 0);
+ assert.deepEqual(files.filter((f) => /iteration|in-the-making|turns\.jsonl|sweep\.md/.test(f)), [], `${audience}: no iteration file`);
+ const leaked = files.filter((f) => /\.(json|html|md|txt|xml)$/.test(f) && readFileSync(path.join(PUBLIC, f), "utf8").includes(MARK));
+ assert.deepEqual(leaked, [], `${audience}: no iteration's words`);
+ const index = readJson<{ reports: { id: string }[] }>(path.join(PUBLIC, "articles", "index.json"));
+ assert.ok(!index.reports.some((r) => r.id === "in-the-making"));
+ }
+});
diff --git a/common/bin/reports-article.test.ts b/common/bin/reports-article.test.ts
@@ -8,7 +8,7 @@
import { after, test } from "node:test";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -30,6 +30,7 @@ const { main: prepareMain } = await import("./reports-prepare");
const { main: exportMain } = await import("./reports-export");
const { attachVideoMain } = await import("./reports-attach-video");
const { readRevisionHead } = await import("../publish/reportHistory");
+const { createIteration, makeCurrent, updateIteration, writeIterationFile } = await import("../lib/report/iterations");
const paths = getPaths();
const CHAN = "lone";
@@ -111,6 +112,35 @@ test("prepare --article: the articles' cache, every published article plus the o
assert.equal(existsSync(path.join(paths.exportIndexDir, "sites")), false, "no site's staging touched");
});
+test("prepare --article <id> --only: that article answers for the run — its gaps fail it, another's are warnings, it alone is exported (release 27 S7)", async () => {
+ // An article whose own moments are all prepared: another's gap is a warning.
+ writeJson(articleFile(paths, "solo"), {
+ format: "archilyzer-report",
+ version: 1,
+ id: "solo",
+ kind: "sweep",
+ title: "Article solo",
+ sections: [{ id: "s", title: "S", body: "Nothing cited here." }],
+ });
+ const exportOptions = { paths, openPdfPrinter: async () => ({ missing: "no browser in the test" }) };
+ const ok = capture();
+ assert.equal(await prepareMain({ article: "solo", only: true, exportOptions }, ok.out), 0, ok.text());
+ assert.match(ok.text(), /warning: 1 problem\(s\) in OTHER articles — not this one's/);
+ assert.match(ok.text(), /missing-media: lone\/abc1\/10\.00-20\.00 \(cited by pub#c1\)/);
+ assert.ok(existsSync(path.join(STAGING, "report-exports", "solo", "report.html")), "this article is exported");
+ // The cache still holds every published article's moments: nothing pruned, the index whole.
+ const index = readJson<{ problems: { citations: string[] }[] }>(path.join(STAGING, "report-media", "index.json"));
+ assert.deepEqual(index.problems.map((p) => p.citations), [["pub#c1"]]);
+ // Its own gap fails the run, named.
+ const own = capture();
+ assert.equal(await prepareMain({ article: "draft", only: true, exportOptions }, own.out), 1);
+ assert.match(own.text(), /reports prepare --article draft --only: 1 problem\(s\):/);
+ assert.match(own.text(), /the article was not exported/);
+ // --only needs an article.
+ const bad = capture();
+ assert.equal(await prepareMain({ siteId: "x", only: true }, bad.out), 2);
+});
+
test("export --article: one article's files under .export-index/articles/, its history in reports/<id>/history-git", async () => {
const c = capture();
assert.equal(
@@ -133,6 +163,38 @@ test("export --article: one article's files under .export-index/articles/, its h
assert.equal(await exportMain({ article: "nope", paths }, none.out), 2);
});
+test("an article's iterations stay out of its history; making one current is the next revision (release 27 S4)", async () => {
+ const gitDir = path.join(path.dirname(articleFile(paths, "pub")), "history-git");
+ await createIteration("pub", { kind: "sweep", model: "qwen3:8b", question: "What was said?" }, paths);
+ await writeIterationFile("pub", 1, "report.json", { ...article("pub"), title: "Article pub, iterated" }, paths);
+ await writeIterationFile("pub", 1, "sweep.md", "# iterated\n", paths);
+ await updateIteration("pub", 1, { status: "done" }, paths);
+ const tree = () =>
+ execFileSync("git", ["--git-dir", gitDir, "ls-tree", "-r", "--name-only", "main"], { encoding: "utf8" }).trim().split("\n");
+ // An export with iterations on disk and the article unchanged: nothing new.
+ const same = capture();
+ assert.equal(await exportMain({ article: "pub", paths, formats: ["md"], allowMissingMedia: true }, same.out), 0, same.text());
+ assert.equal((await readRevisionHead(gitDir))?.revision, 1);
+ await makeCurrent("pub", 1, paths);
+ const c = capture();
+ assert.equal(await exportMain({ article: "pub", paths, formats: ["md"], allowMissingMedia: true }, c.out), 0, c.text());
+ const head = await readRevisionHead(gitDir);
+ assert.equal(head?.revision, 2);
+ assert.deepEqual(head?.summary, ["Title changed: “Article pub” → “Article pub, iterated”"]);
+ assert.deepEqual(tree(), ["exports.json", "report.json", "report.md"]);
+ assert.ok(!readdirSync(path.join(STAGING, "report-exports", "pub")).some((f) => /iteration|sweep|turns/.test(f)));
+});
+
+test("an article in the making is no article to check, prepare or export (release 27 S4)", async () => {
+ await createIteration("making", { kind: "sweep", model: "qwen3:8b", question: "What was said?" }, paths);
+ await writeIterationFile("making", 1, "report.json", article("making"), paths);
+ const check = capture();
+ assert.equal(await checkMain({ article: "making", paths, allowMissingMedia: true }, check.out), 2);
+ assert.match(check.text(), /no article "making"/);
+ const ex = capture();
+ assert.equal(await exportMain({ article: "making", paths }, ex.out), 2);
+});
+
test("verify-quotes takes an article's file", async () => {
const c = capture();
assert.equal(await verifyQuotesMain({ file: articleFile(paths, "pub"), paths }, c.out), 0, c.text());
@@ -166,3 +228,28 @@ test("attach-video --article: `video` written through the registry, the audience
const none = capture();
assert.equal(await attachVideoMain({ article: "nope", video: src }, none.out), 1);
});
+
+test("reports iterations: the list with lineage, the current marked; JSON; an article in the making; refusals (release 27 S4)", async () => {
+ const { iterationsMain } = await import("./reports-iterations");
+ await createIteration("pub", { kind: "revise-report", model: "claude-sonnet-5-5", parent: 1, feedback: "Name the bridge." }, paths);
+ const c = capture();
+ assert.equal(await iterationsMain({ article: "pub", paths }, c.out), 0, c.text());
+ const lines = c.text().split("\n");
+ assert.match(lines[0], /reports iterations pub: 2 iteration\(s\)$/);
+ assert.match(lines[1], /^\* i1 +sweep +qwen3:8b +done .* i1 “What was said\?” ← current article$/);
+ assert.match(lines[2], /^ {2}i2 +revise-report +claude-sonnet-5-5 +queued .* i1 › i2 \(revises i1\) “Name the bridge\.”$/);
+ const j = capture();
+ assert.equal(await iterationsMain({ article: "pub", json: true, paths }, j.out), 0);
+ const parsed = JSON.parse(j.text()) as { inTheMaking: boolean; current: { report: number }; iterations: { n: number; lineage: number[]; currentReport: boolean }[] };
+ assert.equal(parsed.inTheMaking, false);
+ assert.equal(parsed.current.report, 1);
+ assert.deepEqual(parsed.iterations.map((i) => [i.n, i.lineage, i.currentReport]), [[1, [1], true], [2, [1, 2], false]]);
+ const making = capture();
+ assert.equal(await iterationsMain({ article: "making", paths }, making.out), 0);
+ assert.match(making.text(), /an article in the making/);
+ const none = capture();
+ assert.equal(await iterationsMain({ article: "nope", paths }, none.out), 2);
+ assert.match(none.text(), /no article "nope"/);
+ const bad = capture();
+ assert.equal(await iterationsMain({ article: "Bad", paths }, bad.out), 2);
+});
diff --git a/common/bin/reports-iterations.ts b/common/bin/reports-iterations.ts
@@ -0,0 +1,116 @@
+// `archilyzer reports iterations <id> [--json]` (release 27 S4) — an
+// article's iterations (lib/report/iterations.ts): each with its kind, model,
+// status, cost, lineage and what it revised or copied, the current article
+// and current video marked. Reads only.
+//
+// Exit 0 with the list (an article with none says so); 1 when an
+// iteration.json is unsound (it is named); 2 for a bad id, or an id that is
+// neither an article nor an article in the making.
+
+import { getPaths, type Paths } from "../lib/paths";
+import { readArticleState } from "../lib/report/registry";
+import {
+ iterationLabel,
+ iterationUsd,
+ readIterations,
+ type Iteration,
+ type IterationsCurrent,
+} from "../lib/report/iterations";
+import { isReportId } from "../lib/report/schema";
+
+type Out = { log: (s: string) => void; error: (s: string) => void };
+
+export type IterationRow = Iteration & {
+ lineage: number[];
+ usd: number;
+ currentReport: boolean;
+ currentVideo: boolean;
+};
+
+// The lineage of each iteration from the list itself (no further reads): its
+// ancestors by parent, first to it. An unsound ancestor ends the walk.
+export function iterationRows(iterations: readonly Iteration[], current: IterationsCurrent): IterationRow[] {
+ const byN = new Map(iterations.map((i) => [i.n, i]));
+ return iterations.map((it) => {
+ const line: number[] = [];
+ let at: Iteration | undefined = it;
+ while (at) {
+ line.unshift(at.n);
+ at = at.parent === null ? undefined : byN.get(at.parent);
+ }
+ return {
+ ...it,
+ lineage: line,
+ usd: iterationUsd(it),
+ currentReport: current.report === it.n,
+ currentVideo: current.video === it.n,
+ };
+ });
+}
+
+const one = (s: string, max = 60) => {
+ const t = s.replace(/\s+/g, " ").trim();
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t;
+};
+
+export function formatIterationRow(r: IterationRow): string {
+ const marks = [r.currentReport ? "current article" : "", r.currentVideo ? "current video" : ""].filter(Boolean);
+ const from = [
+ r.parent !== null ? `revises ${iterationLabel(r.parent)}` : "",
+ r.copyOf !== null ? `copy of ${iterationLabel(r.copyOf)}` : "",
+ ].filter(Boolean);
+ const words = r.feedback ?? r.question;
+ return [
+ `${r.currentReport || r.currentVideo ? "*" : " "} ${iterationLabel(r.n).padEnd(4)}`,
+ r.kind.padEnd(13),
+ r.model.padEnd(20),
+ r.status.padEnd(9),
+ (r.usd > 0 ? `$${r.usd.toFixed(2)}` : "—").padEnd(7),
+ r.createdAt.slice(0, 16).replace("T", " "),
+ ` ${r.lineage.map(iterationLabel).join(" › ")}`,
+ ...(from.length ? [`(${from.join(", ")})`] : []),
+ ...(words ? [`“${one(words)}”`] : []),
+ ...(marks.length ? [`← ${marks.join(", ")}`] : []),
+ ].join(" ");
+}
+
+export async function iterationsMain(
+ opts: { article: string; json?: boolean; paths?: Pick<Paths, "articlesDir" | "exportIndexDir"> },
+ out: Out = console,
+): Promise<number> {
+ const paths = opts.paths ?? getPaths();
+ const id = opts.article;
+ if (!isReportId(id)) {
+ out.error(`reports iterations: "${id}" is not an article id`);
+ return 2;
+ }
+ let read;
+ try {
+ read = await readIterations(id, paths);
+ } catch (err) {
+ out.error(`reports iterations: ${(err as Error).message}`);
+ return 2;
+ }
+ const exists = (await readArticleState(id, paths)) !== null;
+ if (!exists && read.iterations.length === 0 && read.problems.length === 0) {
+ out.error(`reports iterations: no article "${id}" (no reports/${id}/)`);
+ return 2;
+ }
+ const rows = iterationRows(read.iterations, read.current);
+ if (opts.json) {
+ out.log(
+ JSON.stringify(
+ { article: id, inTheMaking: !exists, current: read.current, iterations: rows, problems: read.problems },
+ null,
+ 2,
+ ),
+ );
+ } else {
+ out.log(
+ `reports iterations ${id}: ${rows.length} iteration(s)${exists ? "" : " — an article in the making (no report.json yet)"}`,
+ );
+ for (const r of rows) out.log(formatIterationRow(r));
+ for (const p of read.problems) out.error(` ${iterationLabel(p.n)}: ${p.problems.join("; ")}`);
+ }
+ return read.problems.length > 0 ? 1 : 0;
+}
diff --git a/common/bin/reports-prepare.ts b/common/bin/reports-prepare.ts
@@ -12,11 +12,22 @@
// Exit 0 when every cited moment has its media and every export was written;
// 1 when any problem is listed (the manifest is written either way, problems
// included); 2 for a site that does not exist.
+//
+// `--article <id> --only` (release 27 S7): the article being readied is what
+// the run answers for. The media is still prepared for every published
+// article too — the articles' cache is one directory and a prepare prunes
+// every clip its run does not cite — but only THAT article's problems fail
+// the run (another's are printed as warnings), and only it is exported.
import { getPaths } from "../lib/paths";
import { formatReportMediaProblems, prepareReportMedia } from "../publish/reportMedia";
-import { exportAfterPrepare, formatReportExportProblems, type ExportSiteReportsOptions } from "../publish/reportExports";
-import { articlesWorkHost, type ReportHost } from "../publish/reportHost";
+import {
+ exportAfterPrepare,
+ exportSiteReports,
+ formatReportExportProblems,
+ type ExportSiteReportsOptions,
+} from "../publish/reportExports";
+import { articlesWorkHost, isArticleProblem, type ReportHost } from "../publish/reportHost";
type Out = { log: (s: string) => void; error: (s: string) => void };
@@ -25,13 +36,19 @@ export async function main(
// The site, or `article` — one article id: the articles' run.
siteId?: string;
article?: string;
+ // With `article`: answer for that article alone (above).
+ only?: boolean;
signal?: AbortSignal;
// Passed to the export at the end (tests inject the PDF printer and zip).
exportOptions?: Partial<Pick<ExportSiteReportsOptions, "openPdfPrinter" | "zipBin" | "paths" | "settings">>;
},
out: Out = console,
): Promise<number> {
- const who = opts.article ? `--article ${opts.article}` : opts.siteId;
+ const who = opts.article ? `--article ${opts.article}${opts.only ? " --only" : ""}` : opts.siteId;
+ if (opts.only && !opts.article) {
+ out.error("reports prepare: --only answers for one article: give --article <id>");
+ return 2;
+ }
let index;
let host: ReportHost | undefined;
try {
@@ -46,6 +63,7 @@ export async function main(
out.error(`reports prepare: ${(err as Error).message}`);
return opts.signal?.aborted ? 1 : 2;
}
+ if (opts.only && opts.article) return onlyArticle(opts.article, index, opts, out);
if (index.problems.length > 0) {
out.error(`reports prepare ${who}: ${index.problems.length} problem(s):`);
for (const line of formatReportMediaProblems(index.problems)) out.error(` ${line}`);
@@ -69,3 +87,45 @@ export async function main(
for (const line of formatReportExportProblems(exported.problems)) out.error(` ${line}`);
return 1;
}
+
+// The rest of a `--only` run: this article's problems fail it, another's are
+// warnings, and this article alone is exported (resolved over a host of it
+// alone, so another article's gap cannot refuse it).
+async function onlyArticle(
+ article: string,
+ index: Awaited<ReturnType<typeof prepareReportMedia>>,
+ opts: Parameters<typeof main>[0],
+ out: Out,
+): Promise<number> {
+ const who = `--article ${article} --only`;
+ const own = index.problems.filter((p) => isArticleProblem(p, article));
+ const others = index.problems.filter((p) => !isArticleProblem(p, article));
+ if (others.length > 0) {
+ out.log(`reports prepare ${who}: warning: ${others.length} problem(s) in OTHER articles — not this one's:`);
+ for (const line of formatReportMediaProblems(others)) out.log(` ${line}`);
+ }
+ if (own.length > 0) {
+ out.error(`reports prepare ${who}: ${own.length} problem(s):`);
+ for (const line of formatReportMediaProblems(own)) out.error(` ${line}`);
+ out.error("reports prepare: the article was not exported (its evidence media is not complete).");
+ return 1;
+ }
+ let exported;
+ try {
+ const paths = opts.exportOptions?.paths ?? getPaths();
+ exported = await exportSiteReports({
+ host: await articlesWorkHost(paths, [article], { only: true }),
+ reportId: article,
+ signal: opts.signal,
+ onLog: out.log,
+ ...opts.exportOptions,
+ });
+ } catch (err) {
+ out.error(`reports prepare: export: ${(err as Error).message}`);
+ return 1;
+ }
+ if (exported.problems.length === 0) return 0;
+ out.error(`reports prepare ${who}: export: ${exported.problems.length} problem(s):`);
+ for (const line of formatReportExportProblems(exported.problems)) out.error(` ${line}`);
+ return 1;
+}
diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts
@@ -398,3 +398,26 @@ test("a Twitch record's v<n> is fetched into, and read from, its data/<n>/ (rele
const written = await readFile(path.join(paths.channelsDir, "c", "data", fresh, "clips", "5.00-15.00.mp4"), "utf8");
assert.equal(written, "mp4");
});
+
+// Release 27 S7 (the owed "pad" bug): `from`/`to` are the window, padding
+// included, and `pad` is provenance. A cached UNPADDED window of the cited
+// span must not answer for the padded ask — it is fetched, and the sidecar
+// records the pad.
+test("a cached unpadded window does not cover a padded ask: it is fetched, its pad recorded", async () => {
+ const paths = await corpus();
+ const clips = path.join(paths.channelsDir, "c", "data", "v1", "clips");
+ await mkdir(clips, { recursive: true });
+ // The cited span alone, as an unpadded fetch left it.
+ await writeFile(path.join(clips, "10.00-20.00.mp4"), "mp4");
+ const h = harness();
+ const before = await spawns();
+ const padded = { ...item("v1", "/pad", 7, 23), pad: 3 };
+ const r = await go(paths, [padded], h);
+ assert.deepEqual([r.cached.length, r.fetched.length], [0, 1], "fetched, not answered from the unpadded window");
+ assert.equal((await spawns()) - before, 1);
+ const sidecar = JSON.parse(await readFile(path.join(clips, "7.00-23.00.json"), "utf8")) as { pad?: number };
+ assert.equal(sidecar.pad, 3);
+ // Asked again, the padded window answers — and the unpadded ask is served by it too.
+ const again = await go(paths, [padded, item("v1", "/exact", 10, 20)], harness());
+ assert.deepEqual([again.cached.length, again.fetched.length], [2, 0]);
+});
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -116,6 +116,14 @@ export type FetchWindowsItem = {
// `<reportId>#<citationId>`, or a manifest's clip id.
clipId?: string;
reason?: string;
+ // How many of the window's seconds, each side, are padding around what is
+ // cited — PROVENANCE, recorded in the window's sidecar. `from` and `to` are
+ // the window, padding included: every caller pads before it asks
+ // (fetch-via-editor.mjs and the MCP's fetch_clip `max(0, start - pad)`,
+ // `end + pad`; the release 27 chain the same), so a cached window covers an
+ // item only when it holds all of [from, to] — padding seconds included. An
+ // unpadded window on disk never answers for a padded ask (release 27 S7 pins
+ // it). Sending the cited span with `pad` set fetches the span unpadded.
pad?: number;
// The page URL when the caller has it; else resolved as the single fetch does.
webpageUrl?: string;
diff --git a/common/lib/report/convert.test.ts b/common/lib/report/convert.test.ts
@@ -616,3 +616,23 @@ test("reportToManifest: a post with no known platform or link is left out with a
postId: "3abcxyz",
});
});
+
+// Release 27 S7: two owed bugs of to-manifest, over the synthetic `paragraphs`
+// sweep (a trailing Coverage section of prose only).
+test("reportToManifest: the title card carries a foot; a section with nothing to show gets no chapter card", async () => {
+ const { convertFixture, deriveFixture } = await import("../../testing/draft/derive");
+ const { report } = await convertFixture("paragraphs");
+ assert.ok(report.sections.some((s) => s.title === "Coverage"), "the report keeps its Coverage section");
+ const result = await reportToManifest(report, { today: "2026-10-13" });
+ assert.ok(result.ok);
+ const timeline = result.manifest.timeline as Record<string, unknown>[];
+ assert.equal(timeline[0].style, "title");
+ assert.equal(timeline[0].foot, "");
+ assert.ok(!timeline.some((e) => e.type === "card" && e.heading === "Coverage"), "no Coverage card");
+ // The cut no longer ends on a card.
+ assert.equal(timeline[timeline.length - 1].type, "clip");
+ assert.ok(result.warnings.some((w) => /section "Coverage" \(.*\): nothing in it to show — no chapter card/.test(w)), result.warnings.join("\n"));
+ // The committed fixture is what the converter now makes.
+ const { manifest } = await deriveFixture("paragraphs");
+ assert.ok(!(manifest.timeline as Record<string, unknown>[]).some((e) => e.heading === "Coverage"));
+});
diff --git a/common/lib/report/convertManifest.ts b/common/lib/report/convertManifest.ts
@@ -435,6 +435,9 @@ export async function reportToManifest(raw: unknown, opts: ManifestOptions = {})
seconds: CARD_SECONDS.title,
heading: report.title,
sub: report.subtitle ?? "",
+ // The title card's third line (render-cards.mjs): empty until the
+ // operator writes one. A card without the key printed "undefined".
+ foot: "",
});
const claimTag = (claim: Claim | null) => (claim?.verdict ? { claim: { id: claim.id, verdict: claim.verdict } } : {});
@@ -525,13 +528,15 @@ export async function reportToManifest(raw: unknown, opts: ManifestOptions = {})
};
for (const section of report.sections) {
- timeline.push({
+ const card = {
type: "card",
id: entryIds.claim(section.id, "section"),
style: "chapter",
seconds: CARD_SECONDS.chapter,
heading: section.title,
- });
+ };
+ timeline.push(card);
+ const at = timeline.length;
for (const cid of citedIds(section.body)) await emit(cid, null);
for (const claim of section.claims ?? []) {
if (claim.sourceQuote) await emit(claim.sourceQuote.citation, claim, true);
@@ -540,6 +545,13 @@ export async function reportToManifest(raw: unknown, opts: ManifestOptions = {})
if (cid !== claim.sourceQuote?.citation) await emit(cid, claim);
}
}
+ // A section with nothing to show (a trailing Coverage note, prose only)
+ // would be a chapter card followed by the next one — or, last, a silent
+ // card at the end of the cut. It gets none; the article keeps the section.
+ if (timeline.length === at) {
+ timeline.pop();
+ warnings.push(`section "${section.title}" (${section.id}): nothing in it to show — no chapter card (the article keeps the section)`);
+ }
}
const channelSlug = [...channels.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? "";
diff --git a/common/lib/report/iterations.test.ts b/common/lib/report/iterations.test.ts
@@ -0,0 +1,276 @@
+// An article's iterations (release 27 S4): created under the registry's lock,
+// validated, never the article until made current. Temp stores only.
+//
+// Run with: node_modules/.bin/tsx --test lib/report/iterations.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import os from "node:os";
+import path from "node:path";
+import {
+ ARTICLES_LOCK_FILENAME,
+ ArticleRegistryError,
+ articleFile,
+ configureArticle,
+ listArticleDirs,
+ listArticles,
+ listPendingArticles,
+ readArticleState,
+ writeArticle,
+} from "./registry";
+import {
+ addIterationUsage,
+ appendIterationTurns,
+ copyIteration,
+ createIteration,
+ currentIteration,
+ iterationDir,
+ iterationUsd,
+ lineage,
+ listIterations,
+ makeCurrent,
+ parseIteration,
+ projectOf,
+ readIteration,
+ readIterationFile,
+ readIterations,
+ recordIterationStep,
+ reportSourceOf,
+ setCurrentVideo,
+ updateIteration,
+ writeIterationFile,
+} from "./iterations";
+
+const ROOTS: string[] = [];
+after(() => {
+ for (const r of ROOTS) rmSync(r, { recursive: true, force: true });
+});
+
+function store() {
+ const root = mkdtempSync(path.join(tmpdir(), "article-iterations-"));
+ ROOTS.push(root);
+ return { articlesDir: path.join(root, "transcripts", "reports"), exportIndexDir: path.join(root, ".export-index") };
+}
+
+const doc = (id: string, over: Record<string, unknown> = {}) => ({
+ format: "archilyzer-report",
+ version: 1,
+ id,
+ kind: "sweep",
+ title: `Article ${id}`,
+ sections: [{ id: "s1", title: "One", body: "Plain words." }],
+ ...over,
+});
+
+const NOW = new Date("2026-10-13T12:00:00.000Z");
+const json = (file: string) => JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
+
+async function done(paths: ReturnType<typeof store>, id: string, n: number, report?: unknown) {
+ if (report) await writeIterationFile(id, n, "report.json", report, paths);
+ return updateIteration(id, n, { status: "done" }, paths, NOW);
+}
+
+test("a new article: its first iteration is not an article until it is made current", async () => {
+ const paths = store();
+ const it = await createIteration("fresh", { kind: "sweep", model: "qwen3:8b", question: "What was said?", scope: { channels: ["synth-kitchen"] } }, paths, NOW);
+ assert.equal(it.n, 1);
+ assert.equal(it.status, "queued");
+ assert.equal(it.parent, null);
+ assert.ok(existsSync(path.join(iterationDir(paths, "fresh", 1), "iteration.json")));
+ // Not listed, not a draft, not readable as an article.
+ assert.deepEqual(await listArticleDirs(paths), []);
+ assert.deepEqual(await listArticles(paths), []);
+ assert.equal(await readArticleState("fresh", paths), null);
+ assert.deepEqual(await listPendingArticles(paths), ["fresh"]);
+ await assert.rejects(configureArticle("fresh", { published: true }, paths), /no article "fresh"/);
+ // Made current, it is a draft like any other.
+ await done(paths, "fresh", 1, doc("fresh"));
+ const { report, current } = await makeCurrent("fresh", 1, paths, NOW);
+ assert.equal(report.title, "Article fresh");
+ assert.deepEqual(current, { report: 1, reportFrom: 1, video: null, reportAt: NOW.toISOString() });
+ assert.deepEqual(await listArticleDirs(paths), ["fresh"]);
+ assert.deepEqual(await listPendingArticles(paths), []);
+ const state = await readArticleState("fresh", paths);
+ assert.equal(state?.published, false);
+ assert.equal(state?.exists, true);
+});
+
+test("lineage, current and copy: revisions chain by parent; a copy shares the base and names its original", async () => {
+ const paths = store();
+ await writeArticle(doc("art"), { paths });
+ await configureArticle("art", { audience: "public" }, paths);
+ await createIteration("art", { kind: "sweep", model: "claude-sonnet-5-5", question: "Q?" }, paths, NOW);
+ await done(paths, "art", 1, doc("art", { title: "First" }));
+ const i2 = await createIteration("art", { kind: "revise-report", model: "qwen3:8b", parent: 1, feedback: " tighter " }, paths, NOW);
+ assert.equal(i2.feedback, "tighter");
+ await done(paths, "art", 2, doc("art", { title: "Second" }));
+ const i3 = await createIteration("art", { kind: "revise-video", model: "qwen3:8b", parent: 2, feedback: "shorter" }, paths, NOW);
+ await done(paths, "art", 3);
+ const i4 = await copyIteration("art", 2, { model: "claude-sonnet-5-5" }, paths, NOW);
+ assert.deepEqual([i4.n, i4.kind, i4.parent, i4.copyOf, i4.feedback, i4.model], [4, "revise-report", 1, 2, "tighter", "claude-sonnet-5-5"]);
+ assert.deepEqual(await lineage("art", 3, paths), [1, 2, 3]);
+ assert.deepEqual(await lineage("art", 4, paths), [1, 4]);
+ assert.equal(i3.n, 3);
+ // A video revision's report is its parent's.
+ assert.equal(await reportSourceOf("art", 3, paths), 2);
+ const made = await makeCurrent("art", 3, paths, NOW);
+ assert.equal(made.report.title, "Second");
+ assert.deepEqual([made.current.report, made.current.reportFrom], [3, 2]);
+ // The audience on disk is the registry's; the iteration's report never sets it.
+ assert.equal(json(articleFile(paths, "art")).audience, "public");
+ // The video: recorded by the chain's attach step, kept by a later makeCurrent.
+ await setCurrentVideo("art", 3, paths, NOW);
+ const again = await makeCurrent("art", 1, paths, NOW);
+ assert.deepEqual([again.current.report, again.current.reportFrom, again.current.video], [1, 1, 3]);
+ assert.equal(json(articleFile(paths, "art")).title, "First");
+ assert.deepEqual((await currentIteration("art", paths)).video, 3);
+ assert.deepEqual((await listIterations("art", paths)).map((i) => i.n), [1, 2, 3, 4]);
+});
+
+test("makeCurrent keeps the article's attached video when the report has none", async () => {
+ const paths = store();
+ await writeArticle(doc("vid", { video: { src: "video.mp4", poster: "poster.jpg" } }), { paths });
+ await createIteration("vid", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW);
+ await done(paths, "vid", 1, doc("vid", { title: "New words" }));
+ await makeCurrent("vid", 1, paths, NOW);
+ const onDisk = json(articleFile(paths, "vid"));
+ assert.equal(onDisk.title, "New words");
+ assert.deepEqual(onDisk.video, { src: "video.mp4", poster: "poster.jpg" });
+});
+
+test("locking under contention: concurrent creates get distinct numbers; a held lock is waited for", async () => {
+ const paths = store();
+ const made = await Promise.all(
+ Array.from({ length: 8 }, (_, i) => createIteration("busy", { kind: "sweep", model: `m${i}`, question: "Q?" }, paths, NOW)),
+ );
+ assert.deepEqual(made.map((m) => m.n).sort((a, b) => a - b), [1, 2, 3, 4, 5, 6, 7, 8]);
+ // Another process holds the store's lock (a live pid on this host): a create waits for it.
+ const lock = path.join(paths.articlesDir, ARTICLES_LOCK_FILENAME);
+ writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), since: Date.now() }));
+ let settled = false;
+ const pending = createIteration("busy", { kind: "sweep", model: "late", question: "Q?" }, paths, NOW).then((it) => {
+ settled = true;
+ return it;
+ });
+ await new Promise((r) => setTimeout(r, 150));
+ assert.equal(settled, false, "waits while the lock is held");
+ rmSync(lock);
+ assert.equal((await pending).n, 9);
+ // Concurrent updates of one iteration: each patch reads it as it is now.
+ await Promise.all(
+ Array.from({ length: 6 }, (_, i) =>
+ recordIterationStep("busy", 1, { task: `step-${i}`, status: "done" }, paths, NOW),
+ ),
+ );
+ assert.equal((await readIteration("busy", 1, paths))?.steps.length, 6);
+});
+
+test("refusals: a revision needs a done parent and feedback; fixed keys; files by allowlist; only done is made current", async () => {
+ const paths = store();
+ await assert.rejects(createIteration("Bad Id", { kind: "sweep", model: "m", question: "Q?" }, paths), /not an article id/);
+ await assert.rejects(createIteration("r", { kind: "sweep", model: "m" }, paths), /needs its question/);
+ await assert.rejects(createIteration("r", { kind: "sweep", model: " ", question: "Q?" }, paths), /names its model/);
+ await assert.rejects(createIteration("r", { kind: "nope" as "sweep", model: "m", question: "Q?" }, paths), /kind must be one of/);
+ await assert.rejects(createIteration("r", { kind: "revise-report", model: "m", feedback: "x" }, paths), /needs the iteration it revises/);
+ await createIteration("r", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW);
+ await assert.rejects(createIteration("r", { kind: "revise-report", model: "m", parent: 1, feedback: "x" }, paths), /i1 is queued: only a done iteration is revised/);
+ await assert.rejects(createIteration("r", { kind: "revise-report", model: "m", parent: 7, feedback: "x" }, paths), /no iteration i7/);
+ await updateIteration("r", 1, { status: "done" }, paths, NOW);
+ await assert.rejects(createIteration("r", { kind: "revise-report", model: "m", parent: 1, feedback: " " }, paths), /needs feedback/);
+ await assert.rejects(updateIteration("r", 1, { kind: "research" } as never, paths), /may not change "kind"/);
+ await assert.rejects(updateIteration("r", 1, { status: "exploded" } as never, paths), /would make it unsound/);
+ await assert.rejects(updateIteration("r", 2, { status: "done" }, paths), /no iteration i2/);
+ await assert.rejects(writeIterationFile("r", 1, "../evil.json" as "sweep.md", "x", paths), /not an iteration file/);
+ await assert.rejects(writeIterationFile("r", 1, "report.json", doc("other"), paths), /is "other", not "r"|does not parse/);
+ await assert.rejects(writeIterationFile("r", 1, "report.json", "{nope", paths), /not JSON/);
+ await assert.rejects(writeIterationFile("r", 1, "turns.jsonl", '{"a":1}\nnope\n', paths), /line 2 is not JSON/);
+ await assert.rejects(writeIterationFile("r", 9, "sweep.md", "# x", paths), /no iteration i9/);
+ // Made current: needs a report in its lineage, and a sound one.
+ await assert.rejects(makeCurrent("r", 1, paths), /has no report.json/);
+ await createIteration("r", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW);
+ await writeIterationFile("r", 2, "report.json", doc("r"), paths);
+ await assert.rejects(makeCurrent("r", 2, paths), /i2 is queued: only a done iteration is made current/);
+ await updateIteration("r", 2, { status: "done" }, paths, NOW);
+ // A report that parses but has a problem (an unknown citation id) is kept in
+ // the iteration and refused as the article.
+ await writeIterationFile("r", 2, "report.json", doc("r", { sections: [{ id: "s1", title: "One", body: "See [x](cite:missing)." }] }), paths);
+ await assert.rejects(makeCurrent("r", 2, paths), (e: unknown) => e instanceof ArticleRegistryError && /not a sound report/.test(e.message));
+ assert.equal(existsSync(articleFile(paths, "r")), false, "nothing written");
+ assert.throws(() => projectOf("/p", "Bad", 1), /not an article id/);
+ assert.throws(() => projectOf("/p", "ok", 0), /not an iteration number/);
+});
+
+test("updates: endedAt stamped when a run ends; usage summed per model; turns appended; steps replaced by task", async () => {
+ const paths = store();
+ await createIteration("u", { kind: "sweep", model: "claude-sonnet-5-5", question: "Q?", status: "running" }, paths, NOW);
+ const later = new Date("2026-10-13T12:05:00.000Z");
+ await addIterationUsage("u", 1, "claude-sonnet-5-5", { usd: 0.25, inputTokens: 1000, outputTokens: 200, cacheReadTokens: 50 }, paths, later);
+ await addIterationUsage("u", 1, "claude-sonnet-5-5", { usd: 0.5, inputTokens: 10, outputTokens: 20, calls: 1 }, paths, later);
+ await addIterationUsage("u", 1, "claude-haiku-4-5", { usd: 0.01, inputTokens: 5, outputTokens: 5 }, paths, later);
+ await recordIterationStep("u", 1, { task: "narrate", model: "qwen3:8b", status: "running" }, paths, later);
+ await recordIterationStep("u", 1, { task: "narrate", model: "qwen3:8b", status: "done", minutes: 2 }, paths, later);
+ await appendIterationTurns("u", 1, [{ role: "user", content: "hi" }], paths);
+ await appendIterationTurns("u", 1, [{ role: "assistant", content: "hello" }, { role: "user", content: "more" }], paths);
+ const it = await updateIteration("u", 1, { status: "done", minutes: 5 }, paths, later);
+ assert.equal(it.endedAt, later.toISOString());
+ assert.equal(it.updatedAt, later.toISOString());
+ assert.equal(it.createdAt, NOW.toISOString());
+ assert.deepEqual(it.usage["claude-sonnet-5-5"], { usd: 0.75, inputTokens: 1010, outputTokens: 220, cacheReadTokens: 50, calls: 1 });
+ assert.equal(iterationUsd(it), 0.76);
+ assert.deepEqual(it.steps, [{ task: "narrate", model: "qwen3:8b", status: "done", minutes: 2 }]);
+ const turns = (await readIterationFile("u", 1, "turns.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l));
+ assert.deepEqual(turns.map((t) => t.content), ["hi", "hello", "more"]);
+ // A key a later slice adds survives an update.
+ await updateIteration("u", 1, { proposalsPending: 2 } as never, paths, later);
+ await updateIteration("u", 1, { minutes: 6 }, paths, later);
+ assert.equal((await readIteration("u", 1, paths) as Record<string, unknown>).proposalsPending, 2);
+});
+
+test("an unsound iteration.json is named, the rest still listed", async () => {
+ const paths = store();
+ await createIteration("p", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW);
+ await createIteration("p", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW);
+ writeFileSync(path.join(iterationDir(paths, "p", 2), "iteration.json"), "{torn");
+ mkdirSync(iterationDir(paths, "p", 3));
+ const read = await readIterations("p", paths);
+ assert.deepEqual(read.iterations.map((i) => i.n), [1]);
+ assert.deepEqual(read.problems.map((p) => p.n), [2, 3]);
+ assert.match(read.problems[0].problems[0], /unparseable/);
+ // The next number is past every directory, sound or not.
+ assert.equal((await createIteration("p", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW)).n, 4);
+});
+
+test("parseIteration: filed under its own article and number; parent and original are earlier", () => {
+ const base = {
+ format: "archilyzer-iteration",
+ version: 1,
+ article: "a",
+ n: 2,
+ kind: "sweep",
+ model: "m",
+ parent: null,
+ copyOf: null,
+ status: "done",
+ usage: {},
+ steps: [],
+ createdAt: NOW.toISOString(),
+ updatedAt: NOW.toISOString(),
+ };
+ assert.equal(parseIteration(base, { article: "a", n: 2 }).ok, true);
+ const bad = (over: Record<string, unknown>, where = { article: "a", n: 2 }) => {
+ const r = parseIteration({ ...base, ...over }, where);
+ return r.ok ? [] : r.problems;
+ };
+ assert.match(bad({}, { article: "b", n: 2 })[0], /filed under "b"/);
+ assert.match(bad({}, { article: "a", n: 3 })[0], /filed under iterations\/3/);
+ assert.match(bad({ parent: 2 })[0], /not an earlier iteration/);
+ assert.match(bad({ copyOf: 5 })[0], /not an earlier iteration/);
+ assert.match(bad({ kind: "revise-video" })[0], /revises an iteration/);
+ assert.match(bad({ scope: { channels: ["../x"] } })[0], /channel slug/);
+});
+
+test("projectOf: <root>/<id>/i<n>/", () => {
+ assert.equal(projectOf("/projects", "my-article", 3), path.join("/projects", "my-article", "i3"));
+});
diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts
@@ -0,0 +1,751 @@
+// AN ARTICLE'S ITERATIONS — one generation's result and its provenance
+// (release 27, S4; plans/release-27.md "Shape" and D1). "Iteration" because
+// "version" (Report.version, the format), "revision" (the site history's
+// "Revision N"), "draft" (an unpublished article) and "take" (umtool's
+// alternative renders) are taken (plans/FACTS.md).
+//
+// transcripts/reports/<id>/iterations/<n>/iteration.json what it is (below)
+// transcripts/reports/<id>/iterations/<n>/report.json the report it made
+// transcripts/reports/<id>/iterations/<n>/sweep.md the sweep's text
+// transcripts/reports/<id>/iterations/<n>/turns.jsonl the model turns
+// transcripts/reports/<id>/iterations/<n>/proposals.json a research run's
+// acquisitions (S11)
+// transcripts/reports/<id>/iterations/current.json which iteration
+// the article and
+// its video are
+//
+// Every write goes through the article registry's lock (registry.ts
+// withArticleStoreLock), is validated, and replaces its file whole. The
+// article's own report.json is the CURRENT iteration's: `makeCurrent` writes
+// it, through the registry's writer, and nothing a generation runs ever does.
+// Its site history (publish/reportHistory.ts) commits report.json alone, so a
+// makeCurrent is a Revision like any other write the next export sees.
+//
+// Iterations are NEVER published: compose copies named files of an article,
+// never its directory; the history commits report.json, report.md and
+// exports.json; the homepage reads the registry. A directory with iterations
+// and no report.json is an article in the making — the registry does not list
+// it (registry.ts listPendingArticles) until its first makeCurrent.
+//
+// A video project lives OFF the corpus disk, under the generation settings'
+// projects root (D1): `projectOf(root, id, n)` = `<root>/<id>/i<n>/`, recorded
+// in the iteration as `projectDir`.
+//
+// SERVER-ONLY (node:fs).
+
+import { appendFile, mkdir, readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import { z } from "zod";
+import { getPaths, type Paths } from "../paths";
+import { readJsonFile, writeFileAtomic, writeJsonAtomic } from "../jsonFile-server";
+import { isReportId, REPORT_ID_RE, type Report } from "./schema";
+import { parseReport } from "./validate";
+import {
+ ARTICLE_ITERATIONS_DIRNAME,
+ ArticleRegistryError,
+ articleDir,
+ articleFile,
+ withArticleStoreLock,
+ writeArticleHoldingLock,
+} from "./registry";
+
+export const ITERATION_FORMAT = "archilyzer-iteration";
+export const ITERATION_VERSION = 1;
+export const ITERATION_FILENAME = "iteration.json";
+export const ITERATIONS_CURRENT_FILENAME = "current.json";
+export const ITERATIONS_CURRENT_FORMAT = "archilyzer-iterations-current";
+
+export const ITERATION_KINDS = ["sweep", "revise-report", "revise-video", "research"] as const;
+export type IterationKind = (typeof ITERATION_KINDS)[number];
+// `queued`: created for a job that has not started; the rest as a job ends.
+export const ITERATION_STATUSES = ["queued", "running", "done", "failed", "cancelled"] as const;
+export type IterationStatus = (typeof ITERATION_STATUSES)[number];
+export const ITERATION_STEP_STATUSES = ["pending", "running", "done", "failed", "cancelled", "skipped"] as const;
+export type IterationStepStatus = (typeof ITERATION_STEP_STATUSES)[number];
+
+// The files writeIterationFile may write (iteration.json is written by
+// create/update only). A later slice adds a name here, never a path.
+export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json"] as const;
+export type IterationFile = (typeof ITERATION_FILES)[number];
+
+// A revision needs something to revise.
+const NEEDS_PARENT: readonly IterationKind[] = ["revise-report", "revise-video"];
+
+// ─── The schema ───
+
+const isoTime = z.string().refine((s) => Number.isFinite(Date.parse(s)), "is not an ISO 8601 time");
+const ymd = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "is not a YYYY-MM-DD date");
+const iterationNumber = z.number().int().positive();
+const channelSlug = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, "is not a channel slug");
+
+// One model's spend in an iteration, summed over its calls.
+export const iterationUsageSchema = z.looseObject({
+ usd: z.number().nonnegative(),
+ inputTokens: z.number().int().nonnegative(),
+ outputTokens: z.number().int().nonnegative(),
+ cacheReadTokens: z.number().int().nonnegative().optional(),
+ cacheWriteTokens: z.number().int().nonnegative().optional(),
+ calls: z.number().int().nonnegative().optional(),
+});
+export type IterationUsage = z.infer<typeof iterationUsageSchema>;
+
+// One step a job or the chain ran over the iteration (narration, the
+// pipeline's steps): what, on which model, how it went, what it cost.
+export const iterationStepSchema = z.looseObject({
+ task: z.string().min(1),
+ model: z.string().min(1).optional(),
+ status: z.enum(ITERATION_STEP_STATUSES),
+ // USD.
+ cost: z.number().nonnegative().optional(),
+ minutes: z.number().nonnegative().optional(),
+ startedAt: isoTime.optional(),
+ endedAt: isoTime.optional(),
+ jobId: z.string().min(1).optional(),
+ // One line: what it did, or why it failed.
+ detail: z.string().optional(),
+});
+export type IterationStep = z.infer<typeof iterationStepSchema>;
+
+export const iterationCheckSchema = z.looseObject({
+ name: z.string().min(1),
+ ok: z.boolean(),
+ detail: z.string().optional(),
+});
+export type IterationCheck = z.infer<typeof iterationCheckSchema>;
+
+export const iterationScopeSchema = z.looseObject({
+ channels: z.array(channelSlug).optional(),
+ from: ymd.optional(),
+ to: ymd.optional(),
+});
+export type IterationScope = z.infer<typeof iterationScopeSchema>;
+
+// Loose: a key a later slice adds survives an update by code that predates it.
+export const iterationSchema = z.looseObject({
+ format: z.literal(ITERATION_FORMAT),
+ version: z.literal(ITERATION_VERSION),
+ article: z.string().regex(REPORT_ID_RE),
+ n: iterationNumber,
+ kind: z.enum(ITERATION_KINDS),
+ model: z.string().min(1),
+ // The iteration it revises (a revision's), else null.
+ parent: iterationNumber.nullable(),
+ // The iteration it is a copy of on another model (same parent, feedback,
+ // question and scope), else null.
+ copyOf: iterationNumber.nullable(),
+ feedback: z.string().optional(),
+ question: z.string().optional(),
+ scope: iterationScopeSchema.optional(),
+ status: z.enum(ITERATION_STATUSES),
+ error: z.string().optional(),
+ // By model id.
+ usage: z.record(z.string(), iterationUsageSchema),
+ ops: z.looseObject({ applied: z.array(z.unknown()), refused: z.array(z.unknown()) }).optional(),
+ minutes: z.number().nonnegative().optional(),
+ checks: z.array(iterationCheckSchema).optional(),
+ steps: z.array(iterationStepSchema),
+ // The video project (projectOf), once one is made.
+ projectDir: z.string().min(1).optional(),
+ // The editor job that generates it.
+ jobId: z.string().min(1).optional(),
+ createdAt: isoTime,
+ updatedAt: isoTime,
+ endedAt: isoTime.optional(),
+});
+export type Iteration = z.infer<typeof iterationSchema>;
+
+// Which iteration the article is, and which its video is. `reportFrom` is the
+// iteration whose report.json the article holds: the iteration itself, or —
+// for a video revision, which has no report of its own — its nearest
+// ancestor's.
+export type IterationsCurrent = {
+ report: number | null;
+ reportFrom: number | null;
+ video: number | null;
+ reportAt?: string;
+ videoAt?: string;
+};
+
+const NO_CURRENT: IterationsCurrent = { report: null, reportFrom: null, video: null };
+
+function problemsOf(error: z.ZodError): string[] {
+ return error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`);
+}
+
+// An iteration.json, checked: the schema, and what the schema cannot say —
+// that it is the article's and the number's it is filed under, and that its
+// parent and original are earlier iterations.
+export function parseIteration(
+ raw: unknown,
+ where: { article: string; n: number },
+): { ok: true; value: Iteration } | { ok: false; problems: string[] } {
+ const r = iterationSchema.safeParse(raw);
+ if (!r.success) return { ok: false, problems: problemsOf(r.error) };
+ const it = r.data;
+ const problems: string[] = [];
+ if (it.article !== where.article) problems.push(`article: "${it.article}" is filed under "${where.article}"`);
+ if (it.n !== where.n) problems.push(`n: ${it.n} is filed under iterations/${where.n}`);
+ if (it.parent !== null && it.parent >= it.n) problems.push(`parent: i${it.parent} is not an earlier iteration`);
+ if (it.copyOf !== null && it.copyOf >= it.n) problems.push(`copyOf: i${it.copyOf} is not an earlier iteration`);
+ if (NEEDS_PARENT.includes(it.kind) && it.parent === null) problems.push(`parent: a ${it.kind} revises an iteration`);
+ return problems.length ? { ok: false, problems } : { ok: true, value: it };
+}
+
+// ─── Where ───
+
+type StorePaths = Pick<Paths, "articlesDir" | "exportIndexDir">;
+
+export function iterationsDir(paths: StorePaths, id: string): string {
+ return path.join(articleDir(paths, id), ARTICLE_ITERATIONS_DIRNAME);
+}
+
+export function iterationDir(paths: StorePaths, id: string, n: number): string {
+ return path.join(iterationsDir(paths, id), String(n));
+}
+
+export function iterationFile(paths: StorePaths, id: string, n: number, name: IterationFile | typeof ITERATION_FILENAME): string {
+ return path.join(iterationDir(paths, id, n), name);
+}
+
+// How an iteration is named to a person: `i3`.
+export function iterationLabel(n: number): string {
+ return `i${n}`;
+}
+
+// An iteration's video project: `<projectsRoot>/<id>/i<n>/` (D1).
+export function projectOf(projectsRoot: string, id: string, n: number): string {
+ assertId(id);
+ assertN(n);
+ return path.join(projectsRoot, id, iterationLabel(n));
+}
+
+function assertId(id: unknown): asserts id is string {
+ if (!isReportId(id)) {
+ throw new ArticleRegistryError(`"${String(id)}" is not an article id (a lowercase slug: [a-z0-9][a-z0-9-]*, at most 64)`);
+ }
+}
+
+function assertN(n: unknown): asserts n is number {
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1) {
+ throw new ArticleRegistryError(`${String(n)} is not an iteration number (1, 2, …)`);
+ }
+}
+
+// ─── Reading ───
+
+// The iteration numbers on disk, ascending: directories named 1, 2, ….
+async function iterationNumbers(paths: StorePaths, id: string): Promise<number[]> {
+ let names: string[];
+ try {
+ names = (await readdir(iterationsDir(paths, id), { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
+ } catch {
+ return [];
+ }
+ return names
+ .filter((n) => /^[1-9]\d{0,8}$/.test(n))
+ .map(Number)
+ .sort((a, b) => a - b);
+}
+
+// One iteration, or null when there is none. Throws when its iteration.json
+// is unreadable or unsound.
+export async function readIteration(id: string, n: number, paths: StorePaths = getPaths()): Promise<Iteration | null> {
+ assertId(id);
+ assertN(n);
+ const read = await readJsonFile(iterationFile(paths, id, n, ITERATION_FILENAME));
+ if (!read.ok) {
+ if (read.reason === "absent") return null;
+ throw new ArticleRegistryError(`reports/${id}/iterations/${n}/${ITERATION_FILENAME} is ${read.reason}`);
+ }
+ const parsed = parseIteration(read.value, { article: id, n });
+ if (!parsed.ok) throw new ArticleRegistryError(`reports/${id}/iterations/${n}/${ITERATION_FILENAME} is not sound`, parsed.problems);
+ return parsed.value;
+}
+
+async function readCurrent(paths: StorePaths, id: string): Promise<IterationsCurrent> {
+ const read = await readJsonFile(path.join(iterationsDir(paths, id), ITERATIONS_CURRENT_FILENAME));
+ if (!read.ok || !read.value || typeof read.value !== "object") return { ...NO_CURRENT };
+ const v = read.value as Record<string, unknown>;
+ const num = (x: unknown) => (typeof x === "number" && Number.isInteger(x) && x > 0 ? x : null);
+ return {
+ report: num(v.report),
+ reportFrom: num(v.reportFrom) ?? num(v.report),
+ video: num(v.video),
+ ...(typeof v.reportAt === "string" ? { reportAt: v.reportAt } : {}),
+ ...(typeof v.videoAt === "string" ? { videoAt: v.videoAt } : {}),
+ };
+}
+
+async function writeCurrent(paths: StorePaths, id: string, current: IterationsCurrent): Promise<void> {
+ await writeJsonAtomic(
+ path.join(iterationsDir(paths, id), ITERATIONS_CURRENT_FILENAME),
+ { format: ITERATIONS_CURRENT_FORMAT, version: 1, ...current },
+ { mkdir: true },
+ );
+}
+
+export type IterationsRead = {
+ // The sound ones, by n.
+ iterations: Iteration[];
+ // One per iteration directory whose iteration.json is absent or unsound.
+ problems: { n: number; problems: string[] }[];
+ current: IterationsCurrent;
+};
+
+// Every iteration of an article, its unsound ones named, and which is current.
+export async function readIterations(id: string, paths: StorePaths = getPaths()): Promise<IterationsRead> {
+ assertId(id);
+ const out: IterationsRead = { iterations: [], problems: [], current: await readCurrent(paths, id) };
+ for (const n of await iterationNumbers(paths, id)) {
+ try {
+ const it = await readIteration(id, n, paths);
+ if (it) out.iterations.push(it);
+ else out.problems.push({ n, problems: [`there is no ${ITERATION_FILENAME}`] });
+ } catch (err) {
+ const e = err as ArticleRegistryError;
+ out.problems.push({ n, problems: e.problems?.length ? e.problems : [e.message] });
+ }
+ }
+ return out;
+}
+
+export async function listIterations(id: string, paths: StorePaths = getPaths()): Promise<Iteration[]> {
+ return (await readIterations(id, paths)).iterations;
+}
+
+// Which iteration the article is and which its video is (nulls: none made
+// current yet, or an article older than iterations).
+export async function currentIteration(id: string, paths: StorePaths = getPaths()): Promise<IterationsCurrent> {
+ assertId(id);
+ return readCurrent(paths, id);
+}
+
+// The iterations from the first to `n` by parent: [1, 3, 5] for i5 revising
+// i3 revising i1. A parent is always earlier (create refuses otherwise), so
+// the walk ends.
+export async function lineage(id: string, n: number, paths: StorePaths = getPaths()): Promise<number[]> {
+ const out: number[] = [];
+ let at: number | null = n;
+ while (at !== null) {
+ const it = await readIteration(id, at, paths);
+ if (!it) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(at)}`);
+ out.unshift(at);
+ at = it.parent;
+ }
+ return out;
+}
+
+// A file of an iteration as text, or null when it has none.
+export async function readIterationFile(
+ id: string,
+ n: number,
+ name: IterationFile,
+ paths: StorePaths = getPaths(),
+): Promise<string | null> {
+ assertId(id);
+ assertN(n);
+ if (!(ITERATION_FILES as readonly string[]).includes(name)) throw new ArticleRegistryError(`"${name}" is not an iteration file`);
+ try {
+ return await readFile(iterationFile(paths, id, n, name), "utf8");
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw err;
+ }
+}
+
+// The iteration whose report.json `n`'s report is: n itself when it made one,
+// else the nearest ancestor that did (a video revision keeps its parent's
+// report). Null when none in its lineage has one.
+export async function reportSourceOf(id: string, n: number, paths: StorePaths = getPaths()): Promise<number | null> {
+ const line = await lineage(id, n, paths);
+ for (let i = line.length - 1; i >= 0; i--) {
+ if ((await readIterationFile(id, line[i], "report.json", paths)) !== null) return line[i];
+ }
+ return null;
+}
+
+// What an iteration cost in USD, over every model.
+export function iterationUsd(it: Pick<Iteration, "usage">): number {
+ return Object.values(it.usage).reduce((s, u) => s + u.usd, 0);
+}
+
+// ─── Writing ───
+
+export type NewIteration = {
+ kind: IterationKind;
+ model: string;
+ parent?: number | null;
+ copyOf?: number | null;
+ feedback?: string;
+ question?: string;
+ scope?: IterationScope;
+ status?: Extract<IterationStatus, "queued" | "running">;
+ projectDir?: string;
+ jobId?: string;
+};
+
+// Write a new iteration.json for `id` at the next number, under the lock the
+// caller holds.
+async function createLocked(id: string, input: NewIteration, paths: StorePaths, now: Date): Promise<Iteration> {
+ const parent = input.parent ?? null;
+ const copyOf = input.copyOf ?? null;
+ if (parent !== null) {
+ assertN(parent);
+ const p = await readIteration(id, parent, paths);
+ if (!p) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(parent)} to revise`);
+ if (p.status !== "done") throw new ArticleRegistryError(`"${id}" ${iterationLabel(parent)} is ${p.status}: only a done iteration is revised`);
+ }
+ if (copyOf !== null) {
+ assertN(copyOf);
+ if (!(await readIteration(id, copyOf, paths))) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(copyOf)} to copy`);
+ }
+ if (NEEDS_PARENT.includes(input.kind)) {
+ if (parent === null) throw new ArticleRegistryError(`a ${input.kind} iteration needs the iteration it revises (parent)`);
+ if (!input.feedback?.trim()) throw new ArticleRegistryError(`a ${input.kind} iteration needs feedback: say what to change`);
+ }
+ if ((input.kind === "sweep" || input.kind === "research") && parent === null && !input.question?.trim() && copyOf === null) {
+ throw new ArticleRegistryError(`a ${input.kind} iteration needs its question`);
+ }
+ const taken = await iterationNumbers(paths, id);
+ const n = (taken[taken.length - 1] ?? 0) + 1;
+ const at = now.toISOString();
+ const raw: Iteration = {
+ format: ITERATION_FORMAT,
+ version: ITERATION_VERSION,
+ article: id,
+ n,
+ kind: input.kind,
+ model: input.model,
+ parent,
+ copyOf,
+ ...(input.feedback?.trim() ? { feedback: input.feedback.trim() } : {}),
+ ...(input.question?.trim() ? { question: input.question.trim() } : {}),
+ ...(input.scope ? { scope: input.scope } : {}),
+ status: input.status ?? "queued",
+ usage: {},
+ steps: [],
+ ...(input.projectDir ? { projectDir: input.projectDir } : {}),
+ ...(input.jobId ? { jobId: input.jobId } : {}),
+ createdAt: at,
+ updatedAt: at,
+ };
+ const parsed = parseIteration(raw, { article: id, n });
+ if (!parsed.ok) throw new ArticleRegistryError(`"${id}": the new iteration is not sound`, parsed.problems);
+ await mkdir(iterationsDir(paths, id), { recursive: true });
+ // Not recursive: a directory that is already there (a writer that did not
+ // take the lock) is refused, never shared.
+ await mkdir(iterationDir(paths, id, n));
+ await writeJsonAtomic(iterationFile(paths, id, n, ITERATION_FILENAME), parsed.value);
+ return parsed.value;
+}
+
+// A NEW ITERATION of `id` — of an article, or of an article in the making
+// (S8's /articles/new: no report.json yet). Its number is the next one,
+// allocated under the lock, so two creates never share one.
+export async function createIteration(
+ id: string,
+ input: NewIteration,
+ paths: StorePaths = getPaths(),
+ now: Date = new Date(),
+): Promise<Iteration> {
+ assertId(id);
+ if (!(ITERATION_KINDS as readonly string[]).includes(input.kind)) {
+ throw new ArticleRegistryError(`kind must be one of ${ITERATION_KINDS.join(", ")}`);
+ }
+ if (!input.model?.trim()) throw new ArticleRegistryError("an iteration names its model");
+ return withArticleStoreLock(() => createLocked(id, { ...input, model: input.model.trim() }, paths, now), paths);
+}
+
+// A COPY of iteration `n` on another model: the same kind, parent, feedback,
+// question and scope, `copyOf` n — to compare two models on the same work.
+export async function copyIteration(
+ id: string,
+ n: number,
+ opts: { model: string; jobId?: string; status?: NewIteration["status"] },
+ paths: StorePaths = getPaths(),
+ now: Date = new Date(),
+): Promise<Iteration> {
+ assertId(id);
+ assertN(n);
+ if (!opts.model?.trim()) throw new ArticleRegistryError("a copy names its model");
+ return withArticleStoreLock(async () => {
+ const src = await readIteration(id, n, paths);
+ if (!src) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)} to copy`);
+ return createLocked(
+ id,
+ {
+ kind: src.kind,
+ model: opts.model.trim(),
+ parent: src.parent,
+ copyOf: n,
+ ...(src.feedback ? { feedback: src.feedback } : {}),
+ ...(src.question ? { question: src.question } : {}),
+ ...(src.scope ? { scope: src.scope } : {}),
+ ...(opts.jobId ? { jobId: opts.jobId } : {}),
+ ...(opts.status ? { status: opts.status } : {}),
+ },
+ paths,
+ now,
+ );
+ }, paths);
+}
+
+// What names an iteration and where it came from: an update never changes it.
+const FIXED_KEYS = ["format", "version", "article", "n", "kind", "parent", "copyOf", "createdAt"] as const;
+
+export type IterationPatch = Partial<Omit<Iteration, (typeof FIXED_KEYS)[number] | "updatedAt">>;
+
+// PATCH AN ITERATION — read inside the lock and patched as it is now (a
+// function patch is given it). A key given as `undefined` is removed. Written
+// only when the result is sound. `updatedAt` is stamped; `endedAt` too when
+// the status becomes done, failed or cancelled and the patch gives none.
+export async function updateIteration(
+ id: string,
+ n: number,
+ patch: IterationPatch | ((current: Iteration) => IterationPatch),
+ paths: StorePaths = getPaths(),
+ now: Date = new Date(),
+): Promise<Iteration> {
+ assertId(id);
+ assertN(n);
+ return withArticleStoreLock(() => updateLocked(id, n, patch, paths, now), paths);
+}
+
+async function updateLocked(
+ id: string,
+ n: number,
+ patch: IterationPatch | ((current: Iteration) => IterationPatch),
+ paths: StorePaths,
+ now: Date,
+): Promise<Iteration> {
+ const cur = await readIteration(id, n, paths);
+ if (!cur) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`);
+ const changes = typeof patch === "function" ? patch(cur) : patch;
+ for (const k of [...FIXED_KEYS, "updatedAt"]) {
+ if (k in (changes as object)) throw new ArticleRegistryError(`"${id}" ${iterationLabel(n)}: an update may not change "${k}"`);
+ }
+ const next: Record<string, unknown> = { ...cur };
+ for (const [k, v] of Object.entries(changes)) {
+ if (v === undefined) delete next[k];
+ else next[k] = v;
+ }
+ next.updatedAt = now.toISOString();
+ const ended = ["done", "failed", "cancelled"].includes(String(next.status));
+ if (ended && cur.status !== next.status && !("endedAt" in changes)) next.endedAt = now.toISOString();
+ const parsed = parseIteration(next, { article: id, n });
+ if (!parsed.ok) throw new ArticleRegistryError(`"${id}" ${iterationLabel(n)}: the update would make it unsound`, parsed.problems);
+ await writeJsonAtomic(iterationFile(paths, id, n, ITERATION_FILENAME), parsed.value);
+ return parsed.value;
+}
+
+// Record one step (narration, a pipeline step): it replaces the newest record
+// of the same task, else is appended — so a step re-run or resumed is one
+// record, as it last ran.
+export async function recordIterationStep(
+ id: string,
+ n: number,
+ step: IterationStep,
+ paths: StorePaths = getPaths(),
+ now: Date = new Date(),
+): Promise<Iteration> {
+ return updateIteration(
+ id,
+ n,
+ (cur) => {
+ const steps = [...cur.steps];
+ let at = -1;
+ for (let i = steps.length - 1; i >= 0; i--) {
+ if (steps[i].task === step.task) {
+ at = i;
+ break;
+ }
+ }
+ if (at >= 0) steps[at] = step;
+ else steps.push(step);
+ return { steps };
+ },
+ paths,
+ now,
+ );
+}
+
+// Add one call's spend to a model's usage.
+export async function addIterationUsage(
+ id: string,
+ n: number,
+ model: string,
+ add: IterationUsage,
+ paths: StorePaths = getPaths(),
+ now: Date = new Date(),
+): Promise<Iteration> {
+ return updateIteration(
+ id,
+ n,
+ (cur) => {
+ const was = cur.usage[model];
+ const sum = (a?: number, b?: number) => (a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0));
+ const next: IterationUsage = {
+ usd: (was?.usd ?? 0) + add.usd,
+ inputTokens: (was?.inputTokens ?? 0) + add.inputTokens,
+ outputTokens: (was?.outputTokens ?? 0) + add.outputTokens,
+ };
+ for (const k of ["cacheReadTokens", "cacheWriteTokens", "calls"] as const) {
+ const v = sum(was?.[k], add[k]);
+ if (v !== undefined) next[k] = v;
+ }
+ return { usage: { ...cur.usage, [model]: next } };
+ },
+ paths,
+ now,
+ );
+}
+
+function fileText(name: IterationFile, data: string | Uint8Array | object, id: string): string | Buffer {
+ if (name === "report.json" || name === "proposals.json") {
+ let value: unknown;
+ if (typeof data === "string" || data instanceof Uint8Array) {
+ try {
+ value = JSON.parse(typeof data === "string" ? data : Buffer.from(data).toString("utf8"));
+ } catch {
+ throw new ArticleRegistryError(`${name} is not JSON`);
+ }
+ } else {
+ value = data;
+ }
+ if (name === "report.json") {
+ const parsed = parseReport(value, { id });
+ if (!parsed.ok) {
+ throw new ArticleRegistryError(`the iteration's report.json does not parse`, parsed.problems.map((p) => `${p.path || "(root)"}: ${p.message}`));
+ }
+ if ((value as { id?: unknown }).id !== id) {
+ throw new ArticleRegistryError(`the iteration's report.json is "${String((value as { id?: unknown }).id)}", not "${id}"`);
+ }
+ } else if (!value || typeof value !== "object") {
+ throw new ArticleRegistryError("proposals.json is a JSON object or list");
+ }
+ return `${JSON.stringify(value, null, 2)}\n`;
+ }
+ if (typeof data !== "string" && !(data instanceof Uint8Array)) throw new ArticleRegistryError(`${name} is text`);
+ const text = typeof data === "string" ? data : Buffer.from(data).toString("utf8");
+ if (name === "turns.jsonl") assertJsonLines(text);
+ return text;
+}
+
+function assertJsonLines(text: string): void {
+ for (const [i, line] of text.split("\n").entries()) {
+ if (!line.trim()) continue;
+ try {
+ JSON.parse(line);
+ } catch {
+ throw new ArticleRegistryError(`turns.jsonl line ${i + 1} is not JSON`);
+ }
+ }
+}
+
+// WRITE ONE FILE OF AN ITERATION — a name from ITERATION_FILES, replaced
+// whole. report.json must parse as a report of this article (its problems
+// are the checks' to name; makeCurrent refuses a report with any); proposals.json
+// must be JSON; turns.jsonl one JSON value a line. Answers the file's path.
+export async function writeIterationFile(
+ id: string,
+ n: number,
+ name: IterationFile,
+ data: string | Uint8Array | object,
+ paths: StorePaths = getPaths(),
+): Promise<string> {
+ assertId(id);
+ assertN(n);
+ if (!(ITERATION_FILES as readonly string[]).includes(name)) {
+ throw new ArticleRegistryError(`"${name}" is not an iteration file (${ITERATION_FILES.join(", ")})`);
+ }
+ const text = fileText(name, data, id);
+ return withArticleStoreLock(async () => {
+ if (!(await readIteration(id, n, paths))) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`);
+ const file = iterationFile(paths, id, n, name);
+ await writeFileAtomic(file, text);
+ return file;
+ }, paths);
+}
+
+// Append turns to turns.jsonl, one JSON line each (a run's transcript grows
+// as it goes; a whole rewrite per turn would be quadratic).
+export async function appendIterationTurns(
+ id: string,
+ n: number,
+ turns: readonly unknown[],
+ paths: StorePaths = getPaths(),
+): Promise<void> {
+ assertId(id);
+ assertN(n);
+ const text = turns.map((t) => `${JSON.stringify(t)}\n`).join("");
+ if (!text) return;
+ await withArticleStoreLock(async () => {
+ if (!(await readIteration(id, n, paths))) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`);
+ await appendFile(iterationFile(paths, id, n, "turns.jsonl"), text);
+ }, paths);
+}
+
+// USE THIS ITERATION: the article's report.json becomes the iteration's
+// report (a video revision's: its nearest ancestor's), written through the
+// registry's writer — the only path that writes it from an iteration, so it is
+// validated (a report with any problem is refused) and keeps the article's
+// audience and its attached video. Only a done iteration is made current.
+// The first makeCurrent of an article in the making creates its report.json:
+// from then on it is a draft like any other.
+export async function makeCurrent(
+ id: string,
+ n: number,
+ paths: StorePaths = getPaths(),
+ now: Date = new Date(),
+): Promise<{ report: Report; current: IterationsCurrent }> {
+ assertId(id);
+ assertN(n);
+ return withArticleStoreLock(async () => {
+ const it = await readIteration(id, n, paths);
+ if (!it) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`);
+ if (it.status !== "done") throw new ArticleRegistryError(`"${id}" ${iterationLabel(n)} is ${it.status}: only a done iteration is made current`);
+ const from = await reportSourceOf(id, n, paths);
+ if (from === null) throw new ArticleRegistryError(`"${id}" ${iterationLabel(n)} has no report.json, nor has any iteration it revises`);
+ const text = await readIterationFile(id, from, "report.json", paths);
+ let doc: unknown;
+ try {
+ doc = JSON.parse(text ?? "");
+ } catch {
+ throw new ArticleRegistryError(`reports/${id}/iterations/${from}/report.json is not JSON`);
+ }
+ // Who may read the article is the registry's (configureArticle), never a
+ // generation's: the article's audience on disk is kept.
+ if (doc && typeof doc === "object" && !Array.isArray(doc)) {
+ const { audience: _audience, ...rest } = doc as Record<string, unknown>;
+ doc = rest;
+ }
+ const report = await writeArticleHoldingLock(doc, { paths, keepAudience: true, keepVideo: true });
+ const was = await readCurrent(paths, id);
+ const current: IterationsCurrent = { ...was, report: n, reportFrom: from, reportAt: now.toISOString() };
+ await writeCurrent(paths, id, current);
+ return { report, current };
+ }, paths);
+}
+
+// Record that the article's video is iteration `n`'s (the chain's attach
+// step, after `reports attach-video` wrote it).
+export async function setCurrentVideo(
+ id: string,
+ n: number,
+ paths: StorePaths = getPaths(),
+ now: Date = new Date(),
+): Promise<IterationsCurrent> {
+ assertId(id);
+ assertN(n);
+ return withArticleStoreLock(async () => {
+ if (!(await readIteration(id, n, paths))) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`);
+ const current: IterationsCurrent = { ...(await readCurrent(paths, id)), video: n, videoAt: now.toISOString() };
+ await writeCurrent(paths, id, current);
+ return current;
+ }, paths);
+}
+
+// Whether the article has a report.json (an article in the making has not).
+export async function hasArticleReport(id: string, paths: StorePaths = getPaths()): Promise<boolean> {
+ return (await readJsonFile(articleFile(paths, id))).ok;
+}
diff --git a/common/lib/report/registry.ts b/common/lib/report/registry.ts
@@ -11,6 +11,13 @@
// transcripts/reports/<id>/report.json the article (REPORT.md), with
// `audience` "public" | "private"
// (absent = private, D2)
+// transcripts/reports/<id>/iterations/ the article's generations
+// (release 27, ./iterations.ts),
+// written under the same lock and
+// never published; a directory with
+// iterations and no report.json is
+// an article in the making, not
+// listed (listPendingArticles)
// transcripts/reports/.registry.lock held while a write runs
//
// THE LOCK is two locks: withJsonFileLock (in-process: the editor's routes and
@@ -123,12 +130,14 @@ export async function readArticlesIndex(paths: Pick<Paths, "articlesDir"> = getP
return parsed.index;
}
-// Every article directory, published or draft: a directory under
-// `transcripts/reports/` whose name is an article id. Sorted.
-export async function listArticleDirs(paths: Pick<Paths, "articlesDir"> = getPaths()): Promise<string[]> {
+// The directory of an article's iterations (release 27, ./iterations.ts).
+// Named here because the registry must know one when it lists articles.
+export const ARTICLE_ITERATIONS_DIRNAME = "iterations";
+
+async function idDirs(dir: string): Promise<string[]> {
let entries: Dirent[];
try {
- entries = await readdir(paths.articlesDir, { withFileTypes: true });
+ entries = await readdir(dir, { withFileTypes: true });
} catch {
return [];
}
@@ -138,6 +147,37 @@ export async function listArticleDirs(paths: Pick<Paths, "articlesDir"> = getPat
.sort((a, b) => a.localeCompare(b));
}
+// An article IN THE MAKING (release 27, S4): a directory with `iterations/`
+// and no report.json — a generation started it, and no iteration has been made
+// current yet. The registry does not list it as an article (not even a draft):
+// nothing that reads the registry — compose, the homepage, the editor's
+// Articles tab, umtool's /articles, `reports check` — sees it until the first
+// makeCurrent writes its report.json. `listPendingArticles` lists them.
+async function isPendingArticleDir(dir: string): Promise<boolean> {
+ if (await stat(path.join(dir, "report.json")).then(() => true, () => false)) return false;
+ return (await stat(path.join(dir, ARTICLE_ITERATIONS_DIRNAME)).catch(() => null))?.isDirectory() ?? false;
+}
+
+// Every article directory, published or draft: a directory under
+// `transcripts/reports/` whose name is an article id — an article in the
+// making (iterations and no report.json) excepted. Sorted.
+export async function listArticleDirs(paths: Pick<Paths, "articlesDir"> = getPaths()): Promise<string[]> {
+ const out: string[] = [];
+ for (const id of await idDirs(paths.articlesDir)) {
+ if (!(await isPendingArticleDir(path.join(paths.articlesDir, id)))) out.push(id);
+ }
+ return out;
+}
+
+// Every article in the making: iterations and no report.json yet. Sorted.
+export async function listPendingArticles(paths: Pick<Paths, "articlesDir"> = getPaths()): Promise<string[]> {
+ const out: string[] = [];
+ for (const id of await idDirs(paths.articlesDir)) {
+ if (await isPendingArticleDir(path.join(paths.articlesDir, id))) out.push(id);
+ }
+ return out;
+}
+
// One article as the registry knows it.
export type ArticleState = {
id: string;
@@ -195,6 +235,8 @@ export async function readArticleState(
if (!read.ok && read.reason === "absent" && !index.published.includes(id)) {
const dir = await stat(articleDir(paths, id)).catch(() => null);
if (!dir?.isDirectory()) return null;
+ // An article in the making is not an article yet.
+ if (await isPendingArticleDir(articleDir(paths, id))) return null;
}
return stateOf(id, read, index);
}
@@ -483,25 +525,48 @@ export async function patchArticle(
// problem. A document with no `audience` keeps the one on disk (regenerating a
// public article does not make it private); `keepAudience: false` writes it as
// given. Its place in the index is untouched: publish with setPublished.
-export async function writeArticle(
- doc: unknown,
- opts: { paths?: Pick<Paths, "articlesDir" | "exportIndexDir">; keepAudience?: boolean } = {},
-): Promise<Report> {
+export type WriteArticleOptions = {
+ paths?: Pick<Paths, "articlesDir" | "exportIndexDir">;
+ keepAudience?: boolean;
+ // Keep the attached `video` on disk when the document has none (release 27:
+ // making a report iteration current does not take the article's video away;
+ // the chain's attach step replaces it). Default false.
+ keepVideo?: boolean;
+};
+
+export async function writeArticle(doc: unknown, opts: WriteArticleOptions = {}): Promise<Report> {
const paths = opts.paths ?? getPaths();
+ articleIdOf(doc); // refused before the lock is taken
+ return withArticleStoreLock(() => writeArticleHoldingLock(doc, { ...opts, paths }), paths);
+}
+
+function articleIdOf(doc: unknown): string {
if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw new ArticleRegistryError("an article is a JSON object");
const id = (doc as { id?: unknown }).id;
assertId(id);
- return withArticleStoreLock(async () => {
- let next = doc as Record<string, unknown>;
- if (opts.keepAudience !== false && next.audience === undefined) {
- const read = await readArticle(paths, id);
- if (read.ok && read.raw.audience !== undefined) next = { ...next, audience: read.raw.audience };
+ return id;
+}
+
+// writeArticle's body, for a caller that already holds withArticleStoreLock
+// and writes more than the article as one (lib/report/iterations.ts
+// makeCurrent). The lock is not re-entrant: never call writeArticle there.
+export async function writeArticleHoldingLock(doc: unknown, opts: WriteArticleOptions = {}): Promise<Report> {
+ const paths = opts.paths ?? getPaths();
+ const id = articleIdOf(doc);
+ let next = doc as Record<string, unknown>;
+ if ((opts.keepAudience !== false && next.audience === undefined) || (opts.keepVideo === true && next.video === undefined)) {
+ const read = await readArticle(paths, id);
+ if (read.ok && opts.keepAudience !== false && next.audience === undefined && read.raw.audience !== undefined) {
+ next = { ...next, audience: read.raw.audience };
}
- const parsed = parseReport(next, { id });
- if (!parsed.ok || parsed.problems.length > 0) {
- throw new ArticleRegistryError(`"${id}" is not a sound report`, problemLines(parsed.problems));
+ if (read.ok && opts.keepVideo === true && next.video === undefined && read.raw.video !== undefined) {
+ next = { ...next, video: read.raw.video };
}
- await writeJsonAtomic(articleFile(paths, id), next, { mkdir: true });
- return parsed.value;
- }, paths);
+ }
+ const parsed = parseReport(next, { id });
+ if (!parsed.ok || parsed.problems.length > 0) {
+ throw new ArticleRegistryError(`"${id}" is not a sound report`, problemLines(parsed.problems));
+ }
+ await writeJsonAtomic(articleFile(paths, id), next, { mkdir: true });
+ return parsed.value;
}
diff --git a/common/publish/reportHost.ts b/common/publish/reportHost.ts
@@ -153,9 +153,15 @@ export function hostCorpusLink(host: ReportHost, channel: string, params: Record
// is not published yet (a draft being readied). Its prepared media and
// exports therefore serve both homepage builds. An included id with no
// report.json is refused.
+//
+// `only: true` (release 27 S7) is `include` alone, published or not: the
+// host one article's EXPORT is resolved over, so another article's gap does
+// not refuse it. Never prepare over it: the articles' media cache is one
+// directory, and a prepare prunes every clip its run does not cite.
export async function articlesWorkHost(
paths: Pick<Paths, "articlesDir" | "exportIndexDir" | "channelsDir">,
include: readonly string[] = [],
+ opts: { only?: boolean } = {},
): Promise<ReportHost> {
for (const id of include) {
if (!isReportId(id)) throw new Error(`"${id}" is not an article id`);
@@ -163,9 +169,16 @@ export async function articlesWorkHost(
throw new Error(`no article "${id}" (no reports/${id}/report.json)`);
}
}
+ if (opts.only) return articlesReportHost(paths, { audience: "private", published: [...new Set(include)] });
const published = await publishedArticleIds("private", paths);
return articlesReportHost(paths, {
audience: "private",
published: [...published, ...include.filter((id) => !published.includes(id))],
});
}
+
+// The problems that are `articleId`'s own: a problem of its report, or of a
+// moment one of its citations cites (`<id>#<citation>`).
+export function isArticleProblem(p: { report?: string; citations?: readonly string[] }, articleId: string): boolean {
+ return p.report === articleId || (p.citations ?? []).some((c) => c.startsWith(`${articleId}#`));
+}
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -18,5 +18,7 @@ transcript, channel or person goes in these fixtures, ever.
| `draft/reports/`, `draft/manifests/` | `basic`, `posts-only`, `paragraphs` converted (`report.json`) and taken to a video manifest, as the converters make them today. |
| `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. |
-As committed (S0), the `paragraphs` manifest shows two owed bugs that release 27 S7 fixes: the title
-card has no `foot`, and the Coverage section becomes a bare chapter card. S7 regenerates it.
+As committed at S0, the `paragraphs` manifest showed two owed bugs: the title card had no `foot`, and
+the Coverage section became a bare chapter card. Release 27 S7 fixed both and regenerated the files:
+every title card has `foot: ""`, and a section with nothing to show (Coverage; `posts-only`'s Posts)
+gets no chapter card.
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/manifests/basic.video.manifest.json b/common/testing/draft/manifests/basic.video.manifest.json
@@ -49,7 +49,8 @@
"style": "title",
"seconds": 4,
"heading": "Synth Kitchen — what the baker says about the bakery",
- "sub": ""
+ "sub": "",
+ "foot": ""
},
{
"type": "card",
diff --git a/common/testing/draft/manifests/paragraphs.video.manifest.json b/common/testing/draft/manifests/paragraphs.video.manifest.json
@@ -49,7 +49,8 @@
"style": "title",
"seconds": 4,
"heading": "Paragraphs between findings",
- "sub": ""
+ "sub": "",
+ "foot": ""
},
{
"type": "card",
@@ -77,13 +78,6 @@
"end": 9.8,
"cite": 5,
"quote": "we tried the sourdough recipe from last week"
- },
- {
- "type": "card",
- "id": "coverage",
- "style": "chapter",
- "seconds": 3.5,
- "heading": "Coverage"
}
]
}
diff --git a/common/testing/draft/manifests/posts-only.video.manifest.json b/common/testing/draft/manifests/posts-only.video.manifest.json
@@ -49,14 +49,8 @@
"style": "title",
"seconds": 4,
"heading": "Posts only",
- "sub": ""
- },
- {
- "type": "card",
- "id": "posts",
- "style": "chapter",
- "seconds": 3.5,
- "heading": "Posts"
+ "sub": "",
+ "foot": ""
}
],
"posts": [
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/common/ytdlp/fetchWindowManaged.test.ts b/common/ytdlp/fetchWindowManaged.test.ts
@@ -122,3 +122,25 @@ test("a rumble.com upload served progressive is retried once without the HLS opt
assert.equal(hasPicky(mine[1]), false);
assert.equal(await readFile(res.file, "utf8"), "mp4");
});
+
+// Release 27 S7 (the owed "pad" bug): from/to are the window, padding
+// included; a cached window of the unpadded span must not answer for a padded
+// ask, and a window that holds the padded seconds does.
+test("a cached unpadded window does not cover a padded ask; a padded one covers it and the unpadded span", async () => {
+ delete process.env.FAKE_MODE;
+ const videoDir = await setup("pad");
+ await mkdir(path.join(videoDir, "clips"), { recursive: true });
+ await writeFile(path.join(videoDir, "clips", "10.00-20.00.mp4"), "mp4");
+ const before = (await runs()).length;
+ const padded = { ...opts(videoDir), videoUrl: "https://example.test/v1", from: 7, to: 23, provenance: { requestedBy: "test", pad: 3 } };
+ const res = await fetchWindowManaged(padded);
+ assert.equal(res.cached, false, "the unpadded window did not answer");
+ assert.deepEqual([res.from, res.to], [7, 23]);
+ assert.equal((await runs()).length - before, 1);
+ const again = await fetchWindowManaged(padded);
+ assert.equal(again.cached, true);
+ const exact = await fetchWindowManaged({ ...padded, from: 10, to: 20 });
+ assert.equal(exact.cached, true);
+ // The tightest window that holds the ask: the unpadded one for the unpadded span.
+ assert.deepEqual([exact.from, exact.to], [10, 20]);
+});
diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts
@@ -167,7 +167,9 @@ export async function fetchWindowManaged(
// ASK THE CACHE FIRST, and accept a WIDER file. A report cites the same
// stream more than once; without containing-window reuse a generous fetch for
- // one clip is worthless to the neighbour it already covers.
+ // one clip is worthless to the neighbour it already covers. `from`/`to` are
+ // the window WITH its padding (`provenance.pad` only records how much), so an
+ // unpadded window on disk never answers for a padded ask (release 27 S7).
const hit = await findContainingClipWindow(videoDir, from, to);
if (hit) {
opts.onLog(
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,11 @@
# Changelog
## [Unreleased]
+- **`umtool chain <article> <n>` takes an article's iteration to a video and a podcast.** One step a process, each recorded in the iteration: make it current, have the editor fetch every cited clip window (padded to the cut's 3 s, so the article's clips and the video share one fetch), `reports prepare --article <id> --only`, have the editor capture this article's missing post screenshots, make the video manifest in `~/reports/articles/<id>/i<n>/` (its narration and voices carried over from the parent iteration's project), voice the narration through the editor, build the video and the podcast, attach the video to the article and check it, and hard-link the segments and voices the article's projects share. Run again, it resumes at the first step not done; `--from <step>` runs from one, `--dry` prints the steps, `--final` crossfades. Nothing is fetched, captured or voiced but by the editor.
+- **`reports prepare --article <id> --only` answers for that article.** Its problems fail the run, another article's are printed as warnings, and only it is exported, so a draft being readied is no longer held up by a gap in a published article. The media of every published article is still prepared (their cache is shared).
+- **A report video made by `reports to-manifest` no longer shows "undefined" under its title or ends on a silent card.** The title card now has an empty third line (and a manifest made before this renders one too), and a section with nothing to show — a trailing Coverage note, a section of posts only — gets no chapter card; the article keeps the section.
+- **`umtool build <project> --dry` names the real pipeline directory wherever it is run from** (it printed `<cwd>/report-to-video`).
+- **`archilyzer reports iterations <id> [--json]` lists an article's iterations.** Release 27 keeps each generation of an article (a sweep, a revision of its report or its video, a research run) as an ITERATION under `transcripts/reports/<id>/iterations/<n>/`, with its kind, model, status, cost, parent and the iteration it copies; the command lists them with their lineage (`i1 › i3 › i4`), and marks the current article and the current video. Iterations are never published: compose, an article's history and the homepage ignore them, and an article whose only content is iterations (no report.json yet) is not listed anywhere until one of them is made current.
- **Orpheus speaks as the operator picked by ear: zac, calmer, quicker, in longer runs.** The default Orpheus voice is now `zac` (leah stays available); the sampler is cooler (temperature 0.55, top_p 0.85) and its repeat penalty higher (1.2), which reads less acted and less over-enunciated; a chunk holds up to 5 sentences and 420 characters, with shorter joins (0.2 s after a sentence, 0.1 s after a clause, 0.4 s after a paragraph), so the voice restarts its phrasing less often; and a very short line gets at least four seconds of budget, so it can no longer fail every take. Orpheus narration made before this is made again the next time it is asked for. Needs a restart of the editor.
- **A site's reports are its pages.** site.json `reports` is now `pages` (a file that still says `reports` reads as `pages` for this release; saving writes `pages`). Each page is served at `/pages/<id>/` and linked from the site's header by its title, after Ask AI; there is no Reports index any more. A site with search off shows its first page as its home, and saving a site with search off and no pages is refused. The site form lists them as **Pages**. Rebuild each site that has pages.
- **Site ids `articles` and `new` are refused.** The editor's `/sites/articles` and `/sites/new` (and umtool's `articles/`) would hide a site of either name, so a save under one is refused, naming why.
diff --git a/plans/release-27.md b/plans/release-27.md
@@ -305,6 +305,72 @@ Gates: tsc clean (all packages); common 3878/3878 (51 new in `lib/llm/`); mcp 30
No builds (no app code).
Found and fixed: `inspect(client)` showed the config's `env`, key included (the key-leak test caught it).
+### S4, as shipped (2026-10-13, lane C)
+
+The iterations store: `common/lib/report/iterations.ts`, on branch `r27/iterations-chain` from `r27/integration`.
+
+| Commit | What |
+| --- | --- |
+| `31ca0a7d` | `iterations.ts` (+ tests); `registry.ts` additions (articles in the making, `writeArticleHoldingLock`, `keepVideo`); `archilyzer reports iterations` (`bin/reports-iterations.ts`, its row, COMMANDS.md); compose/history/check tests; CHANGELOG |
+
+- **On disk:** `reports/<id>/iterations/<n>/` holds `iteration.json`, `report.json`, `sweep.md`, `turns.jsonl` and `proposals.json`. `iterations/current.json` holds `{report, reportFrom, video}`: which iteration the article is, whose report.json it holds (a `revise-video` iteration has none, so it takes its nearest ancestor's), and which iteration the attached video is.
+- **`iteration.json`** is zod (`iterationSchema`, loose, so a key a later slice adds survives an update). It holds `n`, `kind`, `model`, `parent`, `copyOf`, `feedback`/`question`, `scope {channels, from, to}`, `status`, `usage` by model (`usd`, tokens, cache tokens, calls), `ops {applied, refused}`, `minutes`, `checks`, `steps [{task, model, status, cost, minutes, …}]`, `projectDir`, `jobId` and the times.
+ - Statuses: `queued`, `running`, `done`, `failed`, `cancelled`. `queued` was added for an iteration made before its job starts.
+ - Parent and copyOf are always earlier iterations. A revision needs a done parent and feedback; a sweep or research run needs its question.
+- **Writes:** every one runs under `withArticleStoreLock`, is validated and atomic. `n` is allocated under the lock, and its directory is made non-recursively.
+ - `writeIterationFile` takes the allowlist `ITERATION_FILES`. A `report.json` must parse as a report of this article; its problems are kept, and `makeCurrent` refuses them.
+ - `makeCurrent` writes the article through `writeArticleHoldingLock` (writeArticle's body, for a holder of the lock). It drops the iteration's `audience` (the registry's alone) and keeps the article's attached `video` when the report has none. Only a `done` iteration is made current. The next `reports export` commits it as the next Revision (tested).
+- **An article in the making** (iterations, no report.json — S8's `/articles/new`) is INVISIBLE to the registry until its first `makeCurrent`. `listArticleDirs` and `readArticleState` leave it out, so compose, the homepage, the editor's Articles tab, umtool `/articles` and `reports check|prepare|export --article` never see it. `listPendingArticles` lists them, for S8.
+- **Never published:** a test each — the homepage compose (public and private: no iteration path, none of its words), an article's history (the tree stays `exports.json`, `report.json`, `report.md`) and its exports.
+
+Gates: tsc clean (all packages); common 3840/3840 (13 new); `docs cli --check` and `docs files --check` clean.
+
+Exported for S5/S6/S8/S11:
+- `createIteration`, `copyIteration`, `updateIteration`, `recordIterationStep`, `addIterationUsage`;
+- `writeIterationFile`, `appendIterationTurns`, `readIterationFile`;
+- `readIteration`, `readIterations`, `listIterations`, `currentIteration`, `lineage`, `reportSourceOf`;
+- `makeCurrent`, `setCurrentVideo`, `projectOf`, `iterationUsd`, `iterationLabel`, `parseIteration`, `listPendingArticles`, `ITERATION_FILES`.
+
+### S7, as shipped (2026-10-13, lane C)
+
+The pipeline chain over an iteration, and the owed bugs, on `r27/iterations-chain` (after S4).
+
+| Commit | What |
+| --- | --- |
+| `7654e1c4` | to-manifest: the title card's `foot: ""` and render-cards' guard; no chapter card for a section with nothing to show; the derived fixtures regenerated |
+| `4e6db2af` | `reports prepare --article <id> --only`; the window `pad` contract pinned (fetchWindows, fetchWindowManaged); umtool's driver finds the pipeline from its module |
+| `88302d19` | `umtool/lib/report/{chain,chain-run,iterations}.mjs` (+ tests), `umtool chain`; Turbopack opt-outs in the S0 kit's `derive.ts`/`regenerate.ts` |
+
+**The chain.** Ten steps: current, windows, prepare, posts, manifest, voices, video, podcast, attach, dedupe.
+- **One process each:** `node --import tsx umtool/lib/report/chain-run.mjs step <id> <n> <step>`, so lib/jobs.ts runs it as a job (process group, cancel, per-step timeout), and `umtool chain <id> <n> [--from] [--dry] [--final] [--projects-root] [--site-origin]` runs the same argv from a terminal.
+- **Planning and executing are split.** `chain.mjs` plans in plain node (`planChain`, `chainSteps`, `chainStart`, `chainWindows`), and the Next app may import it. `chain-run.mjs` executes, under tsx, over common's TypeScript; the app never imports it.
+- **Recording and resuming.** Each step records `chain:<step>` in the iteration's `steps` (running, then done, failed or cancelled, with minutes and one line). A chain resumes at the first step not done.
+- **Windows** are each cited moment's span, widened by the cut's fetchPad (3 s) and by the citation's own pad, so one editor fetch serves both the evidence clips and the cut.
+- **Posts:** only this article's missing screenshots, through the editor's `capture-posts`; then prepare runs again.
+- **Manifest:** written into `projectOf(projectsRoot, id, n)`. Its QR origin comes from the newest sweep.md in the lineage, or `--site-origin`. It copies the report and its stills, then seeds from the parent's project.
+- **Attach** records the iteration as the article's video (`setCurrentVideo`), runs `reports check`, and keeps its result in the iteration's `checks`.
+- **Defaults and secrets.** `projectsRoot` defaults to `~/reports/articles` until S6's setting. No secret rides in a step: the executor reads the editor's URL and token at run time, the way `pnpm ops` does.
+
+**`iterations.mjs`:**
+- `seedFromParent` carries narration by card id, else by heading, and hard-links the parent's voices.
+- `dedupeMedia` touches `out/<variant>/segments/*.mp4` and `out/narration/*.{wav,json}` only, on the same device, linking through a temp and a rename.
+
+**The owed bugs, each with a test:**
+- **Title foot:** `foot: ""`, and render-cards renders a missing sub or foot empty.
+- **No silent end card:** a section that emits no timeline entry gets no chapter card, and a warning; the article keeps the section. That covers Coverage and `posts-only`'s Posts.
+- **`umtool build --dry`:** the driver finds `report-to-video/` from its own module. Under the Next server, where module URLs are chunk paths, it falls back to the cwd.
+- **`prepare --only`:** only this article's problems fail the run, and another article's are warnings. Only it is exported, over `articlesWorkHost(…, {only: true})`.
+ - The media is still prepared for every published article. The articles' cache is one directory, and a prepare PRUNES every clip its run does not cite, so preparing one article alone would delete the others' clips.
+- **Window `pad`** — not changed; contract pinned. `from`/`to` ARE the window with its padding, and `pad` is provenance.
+ - Every caller pads before it asks: fetch-via-editor.mjs, the MCP's fetch_clip, the chain.
+ - Folding `pad` into coverage would double-pad all of them, and a refetch would rewrite the same file name.
+ - The stopgap's failure was a request of the bare span with `pad: 3`, read as "please pad". Tests pin that a cached unpadded window never answers for a padded ask, and the contract is written on the item type and the cache check.
+
+Gates:
+- tsc clean.
+- Unit suites: common 3844/3844, `test:scripts` 850 pass + 3 skipped of 853, editor unit 264/264, mcp 306/306.
+- `docs cli|files|env --check` clean.
+- **Not run:** the umtool `build.spec.ts` e2e and the capped umtool build. Memory stayed under the 6000 MB floor; the heavy gate waited 9.5 min at 3.4–4.4 GB available, and the attempt was stopped.
## Rollout
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
@@ -8,10 +8,37 @@
//
// The client sends a PROJECT and a PRESET NAME. It never sends a path, an argv
// or an env map -- the same contract /api/browse/build already keeps.
+import { existsSync } from "node:fs";
import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+/**
+ * This package's own root (umtool/): bin/ lives here, and so does
+ * report-to-video/.
+ *
+ * FROM THE MODULE, not the cwd (release 27 S7): `umtool build <p> --dry` run
+ * from the repository root printed `cd <repo>/report-to-video`, a directory
+ * that does not exist, and a umtool CLI run from anywhere else did the same.
+ * The module's own path names the package wherever the process stands. Under
+ * the Next server Turbopack rewrites module URLs into .next/server/chunks
+ * (lib/paths.ts, SONG_CODE), where no report-to-video/ is found — the server
+ * keeps its cwd, which `next dev` and `next start` set to the package root.
+ */
+function packageRoot() {
+ try {
+ 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.
+ }
+ return path.resolve(/* turbopackIgnore: true */ process.cwd());
+}
+
+/** This package's own root. bin/ lives here, and so does report-to-video/. */
+export const UMTOOL_DIR = packageRoot();
/** Where the pipeline lives. One place, so a move is one edit. */
-export const PIPELINE_DIR = path.resolve(/* turbopackIgnore: true */ process.cwd(), "report-to-video");
+export const PIPELINE_DIR = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "report-to-video");
const script = (name) => path.join(/* turbopackIgnore: true */ PIPELINE_DIR, name);
@@ -412,9 +439,6 @@ export function checkSourcesSteps(projects, env = {}) {
// decision the report's author already wrote down.
// ---------------------------------------------------------------------------
-/** This package's own root. bin/ lives here, and so does report-to-video/. */
-export const UMTOOL_DIR = path.resolve(/* turbopackIgnore: true */ process.cwd());
-
const tool = (name) => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", name);
/** The interpreter a project's own scripts are run with. */
diff --git a/umtool/lib/report/driver.test.mjs b/umtool/lib/report/driver.test.mjs
@@ -83,3 +83,33 @@ test("one card's narration: narrate-via-editor --only, its voice kept in out/",
assert.deepEqual(s.argv.slice(2), ["/r/p/video.manifest.json", "--out", "/r/p/out", "--only", "k1", "--progress", "ndjson"]);
assert.deepEqual(s.env, {}, "the token is the server's environment's, never the step's");
});
+
+// Release 27 S7: `umtool build --dry` printed `cd <cwd>/report-to-video` —
+// the pipeline was found from the cwd, so a CLI run from anywhere but umtool/
+// named a directory that is not there.
+test("the pipeline is found from the module, whatever the cwd", async () => {
+ const { execFileSync } = await import("node:child_process");
+ const { existsSync, mkdtempSync, rmSync } = await import("node:fs");
+ const os = await import("node:os");
+ const path = await import("node:path");
+ const { fileURLToPath } = await import("node:url");
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ const want = path.resolve(here, "..", "..", "report-to-video");
+ const { PIPELINE_DIR, UMTOOL_DIR } = await import("./driver.mjs");
+ assert.equal(PIPELINE_DIR, want);
+ assert.equal(UMTOOL_DIR, path.resolve(here, "..", ".."));
+ assert.ok(existsSync(path.join(PIPELINE_DIR, "build-video.mjs")));
+ const elsewhere = mkdtempSync(path.join(os.tmpdir(), "driver-cwd-"));
+ try {
+ const printed = execFileSync(
+ process.execPath,
+ ["--input-type=module", "-e", `import { PIPELINE_DIR } from ${JSON.stringify(path.join(here, "driver.mjs"))}; console.log(PIPELINE_DIR);`],
+ { cwd: elsewhere, encoding: "utf8" },
+ ).trim();
+ assert.equal(printed, want);
+ const steps = buildSteps({ id: "p", dir: "/r/p" }, { preset: "fast" });
+ assert.ok(steps.every((s) => s.cwd === want));
+ } finally {
+ rmSync(elsewhere, { recursive: true, force: true });
+ }
+});
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 });
+});
diff --git a/umtool/report-to-video/render-cards.mjs b/umtool/report-to-video/render-cards.mjs
@@ -94,7 +94,7 @@ const faceOf = (faces, role) => (faces ? { face: faces[role] } : {});
// Each style returns Pango markup for the whole card body. Blank lines are real
// newlines in the markup — Pango honours them, which is how vertical rhythm is
// set without positioning each run separately.
-function markupFor(card, pal, faces = null) {
+export function markupFor(card, pal, faces = null) {
const H = (t, size = 62) =>
span(esc(t), { size, color: pal.fg, weight: "bold", ...faceOf(faces, "display") });
const KICKER = (t) =>
@@ -106,10 +106,13 @@ function markupFor(card, pal, faces = null) {
return [
span(esc(card.heading), { size: 82, color: pal.fg, weight: "bold", ...faceOf(faces, "display") }),
"",
- span(esc(card.sub), { size: 38, color: pal.accent, ...faceOf(faces, "body") }),
+ // A title card without a `sub` or a `foot` (a manifest to-manifest
+ // made before release 27) renders them empty, as "" does — never the
+ // word "undefined".
+ span(esc(card.sub ?? ""), { size: 38, color: pal.accent, ...faceOf(faces, "body") }),
"",
"",
- SUB(card.foot, 24),
+ SUB(card.foot ?? "", 24),
].join("\n");
case "chapter":
diff --git a/umtool/report-to-video/title-card.test.mjs b/umtool/report-to-video/title-card.test.mjs
@@ -0,0 +1,25 @@
+// The title card's markup (release 27 S7): a card without `sub` or `foot` —
+// every manifest `reports to-manifest` made before release 27 lacked `foot` —
+// renders them empty, never the word "undefined".
+//
+// Run with: node --test umtool/report-to-video/title-card.test.mjs
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { markupFor } from "./render-cards.mjs";
+
+const PAL = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" };
+
+test("a title card with no foot and no sub: no 'undefined' in its markup", () => {
+ const markup = markupFor({ type: "card", id: "title", style: "title", heading: "A heading" }, PAL);
+ assert.ok(!markup.includes("undefined"), markup);
+ assert.match(markup, /A heading/);
+});
+
+test("a title card with an empty foot renders the same as one with none", () => {
+ const none = markupFor({ type: "card", id: "title", style: "title", heading: "H", sub: "S" }, PAL);
+ const empty = markupFor({ type: "card", id: "title", style: "title", heading: "H", sub: "S", foot: "" }, PAL);
+ assert.equal(none, empty);
+ const set = markupFor({ type: "card", id: "title", style: "title", heading: "H", sub: "S", foot: "Channel · 2026" }, PAL);
+ assert.match(set, /Channel · 2026/);
+});