commit 31dfc61dca653a0e338e18334da2289be8a51478
parent 0a76bd77a3713a014519d5585a1e7ae9e6260e9e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 22:56:45 -0400
Merge r28/integration into r28/media-d: lanes C, E and F
Conflicts kept both sides: generation settings (cut beside verdicts), the
settings docs, the tasks index (all six media tasks now run; the
not-implemented refusal is gone). SETTINGS.md, settings.json.example and
COMMANDS.md regenerated.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
81 files changed, 7226 insertions(+), 218 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -36,6 +36,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `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 delete` | `<articleId> [--iteration <n>] [--apply] [--force] [--json]` | delete an article — its directory (report, video, history, notes, iterations), its iterations' video projects under settings.generation.projectsRoot and its staged exports — or, with --iteration, one iteration and its project, through the article registry. A dry run printing the plan (every path with its size, what is kept and why, what refuses) unless --apply. Refused: a published article, or a site page naming it with no report of its own (--force unpublishes it and drops the page first); a queued or running iteration; an iteration that is current (article, its report's source, video) or that another revises or copies (exit 1 when refused; 2 for no such article or iteration) |
+| `archilyzer reports bench-verdicts` | `--models <a,b,…> [--report <id,…>] [--window <s>] [--max-usd <n>] [--limit <n>] [--run <id>] [--dry] [--here] [--wait] [--json]` | the verdict bench (release 28): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the claim, its quotes and the transcript within --window seconds (default 60) of each cited span, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT\_FOUND recall, against an always-CORROBORATED baseline). --dry lists the items and the skipped claims and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues. Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /bench) (exit 1 when the run stopped early or was refused; 2 for usage) |
| `archilyzer reports import-local-runs` | `[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>]` | ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused) |
| `archilyzer gen policy` | `[--json]` | the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers |
| `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) |
@@ -93,6 +94,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` |
| `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` |
| `delete-iteration` | delete-iteration deletes one iteration and its video project: {"id", "n"}, "dryRun"?. Its number is never given again. Refused with the plan (409), no override: the current article, the iteration its report.json came from, the current video, a queued or running one, one another revises or copies. | `pnpm ops delete-iteration --json '{"id":"demo-article","n":3}'` |
+| `delete-site` | delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? It removes sites/<id>/ (site.json, its pool and pages, tags, charts, its reports), its publish state and last bundle (export/.export-builds/<id>/) and compose's staging for it (export/.export-index/sites/<id>/). Channel data is never touched; the Pages project, what was deployed and a deployed hub are kept (a delete does not undeploy). Refused with the plan (409) unless "force": a deploy target (cloudflareProject), a deploy in its publish state, reports of its own. Refused, force or not: no such site (404), a site dir that is a link, a publish stage running. | `pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'` |
| `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'` |
| `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` |
| `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` |
@@ -144,7 +146,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` |
| `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` |
| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'` |
-| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -> {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` |
+| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -> {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` |
+| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the claim, its quotes, the transcript within the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues (answered pairs are skipped). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` |
### Usage, flags and environment
diff --git a/OPERATING.md b/OPERATING.md
@@ -247,7 +247,14 @@ pnpm ops report-draft --json '{"task":"sweep","article":"example-article","i
- **Continue** (umtool's **Continue into a sweep**, shown once the run is done and nothing is pending) is a sweep
with `"iteration"` naming the research run: its question, over its channels and every
channel an acquisition wrote into. It is refused while the run waits, unless `"force": true`. A channel on no site
- is in no build: put it on a site and build before continuing. Nothing continues on its own.
+ is in no build: put it on a site and build before continuing.
+- **An `auto` run continues by itself** once its acquisitions settle (every job ended, nothing waiting for you): the
+ editor asks that same sweep, on the run's own model, at the job's end or on its heartbeat. The caps hold (the
+ sweep's per-job cap; past the daily cap it is refused, and tried again the next UTC day). A channel in no build is
+ left out, with the warning `not in any build yet: <slug> — rebuild the site and continue again` (a failed check on
+ the sweep); with nothing left to sweep it waits for a newer build. The queue says "continued automatically by iN",
+ or why not. `propose` and `limits` runs are continued by you. An idle boot (`ARCHILYZER_IDLE_BOOT`) continues
+ nothing.
- **The standing rules hold in every mode**, and a proposal that breaks one is refused: a new channel is created on
no site; an X channel never goes on a site; a Twitch VOD URL is refused (look for the stream on archive.org); every fetch goes through the
editor's queues, holds and cooldowns (one stream, real gaps, backing off on a 429), never yt-dlp or gallery-dl by
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -967,6 +967,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `citationOrigin` | `""` | The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site. |
| `research` | object — see below | A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'. |
| `cut` | object — see below | The cut task's limits (below). |
+| `verdicts` | object — see below | The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`. |
#### `generation.routes`
@@ -1013,7 +1014,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| Key | Default | Description |
|---|---|---|
-| `autonomy` | `"propose"` | `propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD. |
+| `autonomy` | `"propose"` | `propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not; once its acquisitions settle the run continues into its sweep by itself, leaving out a channel in no build). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD. |
| `maxItemsPerRun` | `20` | The most items (videos, archive.org files, posts) one run may acquire without approval. Past it, an acquisition waits. |
| `maxGbPerRun` | `5` | The most GB one run may download without approval. An acquisition of unknown size waits. |
| `maxTranscribeHours` | `6` | The most hours of transcription one run may queue without approval. One of unknown length waits. |
@@ -1026,6 +1027,21 @@ Report and video generation (release 27): where each task runs (`code` = Claude
|---|---|---|
| `maxClips` | `20` | The most entries a drafted cut keeps: clips and stills chosen from the report's citations (at least 3; the code refuses a longer selection, whatever the model says). |
+#### `generation.verdicts`
+
+| Key | Default | Description |
+|---|---|---|
+| `bar` | object — see below | The bar a model must clear on a bench run (below): each a fraction, 0 to 1. All 0 = no bar set. |
+| `models` | `[]` | The models the operator ticked as passing the bar — never set automatically. Empty = none: no verdict proposals. |
+
+#### `generation.verdicts.bar`
+
+| Key | Default | Description |
+|---|---|---|
+| `agreement` | `0` | The least share of claims on which the model's verdict must equal the operator's (strictly: PARTLY is not CORROBORATED). |
+| `contradictedRecall` | `0` | The least share of the claims the operator ruled CONTRADICTED that the model must rule so. |
+| `notFoundRecall` | `0` | The least share of the claims the operator ruled NOT_FOUND that the model must rule so. |
+
Default:
```json
@@ -1076,6 +1092,14 @@ Default:
"maxTranscribeHours": 6,
"newChannelsNeedApproval": true,
"postWalksNeedApproval": true
+ },
+ "verdicts": {
+ "bar": {
+ "agreement": 0,
+ "contradictedRecall": 0,
+ "notFoundRecall": 0
+ },
+ "models": []
}
}
```
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -414,6 +414,13 @@ export const COMMANDS: Command[] = [
},
},
{
+ path: ["reports", "bench-verdicts"],
+ usage:
+ "--models <a,b,…> [--report <id,…>] [--window <s>] [--max-usd <n>] [--limit <n>] [--run <id>] [--dry] [--here] [--wait] [--json] the verdict bench (release 28): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the claim, its quotes and the transcript within --window seconds (default 60) of each cited span, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT_FOUND recall, against an always-CORROBORATED baseline). --dry lists the items and the skipped claims and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues. Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /bench) (exit 1 when the run stopped early or was refused; 2 for usage)",
+ flags: { report: "string", models: "string", window: "string", "max-usd": "string", limit: "string", run: "string", dry: "boolean", here: "boolean", wait: "boolean", json: "boolean" },
+ run: async (ctx) => (await import("./reports-bench-verdicts")).benchRow(ctx),
+ },
+ {
path: ["reports", "import-local-runs"],
usage:
"[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>] ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused)",
diff --git a/common/bin/reports-bench-verdicts.test.ts b/common/bin/reports-bench-verdicts.test.ts
@@ -0,0 +1,91 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { CHANNELS } from "../testing/draft/corpus.mjs";
+import type { Paths } from "../lib/paths";
+import { benchMain, benchOptionsOf } from "./reports-bench-verdicts";
+
+const RULED = path.join(import.meta.dirname, "../testing/draft/reports/ruled.report.json");
+
+// A temp corpus: the ruled fact-check in the article store, and the synthetic
+// recordings' cues on disk, as `diskCuesOf` reads them.
+async function corpus() {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "bench-cli-"));
+ const report = JSON.parse(await readFile(RULED, "utf8"));
+ await mkdir(path.join(dir, "reports", report.id), { recursive: true });
+ await writeFile(path.join(dir, "reports", report.id, "report.json"), JSON.stringify(report));
+ for (const ch of CHANNELS) {
+ for (const r of ch.records) {
+ const rec = path.join(dir, "channels", ch.slug, "data", r.id);
+ await mkdir(rec, { recursive: true });
+ await writeFile(path.join(rec, "transcript.cues.json"), JSON.stringify({ cues: r.cues }));
+ }
+ }
+ const paths = {
+ articlesDir: path.join(dir, "reports"),
+ exportIndexDir: path.join(dir, ".export-index"),
+ channelsDir: path.join(dir, "channels"),
+ generationUsageFile: path.join(dir, ".generation", "usage.jsonl"),
+ } as Paths;
+ return { dir, paths, done: () => rm(dir, { recursive: true, force: true }) };
+}
+
+function capture() {
+ const logs: string[] = [];
+ const errors: string[] = [];
+ return { out: { log: (s: string) => logs.push(s), error: (s: string) => errors.push(s) }, logs, errors };
+}
+
+test("the flags: lists split, numbers read, the options judged before anything runs", () => {
+ assert.deepEqual(benchOptionsOf({ models: "claude-sonnet-5-5, qwen3:8b", report: "a,b", window: "30", "max-usd": "2.5", limit: "4", run: "vb-x" }), {
+ models: ["claude-sonnet-5-5", "qwen3:8b"],
+ reports: ["a", "b"],
+ windowS: 30,
+ maxUsd: 2.5,
+ limit: 4,
+ runId: "vb-x",
+ });
+ assert.throws(() => benchOptionsOf({}), /at least one model/);
+ assert.throws(() => benchOptionsOf({ models: "m", window: "soon" }), /--window takes a number/);
+ assert.throws(() => benchOptionsOf({ models: "m", run: "Not An Id" }), /--run is a run id/);
+});
+
+test("--dry: the items over the local corpus's cues, the skipped claims and the estimate; nothing asked, nothing written", async () => {
+ const c = await corpus();
+ try {
+ const cap = capture();
+ let asked = 0;
+ const code = await benchMain({ models: "claude-sonnet-5-5,claude-opus-5-5,qwen3:8b", dry: true }, { paths: c.paths, runOps: async () => ++asked, out: cap.out });
+ assert.equal(code, 0);
+ assert.equal(asked, 0);
+ assert.match(cap.logs[0]!, /^7 items from 1 fact-check\(s\), a 60 s window; 1 claims skipped$/);
+ assert.ok(cap.logs.includes(" skipped 1: no citation"));
+ assert.ok(cap.logs.some((l) => /^ {2}synth-ruled\/r04 {2}CONTRADICTED {2}1 quote\(s\), \d+ cues$/.test(l)));
+ assert.ok(cap.logs.some((l) => /^ {2}qwen3:8b \(local\): 7 calls, .*~\$0\.0000$/.test(l)));
+ // No claim text without --json.
+ assert.ok(!cap.logs.join("\n").includes("The article says"));
+ await assert.rejects(stat(path.join(c.dir, ".generation")), /ENOENT/);
+ } finally {
+ await c.done();
+ }
+});
+
+test("a run goes through the editor (pnpm ops bench-verdicts); --here refuses a local model", async () => {
+ const c = await corpus();
+ try {
+ const seen: string[][] = [];
+ const code = await benchMain(
+ { models: "claude-sonnet-5-5,qwen3:8b", "max-usd": "5", run: "vb-real", wait: true },
+ { paths: c.paths, runOps: async (argv) => (seen.push(argv), 0), out: capture().out },
+ );
+ assert.equal(code, 0);
+ assert.deepEqual(seen, [["bench-verdicts", "--json", JSON.stringify({ models: ["claude-sonnet-5-5", "qwen3:8b"], run: "vb-real", maxUsd: 5 }), "--wait"]]);
+ const cap = capture();
+ assert.equal(await benchMain({ models: "qwen3:8b", here: true }, { paths: c.paths, runOps: async () => 0, out: cap.out }), 2);
+ assert.match(cap.errors.join("\n"), /qwen3:8b runs on the GPU, which only the editor arbitrates/);
+ } finally {
+ await c.done();
+ }
+});
diff --git a/common/bin/reports-bench-verdicts.ts b/common/bin/reports-bench-verdicts.ts
@@ -0,0 +1,153 @@
+// `archilyzer reports bench-verdicts --models a,b,c [--report <id>,…] [--window 60]
+// [--max-usd 5] [--limit n] [--run <id>] [--dry] [--here] [--wait] [--json]`
+// (release 28, M7) — the verdict bench: every ruled claim of the registry's
+// fact-checks asked of each model, one claim per call, and scored against the
+// operator's rulings (lib/report/draft/bench/).
+//
+// --dry lists the items (key, the operator's verdict, quotes, cues — no
+// claim text unless --json) and the skipped claims with their
+// reasons, and estimates each model's cost. Reads only; asks
+// nothing; writes nothing.
+// (none) THROUGH THE EDITOR: `pnpm ops bench-verdicts` (a child), so a
+// local model gets the GPU arbiter's turn and is unloaded after —
+// the only correct path for one. `--wait` follows the job.
+// --here in this process, for API models only (a local model is refused:
+// the GPU is arbitrated in the editor alone). The day's cap and the
+// usage ledger hold as in the editor's job.
+//
+// The results are local-only, in `.generation/bench/verdicts/<run>/`
+// (items.jsonl, results.jsonl, summary.json); umtool's /bench shows them.
+// A `--run` that exists continues it.
+//
+// Exit 0 when the run is done (a dry run: when it has items); 1 when it
+// stopped early (the cap, a cancel, a failure) or the editor refused; 2 for
+// usage.
+
+import type { CommandContext } from "./_cli";
+import type { FlagValue } from "./_parseFlags";
+import { getPaths, type Paths } from "../lib/paths";
+import { getSettings } from "../lib/settings";
+import { diskCuesOf } from "../lib/report/convert-server";
+import {
+ BenchInputError,
+ isBenchRunId,
+ newBenchRunId,
+ validateBenchOptions,
+ planVerdictBench,
+ type BenchOptions,
+ type BenchPlan,
+} from "../lib/report/draft/bench/index";
+import { benchDailyCapRefusal, runBenchWithSettings } from "../controller/benchVerdicts";
+import { runOpsChild } from "./gen";
+
+type Out = { log: (s: string) => void; error: (s: string) => void };
+
+const list = (v: FlagValue | undefined) => (typeof v === "string" ? v.split(",").map((s) => s.trim()).filter(Boolean) : []);
+
+function num(v: FlagValue | undefined, name: string): number | undefined {
+ if (v === undefined) return undefined;
+ const n = typeof v === "string" ? Number(v) : NaN;
+ if (!Number.isFinite(n)) throw new BenchInputError(`--${name} takes a number`);
+ return n;
+}
+
+export function benchOptionsOf(flags: Record<string, FlagValue>): BenchOptions {
+ const o: BenchOptions = { models: list(flags.models) };
+ const reports = list(flags.report);
+ if (reports.length) o.reports = reports;
+ const w = num(flags.window, "window");
+ if (w !== undefined) o.windowS = w;
+ const m = num(flags["max-usd"], "max-usd");
+ if (m !== undefined) o.maxUsd = m;
+ const l = num(flags.limit, "limit");
+ if (l !== undefined) o.limit = l;
+ if (typeof flags.run === "string") o.runId = flags.run;
+ validateBenchOptions(o);
+ if (o.runId !== undefined && !isBenchRunId(o.runId)) throw new BenchInputError("--run is a run id: lowercase letters, digits and dashes");
+ return o;
+}
+
+export function formatBenchPlan(plan: BenchPlan): string[] {
+ const lines: string[] = [];
+ lines.push(`${plan.items.length} items from ${plan.reports.length} fact-check(s), a ${plan.windowS} s window; ${plan.skipped.length} claims skipped`);
+ const reasons = new Map<string, number>();
+ for (const s of plan.skipped) reasons.set(s.reason, (reasons.get(s.reason) ?? 0) + 1);
+ for (const [r, n] of reasons) lines.push(` skipped ${n}: ${r}`);
+ const ruled = new Map<string, number>();
+ for (const it of plan.items) ruled.set(it.verdict, (ruled.get(it.verdict) ?? 0) + 1);
+ lines.push(` ruled: ${[...ruled].map(([v, n]) => `${v} ${n}`).join(", ") || "none"}`);
+ lines.push("items:");
+ for (const it of plan.items) {
+ const cues = it.windows.reduce((s, w) => s + w.cues.length, 0);
+ lines.push(` ${it.key} ${it.verdict} ${it.quotes.length} quote(s), ${cues} cues`);
+ }
+ for (const s of plan.skipped) lines.push(` skipped ${s.key}: ${s.reason}`);
+ lines.push("estimate:");
+ for (const e of plan.estimate) {
+ lines.push(` ${e.model} (${e.provider}): ${e.calls} calls, ~${e.inputTokens} in / ~${e.outputTokens} out tokens, ~$${e.usd.toFixed(4)}`);
+ }
+ lines.push(` total ~$${plan.estimateUsd.toFixed(4)} (the run stops at its --max-usd, default $5)`);
+ return lines;
+}
+
+export type BenchDeps = {
+ paths: Paths;
+ runOps: (argv: string[]) => Promise<number>;
+ out?: Out;
+};
+
+export async function benchMain(flags: Record<string, FlagValue>, deps: BenchDeps): Promise<number> {
+ const out = deps.out ?? console;
+ let opts: BenchOptions;
+ try {
+ opts = benchOptionsOf(flags);
+ if (flags.dry === true) {
+ const plan = await planVerdictBench(opts, { paths: deps.paths, cuesOf: diskCuesOf(deps.paths.channelsDir) });
+ if (flags.json === true) out.log(JSON.stringify(plan, null, 2));
+ else for (const l of formatBenchPlan(plan)) out.log(l);
+ return plan.items.length ? 0 : 1;
+ }
+ } catch (e) {
+ if (e instanceof BenchInputError) {
+ out.error(`reports bench-verdicts: ${e.message}`);
+ return 2;
+ }
+ throw e;
+ }
+ if (flags.here === true) {
+ const gen = getSettings().generation;
+ const refusal = await benchDailyCapRefusal(opts, deps.paths, gen);
+ if (refusal) {
+ out.error(`reports bench-verdicts: ${refusal}`);
+ return 1;
+ }
+ const runId = opts.runId ?? newBenchRunId();
+ const ac = new AbortController();
+ const stop = () => ac.abort();
+ process.once("SIGINT", stop);
+ try {
+ const r = await runBenchWithSettings({ ...opts, runId }, { paths: deps.paths, gen, onLog: (l) => out.error(l), signal: ac.signal, jobId: `cli-${runId}`, gpu: false });
+ out.log(JSON.stringify({ run: r.id, dir: r.dir, status: r.summary.status, items: r.summary.items, spentUsd: r.summary.spentUsd, ...(r.summary.stopped ? { stopped: r.summary.stopped } : {}) }));
+ return r.summary.status === "done" ? 0 : 1;
+ } catch (e) {
+ if (e instanceof BenchInputError) {
+ out.error(`reports bench-verdicts: ${e.message}`);
+ return 2;
+ }
+ throw e;
+ } finally {
+ process.off("SIGINT", stop);
+ }
+ }
+ const body: Record<string, unknown> = { models: opts.models };
+ if (opts.runId) body.run = opts.runId;
+ if (opts.reports) body.reports = opts.reports;
+ if (opts.windowS !== undefined) body.window = opts.windowS;
+ if (opts.maxUsd !== undefined) body.maxUsd = opts.maxUsd;
+ if (opts.limit !== undefined) body.limit = opts.limit;
+ return deps.runOps(["bench-verdicts", "--json", JSON.stringify(body), ...(flags.wait === true ? ["--wait"] : [])]);
+}
+
+export async function benchRow(ctx: CommandContext): Promise<number> {
+ return benchMain(ctx.flags, { paths: getPaths(), runOps: runOpsChild });
+}
diff --git a/common/controller/benchVerdicts.ts b/common/controller/benchVerdicts.ts
@@ -0,0 +1,215 @@
+// `bench-verdicts` — the verdict bench (release 28, M7) as an editor job:
+// `archilyzer reports bench-verdicts` → `pnpm ops bench-verdicts` →
+// POST /api/ops/bench-verdicts → here.
+//
+// run the run's id: a new one, or one to continue (default vb-<stamp>)
+// reports the fact-check articles to read (default: every one)
+// models the models to ask (required)
+// window seconds of transcript either side of each cited span (default 60)
+// maxUsd the whole run's API cap (default 5, at most 50)
+// limit the first n items only
+//
+// WHY A JOB IN THE EDITOR, NOT A `report-draft`: a bench writes no iteration
+// and is no task of an article, so `report-draft`'s machinery (an iteration
+// created queued, the task registry) would be bent to fit it. What it needs
+// of release 27 is the GPU path, which is the editor's alone (the arbiter's
+// holds are in-process): a run with any LOCAL model goes on `draft:local`,
+// every ollama call through `gpuGatedFetch` (it waits for transcription and
+// for a synthesis, and holds the card while it runs), and ollama is unloaded
+// when the job ends, however it ends — exactly as a `report-draft` on
+// `draft:local`. A run of API models only goes on `draft:api`.
+//
+// An API run is refused past the day's cap (settings.generation.caps.daily),
+// and its spend is appended to the usage ledger (task `bench-verdicts`, no
+// article) so the day's total counts it. The cues are the local corpus's
+// (`diskCuesOf`): a fact-check may cite channels no build carries. The log
+// ends `@@bench-verdicts {json}` with the run's id, status and spend.
+
+import { getSettings } from "../lib/settings";
+import type { Paths } from "../lib/paths";
+import type { GenerationSettings } from "../lib/generationSettings";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys";
+import { providerOf, unloadOllama } from "../lib/llm";
+import { diskCuesOf } from "../lib/report/convert-server";
+import {
+ BenchInputError,
+ DEFAULT_BENCH_MAX_USD,
+ isBenchRunId,
+ newBenchRunId,
+ runVerdictBench,
+ validateBenchOptions,
+ type BenchOptions,
+} from "../lib/report/draft/bench/index";
+import { isReportId } from "../lib/report/schema";
+import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
+import { llmConfigOf } from "./reportDraft";
+
+export const BENCH_VERDICTS_JOB_KIND = "bench-verdicts";
+export const BENCH_VERDICTS_RESULT_MARKER = "@@bench-verdicts ";
+export const BENCH_VERDICTS_BODY_KEYS = ["run", "reports", "models", "window", "maxUsd", "limit"] as const;
+
+const fail = (msg: string): never => {
+ throw new BenchInputError(msg);
+};
+
+// The body, judged without touching the disk.
+export function parseBenchVerdictsBody(b: Record<string, unknown>): BenchOptions {
+ const out: BenchOptions = { models: [] };
+ if (b.run !== undefined) {
+ if (!isBenchRunId(b.run)) fail(`"run" is a run id: lowercase letters, digits and dashes`);
+ out.runId = b.run as string;
+ }
+ if (b.reports !== undefined) {
+ if (!Array.isArray(b.reports) || !b.reports.every((r) => isReportId(r))) fail(`"reports" is a list of article ids`);
+ out.reports = b.reports as string[];
+ }
+ const models = typeof b.models === "string" ? b.models.split(",") : b.models;
+ if (!Array.isArray(models) || !models.every((m) => typeof m === "string")) fail(`"models" is a list of model names`);
+ out.models = (models as string[]).map((m) => m.trim()).filter(Boolean);
+ if (b.window !== undefined) {
+ if (typeof b.window !== "number") fail(`"window" is a number of seconds`);
+ out.windowS = b.window as number;
+ }
+ if (b.maxUsd !== undefined) {
+ if (typeof b.maxUsd !== "number") fail(`"maxUsd" is a number of dollars`);
+ out.maxUsd = b.maxUsd as number;
+ }
+ if (b.limit !== undefined) {
+ if (typeof b.limit !== "number") fail(`"limit" is a number of items`);
+ out.limit = b.limit as number;
+ }
+ validateBenchOptions(out);
+ return out;
+}
+
+export type BenchVerdictsDeps = {
+ paths: Paths;
+ settings?: () => { generation: GenerationSettings };
+ now?: () => Date;
+ // Where runs live (tests); default `.generation/bench/verdicts/`.
+ root?: string;
+};
+
+export type BenchVerdictsEnqueued = { result: StreamActionResult; run: string };
+
+// One run with the settings' providers: the job's body, and `archilyzer
+// reports bench-verdicts --here` (API models only: no GPU arbiter outside the
+// editor, so a local model there is refused). The ledger gets this run's API
+// spend; a local model is unloaded at the end. Answers the outcome.
+export async function runBenchWithSettings(
+ opts: BenchOptions & { runId: string },
+ o: {
+ paths: Paths;
+ gen: GenerationSettings;
+ onLog: (line: string) => void;
+ signal?: AbortSignal;
+ jobId: string;
+ // In the editor: every ollama call through the GPU arbiter.
+ gpu: boolean;
+ now?: () => Date;
+ root?: string;
+ },
+): Promise<Awaited<ReturnType<typeof runVerdictBench>>> {
+ const { paths, gen: g, onLog } = o;
+ const locals = opts.models.filter((m) => providerOf(m) === "local");
+ if (locals.length && !o.gpu) {
+ throw new BenchInputError(`${locals.join(", ")} run${locals.length === 1 ? "s" : ""} on the GPU, which only the editor arbitrates: run the bench through the editor (pnpm ops bench-verdicts)`);
+ }
+ let spent: Awaited<ReturnType<typeof runVerdictBench>>["spent"] | null = null;
+ try {
+ const out = await runVerdictBench(opts, {
+ paths,
+ ...(o.root ? { root: o.root } : {}),
+ cuesOf: diskCuesOf(paths.channelsDir),
+ llm: llmConfigOf(g, paths, locals.length ? { onLog, ...(o.signal ? { signal: o.signal } : {}) } : undefined),
+ log: onLog,
+ ...(o.signal ? { signal: o.signal } : {}),
+ ...(o.now ? { now: o.now } : {}),
+ });
+ spent = out.spent;
+ const s = out.summary;
+ onLog(
+ `${BENCH_VERDICTS_RESULT_MARKER}${JSON.stringify({
+ run: s.id,
+ status: s.status,
+ items: s.items,
+ skipped: s.skipped.length,
+ spentUsd: s.spentUsd,
+ ...(s.stopped ? { stopped: s.stopped } : {}),
+ })}`,
+ );
+ return out;
+ } finally {
+ for (const m of locals) {
+ await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, m).then(
+ () => onLog(`unloaded ${m} from ollama`),
+ (e) => onLog(`ollama unload failed: ${(e as Error).message}`),
+ );
+ }
+ if (spent) {
+ const now = o.now?.() ?? new Date();
+ const rows: GenerationUsageRow[] = Object.entries(spent.byModel)
+ .filter(([m, t]) => providerOf(m) === "api" && (t.usd > 0 || t.calls > 0))
+ .map(([m, t]) => ({
+ at: now.toISOString(),
+ day: utcDay(now),
+ jobId: o.jobId,
+ article: "",
+ iteration: 0,
+ task: BENCH_VERDICTS_JOB_KIND,
+ model: m,
+ inputTokens: t.input,
+ outputTokens: t.output,
+ cacheReadTokens: t.cacheRead,
+ cacheWriteTokens: t.cacheWrite,
+ usd: Math.round(t.usd * 10_000) / 10_000,
+ }));
+ await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`));
+ }
+ }
+}
+
+// The day's cap, for a run with an API model: the refusal, or null.
+export async function benchDailyCapRefusal(opts: BenchOptions, paths: Pick<Paths, "generationUsageFile">, gen: GenerationSettings, now?: Date): Promise<string | null> {
+ if (!opts.models.some((m) => providerOf(m) === "api")) return null;
+ return dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(now)), gen.caps.daily);
+}
+
+export async function enqueueVerdictBench(
+ raw: Record<string, unknown>,
+ deps: BenchVerdictsDeps,
+): Promise<BenchVerdictsEnqueued | { result: StreamActionResult & { ok: false } }> {
+ const refuse = (error: string) => ({ result: { ok: false as const, error } });
+ let opts: BenchOptions;
+ try {
+ opts = parseBenchVerdictsBody(raw);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ const anyLocal = opts.models.some((m) => providerOf(m) === "local");
+ const refusal = await benchDailyCapRefusal(opts, paths, gen, deps.now?.());
+ if (refusal) return refuse(refusal);
+ const run = opts.runId ?? newBenchRunId(deps.now?.() ?? new Date());
+ const result = await runManagedFunction({
+ kind: BENCH_VERDICTS_JOB_KIND,
+ queueKey: anyLocal ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE,
+ paths,
+ fn: async (onLog, signal, _progress, ctx) => {
+ const g = (deps.settings ?? getSettings)().generation;
+ // Again at the job's turn: jobs ahead in the queue may have spent the day.
+ const late = await benchDailyCapRefusal(opts, paths, g, deps.now?.());
+ if (late) throw new Error(late);
+ onLog(`verdict bench ${run}: ${opts.models.join(", ")} (API cap $${opts.maxUsd ?? DEFAULT_BENCH_MAX_USD})`);
+ const out = await runBenchWithSettings(
+ { ...opts, runId: run },
+ { paths, gen: g, onLog, signal, jobId: ctx.jobId, gpu: true, ...(deps.now ? { now: deps.now } : {}), ...(deps.root ? { root: deps.root } : {}) },
+ );
+ if (out.summary.status === "cancelled" || signal.aborted) throw new Error("cancelled");
+ },
+ });
+ if (!result.ok) return { result };
+ return { result, run };
+}
diff --git a/common/controller/relocateChannelMedia.test.ts b/common/controller/relocateChannelMedia.test.ts
@@ -749,6 +749,15 @@ async function leftoverCopies(channelDir: string): Promise<string[]> {
// rsync -a of the tree, so the seeded "already copied" target is byte-for-byte
// what a completed copy phase would have left — including mtimes, which the
// re-verify compares. Over `media/` only: it holds no links.
+// Every directory under (and including) `dir` set to MTIME, so a test's
+// itemized drift is the files' alone, whatever second the setup ran in.
+async function pinDirTimes(dir: string): Promise<void> {
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ if (entry.isDirectory()) await pinDirTimes(path.join(dir, entry.name));
+ }
+ await utimes(dir, MTIME, MTIME);
+}
+
async function copyTree(src: string, dest: string): Promise<void> {
await mkdir(dest, { recursive: true });
for (const entry of await readdir(src, { withFileTypes: true })) {
@@ -1612,6 +1621,12 @@ test("reconcile: an extra and a changed file on the destination are settled, and
await copyTree(mediaLink, target);
await writeFile(path.join(target, "v1", "stale.json"), "{}");
await writeFile(path.join(target, "v1", "transcript.live_chat.json"), '{"v":1}');
+ // Every directory's mtime pinned on both sides: writing stale.json moved
+ // the target's v1/ mtime, and when the setup crossed a second boundary
+ // rsync (comparing whole seconds) itemized `.d..t v1/` as a third
+ // difference — the release 28 flake. Only the two files differ now.
+ await pinDirTimes(mediaLink);
+ await pinDirTimes(target);
await seedMarker(paths, "alpha", { target, direction: "out", phase: "copy" });
const lines: string[] = [];
diff --git a/common/controller/researchAutoContinue.test.ts b/common/controller/researchAutoContinue.test.ts
@@ -0,0 +1,341 @@
+// An `auto` research run continues into its sweep by itself (release 28 F1):
+// the job-end trigger and the scan, once only, the caps, the builds, the idle
+// boot. A temp store, temp builds, real registry jobs; the sweep it enqueues
+// fails at its corpus (a stub that throws) — what is asserted is that it was
+// asked for, once, as Continue asks it. No LLM is called.
+
+import { after, afterEach, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { sanitizeGeneration, type GenerationSettings } from "../lib/generationSettings";
+import { getRegistry } from "../jobs/registry";
+import { runManagedFunction } from "../jobs/streamCommand";
+import { createIteration, iterationFile, listIterations, readIteration, updateIteration, type Iteration } from "../lib/report/iterations";
+import { newResearchState, writeResearchState, type ResearchRecord } from "../lib/report/draft/research/state";
+import { DEFAULT_RESEARCH_LIMITS, type Autonomy, type Proposal } from "../lib/report/draft/research/decide";
+import { appendGenerationUsage, utcDay } from "./generationUsage";
+import type { ReportDraftDeps } from "./reportDraft";
+import {
+ armResearchAutoContinue,
+ disarmResearchAutoContinue,
+ isResearchAutoContinueArmed,
+ maybeAutoContinue,
+ researchAutoContinueTick,
+ UNBUILT_CHECK,
+} from "./researchAutoContinue";
+
+let tmp: string;
+let paths: Paths;
+let gen: GenerationSettings;
+const MODEL = "claude-sonnet-5-5";
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "research-auto-"));
+ paths = {
+ jobsDir: path.join(tmp, ".jobs"),
+ articlesDir: path.join(tmp, "reports"),
+ exportIndexDir: path.join(tmp, ".export-index"),
+ exportBuildsDir: path.join(tmp, ".export-builds"),
+ sitesDir: path.join(tmp, "sites"),
+ channelsDir: path.join(tmp, "channels"),
+ generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"),
+ ollamaUrl: "http://127.0.0.1:9",
+ } as Paths;
+ await mkdir(paths.channelsDir, { recursive: true });
+ gen = sanitizeGeneration({ anthropicBaseUrl: "http://127.0.0.1:9", caps: { sweep: 2, daily: 20, max: 5 } });
+ await writeBuild("synth", ["synth-kitchen"]);
+});
+
+afterEach(() => disarmResearchAutoContinue());
+
+after(async () => {
+ // Every job this file started has ended (asserted per test).
+ await rm(tmp, { recursive: true, force: true });
+});
+
+async function writeBuild(build: string, channels: string[], mtime?: Date) {
+ const dir = path.join(paths.exportBuildsDir, build, "out");
+ await mkdir(dir, { recursive: true });
+ const file = path.join(dir, "corpus.json");
+ await writeFile(file, JSON.stringify({ channels: channels.map((slug) => ({ slug })) }));
+ if (mtime) await utimes(file, mtime, mtime);
+}
+
+const corpusAsked: string[] = [];
+const deps = (o: { now?: () => Date; jobOf?: ReportDraftDeps["jobOf"] } = {}): ReportDraftDeps => ({
+ paths,
+ corpusTools: async (source) => {
+ corpusAsked.push(source);
+ throw new Error("the test's corpus is a stub");
+ },
+ settings: () => ({ generation: gen }),
+ ...o,
+});
+
+const prop = (id: string, action: Proposal["action"], args: Record<string, unknown>, status: Proposal["status"], extra: Partial<Proposal> = {}): Proposal => ({
+ id,
+ action,
+ args,
+ reason: "r",
+ evidence: [],
+ status,
+ ...extra,
+});
+
+// A research run whose job has ended: its proposals and autonomy.
+async function makeRun(article: string, o: { autonomy?: Autonomy; channels?: string[]; proposals?: Proposal[] } = {}): Promise<number> {
+ const it = await createIteration(article, { kind: "research", model: MODEL, question: "Where did the second shop story start?", scope: o.channels ? { channels: o.channels } : {} }, paths);
+ const state = newResearchState(o.autonomy ?? "auto", DEFAULT_RESEARCH_LIMITS);
+ state.proposals = o.proposals ?? [prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/1" }, "done", { doneAt: "2026-10-13T10:00:00.000Z" })];
+ await writeResearchState(article, it.n, state, paths);
+ await updateIteration(article, it.n, { status: "done", research: { autonomy: o.autonomy ?? "auto", phase: "wait" } } as never, paths);
+ return it.n;
+}
+
+const recOf = async (article: string, n: number) => ((await readIteration(article, n, paths)) as Iteration & { research?: ResearchRecord }).research!;
+const sweepsOf = async (article: string, n: number) => (await listIterations(article, paths)).filter((x) => x.kind === "sweep" && x.parent === n);
+const turnsOf = async (article: string, n: number) =>
+ (await readFile(iterationFile(paths, article, n, "turns.jsonl"), "utf8").catch(() => ""))
+ .split("\n")
+ .filter(Boolean)
+ .map((l) => JSON.parse(l) as { kind: string; outcome: string });
+
+// A job's end, waited for (the sweep the continuation enqueued fails at its stub corpus).
+async function ended(jobId: string) {
+ for (let i = 0; i < 200; i++) {
+ const s = getRegistry().get(jobId)?.status;
+ if (s && s !== "queued" && s !== "running") return s;
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ throw new Error(`job ${jobId} did not end`);
+}
+
+async function until<T>(fn: () => Promise<T | undefined | null | false>, what: string): Promise<T> {
+ for (let i = 0; i < 250; i++) {
+ const v = await fn();
+ if (v) return v;
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ throw new Error(`timed out waiting for ${what}`);
+}
+
+test("an auto run continues once, by itself, when its last acquisition's job ends", async () => {
+ // A real editor job stands for the acquisition: it runs until released.
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const acq = await runManagedFunction({ kind: "import-video", queueKey: "", paths, fn: async () => gate });
+ assert.ok(acq.ok);
+ void acq.stream.cancel();
+ const article = "synth-auto-end";
+ const n = await makeRun(article, {
+ channels: ["synth-kitchen"],
+ proposals: [prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/2" }, "enqueued", { jobId: acq.jobId })],
+ });
+ assert.ok(armResearchAutoContinue(deps(), { bootScan: false, env: {} }));
+
+ // While the job runs: not now, and nothing written but the phase.
+ const early = await maybeAutoContinue(article, n, deps());
+ assert.deepEqual(early, { outcome: "not-now", why: `waits on job(s): ${acq.jobId}` });
+ assert.equal((await recOf(article, n)).autoContinue, undefined);
+
+ // The job ends: the listener continues the run, with nothing else asked.
+ release();
+ await acq.done;
+ const rec = await until(async () => {
+ const r = await recOf(article, n);
+ return r.autoContinue?.status === "continued" ? r : null;
+ }, "the continuation");
+ const sweeps = await sweepsOf(article, n);
+ assert.equal(sweeps.length, 1);
+ const sweep = sweeps[0]!;
+ assert.deepEqual(rec.continuedBy, [sweep.n]);
+ assert.equal(rec.phase, "continued");
+ assert.equal(rec.autoContinue!.by, sweep.n);
+ assert.equal(sweep.model, MODEL, "the run's own model");
+ assert.equal(sweep.question, "Where did the second shop story start?");
+ assert.deepEqual(sweep.scope?.channels, ["synth-kitchen"]);
+ assert.equal(getRegistry().get(sweep.jobId!)?.queueKey, "draft:api");
+ assert.equal(await ended(sweep.jobId!), "failed", "the stub corpus");
+ assert.deepEqual((await turnsOf(article, n)).map((t) => [t.kind, t.outcome]), [["auto-continue", "continued"]]);
+
+ // Again, by either trigger: nothing more.
+ assert.deepEqual(await maybeAutoContinue(article, n, deps()), { outcome: "not-now", why: "continued already", final: true });
+ await researchAutoContinueTick();
+ assert.equal((await sweepsOf(article, n)).length, 1);
+});
+
+test("the heartbeat and job ends racing continue once; a claim held elsewhere is respected, a stale one looked into", async () => {
+ const article = "synth-auto-race";
+ const n = await makeRun(article, { channels: ["synth-kitchen"] });
+ armResearchAutoContinue(deps(), { bootScan: false, env: {} });
+ const [tick, a, b] = await Promise.all([researchAutoContinueTick(), maybeAutoContinue(article, n, deps()), maybeAutoContinue(article, n, deps())]);
+ const outcomes = [...(tick?.continued.filter((c) => c.article === article).map(() => "continued") ?? []), a.outcome, b.outcome];
+ assert.equal(outcomes.filter((o) => o === "continued").length, 1, JSON.stringify({ tick, a, b }));
+ const sweeps = await sweepsOf(article, n);
+ assert.equal(sweeps.length, 1);
+ assert.deepEqual((await recOf(article, n)).continuedBy, [sweeps[0]!.n]);
+ await ended(sweeps[0]!.jobId!);
+ // The sweep's end starts a scan: let it finish, then stop listening.
+ await researchAutoContinueTick();
+ disarmResearchAutoContinue();
+
+ // Another process's fresh claim (the store's lock is what it took): not now.
+ const held = await makeRun("synth-auto-claimed", { channels: ["synth-kitchen"] });
+ await updateIteration("synth-auto-claimed", held, (cur) => ({ research: { ...(cur as unknown as { research: ResearchRecord }).research, autoContinue: { status: "claimed", at: new Date().toISOString() } } }) as never, paths);
+ assert.deepEqual(await maybeAutoContinue("synth-auto-claimed", held, deps()), { outcome: "not-now", why: "being continued" });
+ assert.equal((await sweepsOf("synth-auto-claimed", held)).length, 0);
+
+ // A stale claim whose sweep was made (the editor died before marking it): recorded, not made again.
+ const stale = await makeRun("synth-auto-stale", { channels: ["synth-kitchen"] });
+ await updateIteration("synth-auto-stale", stale, (cur) => ({ research: { ...(cur as unknown as { research: ResearchRecord }).research, autoContinue: { status: "claimed", at: "2026-01-01T00:00:00.000Z" } } }) as never, paths);
+ const made = await createIteration("synth-auto-stale", { kind: "sweep", model: MODEL, parent: stale, question: "q", scope: { channels: ["synth-kitchen"] } }, paths);
+ const r = await maybeAutoContinue("synth-auto-stale", stale, deps());
+ assert.deepEqual(r, { outcome: "continued", by: made.n, warnings: [] });
+ assert.deepEqual((await recOf("synth-auto-stale", stale)).continuedBy, [made.n]);
+ assert.equal((await sweepsOf("synth-auto-stale", stale)).length, 1);
+});
+
+test("propose and limits never continue by themselves; a proposal waiting for approval holds an auto run", async () => {
+ for (const autonomy of ["propose", "limits"] as const) {
+ const article = `synth-auto-${autonomy}`;
+ const n = await makeRun(article, { autonomy, channels: ["synth-kitchen"] });
+ const r = await maybeAutoContinue(article, n, deps());
+ assert.deepEqual(r, { outcome: "not-now", why: `autonomy ${autonomy}: the operator continues it`, final: true });
+ assert.equal((await sweepsOf(article, n)).length, 0);
+ }
+ const article = "synth-auto-pending";
+ const n = await makeRun(article, {
+ channels: ["synth-kitchen"],
+ proposals: [
+ prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/3" }, "done", { doneAt: "2026-10-13T10:00:00.000Z" }),
+ prop("p02", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/4" }, "proposed", { note: "a download of unknown size waits" }),
+ ],
+ });
+ assert.deepEqual(await maybeAutoContinue(article, n, deps()), { outcome: "not-now", why: "waits for approval: p02" });
+ assert.equal((await sweepsOf(article, n)).length, 0);
+ assert.equal((await recOf(article, n)).autoContinue, undefined, "nothing recorded");
+ // A run still running is not read further.
+ await updateIteration(article, n, { status: "running" }, paths);
+ assert.deepEqual(await maybeAutoContinue(article, n, deps()), { outcome: "not-now", why: "the run is running" });
+});
+
+test("the daily cap: refused and recorded, not tried again the same UTC day, continued the next", async () => {
+ const day1 = new Date("2031-03-04T12:00:00.000Z");
+ const day2 = new Date("2031-03-05T00:30:00.000Z");
+ await appendGenerationUsage(paths.generationUsageFile, [
+ { at: day1.toISOString(), day: utcDay(day1), jobId: "x", article: "other", iteration: 1, task: "sweep", model: MODEL, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 20 },
+ ]);
+ const article = "synth-auto-cap";
+ const n = await makeRun(article, { channels: ["synth-kitchen"] });
+ const r = await maybeAutoContinue(article, n, deps({ now: () => day1 }));
+ assert.equal(r.outcome, "refused");
+ assert.match((r as { reason: string }).reason, /daily/i);
+ const rec = await recOf(article, n);
+ assert.equal(rec.autoContinue!.status, "refused");
+ assert.equal(rec.autoContinue!.day, "2031-03-04");
+ const updatedAt = (await readIteration(article, n, paths))!.updatedAt;
+
+ // The same day, later: not tried, nothing written.
+ const again = await maybeAutoContinue(article, n, deps({ now: () => new Date("2031-03-04T23:59:00.000Z") }));
+ assert.equal(again.outcome, "not-now");
+ assert.match((again as { why: string }).why, /^refused today .*tried again tomorrow \(UTC\)$/);
+ assert.equal((await readIteration(article, n, paths))!.updatedAt, updatedAt);
+ assert.equal((await sweepsOf(article, n)).length, 0);
+
+ // The next UTC day: the day's total is 0 again, and it continues.
+ const next = await maybeAutoContinue(article, n, deps({ now: () => day2 }));
+ assert.equal(next.outcome, "continued", JSON.stringify(next));
+ const sweeps = await sweepsOf(article, n);
+ assert.equal(sweeps.length, 1);
+ await ended(sweeps[0]!.jobId!);
+ assert.deepEqual((await turnsOf(article, n)).map((t) => t.outcome), ["refused", "continued"]);
+});
+
+test("channels in no build are left out with a warning; with nothing left the run is held until a newer build", async () => {
+ // Acquired into a new channel (in no build) beside the run's own.
+ const article = "synth-auto-unbuilt";
+ const n = await makeRun(article, {
+ channels: ["synth-kitchen"],
+ proposals: [
+ prop("p01", "create-channel", { fields: { name: "Synth Radio" } }, "done", { channel: "synth-radio", doneAt: "2026-10-13T10:00:00.000Z" }),
+ prop("p02", "import-video", { slug: "synth-radio", url: "https://video.example/v/5" }, "done", { doneAt: "2026-10-13T10:05:00.000Z" }),
+ ],
+ });
+ const r = await maybeAutoContinue(article, n, deps());
+ assert.equal(r.outcome, "continued", JSON.stringify(r));
+ const warning = "not in any build yet: synth-radio — rebuild the site and continue again";
+ assert.ok((r as { warnings: string[] }).warnings.includes(warning));
+ const sweep = (await sweepsOf(article, n))[0]!;
+ assert.deepEqual(sweep.scope?.channels, ["synth-kitchen"]);
+ assert.deepEqual(
+ (await readIteration(article, sweep.n, paths))!.checks?.find((c) => c.name === UNBUILT_CHECK),
+ { name: UNBUILT_CHECK, ok: false, detail: warning },
+ );
+ assert.ok((await recOf(article, n)).autoContinue!.warnings!.includes(warning));
+ await ended(sweep.jobId!);
+
+ // Nothing of its own, and its one acquisition in no build: held.
+ const only = "synth-auto-held";
+ const h = await makeRun(only, {
+ proposals: [prop("p01", "create-channel", { fields: { name: "Synth Late" } }, "done", { channel: "synth-late", doneAt: "2026-10-13T10:00:00.000Z" })],
+ });
+ const held = await maybeAutoContinue(only, h, deps());
+ assert.deepEqual(held, { outcome: "held", reason: "not in any build yet: synth-late — rebuild the site, and it continues by itself" });
+ assert.equal((await recOf(only, h)).autoContinue!.status, "held");
+ const before = (await readIteration(only, h, paths))!.updatedAt;
+ const quiet = await maybeAutoContinue(only, h, deps());
+ assert.equal(quiet.outcome, "not-now", "the same day and no newer build: not read further");
+ assert.equal((await readIteration(only, h, paths))!.updatedAt, before);
+ // A build that holds it, newer than the hold: it continues.
+ await writeBuild("synth-late", ["synth-late"], new Date(Date.now() + 60_000));
+ const now = await maybeAutoContinue(only, h, deps());
+ assert.equal(now.outcome, "continued", JSON.stringify(now));
+ const s = (await sweepsOf(only, h))[0]!;
+ assert.deepEqual(s.scope?.channels, ["synth-late"]);
+ await ended(s.jobId!);
+});
+
+test("a held run continues when a site build that holds its channel ends", async () => {
+ const article = "synth-auto-rebuilt";
+ const n = await makeRun(article, {
+ proposals: [prop("p01", "create-channel", { fields: { name: "Synth Rebuilt" } }, "done", { channel: "synth-rebuilt", doneAt: "2026-10-13T10:00:00.000Z" })],
+ });
+ assert.equal((await maybeAutoContinue(article, n, deps())).outcome, "held");
+ armResearchAutoContinue(deps(), { bootScan: false, env: {} });
+ // The operator puts it on a site and builds it: the build job's end runs the scan.
+ const build = await runManagedFunction({
+ kind: "build-export",
+ queueKey: "",
+ paths,
+ fn: async () => writeBuild("synth-rebuilt", ["synth-rebuilt"], new Date(Date.now() + 120_000)),
+ });
+ assert.ok(build.ok);
+ void build.stream.cancel();
+ await build.done;
+ const rec = await until(async () => {
+ const r = await recOf(article, n);
+ return r.autoContinue?.status === "continued" ? r : null;
+ }, "the continuation after the build");
+ const sweep = (await sweepsOf(article, n))[0]!;
+ assert.equal(rec.autoContinue!.by, sweep.n);
+ assert.deepEqual(sweep.scope?.channels, ["synth-rebuilt"]);
+ await ended(sweep.jobId!);
+ await researchAutoContinueTick();
+});
+
+test("an idle boot arms nothing: no listener, and the heartbeat's call is a no-op", async () => {
+ const article = "synth-auto-idle";
+ const n = await makeRun(article, { channels: ["synth-kitchen"] });
+ assert.equal(armResearchAutoContinue(deps(), { env: { ARCHILYZER_IDLE_BOOT: "1" } }), false);
+ assert.equal(isResearchAutoContinueArmed(), false);
+ assert.equal(await researchAutoContinueTick(), null);
+ assert.equal((await sweepsOf(article, n)).length, 0);
+ // Armed, the boot scan finds it.
+ assert.equal(armResearchAutoContinue(deps(), { env: {}, bootScan: false }), true);
+ const tick = await researchAutoContinueTick();
+ assert.ok(tick?.continued.some((c) => c.article === article && c.n === n), JSON.stringify(tick));
+ await ended((await sweepsOf(article, n))[0]!.jobId!);
+});
diff --git a/common/controller/researchAutoContinue.ts b/common/controller/researchAutoContinue.ts
@@ -0,0 +1,357 @@
+// AN `auto` RESEARCH RUN CONTINUES INTO ITS SWEEP BY ITSELF (release 28 F1).
+//
+// What the operator's "Continue into a sweep" does — `report-draft {task:
+// "sweep", iteration: n}` (controller/reportDraft.ts, through continuationOf)
+// — done by the editor once the run's acquisitions settle, for a run whose
+// autonomy is `auto` (`propose` and `limits` are always continued by the
+// operator). maybeAutoContinue(article, n) is the one function; it is
+// idempotent, and two triggers call it:
+// - the end of a job the run waits on: settle (researchRuns.ts) names an
+// `auto` run's pending editor jobs, and the registry's job-end listener
+// takes the run of one that ended; a `report-draft` job's end (the
+// research job itself, among others) or a site build's runs the scan
+// below;
+// - the scan, on the editor's heartbeat and once at boot: the research
+// iterations (a proposals.json) of every article, a run already finished
+// with (continued, or not `auto`) remembered and not read again.
+// Both are armed by the editor's instrumentation BELOW the idle gate
+// (armResearchAutoContinue refuses an idle boot too): ARCHILYZER_IDLE_BOOT
+// arms nothing, and the heartbeat's call is a no-op unarmed.
+//
+// A run continues when:
+// - it is a done research run, `auto`, not continued (no `continuedBy`, no
+// fresh claim), with nothing waiting for the operator's yes or no and
+// every acquisition job ended (done, failed or cancelled);
+// - something it would sweep is in a composed build: a channel in none
+// (a created channel is on no site until the operator puts it on one and
+// builds it) is left out, and the sweep carries the warning "not in any
+// build yet: <slug> — rebuild the site and continue again". With nothing
+// left the run is `held`, and tried again once a newer build exists (or
+// on a later day);
+// - the caps hold: the sweep is the run's own model, its per-job cap the
+// sweep's (caps.sweep), and an API model is refused past the daily cap —
+// `refused`, tried again on a later UTC day, never in a loop. Any other
+// refusal of the ask is recorded and retried the same way.
+// The once-only mark is a claim taken under the article store's lock
+// (updateIteration's read-patch-write): a heartbeat and a job end racing, in
+// this process or another, continue once. A claim older than CLAIM_STALE_MS
+// (the editor died between the claim and the enqueue) is looked into: a
+// sweep it made is recorded, else it is claimed again.
+//
+// Every outcome is on the run: `research.autoContinue` in its iteration.json
+// (the umtool queue shows it), a `{kind: "auto-continue"}` line in its
+// turns.jsonl, and — for channels left out — a failed `unbuilt channels`
+// check on the sweep it made.
+
+import { readdir, stat } from "node:fs/promises";
+import { isIdleBoot } from "../lib/idleBoot";
+import { getSettings } from "../lib/settings";
+import { providerOf } from "../lib/llm";
+import { onJobEnd } from "../jobs/registry";
+import { REPORT_ID_RE } from "../lib/report/schema";
+import {
+ appendIterationTurns,
+ iterationDirNumbers,
+ iterationFile,
+ listIterations,
+ readIteration,
+ updateIteration,
+ type Iteration,
+} from "../lib/report/iterations";
+import { listCorpusBuilds } from "../lib/report/draft/tasks/corpusSource";
+import { readResearchState, widenedChannels, type AutoContinueRecord, type ResearchRecord } from "../lib/report/draft/research/state";
+import { dailyCapRefusal, dayUsage, utcDay } from "./generationUsage";
+import { enqueueReportDraft, REPORT_DRAFT_JOB_KIND, type ReportDraftDeps } from "./reportDraft";
+import { markContinued, researchState, takeWatchedRun } from "./researchRuns";
+
+export const CLAIM_STALE_MS = 10 * 60_000;
+
+// The jobs whose end runs the scan: a generation's (the research job's own
+// among them) and a site build's (a held run may now have its build).
+export const SCAN_ON_END = new Set([REPORT_DRAFT_JOB_KIND, "publish-build-site", "build-export", "build-deploy", "build-all", "build-deploy-all"]);
+export const UNBUILT_CHECK = "unbuilt channels";
+
+export type AutoContinueResult =
+ | { outcome: "continued"; by: number; jobId?: string; warnings: string[] }
+ | { outcome: "held" | "refused"; reason: string }
+ // Not now (nothing written). `final`: never — the scan stops reading it.
+ | { outcome: "not-now"; why: string; final?: boolean };
+
+const recordOf = (it: Iteration): ResearchRecord | undefined => (it as { research?: ResearchRecord }).research;
+
+// One attempt per run at a time, in this process (the claim below is the
+// guard across processes).
+const chains = new Map<string, Promise<unknown>>();
+function serial<T>(key: string, fn: () => Promise<T>): Promise<T> {
+ const prev = chains.get(key) ?? Promise.resolve();
+ const next = prev.then(fn, fn);
+ const tail = next.catch(() => {});
+ chains.set(key, tail);
+ void tail.then(() => {
+ if (chains.get(key) === tail) chains.delete(key);
+ });
+ return next;
+}
+
+class NotNow extends Error {}
+
+async function record(article: string, n: number, ac: AutoContinueRecord, deps: ReportDraftDeps, now: Date): Promise<void> {
+ await updateIteration(
+ article,
+ n,
+ (cur) => ({ research: { ...(recordOf(cur) ?? { autonomy: "auto" as const, phase: "ready" as const }), autoContinue: ac } }),
+ deps.paths,
+ now,
+ );
+ const { status, ...rest } = ac;
+ await appendIterationTurns(article, n, [{ kind: "auto-continue", outcome: status, ...rest }], deps.paths).catch(() => {});
+}
+
+// Why run `it` is not continued now, from its iteration.json alone (null:
+// read on). `final` when it never will be.
+function notYet(it: Iteration | null, now: Date): { why: string; final?: boolean } | null {
+ if (!it) return { why: "no such iteration", final: true };
+ if (it.kind !== "research") return { why: `a ${it.kind} iteration, not a research run`, final: true };
+ const rec = recordOf(it);
+ if (rec && rec.autonomy !== "auto") return { why: `autonomy ${rec.autonomy}: the operator continues it`, final: true };
+ if ((rec?.continuedBy?.length ?? 0) > 0 || rec?.autoContinue?.status === "continued") return { why: "continued already", final: true };
+ if (it.status === "failed" || it.status === "cancelled") return { why: `the run ${it.status}`, final: true };
+ if (it.status !== "done") return { why: `the run is ${it.status}` };
+ const ac = rec?.autoContinue;
+ if (ac?.status === "claimed" && now.getTime() - Date.parse(ac.at) < CLAIM_STALE_MS) return { why: "being continued" };
+ if (ac?.status === "refused" && ac.day === utcDay(now)) return { why: `refused today (${ac.reason}); tried again tomorrow (UTC)` };
+ return null;
+}
+
+// Continue research run `n` of `article` into its sweep if it is ready to be
+// (see the head of this file). Idempotent.
+export function maybeAutoContinue(article: string, n: number, deps: ReportDraftDeps): Promise<AutoContinueResult> {
+ return serial(`${article}/${n}`, () => attempt(article, n, deps));
+}
+
+async function attempt(article: string, n: number, deps: ReportDraftDeps): Promise<AutoContinueResult> {
+ const paths = deps.paths;
+ const now = deps.now?.() ?? new Date();
+ const today = utcDay(now);
+ const it = await readIteration(article, n, paths).catch(() => null);
+ const no = notYet(it, now);
+ if (no) return { outcome: "not-now", ...no };
+ const run = it!;
+ const rec = recordOf(run);
+ if (!rec) {
+ // A record is written with the run's first proposals; without one, its
+ // autonomy is proposals.json's.
+ const state = await readResearchState(article, n, paths);
+ if (!state) return { outcome: "not-now", why: "no proposals yet" };
+ if (state.autonomy !== "auto") return { outcome: "not-now", why: `autonomy ${state.autonomy}: the operator continues it`, final: true };
+ }
+ const builds = await listCorpusBuilds(paths.exportBuildsDir);
+ const newest = Math.max(0, ...builds.map((b) => b.mtimeMs));
+ const ac = rec?.autoContinue;
+ if (ac?.status === "held" && ac.day === today && newest <= (ac.buildsAt ?? 0)) {
+ return { outcome: "not-now", why: `held (${ac.reason}) until a newer build` };
+ }
+
+ // The run now: its acquisitions refreshed from their jobs (and its phase
+ // written, and its pending jobs watched).
+ const view = await researchState(article, n, { paths, ...(deps.jobOf ? { jobOf: deps.jobOf } : {}) });
+ if (view.autonomy !== "auto") return { outcome: "not-now", why: `autonomy ${view.autonomy}: the operator continues it`, final: true };
+ if (view.waitingOn.approval.length) return { outcome: "not-now", why: `waits for approval: ${view.waitingOn.approval.join(", ")}` };
+ if (view.waitingOn.jobs.length) return { outcome: "not-now", why: `waits on job(s): ${view.waitingOn.jobs.join(", ")}` };
+ if (view.phase !== "ready") return { outcome: "not-now", why: `its phase is ${view.phase}`, ...(view.phase === "continued" ? { final: true } : {}) };
+
+ // The scope: the run's channels and what it acquired into, less any in no build.
+ const channels = widenedChannels(run.scope?.channels ?? [], view);
+ const built = new Set(builds.flatMap((b) => b.channels));
+ const unbuilt = channels.filter((c) => !built.has(c));
+ const kept = channels.filter((c) => built.has(c));
+ const warnings = unbuilt.length ? [`not in any build yet: ${unbuilt.join(", ")} — rebuild the site and continue again`] : [];
+ if (!kept.length) {
+ const reason = channels.length ? `not in any build yet: ${unbuilt.join(", ")} — rebuild the site, and it continues by itself` : "it names no channel and acquired into none";
+ await record(article, n, { status: "held", at: now.toISOString(), reason, day: today, buildsAt: newest }, deps, now);
+ return { outcome: "held", reason };
+ }
+
+ // The caps: an API model is refused past the day's total (and the ask
+ // refuses again; the job, at its turn).
+ const gen = (deps.settings ?? getSettings)().generation;
+ const model = run.model;
+ if (providerOf(model) === "api") {
+ const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, today), gen.caps.daily);
+ if (refusal) {
+ await record(article, n, { status: "refused", at: now.toISOString(), reason: refusal, day: today }, deps, now);
+ return { outcome: "refused", reason: refusal };
+ }
+ }
+
+ // A stale claim: the sweep it made, if any, is the continuation.
+ if (ac?.status === "claimed") {
+ const made = (await listIterations(article, paths)).find((x) => x.kind === "sweep" && x.parent === n && Date.parse(x.createdAt) >= Date.parse(ac.at));
+ if (made) {
+ await markContinued(article, n, made.n, paths);
+ await record(article, n, { status: "continued", at: now.toISOString(), by: made.n, ...(ac.warnings?.length ? { warnings: ac.warnings } : {}) }, deps, now);
+ return { outcome: "continued", by: made.n, warnings: ac.warnings ?? [] };
+ }
+ }
+
+ // THE CLAIM: checked and marked in one write under the store's lock.
+ try {
+ await updateIteration(
+ article,
+ n,
+ (cur) => {
+ const r = recordOf(cur);
+ if ((r?.continuedBy?.length ?? 0) > 0 || r?.autoContinue?.status === "continued") throw new NotNow("continued already");
+ const c = r?.autoContinue;
+ if (c?.status === "claimed" && now.getTime() - Date.parse(c.at) < CLAIM_STALE_MS) throw new NotNow("being continued");
+ return {
+ research: {
+ ...(r ?? { autonomy: "auto" as const, phase: "ready" as const }),
+ autoContinue: { status: "claimed" as const, at: now.toISOString(), ...(warnings.length ? { warnings } : {}) },
+ },
+ };
+ },
+ paths,
+ now,
+ );
+ } catch (e) {
+ if (e instanceof NotNow) return { outcome: "not-now", why: e.message };
+ throw e;
+ }
+
+ // The continuation, as the operator's Continue asks it.
+ const out = await enqueueReportDraft({ task: "sweep", article, iteration: n, model, channels: kept }, deps);
+ if (!out.result.ok || !("iteration" in out)) {
+ const reason = (out.result as { error: string }).error;
+ await record(article, n, { status: "refused", at: now.toISOString(), reason, day: today }, deps, now);
+ return { outcome: "refused", reason };
+ }
+ // Nobody reads the job's stream (the ops routes release it the same way).
+ void out.result.stream.cancel();
+ const all = [...warnings, ...(out.warnings ?? [])];
+ await record(article, n, { status: "continued", at: now.toISOString(), by: out.iteration, ...(all.length ? { warnings: all } : {}) }, deps, now);
+ if (unbuilt.length) {
+ await updateIteration(
+ article,
+ out.iteration,
+ (cur) => ({ checks: [...(cur.checks ?? []).filter((c) => c.name !== UNBUILT_CHECK), { name: UNBUILT_CHECK, ok: false, detail: warnings[0] }] }),
+ paths,
+ now,
+ ).catch(() => {});
+ }
+ return { outcome: "continued", by: out.iteration, jobId: out.result.jobId, warnings: all };
+}
+
+// ─── the scan ───
+
+// Runs the scan has finished with (continued, or never `auto`): not read again.
+const finished = new Set<string>();
+let scanning: Promise<ScanResult> | null = null;
+
+export type ScanResult = { runs: number; continued: { article: string; n: number; by: number }[]; held: string[]; refused: string[] };
+
+// Every research run that might continue, tried once. One scan at a time (a
+// second caller shares the one going).
+export function scanAutoContinue(deps: ReportDraftDeps, log?: (line: string) => void): Promise<ScanResult> {
+ if (!scanning) {
+ scanning = scan(deps, log).finally(() => {
+ scanning = null;
+ });
+ }
+ return scanning;
+}
+
+async function scan(deps: ReportDraftDeps, log?: (line: string) => void): Promise<ScanResult> {
+ const out: ScanResult = { runs: 0, continued: [], held: [], refused: [] };
+ let articles: string[];
+ try {
+ articles = (await readdir(deps.paths.articlesDir, { withFileTypes: true })).filter((e) => e.isDirectory() && REPORT_ID_RE.test(e.name)).map((e) => e.name);
+ } catch {
+ return out;
+ }
+ for (const article of articles) {
+ let ns: number[];
+ try {
+ ns = await iterationDirNumbers(article, deps.paths);
+ } catch {
+ continue;
+ }
+ for (const n of ns) {
+ const key = `${article}/${n}`;
+ if (finished.has(key)) continue;
+ // Only a research run has a proposals.json.
+ if (!(await stat(iterationFile(deps.paths, article, n, "proposals.json")).then(() => true, () => false))) continue;
+ out.runs++;
+ const r: AutoContinueResult = await maybeAutoContinue(article, n, deps).catch((e): AutoContinueResult => ({ outcome: "not-now", why: (e as Error).message }));
+ report(article, n, r, out, log);
+ if (r.outcome === "continued" || (r.outcome === "not-now" && r.final)) finished.add(key);
+ }
+ }
+ return out;
+}
+
+function report(article: string, n: number, r: AutoContinueResult, out: ScanResult | null, log?: (line: string) => void) {
+ if (r.outcome === "continued") {
+ out?.continued.push({ article, n, by: r.by });
+ log?.(`research auto-continue: ${article} i${n} continued by i${r.by}${r.warnings.length ? ` (${r.warnings.join("; ")})` : ""}`);
+ } else if (r.outcome === "held" || r.outcome === "refused") {
+ out?.[r.outcome].push(`${article}/${n}`);
+ log?.(`research auto-continue: ${article} i${n} ${r.outcome}: ${r.reason}`);
+ }
+}
+
+// ─── arming (the editor's instrumentation, below the idle gate) ───
+
+type Armed = { deps: ReportDraftDeps; log?: (line: string) => void; off: () => void };
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttResearchAutoContinue__: Armed | undefined;
+}
+
+// Arm both triggers: the job-end listener now, the boot scan now, and the
+// heartbeat's tick from here on. Refused (false) on an idle boot. Idempotent:
+// a second call only replaces the deps.
+export function armResearchAutoContinue(deps: ReportDraftDeps, o: { log?: (line: string) => void; env?: Record<string, string | undefined>; bootScan?: boolean } = {}): boolean {
+ if (isIdleBoot(o.env)) return false;
+ const armed = globalThis.__yttResearchAutoContinue__;
+ if (armed) {
+ armed.deps = deps;
+ armed.log = o.log;
+ return true;
+ }
+ const state: Armed = { deps, ...(o.log ? { log: o.log } : {}), off: () => {} };
+ state.off = onJobEnd((job) => {
+ const run = takeWatchedRun(job.id);
+ if (run) {
+ void maybeAutoContinue(run.article, run.n, state.deps).then(
+ (r) => report(run.article, run.n, r, null, state.log),
+ (e) => state.log?.(`research auto-continue: ${run.article} i${run.n}: ${(e as Error).message}`),
+ );
+ } else if (SCAN_ON_END.has(job.kind)) {
+ // A research job's end (or any generation's) — the scan finds its run —
+ // or a site build's, which may hold what a held run waits for.
+ void scanAutoContinue(state.deps, state.log).catch(() => {});
+ }
+ });
+ globalThis.__yttResearchAutoContinue__ = state;
+ if (o.bootScan !== false) void scanAutoContinue(deps, o.log).catch(() => {});
+ return true;
+}
+
+export function disarmResearchAutoContinue(): void {
+ globalThis.__yttResearchAutoContinue__?.off();
+ globalThis.__yttResearchAutoContinue__ = undefined;
+ finished.clear();
+}
+
+export function isResearchAutoContinueArmed(): boolean {
+ return globalThis.__yttResearchAutoContinue__ !== undefined;
+}
+
+// The heartbeat's call: a scan when armed, else nothing (null).
+export async function researchAutoContinueTick(): Promise<ScanResult | null> {
+ const armed = globalThis.__yttResearchAutoContinue__;
+ if (!armed) return null;
+ return scanAutoContinue(armed.deps, armed.log);
+}
diff --git a/common/controller/researchRuns.ts b/common/controller/researchRuns.ts
@@ -18,7 +18,9 @@
// THE CONTINUATION is `report-draft {task: "sweep", iteration: <research n>}`
// (controller/reportDraft.ts, through continuationOf here): a sweep iteration
// whose parent is the research run, over the run's channels and every channel
-// a done acquisition wrote into.
+// a done acquisition wrote into. An `auto` run asks it by itself once its
+// acquisitions settle (release 28 F1, controller/researchAutoContinue.ts):
+// settle below names the jobs such a run still waits on (watchResearchJobs).
import type { Paths } from "../lib/paths";
import { getJobEntry } from "../jobs/listJobs";
@@ -35,6 +37,7 @@ import {
waitingOn,
widenedChannels,
writeResearchState,
+ type AutoContinueRecord,
type JobOf,
type ResearchPhase,
type ResearchRecord,
@@ -95,9 +98,48 @@ async function settle(article: string, it: Iteration, state: ResearchState, chan
if (it.status !== "queued" && it.status !== "running" && rec?.phase !== phase) {
await updateIteration(article, it.n, (cur) => ({ research: { ...(recordOf(cur) ?? { autonomy: state.autonomy }), phase } }), paths);
}
+ // An `auto` run hears its acquisitions end (release 28 F1).
+ if (state.autonomy === "auto" && phase !== "continued") watchResearchJobs(article, it.n, waitingOn(state).jobs);
return phase;
}
+// ─── the jobs an `auto` run waits on (release 28 F1) ───
+//
+// Job id → the run, in this process: whoever refreshes an `auto` run (settle,
+// above) names the editor jobs it still waits on, and the job-end listener
+// (controller/researchAutoContinue.ts) takes the run of a job that ended. A
+// restart forgets them; the boot pass and the heartbeat find the runs again.
+
+const WATCH_MAX = 2000;
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttResearchJobWatch__: Map<string, { article: string; n: number }> | undefined;
+}
+
+const watch = () => (globalThis.__yttResearchJobWatch__ ??= new Map());
+
+export function watchResearchJobs(article: string, n: number, jobIds: readonly string[]): void {
+ const m = watch();
+ for (const id of jobIds) {
+ m.delete(id);
+ m.set(id, { article, n });
+ }
+ // Oldest first out: a map past its bound forgets the longest-watched.
+ for (const id of m.keys()) {
+ if (m.size <= WATCH_MAX) break;
+ m.delete(id);
+ }
+}
+
+// The run waiting on job `id`, once (the watch is taken).
+export function takeWatchedRun(id: string): { article: string; n: number } | undefined {
+ const m = watch();
+ const run = m.get(id);
+ if (run) m.delete(id);
+ return run;
+}
+
export type ResearchView = {
article: string;
iteration: number;
@@ -111,6 +153,9 @@ export type ResearchView = {
continuedBy: number[];
// The agent's closing words: what the archive holds, what it asked for.
notes?: string;
+ // An `auto` run's own continuation: continued (by), refused or held, and
+ // why (release 28 F1).
+ autoContinue?: AutoContinueRecord;
};
function viewOf(article: string, it: Iteration, state: ResearchState, phase: ResearchPhase): ResearchView {
@@ -126,6 +171,7 @@ function viewOf(article: string, it: Iteration, state: ResearchState, phase: Res
waitingOn: waitingOn(state),
continuedBy: recordOf(it)?.continuedBy ?? [],
...(recordOf(it)?.notes ? { notes: recordOf(it)!.notes } : {}),
+ ...(recordOf(it)?.autoContinue ? { autoContinue: recordOf(it)!.autoContinue } : {}),
};
}
diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts
@@ -99,6 +99,8 @@ const ADDED_KINDS: Record<string, { label: string; drainable: boolean }> = {
"transcribe-file": { label: "Transcribe file", drainable: false },
// One synthesis (pnpm ops tts): one engine run, or a cache hit.
"tts-file": { label: "Text to speech", drainable: false },
+ // The verdict bench (pnpm ops bench-verdicts, release 28 M7): one run.
+ "bench-verdicts": { label: "Verdict bench", drainable: false },
};
test("added kinds carry their pinned label and drainability", () => {
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -942,6 +942,19 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
replayable: false,
queueKeyStrategy: "custom",
},
+ // The verdict bench (release 28 M7): ruled fact-check claims asked of
+ // models, one per call — `pnpm ops bench-verdicts`, on `draft:local` when
+ // any model is local (the GPU arbiter's path) else `draft:api`. It reads
+ // the article registry and cues' text, and writes only under the checkout's
+ // `.generation/bench/`; neither guard. Not replayable: a re-run of the same
+ // run id resumes it.
+ "bench-verdicts": {
+ kind: "bench-verdicts",
+ label: "Verdict bench",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ },
"tts-file": {
kind: "tts-file",
label: "Text to speech",
diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts
@@ -191,6 +191,45 @@ function markTerminal(
if (typeof exitCode === "number") job.exitCode = exitCode;
}
+// WHO HEARS A JOB END (release 28 F1): a listener is told once per job, after
+// its terminal state is set, on a later turn of the event loop (so the job's
+// own end — its sidecar write — goes first), and a listener that throws never
+// touches the job. Kept on globalThis like the registry. An `auto` research
+// run listens for its acquisitions here (controller/researchAutoContinue.ts).
+export type JobEndListener = (job: Readonly<Pick<JobRecord, "id" | "kind" | "status" | "channelSlug">>) => void;
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttJobEndListeners__: Set<JobEndListener> | undefined;
+}
+
+const endNotified = new WeakSet<JobRecord>();
+
+// Listen for every job's end; the answer stops listening.
+export function onJobEnd(listener: JobEndListener): () => void {
+ const set = (globalThis.__yttJobEndListeners__ ??= new Set());
+ set.add(listener);
+ return () => {
+ set.delete(listener);
+ };
+}
+
+function notifyJobEnd(job: JobRecord): void {
+ const set = globalThis.__yttJobEndListeners__;
+ if (!set?.size || endNotified.has(job)) return;
+ endNotified.add(job);
+ const seen = { id: job.id, kind: job.kind, status: job.status, ...(job.channelSlug ? { channelSlug: job.channelSlug } : {}) };
+ setImmediate(() => {
+ for (const fn of set) {
+ try {
+ fn(seen);
+ } catch {
+ // a listener never breaks a job's end
+ }
+ }
+ });
+}
+
// The registry owns job LIFECYCLE/STATE (the JobRecord, meta sidecars, tasks,
// terminal transitions). Queue ORDERING — which job runs vs. waits, and the
// foreground-before-background priority — is delegated to the shared Scheduler
@@ -292,6 +331,7 @@ class JobRegistry {
job.tasks = [];
job.drainController = undefined;
getScheduler().complete(id);
+ notifyJobEnd(job);
}
cancel(id: string): boolean {
diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts
@@ -110,3 +110,12 @@ test("cut (release 28 M1): the most entries a drafted cut keeps, 20 by default,
assert.equal(sanitizeGeneration({ cut: { maxClips: 12 } }).cut.maxClips, 12);
for (const bad of [2, 12.5, -1, "12", null]) assert.equal(sanitizeGeneration({ cut: { maxClips: bad } }).cut.maxClips, 20, String(bad));
});
+
+test("generation settings: the verdict bench's bar (fractions, clamped) and the ticked models; none by default", () => {
+ assert.deepEqual(DEFAULT_GENERATION_SETTINGS.verdicts, { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] });
+ assert.deepEqual(sanitizeGeneration({}).verdicts, DEFAULT_GENERATION_SETTINGS.verdicts);
+ const v = sanitizeGeneration({
+ verdicts: { bar: { agreement: 0.756789, contradictedRecall: 1.5, notFoundRecall: "x" }, models: ["claude-sonnet-5-5", " qwen3:8b ", "bad model", 3, "claude-sonnet-5-5"] },
+ }).verdicts;
+ assert.deepEqual(v, { bar: { agreement: 0.7568, contradictedRecall: 1, notFoundRecall: 0 }, models: ["claude-sonnet-5-5", "qwen3:8b"] });
+});
diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts
@@ -57,6 +57,12 @@ export type GenerationResearch = {
// The cut task's limits (release 28 M1).
export type GenerationCut = { maxClips: number };
+// The verdict bench's bar and the models that cleared it (release 28 M7):
+// the bar is the operator's, set on umtool's /bench after reading a run;
+// `models` are the passing models the operator ticked — never set
+// automatically. M8's verdict proposals run only on these.
+export type GenerationVerdictBar = { agreement: number; contradictedRecall: number; notFoundRecall: number };
+export type GenerationVerdicts = { bar: GenerationVerdictBar; models: string[] };
export type GenerationSettings = {
preset: GenerationPreset | "custom";
@@ -72,8 +78,11 @@ export type GenerationSettings = {
citationOrigin: string;
research: GenerationResearch;
cut: GenerationCut;
+ verdicts: GenerationVerdicts;
};
+export const DEFAULT_GENERATION_VERDICTS: GenerationVerdicts = { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] };
+
export const DEFAULT_GENERATION_RESEARCH: GenerationResearch = { autonomy: "propose", ...DEFAULT_RESEARCH_LIMITS };
export const DEFAULT_API_KEY_FILE = "~/.config/archilyzer/anthropic.env";
@@ -92,6 +101,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = {
citationOrigin: "",
research: { ...DEFAULT_GENERATION_RESEARCH },
cut: { maxClips: 20 },
+ verdicts: { bar: { ...DEFAULT_GENERATION_VERDICTS.bar }, models: [] },
};
export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
@@ -112,6 +122,19 @@ export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
"The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site.",
research: "A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'.",
cut: "The cut task's limits (below).",
+ verdicts:
+ "The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`.",
+};
+
+export const GENERATION_VERDICTS_FIELD_DOCS: FieldDocs<GenerationVerdicts> = {
+ bar: "The bar a model must clear on a bench run (below): each a fraction, 0 to 1. All 0 = no bar set.",
+ models: "The models the operator ticked as passing the bar — never set automatically. Empty = none: no verdict proposals.",
+};
+
+export const GENERATION_VERDICT_BAR_FIELD_DOCS: FieldDocs<GenerationVerdictBar> = {
+ agreement: "The least share of claims on which the model's verdict must equal the operator's (strictly: PARTLY is not CORROBORATED).",
+ contradictedRecall: "The least share of the claims the operator ruled CONTRADICTED that the model must rule so.",
+ notFoundRecall: "The least share of the claims the operator ruled NOT_FOUND that the model must rule so.",
};
export const GENERATION_CUT_FIELD_DOCS: FieldDocs<GenerationCut> = {
@@ -155,7 +178,7 @@ export const GENERATION_WEB_FIELD_DOCS: FieldDocs<GenerationWeb> = {
export const GENERATION_RESEARCH_FIELD_DOCS: FieldDocs<GenerationResearch> = {
autonomy:
- "`propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD.",
+ "`propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not; once its acquisitions settle the run continues into its sweep by itself, leaving out a channel in no build). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD.",
maxItemsPerRun: "The most items (videos, archive.org files, posts) one run may acquire without approval. Past it, an acquisition waits.",
maxGbPerRun: "The most GB one run may download without approval. An acquisition of unknown size waits.",
maxTranscribeHours: "The most hours of transcription one run may queue without approval. One of unknown length waits.",
@@ -249,9 +272,20 @@ export function sanitizeGeneration(value: unknown): GenerationSettings {
newChannelsNeedApproval: typeof rs.newChannelsNeedApproval === "boolean" ? rs.newChannelsNeedApproval : dr.newChannelsNeedApproval,
postWalksNeedApproval: typeof rs.postWalksNeedApproval === "boolean" ? rs.postWalksNeedApproval : dr.postWalksNeedApproval,
},
+ verdicts: sanitizeVerdicts(r.verdicts),
};
}
+function sanitizeVerdicts(v: unknown): GenerationVerdicts {
+ const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
+ const b = o.bar && typeof o.bar === "object" && !Array.isArray(o.bar) ? (o.bar as Record<string, unknown>) : {};
+ const frac = (x: unknown) => (typeof x === "number" && Number.isFinite(x) ? Math.min(1, Math.max(0, Math.round(x * 10_000) / 10_000)) : 0);
+ const models = Array.isArray(o.models)
+ ? [...new Set(o.models.filter((m): m is string => typeof m === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(m.trim())).map((m) => m.trim()))]
+ : [];
+ return { bar: { agreement: frac(b.agreement), contradictedRecall: frac(b.contradictedRecall), notFoundRecall: frac(b.notFoundRecall) }, models };
+}
+
export function presetOf(routes: GenerationRoutes): GenerationPreset | "custom" {
return GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => routes[t] === GENERATION_PRESETS[p][t])) ?? "custom";
}
diff --git a/common/lib/report/draft/bench/bench.test.ts b/common/lib/report/draft/bench/bench.test.ts
@@ -0,0 +1,361 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { errorTurn, startFakeAnthropic, toolTurn } from "../../../../testing/llm/fakeAnthropic.mjs";
+import { jsonReply, reply, startFakeOllama } from "../../../../testing/llm/fakeOllama.mjs";
+import { cuesOf } from "../../../../testing/draft/corpus.mjs";
+import { VERDICTS, type Verdict } from "../../verdicts";
+import {
+ BASELINE_MODEL,
+ benchItemsOf,
+ benchPrompt,
+ benchReportsOf,
+ benchRootOf,
+ LOCAL_PROMPT_CAP,
+ passesBar,
+ planVerdictBench,
+ readBenchRun,
+ runVerdictBench,
+ scoreBench,
+ VERDICT_BENCH_SYSTEM,
+ type BenchItem,
+ type BenchResult,
+} from "./index";
+import { promptEstimate } from "../../../llm/ollama";
+
+const RULED = path.join(import.meta.dirname, "../../../../testing/draft/reports/ruled.report.json");
+
+// The operator's rulings in the synthetic fact-check, by claim.
+const TRUTH: Record<string, Verdict> = {
+ r01: "CORROBORATED",
+ r02: "PARTLY",
+ r03: "PARTLY",
+ r04: "CONTRADICTED",
+ r05: "CONTRADICTED",
+ r06: "CORROBORATED",
+ r07: "NOT_FOUND",
+};
+
+async function store(mutate?: (r: any) => void) {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "bench-"));
+ const report = JSON.parse(await readFile(RULED, "utf8"));
+ mutate?.(report);
+ await mkdir(path.join(dir, "reports", report.id), { recursive: true });
+ await writeFile(path.join(dir, "reports", report.id, "report.json"), JSON.stringify(report));
+ // A sweep beside it: never an item.
+ await mkdir(path.join(dir, "reports", "a-sweep"), { recursive: true });
+ await writeFile(
+ path.join(dir, "reports", "a-sweep", "report.json"),
+ JSON.stringify({ format: "archilyzer-report", version: 1, id: "a-sweep", kind: "sweep", title: "A sweep", sections: [] }),
+ );
+ const paths = {
+ articlesDir: path.join(dir, "reports"),
+ exportIndexDir: path.join(dir, "export-index"),
+ generationUsageFile: path.join(dir, ".generation", "usage.jsonl"),
+ };
+ return { dir, paths, done: () => rm(dir, { recursive: true, force: true }) };
+}
+
+const claimOf = (user: string) => /^Claim: (.*)$/m.exec(user)?.[1] ?? "";
+
+// The synthetic claims' texts, to answer by.
+async function claimTexts(): Promise<Record<string, string>> {
+ const report = JSON.parse(await readFile(RULED, "utf8"));
+ const out: Record<string, string> = {};
+ for (const s of report.sections) for (const c of s.claims) out[c.text] = c.id;
+ return out;
+}
+
+function userOf(body: any): string {
+ const m = body.messages?.[0]?.content;
+ return typeof m === "string" ? m : "";
+}
+
+test("items: the ruled claims with cues; a claim with no citation skipped, with its reason; the answer kept off the prompt", async () => {
+ const s = await store();
+ try {
+ const reports = await benchReportsOf(s.paths);
+ assert.deepEqual(reports.map((r) => r.id), ["synth-ruled"]);
+ const { items, skipped } = await benchItemsOf(reports, { cuesOf, windowS: 60 });
+ assert.deepEqual(items.map((i) => i.claim), ["r01", "r02", "r03", "r04", "r05", "r06", "r07"]);
+ assert.deepEqual(skipped, [{ key: "synth-ruled/r08", report: "synth-ruled", claim: "r08", reason: "no citation" }]);
+ for (const it of items) assert.equal(it.verdict, TRUTH[it.claim]);
+ const r04 = items.find((i) => i.claim === "r04")!;
+ assert.equal(r04.windows.length, 1);
+ const w = r04.windows[0]!;
+ assert.equal(w.from, 150);
+ assert.equal(w.to, 274.8);
+ assert.ok(w.cues.length > 0 && w.cues.every((c) => c.end >= 150 && c.start <= 274.8));
+ // Nothing the check found is on an item, and the prompt never shows the verdict.
+ for (const it of items) {
+ assert.equal("findings" in it, false);
+ const p = benchPrompt(it);
+ assert.ok(p.user.includes(it.text));
+ assert.ok(p.user.includes(it.quotes[0]!.quote));
+ assert.ok(!p.user.includes(it.verdict), `${it.claim}'s prompt names its verdict`);
+ }
+ const findings = JSON.parse(await readFile(RULED, "utf8")).sections.flatMap((x: any) => x.claims).map((c: any) => c.findings);
+ for (const it of items) for (const f of findings) assert.ok(!benchPrompt(it).user.includes(f));
+ } finally {
+ await s.done();
+ }
+});
+
+test("items: a citation whose recording has no cues, and a post-only claim, are skipped; a named report must be a fact-check", async () => {
+ const s = await store((r) => {
+ r.citations.q07.id = "no-such-recording";
+ r.citations.p1 = { kind: "post", channel: "synth-kitchen-posts", id: "p-1", quote: "a post" };
+ r.sections[1].claims[1].citations = ["q07"];
+ r.sections[1].claims.push({ id: "r09", text: "The article says she posted about it.", verdict: "CORROBORATED", citations: ["p1"] });
+ });
+ try {
+ const { items, skipped } = await benchItemsOf(await benchReportsOf(s.paths, ["synth-ruled"]), { cuesOf });
+ assert.equal(items.length, 6);
+ assert.deepEqual(
+ skipped.map((x) => [x.claim, x.reason]),
+ [
+ ["r07", "no cited recording has cues around the cited seconds"],
+ ["r08", "no citation"],
+ ["r09", "no video or audio citation"],
+ ],
+ );
+ await assert.rejects(benchReportsOf(s.paths, ["a-sweep"]), /a sweep, not a factcheck/);
+ await assert.rejects(benchReportsOf(s.paths, ["nope"]), /no article "nope"/);
+ } finally {
+ await s.done();
+ }
+});
+
+test("prompt: rules only (every verdict defined, no example); a local prompt's window trimmed to the cap, never the claim", async () => {
+ for (const v of VERDICTS) assert.ok(VERDICT_BENCH_SYSTEM.includes(`- ${v}:`), v);
+ assert.ok(!/example/i.test(VERDICT_BENCH_SYSTEM));
+ // A claim with a very long window: thousands of cues.
+ const cues = Array.from({ length: 4000 }, (_, i) => ({ start: i * 5, end: i * 5 + 4.9, text: `line ${i} of a long stream about the bakery and the oven` }));
+ const item: BenchItem = {
+ key: "x/c1",
+ report: "x",
+ claim: "c1",
+ text: "The article says the oven was broken.",
+ verdict: "PARTLY",
+ quotes: [{ citation: "q", channel: "c", id: "v", start: 10000, end: 10004.9, quote: "the oven was fine" }],
+ windows: [{ channel: "c", id: "v", from: 0, to: 20000, cited: [{ start: 10000, end: 10004.9 }], cues }],
+ };
+ const whole = benchPrompt(item);
+ assert.equal(whole.cuesTrimmed, 0);
+ assert.ok(whole.estimate > 8000);
+ const local = benchPrompt(item, { capTokens: LOCAL_PROMPT_CAP });
+ assert.ok(local.cuesTrimmed > 0);
+ assert.ok(local.estimate <= LOCAL_PROMPT_CAP && LOCAL_PROMPT_CAP < 8000);
+ assert.equal(local.estimate, promptEstimate({ messages: [{ role: "system", content: local.system }, { role: "user", content: local.user }], format: (await import("./prompt")).VERDICT_ANSWER_SCHEMA }));
+ assert.ok(local.user.includes("Claim: The article says the oven was broken."));
+ assert.ok(local.user.includes('"the oven was fine"'));
+ // The cues nearest the cited span stay; the farthest go.
+ assert.ok(local.user.includes("line 2000 of"));
+ assert.ok(!local.user.includes("line 0 of"));
+ assert.ok(!local.user.includes("line 3999 of"));
+});
+
+test("score: agreement, the matrix, the recalls (PARTLY strict and adjacent), failures, and the always-CORROBORATED baseline", () => {
+ const items = Object.entries(TRUTH).map(([claim, verdict]) => ({ key: `r/${claim}`, verdict }));
+ const said: Record<string, Verdict | "parse" | "error"> = {
+ r01: "CORROBORATED",
+ r02: "CORROBORATED", // adjacent
+ r03: "PARTLY",
+ r04: "CONTRADICTED",
+ r05: "PARTLY",
+ r06: "parse",
+ r07: "NOT_FOUND",
+ };
+ const results: BenchResult[] = Object.entries(said).map(([claim, v]) => ({
+ key: `r/${claim}`,
+ model: "m",
+ verdict: v === "parse" || v === "error" ? null : v,
+ ...(v === "parse" ? { failure: "parse" as const } : {}),
+ ms: 100,
+ usd: 0.01,
+ inputTokens: 10,
+ outputTokens: 5,
+ at: "",
+ }));
+ const s = scoreBench(items, results, ["m"]);
+ const m = s.models[0]!;
+ assert.equal(s.items, 7);
+ assert.deepEqual(s.ruled, { CORROBORATED: 2, PARTLY: 2, CONTRADICTED: 2, NOT_FOUND: 1, UNTESTABLE: 0 });
+ assert.equal(m.asked, 7);
+ assert.equal(m.answered, 6);
+ assert.equal(m.parseFailures, 1);
+ assert.equal(m.agreed, 4); // r01 r03 r04 r07
+ assert.equal(m.agreement, 0.5714);
+ assert.equal(m.agreedAdjacent, 5); // + r02
+ const C = VERDICTS.indexOf("CORROBORATED");
+ const P = VERDICTS.indexOf("PARTLY");
+ const X = VERDICTS.indexOf("CONTRADICTED");
+ assert.equal(m.matrix[P]![C], 1);
+ assert.equal(m.matrix[X]![P], 1);
+ assert.equal(m.unanswered[C], 1);
+ assert.deepEqual(m.recall.CONTRADICTED, { ruled: 2, matched: 1, recall: 0.5 });
+ assert.deepEqual(m.recall.NOT_FOUND, { ruled: 1, matched: 1, recall: 1 });
+ assert.deepEqual(m.recall.PARTLY, { ruled: 2, matched: 1, recall: 0.5 });
+ assert.deepEqual(m.recall.PARTLY_ADJACENT, { ruled: 2, matched: 2, recall: 1 });
+ assert.equal(m.usd, 0.07);
+ assert.equal(m.latency.medianMs, 100);
+ // The baseline: right on every CORROBORATED, finds no CONTRADICTED or NOT_FOUND.
+ assert.equal(s.baseline.model, BASELINE_MODEL);
+ assert.equal(s.baseline.agreement, 0.2857);
+ assert.equal(s.baseline.agreementAdjacent, 0.5714);
+ assert.equal(s.baseline.recall.CONTRADICTED.recall, 0);
+ assert.equal(s.baseline.recall.NOT_FOUND.recall, 0);
+ // The bar.
+ assert.deepEqual(passesBar(m, { agreement: 0.5, contradictedRecall: 0.5, notFoundRecall: 0.5 }), { pass: true, misses: [] });
+ const fail = passesBar(m, { agreement: 0.6, contradictedRecall: 0.75, notFoundRecall: 0 });
+ assert.equal(fail.pass, false);
+ assert.equal(fail.misses.length, 2);
+ assert.equal(passesBar(s.baseline, { agreement: 0, contradictedRecall: 0.1, notFoundRecall: 0 }).pass, false);
+});
+
+test("run: Sonnet over the fake API, qwen over the fake ollama — answers written as they land, scored, costed; a parse failure counted", async () => {
+ const s = await store();
+ const texts = await claimTexts();
+ const api = await startFakeAnthropic();
+ const ol = await startFakeOllama();
+ // Sonnet: right on everything but r05 (PARTLY).
+ for (let i = 0; i < 7; i++) {
+ api.push((body: any) => {
+ const id = texts[claimOf(userOf(body))]!;
+ return toolTurn("answer", { verdict: id === "r05" ? "PARTLY" : TRUTH[id], reason: `ruled on ${id} ${"x".repeat(400)}` });
+ });
+ }
+ // qwen: always CORROBORATED, and r03's answer is not JSON (twice: the retry too).
+ for (let i = 0; i < 8; i++) {
+ ol.push((body: any) => {
+ const id = texts[claimOf(body.messages[1].content)]!;
+ return id === "r03" ? reply("I think it is partly true") : jsonReply({ verdict: "CORROBORATED", reason: "she says so" });
+ });
+ }
+ try {
+ const lines: string[] = [];
+ const out = await runVerdictBench(
+ { runId: "vb-test", models: ["claude-sonnet-5-5", "qwen3:8b"] },
+ {
+ paths: s.paths,
+ cuesOf,
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }, ollama: { baseUrl: ol.url } },
+ log: (l) => lines.push(l),
+ },
+ );
+ assert.equal(out.summary.status, "done");
+ assert.equal(out.dir, path.join(benchRootOf(s.paths), "vb-test"));
+ assert.equal(api.requests.length, 7);
+ // The strict model's way: the answer tool, tool_choice auto, no temperature.
+ assert.equal(api.requests[0].tool_choice.type, "auto");
+ assert.equal(api.requests[0].tools[0].name, "answer");
+ // The findings never reach a model.
+ for (const r of [...api.requests.map((b: any) => JSON.stringify(b)), ...ol.requests.map((b: any) => JSON.stringify(b))]) {
+ assert.ok(!r.includes("She calls it a small place"));
+ }
+ const sonnet = out.summary.score.models[0]!;
+ assert.equal(sonnet.model, "claude-sonnet-5-5");
+ assert.equal(sonnet.agreed, 6);
+ assert.ok(sonnet.usd > 0);
+ assert.ok(Math.abs(out.summary.spentUsd - sonnet.usd) < 1e-5);
+ const qwen = out.summary.score.models[1]!;
+ assert.equal(qwen.parseFailures, 1);
+ assert.equal(qwen.agreed, 2);
+ assert.equal(qwen.usd, 0);
+ // On disk: the items (answer key included), every result, the summary.
+ const run = (await readBenchRun(benchRootOf(s.paths), "vb-test"))!;
+ assert.equal(run.items.length, 7);
+ assert.equal(run.results.length, 14);
+ assert.ok(run.results.every((r) => (r.reason ?? "").length <= 300));
+ assert.equal(run.summary.skipped.length, 1);
+ assert.equal(run.summary.score.baseline.agreed, 2);
+ assert.ok(lines.some((l) => l.startsWith("run vb-test: 7 items")));
+ } finally {
+ await api.close();
+ await ol.close();
+ await s.done();
+ }
+});
+
+test("run: the cap is checked before each API call — past it the run stops capped, with what it did", async () => {
+ const s = await store();
+ const api = await startFakeAnthropic();
+ for (let i = 0; i < 7; i++) api.push(toolTurn("answer", { verdict: "CORROBORATED", reason: "ok" }));
+ try {
+ // One call costs about a cent at Opus 5.5's price; a two-cent cap stops early.
+ const out = await runVerdictBench(
+ { runId: "vb-cap", models: ["claude-opus-5-5"], maxUsd: 0.02 },
+ { paths: s.paths, cuesOf, llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } } },
+ );
+ assert.equal(out.summary.status, "capped");
+ assert.ok(api.requests.length >= 1 && api.requests.length < 7, `${api.requests.length} calls`);
+ assert.ok(out.summary.spentUsd <= 0.02);
+ assert.match(out.summary.stopped![0]!, /the cap/);
+ assert.equal(out.summary.score.models[0]!.asked, api.requests.length);
+ // A cap smaller than one call: nothing is sent at all.
+ const none = await runVerdictBench(
+ { runId: "vb-cap-0", models: ["claude-opus-5-5"], maxUsd: 0.0001 },
+ { paths: s.paths, cuesOf, llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } } },
+ );
+ assert.equal(none.summary.status, "capped");
+ assert.equal(none.summary.score.models[0]!.asked, 0);
+ } finally {
+ await api.close();
+ await s.done();
+ }
+});
+
+test("run: a re-run with the same id resumes — answered pairs skipped, failed ones asked again; three errors in a row stop a model", async () => {
+ const s = await store();
+ const texts = await claimTexts();
+ const api = await startFakeAnthropic();
+ const llm = { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } };
+ // First run: r01–r03 answered, then three 400s in a row (not retried) stop the model.
+ for (let i = 0; i < 3; i++) api.push((body: any) => toolTurn("answer", { verdict: TRUTH[texts[claimOf(userOf(body))]!], reason: "ok" }));
+ for (let i = 0; i < 3; i++) api.push(errorTurn(400, "invalid_request_error", "a bad request"));
+ try {
+ const first = await runVerdictBench({ runId: "vb-resume", models: ["claude-sonnet-5-5"] }, { paths: s.paths, cuesOf, llm });
+ assert.equal(first.summary.status, "done");
+ assert.equal(api.requests.length, 6);
+ assert.match(first.summary.stopped![0]!, /stopped after 3 errors in a row/);
+ assert.equal(first.summary.score.models[0]!.errors, 3);
+ assert.equal(first.summary.score.models[0]!.asked, 6);
+ // The re-run asks only the four not answered (three failed, one never asked).
+ for (let i = 0; i < 4; i++) api.push((body: any) => toolTurn("answer", { verdict: TRUTH[texts[claimOf(userOf(body))]!], reason: "ok" }));
+ const again = await runVerdictBench({ runId: "vb-resume", models: ["claude-sonnet-5-5"] }, { paths: s.paths, cuesOf, llm });
+ assert.equal(api.requests.length, 10);
+ const asked = api.requests.slice(6).map((b: any) => texts[claimOf(userOf(b))]);
+ assert.deepEqual(asked, ["r04", "r05", "r06", "r07"]);
+ assert.equal(again.summary.status, "done");
+ assert.equal(again.summary.score.models[0]!.agreed, 7);
+ assert.equal(again.summary.score.models[0]!.errors, 0);
+ assert.equal((await readBenchRun(benchRootOf(s.paths), "vb-resume"))!.results.length, 7);
+ // The window is the run's: another one is refused.
+ await assert.rejects(runVerdictBench({ runId: "vb-resume", models: ["claude-sonnet-5-5"], windowS: 30 }, { paths: s.paths, cuesOf, llm }), /60 s window/);
+ } finally {
+ await api.close();
+ await s.done();
+ }
+});
+
+test("plan (the dry run): the items, the skipped, an estimate per model; nothing asked, nothing written", async () => {
+ const s = await store();
+ try {
+ const plan = await planVerdictBench({ models: ["claude-sonnet-5-5", "claude-opus-5-5", "qwen3:8b"], limit: 5 }, { paths: s.paths, cuesOf });
+ assert.equal(plan.items.length, 5);
+ assert.equal(plan.skipped.length, 1);
+ assert.deepEqual(plan.reports, ["synth-ruled"]);
+ const [sonnet, opus, qwen] = plan.estimate;
+ assert.ok(sonnet!.usd > 0 && opus!.usd > sonnet!.usd);
+ assert.equal(qwen!.usd, 0);
+ assert.equal(qwen!.provider, "local");
+ assert.equal(plan.estimateUsd, Math.round((sonnet!.usd + opus!.usd) * 10_000) / 10_000);
+ await assert.rejects(readFile(path.join(benchRootOf(s.paths), "x")), /ENOENT/);
+ await assert.rejects(planVerdictBench({ models: [] }, { paths: s.paths, cuesOf }), /at least one model/);
+ await assert.rejects(planVerdictBench({ models: ["m"], maxUsd: 500 }, { paths: s.paths, cuesOf }), /over the bench's limit/);
+ } finally {
+ await s.done();
+ }
+});
diff --git a/common/lib/report/draft/bench/index.ts b/common/lib/report/draft/bench/index.ts
@@ -0,0 +1,8 @@
+// The verdict bench (release 28, M7): items from ruled fact-checks, one claim
+// per call, scored against the operator's rulings. See ./run.ts.
+
+export * from "./items";
+export * from "./prompt";
+export * from "./score";
+export * from "./store";
+export * from "./run";
diff --git a/common/lib/report/draft/bench/items.ts b/common/lib/report/draft/bench/items.ts
@@ -0,0 +1,209 @@
+// THE VERDICT BENCH'S ITEMS (release 28, M7): one per ruled fact-check claim.
+//
+// An item is a claim of a `kind: "factcheck"` article that carries the
+// operator's `verdict` and at least one span citation (video or audio) whose
+// recording has cues around the cited seconds: the claim's text, the cited
+// quotes, and the transcript WINDOW (the cues within ±`windowS` of each cited
+// span, overlapping windows of one recording merged). Every other claim is
+// SKIPPED, with its reason, and counted.
+//
+// The operator's `verdict` is the answer key: it is kept on the item for the
+// scorer, and the prompt (./prompt.ts) never reads it. The claim's `findings`,
+// `gist`, `flag` and `title` are never copied onto an item at all — they say
+// what the check found.
+//
+// The reports are read through the article registry (`listArticleDirs`,
+// `articleFile`, `parseReport`), never by globbing the corpus; the cues through
+// a `CuesOf` (the local corpus's `diskCuesOf`, or the synthetic corpus in tests).
+
+import { readJsonFile } from "../../../jsonFile-server";
+import type { Paths } from "../../../paths";
+import { isSpanCitation, type Citation } from "../../../citations/schema";
+import type { CuesOf } from "../../convertShared";
+import { articleFile, listArticleDirs } from "../../registry";
+import type { Report } from "../../schema";
+import { parseReport } from "../../validate";
+import { isVerdict, type Verdict } from "../../verdicts";
+
+export const DEFAULT_WINDOW_S = 60;
+
+export type BenchCue = { start: number; end: number; text: string };
+
+export type BenchQuote = {
+ citation: string;
+ channel: string;
+ id: string;
+ start: number;
+ end: number;
+ quote: string;
+ label?: string;
+ speaker?: string;
+ date?: string;
+};
+
+// One recording's cues around the cited spans in it.
+export type BenchWindow = {
+ channel: string;
+ id: string;
+ label?: string;
+ from: number;
+ to: number;
+ // The cited spans in this window (for the trim: the cues nearest them stay).
+ cited: { start: number; end: number }[];
+ cues: BenchCue[];
+};
+
+export type BenchItem = {
+ // `<report>/<claim>`: unique across a run.
+ key: string;
+ report: string;
+ claim: string;
+ text: string;
+ // THE ANSWER: the operator's ruling. Never shown to a model.
+ verdict: Verdict;
+ quotes: BenchQuote[];
+ windows: BenchWindow[];
+};
+
+export type BenchSkipped = { key: string; report: string; claim: string; reason: string };
+
+export type BenchReport = { id: string; report: Report };
+
+export type BenchItems = { items: BenchItem[]; skipped: BenchSkipped[] };
+
+export class BenchInputError extends Error {}
+
+// The fact-checks the bench reads: every article of kind `factcheck` (or the
+// named ones, each of which must be one), in id order.
+export async function benchReportsOf(
+ paths: Pick<Paths, "articlesDir" | "exportIndexDir">,
+ ids?: readonly string[],
+): Promise<BenchReport[]> {
+ const all = await listArticleDirs(paths);
+ const wanted = ids && ids.length ? [...new Set(ids)] : null;
+ if (wanted) {
+ const missing = wanted.filter((id) => !all.includes(id));
+ if (missing.length) throw new BenchInputError(`no article ${missing.map((m) => `"${m}"`).join(", ")} in the registry`);
+ }
+ const out: BenchReport[] = [];
+ for (const id of wanted ?? all) {
+ const read = await readJsonFile(articleFile(paths, id));
+ if (!read.ok) {
+ if (wanted) throw new BenchInputError(`article "${id}": report.json is ${read.reason}`);
+ continue;
+ }
+ const parsed = parseReport(read.value, { id });
+ if (!parsed.ok) {
+ if (wanted) throw new BenchInputError(`article "${id}": report.json does not parse as a report`);
+ continue;
+ }
+ if (parsed.value.kind !== "factcheck") {
+ if (wanted) throw new BenchInputError(`article "${id}" is a ${parsed.value.kind}, not a factcheck`);
+ continue;
+ }
+ out.push({ id, report: parsed.value });
+ }
+ return out;
+}
+
+function mergeWindows(windows: BenchWindow[]): BenchWindow[] {
+ const byRecord = new Map<string, BenchWindow[]>();
+ for (const w of windows) {
+ const k = `${w.channel}/${w.id}`;
+ byRecord.set(k, [...(byRecord.get(k) ?? []), w]);
+ }
+ const out: BenchWindow[] = [];
+ for (const list of byRecord.values()) {
+ list.sort((a, b) => a.from - b.from);
+ let cur: BenchWindow | null = null;
+ for (const w of list) {
+ if (cur && w.from <= cur.to) {
+ cur.to = Math.max(cur.to, w.to);
+ cur.cited.push(...w.cited);
+ const seen = new Set(cur.cues.map((c) => `${c.start}`));
+ for (const c of w.cues) if (!seen.has(`${c.start}`)) cur.cues.push(c);
+ cur.cues.sort((a, b) => a.start - b.start);
+ } else {
+ if (cur) out.push(cur);
+ cur = { ...w, cited: [...w.cited], cues: [...w.cues] };
+ }
+ }
+ if (cur) out.push(cur);
+ }
+ return out;
+}
+
+// The items of one report: its ruled claims with a span citation that has cues.
+export async function benchItemsOfReport(
+ r: BenchReport,
+ o: { cuesOf: CuesOf; windowS?: number },
+): Promise<BenchItems> {
+ const windowS = o.windowS ?? DEFAULT_WINDOW_S;
+ const items: BenchItem[] = [];
+ const skipped: BenchSkipped[] = [];
+ const citations = (r.report.citations ?? {}) as Record<string, Citation>;
+ for (const section of r.report.sections) {
+ for (const claim of section.claims ?? []) {
+ const key = `${r.id}/${claim.id}`;
+ const skip = (reason: string) => skipped.push({ key, report: r.id, claim: claim.id, reason });
+ if (!isVerdict(claim.verdict)) {
+ skip("no operator verdict");
+ continue;
+ }
+ const ids = claim.citations ?? [];
+ if (!ids.length) {
+ skip("no citation");
+ continue;
+ }
+ const spans = ids.map((id) => [id, citations[id]] as const).filter((e): e is readonly [string, Citation] => !!e[1] && isSpanCitation(e[1]));
+ if (!spans.length) {
+ skip("no video or audio citation");
+ continue;
+ }
+ const quotes: BenchQuote[] = [];
+ const windows: BenchWindow[] = [];
+ for (const [cid, c] of spans) {
+ if (!isSpanCitation(c)) continue;
+ const cues = await o.cuesOf(c.channel, c.id).catch(() => null);
+ if (!cues || !cues.length) continue;
+ const from = Math.max(0, c.start - windowS);
+ const to = c.end + windowS;
+ const inWindow = cues.filter((q) => q.end >= from && q.start <= to).map((q) => ({ start: q.start, end: q.end, text: q.text }));
+ if (!inWindow.length) continue;
+ quotes.push({
+ citation: cid,
+ channel: c.channel,
+ id: c.id,
+ start: c.start,
+ end: c.end,
+ quote: c.quote,
+ ...(c.label ? { label: c.label } : {}),
+ ...(c.speaker ? { speaker: c.speaker } : {}),
+ ...(c.date ? { date: c.date } : {}),
+ });
+ windows.push({ channel: c.channel, id: c.id, ...(c.label ? { label: c.label } : {}), from, to, cited: [{ start: c.start, end: c.end }], cues: inWindow });
+ }
+ if (!quotes.length) {
+ skip("no cited recording has cues around the cited seconds");
+ continue;
+ }
+ items.push({ key, report: r.id, claim: claim.id, text: claim.text, verdict: claim.verdict, quotes, windows: mergeWindows(windows) });
+ }
+ }
+ return { items, skipped };
+}
+
+// Every item of every report, in report then claim order; `limit` keeps the first n.
+export async function benchItemsOf(
+ reports: readonly BenchReport[],
+ o: { cuesOf: CuesOf; windowS?: number; limit?: number },
+): Promise<BenchItems> {
+ const items: BenchItem[] = [];
+ const skipped: BenchSkipped[] = [];
+ for (const r of reports) {
+ const got = await benchItemsOfReport(r, o);
+ items.push(...got.items);
+ skipped.push(...got.skipped);
+ }
+ return { items: o.limit !== undefined && o.limit >= 0 ? items.slice(0, o.limit) : items, skipped };
+}
diff --git a/common/lib/report/draft/bench/prompt.ts b/common/lib/report/draft/bench/prompt.ts
@@ -0,0 +1,122 @@
+// THE VERDICT BENCH'S PROMPT (release 28, M7): one claim per call.
+//
+// Q0: the system prompt is rules only — what each verdict means, and that the
+// model judges only what the window shows — with no worked example. The reason's
+// length is enforced in code (./run.ts cuts it at REASON_MAX), not trusted to
+// the prompt. A local model's prompt is held under its cap (8k tokens) by
+// trimming the WINDOW, the cues farthest from a cited span first; the claim
+// and the cited quotes are never trimmed.
+//
+// The prompt reads an item's claim text, its quotes and its windows — never
+// its `verdict` (the operator's ruling, the answer).
+
+import { VERDICTS } from "../../verdicts";
+import { PROMPT_CAP_TOKENS, promptEstimate } from "../../../llm/ollama";
+import type { BenchItem, BenchWindow } from "./items";
+
+export const REASON_MAX = 300;
+
+export const VERDICT_ANSWER_SCHEMA = {
+ type: "object",
+ properties: {
+ verdict: { type: "string", enum: [...VERDICTS], description: "The ruling on the claim." },
+ reason: {
+ type: "string",
+ description: `Why, in one or two plain sentences of at most ${REASON_MAX} characters, naming what the transcript shows.`,
+ },
+ },
+ required: ["verdict", "reason"],
+} as const;
+
+export const VERDICT_BENCH_SYSTEM = [
+ "You rule on one claim about what a person said in recordings, using only the transcript you are given.",
+ "",
+ "You are shown the claim, the lines it cites, and the transcript around each cited line (each line stamped with its time in the recording).",
+ "",
+ "Rules:",
+ "- Judge only from the transcript shown. Do not use outside knowledge, and do not assume what may have been said elsewhere or off the record.",
+ "- The cited lines are where the claim's evidence was found; read the transcript around them before ruling, since context can change their meaning.",
+ "- The transcript is automatic speech recognition: forgive misspellings and missing punctuation, never a change of meaning.",
+ "",
+ "The verdicts:",
+ "- CORROBORATED: the transcript shows the claim is true as stated.",
+ "- PARTLY: the transcript supports part of the claim, and another part is unsupported, overstated or wrong.",
+ "- CONTRADICTED: the transcript shows the opposite of the claim, or something that cannot be true at the same time as it.",
+ "- NOT_FOUND: the claim could be checked against what was said, and the transcript shown does not contain it — the topic may come up without what the claim says about it.",
+ "- UNTESTABLE: the claim is an opinion, a judgement, a prediction, or anything else a transcript cannot show to be true or false.",
+ "",
+ `Give the verdict and a reason of at most ${REASON_MAX} characters that names what the transcript says.`,
+].join("\n");
+
+const stamp = (s: number) => {
+ const t = Math.max(0, Math.floor(s));
+ const h = Math.floor(t / 3600);
+ const m = Math.floor((t % 3600) / 60);
+ const ss = String(t % 60).padStart(2, "0");
+ return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
+};
+
+type Prompted = Pick<BenchItem, "text" | "quotes" | "windows">;
+
+function render(item: Prompted, windows: BenchWindow[]): string {
+ const lines: string[] = [`Claim: ${item.text}`, "", "Cited lines:"];
+ for (const q of item.quotes) {
+ const where = [q.label, stamp(q.start)].filter(Boolean).join(", ");
+ const who = [q.speaker ? `speaker: ${q.speaker}` : "", q.date ? `date: ${q.date}` : ""].filter(Boolean).join("; ");
+ lines.push(`- [${where}] "${q.quote}"${who ? ` (${who})` : ""}`);
+ }
+ lines.push("", "Transcript:");
+ windows.forEach((w, i) => {
+ lines.push("", `## ${w.label ?? `Recording ${i + 1}`}, ${stamp(w.from)} to ${stamp(w.to)}`);
+ if (!w.cues.length) lines.push("(trimmed to fit)");
+ for (const c of w.cues) lines.push(`[${stamp(c.start)}] ${c.text}`);
+ });
+ return lines.join("\n");
+}
+
+// The distance of a cue from the nearest cited span of its window, in seconds.
+function distance(w: BenchWindow, c: { start: number; end: number }): number {
+ let best = Number.POSITIVE_INFINITY;
+ for (const s of w.cited) {
+ const d = c.end < s.start ? s.start - c.end : c.start > s.end ? c.start - s.end : 0;
+ best = Math.min(best, d);
+ }
+ return best;
+}
+
+export type BenchPrompt = { system: string; user: string; estimate: number; cuesShown: number; cuesTrimmed: number };
+
+// The prompt for one item. With `capTokens` (a local model), the window is
+// trimmed until system + user + the schema fit under it; without, it is whole.
+export function benchPrompt(item: Prompted, o: { capTokens?: number } = {}): BenchPrompt {
+ const total = item.windows.reduce((s, w) => s + w.cues.length, 0);
+ const estimateOf = (user: string) =>
+ promptEstimate({ messages: [{ role: "system", content: VERDICT_BENCH_SYSTEM }, { role: "user", content: user }], format: VERDICT_ANSWER_SCHEMA });
+ const whole = render(item, item.windows);
+ const cap = o.capTokens;
+ if (cap === undefined || estimateOf(whole) <= cap) {
+ return { system: VERDICT_BENCH_SYSTEM, user: whole, estimate: estimateOf(whole), cuesShown: total, cuesTrimmed: 0 };
+ }
+ // Every cue, farthest from a cited span first: dropping the first k of them
+ // is the k-trim. The fewest drops that fit, found by bisection.
+ const order: { w: number; c: number; d: number }[] = [];
+ item.windows.forEach((w, wi) => w.cues.forEach((c, ci) => order.push({ w: wi, c: ci, d: distance(w, c) })));
+ order.sort((a, b) => b.d - a.d || a.w - b.w || b.c - a.c);
+ const keepAfter = (k: number): BenchWindow[] => {
+ const drop = new Set(order.slice(0, k).map((e) => `${e.w}:${e.c}`));
+ return item.windows.map((w, wi) => ({ ...w, cues: w.cues.filter((_, ci) => !drop.has(`${wi}:${ci}`)) }));
+ };
+ let lo = 0;
+ let hi = order.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (estimateOf(render(item, keepAfter(mid))) <= cap) hi = mid;
+ else lo = mid + 1;
+ }
+ const user = render(item, keepAfter(lo));
+ return { system: VERDICT_BENCH_SYSTEM, user, estimate: estimateOf(user), cuesShown: total - lo, cuesTrimmed: lo };
+}
+
+// The cap a local prompt is held to: the ollama client's (8k), less a margin
+// for the estimate's slack.
+export const LOCAL_PROMPT_CAP = PROMPT_CAP_TOKENS - 200;
diff --git a/common/lib/report/draft/bench/run.ts b/common/lib/report/draft/bench/run.ts
@@ -0,0 +1,334 @@
+// THE VERDICT BENCH (release 28, M7): can a model propose a fact-check verdict
+// well enough to be worth an operator's review?
+//
+// `planVerdictBench` reads only: the items, the skipped claims, and an
+// estimate of what each model would cost (the `--dry`). `runVerdictBench`
+// asks each model about each item, one claim per call — `structuredAnswer`
+// against {verdict, reason} — writes every answer as it lands, and scores the
+// run (./score.ts). The calls are SEQUENTIAL (API and local alike; a local
+// model's GPU turn is the caller's `llm` config — the editor's job passes the
+// GPU arbiter's gated fetch).
+//
+// THE CAP: `maxUsd` (default 5) for the whole run, resumed spend included,
+// checked before each API call against the spend so far plus that call's
+// estimate — past it the run stops `capped` with what it did. A model with
+// three errors in a row is stopped (the rest of its items stay unasked) and
+// the run goes on with the next.
+//
+// RESUME: a run id whose directory exists continues it — its items are the
+// stored ones, and each (item, model) pair already ANSWERED is skipped; a
+// failed one is asked again.
+
+import { mkdir } from "node:fs/promises";
+import type { Paths } from "../../../paths";
+import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, type LlmConfig } from "../../../llm";
+import { ApiKeyError } from "../../../llm/anthropic";
+import { CHARS_PER_TOKEN } from "../../../llm/ollama";
+import type { CuesOf } from "../../convertShared";
+import { isVerdict } from "../../verdicts";
+import { benchItemsOf, benchReportsOf, BenchInputError, DEFAULT_WINDOW_S, type BenchItem, type BenchSkipped } from "./items";
+import { benchPrompt, LOCAL_PROMPT_CAP, REASON_MAX, VERDICT_ANSWER_SCHEMA } from "./prompt";
+import { scoreBench, type BenchResult } from "./score";
+import {
+ BENCH_FORMAT,
+ BENCH_VERSION,
+ benchRootOf,
+ benchRunDir,
+ newBenchRunId,
+ readBenchRun,
+ writeBenchItems,
+ writeBenchResults,
+ writeBenchSummary,
+ type BenchStatus,
+ type BenchSummary,
+} from "./store";
+
+export const DEFAULT_BENCH_MAX_USD = 5;
+// Above this a run is refused outright (the release's real run is ≤ $5).
+export const BENCH_MAX_USD_LIMIT = 50;
+// A model stopped after this many errors in a row.
+export const BENCH_ERROR_STREAK = 3;
+// The estimate's allowances per call: the tool definition and instruction
+// around the prompt, and the answer (with a strict model's possible re-ask).
+const CALL_OVERHEAD_TOKENS = 350;
+const ANSWER_TOKENS = 300;
+const MAX_ANSWER_TOKENS = 1024;
+
+export type BenchOptions = {
+ // A run to continue, or the new run's id (default `vb-<stamp>`).
+ runId?: string;
+ // The fact-checks to read (default: every one in the registry).
+ reports?: string[];
+ models: string[];
+ windowS?: number;
+ maxUsd?: number;
+ limit?: number;
+};
+
+export type BenchDeps = {
+ paths: Pick<Paths, "articlesDir" | "exportIndexDir" | "generationUsageFile">;
+ // Where runs live (default `.generation/bench/verdicts/`, ./store.ts).
+ root?: string;
+ cuesOf: CuesOf;
+ // The providers' config (the editor's job gates a local model's calls on the GPU).
+ llm: LlmConfig;
+ log?: (line: string) => void;
+ signal?: AbortSignal;
+ now?: () => Date;
+ // A local prompt's cap in tokens (default LOCAL_PROMPT_CAP, under the 8k).
+ localCapTokens?: number;
+};
+
+export type BenchModelEstimate = { model: string; provider: "api" | "local"; calls: number; inputTokens: number; outputTokens: number; usd: number };
+
+export type BenchPlan = {
+ items: BenchItem[];
+ skipped: BenchSkipped[];
+ reports: string[];
+ windowS: number;
+ estimate: BenchModelEstimate[];
+ estimateUsd: number;
+};
+
+export function validateBenchOptions(o: BenchOptions): { models: string[]; windowS: number; maxUsd: number; limit?: number } {
+ const models = [...new Set((o.models ?? []).map((m) => m.trim()).filter(Boolean))];
+ if (!models.length) throw new BenchInputError("name at least one model (--models a,b,c)");
+ for (const m of models) {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(m)) throw new BenchInputError(`"${m}" is not a model name`);
+ }
+ const windowS = o.windowS ?? DEFAULT_WINDOW_S;
+ if (!Number.isFinite(windowS) || windowS < 0 || windowS > 600) throw new BenchInputError("the window is 0 to 600 seconds");
+ const maxUsd = o.maxUsd ?? DEFAULT_BENCH_MAX_USD;
+ if (!Number.isFinite(maxUsd) || maxUsd <= 0) throw new BenchInputError("maxUsd must be a positive number of dollars");
+ if (maxUsd > BENCH_MAX_USD_LIMIT) throw new BenchInputError(`maxUsd $${maxUsd} is over the bench's limit of $${BENCH_MAX_USD_LIMIT}`);
+ if (o.limit !== undefined && (!Number.isInteger(o.limit) || o.limit < 1)) throw new BenchInputError("limit is a whole number of items, at least 1");
+ return { models, windowS, maxUsd, ...(o.limit !== undefined ? { limit: o.limit } : {}) };
+}
+
+// What one call to `model` about `item` would cost, by the prompt's size.
+export function estimateCall(item: BenchItem, model: string, localCapTokens = LOCAL_PROMPT_CAP): { inputTokens: number; outputTokens: number; usd: number } {
+ const local = providerOf(model) === "local";
+ const p = benchPrompt(item, local ? { capTokens: localCapTokens } : {});
+ const inputTokens = Math.ceil((p.system.length + p.user.length + JSON.stringify(VERDICT_ANSWER_SCHEMA).length) / CHARS_PER_TOKEN) + CALL_OVERHEAD_TOKENS;
+ const outputTokens = ANSWER_TOKENS;
+ const price = priceOf(model);
+ return { inputTokens, outputTokens, usd: (inputTokens * price.input + outputTokens * price.output) / 1e6 };
+}
+
+function estimateOf(items: readonly BenchItem[], models: readonly string[], localCapTokens?: number): BenchModelEstimate[] {
+ return models.map((model) => {
+ let inputTokens = 0;
+ let outputTokens = 0;
+ let usd = 0;
+ for (const it of items) {
+ const e = estimateCall(it, model, localCapTokens);
+ inputTokens += e.inputTokens;
+ outputTokens += e.outputTokens;
+ usd += e.usd;
+ }
+ return { model, provider: providerOf(model), calls: items.length, inputTokens, outputTokens, usd: Math.round(usd * 10_000) / 10_000 };
+ });
+}
+
+// The dry run: the items, the skipped claims and the estimate. Reads only.
+export async function planVerdictBench(o: BenchOptions, deps: Pick<BenchDeps, "paths" | "cuesOf" | "localCapTokens">): Promise<BenchPlan> {
+ const v = validateBenchOptions(o);
+ const reports = await benchReportsOf(deps.paths, o.reports);
+ const { items, skipped } = await benchItemsOf(reports, { cuesOf: deps.cuesOf, windowS: v.windowS, ...(v.limit ? { limit: v.limit } : {}) });
+ const estimate = estimateOf(items, v.models, deps.localCapTokens);
+ return {
+ items,
+ skipped,
+ reports: reports.map((r) => r.id),
+ windowS: v.windowS,
+ estimate,
+ estimateUsd: Math.round(estimate.reduce((s, e) => s + e.usd, 0) * 10_000) / 10_000,
+ };
+}
+
+// `spent`: this invocation's spend per model (a resumed run's earlier spend is
+// in `summary.spentUsd`, not here) — what a job's usage ledger rows record.
+export type BenchOutcome = { id: string; dir: string; summary: BenchSummary; spent: ReturnType<Meter["summary"]> };
+
+const round6 = (v: number) => Math.round(v * 1e6) / 1e6;
+
+export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise<BenchOutcome> {
+ const v = validateBenchOptions(o);
+ const now = () => (deps.now ? deps.now() : new Date());
+ const log = deps.log ?? (() => {});
+ const root = deps.root ?? benchRootOf(deps.paths);
+ const id = o.runId ?? newBenchRunId(now());
+ const dir = benchRunDir(root, id);
+ const localCap = deps.localCapTokens ?? LOCAL_PROMPT_CAP;
+
+ // A new run, or the stored one continued.
+ const prior = await readBenchRun(root, id);
+ let items: BenchItem[];
+ let skipped: BenchSkipped[];
+ let results: BenchResult[];
+ let models: string[];
+ let reportsAsked: string[];
+ let createdAt: string;
+ if (prior) {
+ const s = prior.summary;
+ if (o.windowS !== undefined && o.windowS !== s.windowS) {
+ throw new BenchInputError(`run ${id} was made with a ${s.windowS} s window: drop the window, or start a new run`);
+ }
+ if (o.reports?.length && [...o.reports].sort().join(",") !== [...s.reports].sort().join(",")) {
+ throw new BenchInputError(`run ${id} was made over other reports: drop them, or start a new run`);
+ }
+ items = prior.items;
+ skipped = s.skipped;
+ results = prior.results;
+ models = [...s.models, ...v.models.filter((m) => !s.models.includes(m))];
+ reportsAsked = s.reports;
+ createdAt = s.createdAt;
+ log(`continuing run ${id}: ${items.length} items, ${results.filter((r) => r.verdict !== null).length} answers on disk`);
+ } else {
+ const reports = await benchReportsOf(deps.paths, o.reports);
+ const got = await benchItemsOf(reports, { cuesOf: deps.cuesOf, windowS: v.windowS, ...(v.limit ? { limit: v.limit } : {}) });
+ items = got.items;
+ skipped = got.skipped;
+ results = [];
+ models = v.models;
+ reportsAsked = o.reports?.length ? [...new Set(o.reports)] : [];
+ createdAt = now().toISOString();
+ await mkdir(dir, { recursive: true });
+ await writeBenchItems(dir, items);
+ log(`run ${id}: ${items.length} items from ${reports.length} fact-check(s), ${skipped.length} claims skipped`);
+ }
+
+ const priorSpend = round6(results.reduce((s, r) => s + r.usd, 0));
+ const meter = new Meter();
+ let status: BenchStatus = "running";
+ const stopped: string[] = [];
+ const summaryOf = (): BenchSummary => ({
+ format: BENCH_FORMAT,
+ version: BENCH_VERSION,
+ id,
+ createdAt,
+ updatedAt: now().toISOString(),
+ status,
+ ...(stopped.length ? { stopped: [...stopped] } : {}),
+ models,
+ windowS: prior?.summary.windowS ?? v.windowS,
+ maxUsd: v.maxUsd,
+ reports: reportsAsked,
+ ...(prior?.summary.limit !== undefined ? { limit: prior.summary.limit } : v.limit !== undefined ? { limit: v.limit } : {}),
+ spentUsd: round6(priorSpend + meter.usd),
+ items: items.length,
+ skipped,
+ score: scoreBench(items, results, models),
+ });
+ const save = async () => {
+ await writeBenchResults(dir, results);
+ await writeBenchSummary(dir, summaryOf());
+ };
+ const record = (r: BenchResult) => {
+ const at = results.findIndex((x) => x.key === r.key && x.model === r.model);
+ if (at >= 0) results[at] = r;
+ else results.push(r);
+ };
+ await save();
+
+ const answered = new Set(results.filter((r) => r.verdict !== null).map((r) => `${r.model}\u0000${r.key}`));
+ try {
+ models: for (const model of models) {
+ const local = providerOf(model) === "local";
+ let streak = 0;
+ for (const item of items) {
+ if (answered.has(`${model}\u0000${item.key}`)) continue;
+ if (deps.signal?.aborted) {
+ status = "cancelled";
+ stopped.push("cancelled");
+ break models;
+ }
+ if (!local) {
+ const next = estimateCall(item, model, localCap).usd;
+ const spent = priorSpend + meter.usd;
+ if (spent + next > v.maxUsd) {
+ status = "capped";
+ stopped.push(`the cap: $${spent.toFixed(4)} spent, the next call (~$${next.toFixed(4)}) would pass $${v.maxUsd}`);
+ log(`stopped at the cap ($${spent.toFixed(4)} of $${v.maxUsd})`);
+ break models;
+ }
+ }
+ const prompt = benchPrompt(item, local ? { capTokens: localCap } : {});
+ const before = meter.summary().byModel[model];
+ const usdBefore = meter.usd;
+ const t0 = Date.now();
+ let r: BenchResult;
+ try {
+ const ans = await structuredAnswer<{ verdict?: unknown; reason?: unknown }>({
+ llm: deps.llm,
+ model,
+ system: prompt.system,
+ user: prompt.user,
+ schema: VERDICT_ANSWER_SCHEMA,
+ meter,
+ ...(deps.signal ? { signal: deps.signal } : {}),
+ maxTokens: MAX_ANSWER_TOKENS,
+ });
+ const verdict = isVerdict(ans?.verdict) ? ans.verdict : null;
+ const reason = typeof ans?.reason === "string" ? ans.reason.trim().slice(0, REASON_MAX) : null;
+ r = {
+ key: item.key,
+ model,
+ verdict: verdict && reason !== null ? verdict : null,
+ ...(reason !== null ? { reason } : {}),
+ ...(verdict && reason !== null ? {} : { failure: "parse" as const, error: verdict ? "no reason" : `not a verdict: ${JSON.stringify(ans?.verdict ?? null).slice(0, 60)}` }),
+ ms: Date.now() - t0,
+ usd: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ at: now().toISOString(),
+ };
+ streak = 0;
+ } catch (err) {
+ if (deps.signal?.aborted) {
+ status = "cancelled";
+ stopped.push("cancelled");
+ break models;
+ }
+ const parse = err instanceof StructuredAnswerError;
+ r = {
+ key: item.key,
+ model,
+ verdict: null,
+ failure: parse ? "parse" : "error",
+ error: (err as Error).message.slice(0, 300),
+ ms: Date.now() - t0,
+ usd: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ at: now().toISOString(),
+ };
+ if (parse) streak = 0;
+ else streak++;
+ if (err instanceof ApiKeyError) streak = BENCH_ERROR_STREAK;
+ }
+ const after = meter.summary().byModel[model];
+ r.usd = round6(meter.usd - usdBefore);
+ r.inputTokens = (after?.input ?? 0) + (after?.cacheRead ?? 0) + (after?.cacheWrite ?? 0) - ((before?.input ?? 0) + (before?.cacheRead ?? 0) + (before?.cacheWrite ?? 0));
+ r.outputTokens = (after?.output ?? 0) - (before?.output ?? 0);
+ if (prompt.cuesTrimmed) r.cuesTrimmed = prompt.cuesTrimmed;
+ record(r);
+ await save();
+ log(`${model} ${item.key}: ${r.verdict ?? `(${r.failure}: ${r.error})`} ${r.ms} ms${r.usd ? ` $${r.usd.toFixed(4)}` : ""}`);
+ if (streak >= BENCH_ERROR_STREAK) {
+ stopped.push(`${model}: stopped after ${BENCH_ERROR_STREAK} errors in a row (${r.error})`);
+ log(`${model}: stopped after ${BENCH_ERROR_STREAK} errors in a row`);
+ continue models;
+ }
+ }
+ }
+ if (status === "running") status = "done";
+ } catch (err) {
+ status = "failed";
+ stopped.push((err as Error).message);
+ await save();
+ throw err;
+ }
+ await save();
+ return { id, dir, summary: summaryOf(), spent: meter.summary() };
+}
diff --git a/common/lib/report/draft/bench/score.ts b/common/lib/report/draft/bench/score.ts
@@ -0,0 +1,186 @@
+// THE VERDICT BENCH'S SCORE (release 28, M7) — pure.
+//
+// Per model, over the items it was asked:
+// - agreement: the model's verdict equals the operator's, over every item
+// asked (a failed answer — a parse failure or an error — counts as a miss);
+// - agreementAdjacent: the same, with PARTLY and CORROBORATED counted as
+// agreeing with each other ("PARTLY adjacent to CORROBORATED");
+// - the confusion matrix, 5×5 in VERDICTS order (rows: the operator's
+// verdict, columns: the model's), with each row's failed answers beside it
+// (`unanswered`);
+// - recall for CONTRADICTED and NOT_FOUND (of the items the operator ruled
+// so, the share the model ruled so), and for PARTLY strictly and adjacent;
+// - cost (USD from the Meter), latency (ms per call), parse failures, errors.
+// The BASELINE is a model that always answers CORROBORATED, scored the same way
+// over the same items. A pass against the operator's bar is `passesBar`.
+
+import { VERDICTS, type Verdict } from "../../verdicts";
+
+export type BenchResult = {
+ key: string;
+ model: string;
+ // The model's verdict, or null when it gave none.
+ verdict: Verdict | null;
+ reason?: string;
+ // `parse`: no structured answer, or one outside the schema; `error`: the
+ // call failed (the API, the network, a prompt over the local cap).
+ failure?: "parse" | "error";
+ error?: string;
+ ms: number;
+ usd: number;
+ inputTokens: number;
+ outputTokens: number;
+ at: string;
+ // The local prompt's window trim, when one was needed.
+ cuesTrimmed?: number;
+};
+
+export type Recall = { ruled: number; matched: number; recall: number | null };
+
+export type ModelScore = {
+ model: string;
+ asked: number;
+ answered: number;
+ agreed: number;
+ agreement: number | null;
+ agreedAdjacent: number;
+ agreementAdjacent: number | null;
+ // matrix[operator][model], VERDICTS order.
+ matrix: number[][];
+ unanswered: number[];
+ recall: { CONTRADICTED: Recall; NOT_FOUND: Recall; PARTLY: Recall; PARTLY_ADJACENT: Recall };
+ parseFailures: number;
+ errors: number;
+ usd: number;
+ latency: { meanMs: number | null; medianMs: number | null; p90Ms: number | null };
+};
+
+export type BenchScore = {
+ items: number;
+ // How many items the operator ruled each verdict.
+ ruled: Record<Verdict, number>;
+ models: ModelScore[];
+ baseline: ModelScore;
+};
+
+export type VerdictBar = { agreement: number; contradictedRecall: number; notFoundRecall: number };
+
+export const BASELINE_MODEL = "always-CORROBORATED";
+
+const idx = (v: Verdict) => VERDICTS.indexOf(v);
+const ratio = (a: number, b: number) => (b > 0 ? Math.round((a / b) * 10_000) / 10_000 : null);
+const adjacent = (a: Verdict, b: Verdict) => a === b || ((a === "PARTLY" || a === "CORROBORATED") && (b === "PARTLY" || b === "CORROBORATED"));
+
+function percentile(sorted: number[], p: number): number | null {
+ if (!sorted.length) return null;
+ const i = Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1));
+ return sorted[i]!;
+}
+
+function recallOf(matrix: number[][], unanswered: number[], v: Verdict, also?: Verdict): Recall {
+ const row = matrix[idx(v)]!;
+ const ruled = row.reduce((s, n) => s + n, 0) + unanswered[idx(v)]!;
+ const matched = row[idx(v)]! + (also ? row[idx(also)]! : 0);
+ return { ruled, matched, recall: ratio(matched, ruled) };
+}
+
+// One model's score over `truth` (key → the operator's verdict). Only the
+// results whose key is in `truth` count; the last result per key wins.
+export function scoreModel(model: string, truth: ReadonlyMap<string, Verdict>, results: readonly BenchResult[]): ModelScore {
+ const last = new Map<string, BenchResult>();
+ for (const r of results) if (r.model === model && truth.has(r.key)) last.set(r.key, r);
+ const matrix = VERDICTS.map(() => VERDICTS.map(() => 0));
+ const unanswered = VERDICTS.map(() => 0);
+ let agreed = 0;
+ let agreedAdjacent = 0;
+ let parseFailures = 0;
+ let errors = 0;
+ let usd = 0;
+ const ms: number[] = [];
+ for (const [key, r] of last) {
+ const op = truth.get(key)!;
+ usd += r.usd;
+ if (r.ms > 0) ms.push(r.ms);
+ if (r.verdict === null) {
+ unanswered[idx(op)]! += 1;
+ if (r.failure === "parse") parseFailures++;
+ else errors++;
+ continue;
+ }
+ matrix[idx(op)]![idx(r.verdict)]! += 1;
+ if (r.verdict === op) agreed++;
+ if (adjacent(op, r.verdict)) agreedAdjacent++;
+ }
+ const asked = last.size;
+ ms.sort((a, b) => a - b);
+ return {
+ model,
+ asked,
+ answered: asked - parseFailures - errors,
+ agreed,
+ agreement: ratio(agreed, asked),
+ agreedAdjacent,
+ agreementAdjacent: ratio(agreedAdjacent, asked),
+ matrix,
+ unanswered,
+ recall: {
+ CONTRADICTED: recallOf(matrix, unanswered, "CONTRADICTED"),
+ NOT_FOUND: recallOf(matrix, unanswered, "NOT_FOUND"),
+ PARTLY: recallOf(matrix, unanswered, "PARTLY"),
+ PARTLY_ADJACENT: recallOf(matrix, unanswered, "PARTLY", "CORROBORATED"),
+ },
+ parseFailures,
+ errors,
+ usd: Math.round(usd * 1e6) / 1e6,
+ latency: {
+ meanMs: ms.length ? Math.round(ms.reduce((s, n) => s + n, 0) / ms.length) : null,
+ medianMs: percentile(ms, 0.5),
+ p90Ms: percentile(ms, 0.9),
+ },
+ };
+}
+
+// The whole run's score: each model in `models` order, and the baseline over
+// every item.
+export function scoreBench(
+ items: readonly { key: string; verdict: Verdict }[],
+ results: readonly BenchResult[],
+ models: readonly string[],
+): BenchScore {
+ const truth = new Map(items.map((i) => [i.key, i.verdict] as const));
+ const ruled = Object.fromEntries(VERDICTS.map((v) => [v, 0])) as Record<Verdict, number>;
+ for (const i of items) ruled[i.verdict]++;
+ const baselineResults: BenchResult[] = items.map((i) => ({
+ key: i.key,
+ model: BASELINE_MODEL,
+ verdict: "CORROBORATED",
+ ms: 0,
+ usd: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ at: "",
+ }));
+ return {
+ items: items.length,
+ ruled,
+ models: models.map((m) => scoreModel(m, truth, results)),
+ baseline: scoreModel(BASELINE_MODEL, truth, baselineResults),
+ };
+}
+
+export type BarCheck = { pass: boolean; misses: string[] };
+
+// A model against the operator's bar (fractions 0..1): strict agreement, and
+// the CONTRADICTED and NOT_FOUND recalls. A recall with nothing ruled that way
+// is not a miss (there was nothing to find).
+export function passesBar(s: ModelScore, bar: VerdictBar): BarCheck {
+ const misses: string[] = [];
+ const pct = (v: number) => `${Math.round(v * 1000) / 10}%`;
+ if ((s.agreement ?? 0) < bar.agreement) misses.push(`agreement ${pct(s.agreement ?? 0)} < ${pct(bar.agreement)}`);
+ const c = s.recall.CONTRADICTED.recall;
+ if (c !== null && c < bar.contradictedRecall) misses.push(`CONTRADICTED recall ${pct(c)} < ${pct(bar.contradictedRecall)}`);
+ const nf = s.recall.NOT_FOUND.recall;
+ if (nf !== null && nf < bar.notFoundRecall) misses.push(`NOT_FOUND recall ${pct(nf)} < ${pct(bar.notFoundRecall)}`);
+ if (s.asked === 0) misses.push("no items asked");
+ return { pass: misses.length === 0, misses };
+}
diff --git a/common/lib/report/draft/bench/store.ts b/common/lib/report/draft/bench/store.ts
@@ -0,0 +1,148 @@
+// WHERE A VERDICT BENCH RUN LIVES (release 28, M7): local-only, under the
+// checkout's gitignored `.generation/` (beside the usage ledger):
+//
+// .generation/bench/verdicts/<run-id>/
+// items.jsonl one item per line (./items.ts) — the operator's verdict
+// included: the answer key, never shown to a model
+// results.jsonl one answer per (item, model) (./score.ts BenchResult)
+// summary.json the run's parameters, status, spend, skipped claims and
+// its score
+//
+// Never `transcripts/`, never a commit: the items quote ruled claims. Every
+// write is atomic (tmp + rename, the whole file); a re-run with the same id
+// resumes (./run.ts skips each pair already answered).
+
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import { writeFileAtomic, writeJsonAtomic } from "../../../jsonFile-server";
+import type { Paths } from "../../../paths";
+import type { BenchItem, BenchSkipped } from "./items";
+import type { BenchResult, BenchScore } from "./score";
+
+export const BENCH_FORMAT = "archilyzer-verdict-bench";
+export const BENCH_VERSION = 1;
+
+export const BENCH_ITEMS_FILE = "items.jsonl";
+export const BENCH_RESULTS_FILE = "results.jsonl";
+export const BENCH_SUMMARY_FILE = "summary.json";
+
+export const BENCH_STATUSES = ["running", "done", "capped", "cancelled", "failed"] as const;
+export type BenchStatus = (typeof BENCH_STATUSES)[number];
+
+export type BenchSummary = {
+ format: typeof BENCH_FORMAT;
+ version: typeof BENCH_VERSION;
+ id: string;
+ createdAt: string;
+ updatedAt: string;
+ status: BenchStatus;
+ // Why the run stopped early (the cap, a cancel, a model's errors), when it did.
+ stopped?: string[];
+ models: string[];
+ windowS: number;
+ maxUsd: number;
+ // The reports asked for (empty: every fact-check in the registry).
+ reports: string[];
+ limit?: number;
+ spentUsd: number;
+ items: number;
+ skipped: BenchSkipped[];
+ score: BenchScore;
+};
+
+export type BenchRun = { summary: BenchSummary; items: BenchItem[]; results: BenchResult[] };
+
+const RUN_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+
+export function isBenchRunId(v: unknown): v is string {
+ return typeof v === "string" && RUN_ID_RE.test(v);
+}
+
+// A new run's id: `vb-<UTC yyyymmdd-hhmmss>`.
+export function newBenchRunId(now: Date = new Date()): string {
+ const s = now.toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
+ return `vb-${s}`;
+}
+
+// The runs' directory: `.generation/bench/verdicts/`, beside the usage ledger.
+export function benchRootOf(paths: Pick<Paths, "generationUsageFile">): string {
+ return path.join(path.dirname(paths.generationUsageFile), "bench", "verdicts");
+}
+
+export function benchRunDir(root: string, id: string): string {
+ if (!isBenchRunId(id)) throw new Error(`"${id}" is not a run id (lowercase letters, digits and dashes)`);
+ return path.join(root, id);
+}
+
+function jsonl(rows: readonly unknown[]): string {
+ return rows.map((r) => `${JSON.stringify(r)}\n`).join("");
+}
+
+async function readJsonl<T>(file: string): Promise<T[]> {
+ let text: string;
+ try {
+ text = await readFile(file, "utf8");
+ } catch {
+ return [];
+ }
+ const out: T[] = [];
+ for (const line of text.split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ out.push(JSON.parse(line) as T);
+ } catch {
+ // a torn line is skipped
+ }
+ }
+ return out;
+}
+
+export async function writeBenchItems(dir: string, items: readonly BenchItem[]): Promise<void> {
+ await writeFileAtomic(path.join(dir, BENCH_ITEMS_FILE), jsonl(items), { mkdir: true });
+}
+
+export async function writeBenchResults(dir: string, results: readonly BenchResult[]): Promise<void> {
+ await writeFileAtomic(path.join(dir, BENCH_RESULTS_FILE), jsonl(results), { mkdir: true });
+}
+
+export async function writeBenchSummary(dir: string, summary: BenchSummary): Promise<void> {
+ await writeJsonAtomic(path.join(dir, BENCH_SUMMARY_FILE), summary, { mkdir: true });
+}
+
+export async function readBenchSummary(dir: string): Promise<BenchSummary | null> {
+ try {
+ const v = JSON.parse(await readFile(path.join(dir, BENCH_SUMMARY_FILE), "utf8")) as BenchSummary;
+ return v && v.format === BENCH_FORMAT ? v : null;
+ } catch {
+ return null;
+ }
+}
+
+export async function readBenchRun(root: string, id: string): Promise<BenchRun | null> {
+ const dir = benchRunDir(root, id);
+ const summary = await readBenchSummary(dir);
+ if (!summary) return null;
+ const [items, results] = await Promise.all([
+ readJsonl<BenchItem>(path.join(dir, BENCH_ITEMS_FILE)),
+ readJsonl<BenchResult>(path.join(dir, BENCH_RESULTS_FILE)),
+ ]);
+ return { summary, items, results };
+}
+
+// Every run's summary, newest first.
+export async function listBenchRuns(root: string): Promise<BenchSummary[]> {
+ let names: string[];
+ try {
+ names = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory() && isBenchRunId(e.name)).map((e) => e.name);
+ } catch {
+ return [];
+ }
+ const out: BenchSummary[] = [];
+ for (const n of names) {
+ const s = await readBenchSummary(path.join(root, n));
+ if (s) out.push(s);
+ }
+ return out.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id));
+}
+
+export { readJsonl as readBenchJsonl };
diff --git a/common/lib/report/draft/research/state.ts b/common/lib/report/draft/research/state.ts
@@ -51,6 +51,28 @@ export type ResearchRecord = {
continuedBy?: number[];
// The agent's closing words (what the corpus holds, what it proposed).
notes?: string;
+ // An `auto` run continuing by itself (release 28 F1).
+ autoContinue?: AutoContinueRecord;
+};
+
+// What became of an `auto` run's own continuation (controller/
+// researchAutoContinue.ts):
+// claimed a continuation is being enqueued (the once-only mark, taken
+// under the article store's lock; stale after 10 minutes)
+// continued sweep `by` continues it (`warnings`: channels left out)
+// refused the ask was refused (the daily cap, a build, a route): tried
+// again on a later UTC day than `day`
+// held nothing it could sweep is in a build yet: tried again once a
+// build newer than `buildsAt` (ms) exists, or on a later day
+export const AUTO_CONTINUE_STATUSES = ["claimed", "continued", "refused", "held"] as const;
+export type AutoContinueRecord = {
+ status: (typeof AUTO_CONTINUE_STATUSES)[number];
+ at: string;
+ by?: number;
+ reason?: string;
+ warnings?: string[];
+ day?: string;
+ buildsAt?: number;
};
export function newResearchState(autonomy: Autonomy, limits: ResearchLimits): ResearchState {
diff --git a/common/lib/report/draft/tasks/clipEvidence.ts b/common/lib/report/draft/tasks/clipEvidence.ts
@@ -0,0 +1,171 @@
+// What the flips, threads and youtube drafts read (release 28, M4–M6): the
+// cut's clips as facts code can check against — each clip's quote, the claim
+// it stands for (and that claim's verdict), the chapter it sits under, and
+// the date its recording was made — and the one check of a short line of
+// text (a topic, a label, a title) against the report.
+//
+// THE DATE is code's, never the model's: the entry's own `date` (the
+// operator's, what the clip's header shows), else the recording's upload date
+// from the corpus record (`get_video_metadata`, the reader the other tasks
+// use), else the citation's `date`. A clip with none is in no pair.
+
+import { strictNormalize } from "../../../citations/verify";
+import { extractJsonObject } from "../../../parseStdoutJson";
+import { checkNarration, type GroundingInput, type GroundingResult } from "../grounding";
+import type { ManifestEntry, VideoManifest } from "../videoOps";
+import type { MediaReport } from "./media";
+import type { CorpusToolsLike } from "./types";
+
+export type ClipClaim = { id?: string; text: string; verdict?: string };
+
+/** One clip of the cut, as the media drafts read it. */
+export type ClipFact = {
+ id: string;
+ // The clip's first place in the timeline.
+ index: number;
+ quote: string;
+ claim: ClipClaim | null;
+ // The chapter card it sits under (its heading), if any.
+ section: string | null;
+ // YYYY-MM-DD, or null when nothing says.
+ date: string | null;
+ dateFrom: "entry" | "record" | "citation" | null;
+};
+
+const stripCites = (s: string) => s.replace(/\[([^\]]*)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim();
+
+/** `20260105`, `2026-01-05` or an ISO stamp → `2026-01-05`; else null. */
+export function isoDay(v: unknown): string | null {
+ if (typeof v !== "string") return null;
+ const t = v.trim();
+ let m = /^(\d{4})(\d{2})(\d{2})$/.exec(t);
+ if (m) return `${m[1]}-${m[2]}-${m[3]}`;
+ m = /^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(t);
+ return m ? `${m[1]}-${m[2]}-${m[3]}` : null;
+}
+
+const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+
+/** A side's `when`, written by code from its date: `Jan 2026`. */
+export const whenOf = (day: string) => `${MONTHS[Number(day.slice(5, 7)) - 1] ?? ""} ${day.slice(0, 4)}`.trim();
+
+// Every claim of the report by id, and by the citations it cites.
+function claimIndex(report: MediaReport) {
+ const byId = new Map<string, ClipClaim>();
+ const byCite = new Map<string, ClipClaim>();
+ for (const s of (report.sections ?? []) as { claims?: { id?: string; text?: string; citations?: string[]; verdict?: string }[] }[]) {
+ for (const c of s.claims ?? []) {
+ const claim: ClipClaim = { ...(c.id ? { id: c.id } : {}), text: stripCites(c.text ?? ""), ...(c.verdict ? { verdict: c.verdict } : {}) };
+ if (c.id) byId.set(c.id, claim);
+ for (const cid of c.citations ?? []) if (!byCite.has(cid)) byCite.set(cid, claim);
+ }
+ }
+ return { byId, byCite };
+}
+
+/**
+ * The cut's clips (every clip of the timeline once, in timeline order), with
+ * their claims, chapters and dates. `corpus` is asked for the dates the
+ * entries do not carry; a failed read leaves the date to the citation's.
+ */
+export async function clipFacts(
+ manifest: VideoManifest,
+ report: MediaReport,
+ corpus: Pick<CorpusToolsLike, "call"> | null,
+ { dates = true }: { dates?: boolean } = {},
+): Promise<ClipFact[]> {
+ const { byId, byCite } = claimIndex(report);
+ const cites = (report.citations ?? {}) as Record<string, { date?: string } | undefined>;
+ const prov = (manifest.provenance ?? {}) as { channelSlug?: string };
+ const recordDates = new Map<string, Promise<string | null>>();
+ const recordDate = (channel: string, video: string) => {
+ const key = `${channel}/${video}`;
+ let p = recordDates.get(key);
+ if (!p) {
+ p = (corpus ? corpus.call("get_video_metadata", { channel, video_id: video }) : Promise.resolve(""))
+ .then((t) => isoDay((extractJsonObject(t) as { uploadDate?: unknown } | null)?.uploadDate))
+ .catch(() => null);
+ recordDates.set(key, p);
+ }
+ return p;
+ };
+ const out: ClipFact[] = [];
+ const seen = new Set<string>();
+ let section: string | null = null;
+ for (const [index, e] of manifest.timeline.entries()) {
+ if (e.type === "card" && e.style === "chapter") section = e.heading ?? null;
+ if (e.type !== "clip" || seen.has(e.id)) continue;
+ seen.add(e.id);
+ const claimRef = (e.claim ?? null) as { id?: string; verdict?: string } | null;
+ const base = (claimRef?.id ? byId.get(claimRef.id) : undefined) ?? byCite.get(e.id) ?? null;
+ const claim = base || claimRef?.verdict ? { ...(base ?? { text: "" }), ...(claimRef?.verdict ? { verdict: claimRef.verdict } : {}) } : null;
+ const channel = String(e.siteChannel ?? e.channel ?? prov.channelSlug ?? "");
+ const video = String(e.siteVideo ?? e.video ?? "");
+ let date = dates ? isoDay(e.date) : null;
+ let dateFrom: ClipFact["dateFrom"] = date ? "entry" : null;
+ if (dates && !date && channel && video) {
+ date = await recordDate(channel, video);
+ if (date) dateFrom = "record";
+ }
+ if (dates && !date) {
+ date = isoDay(cites[e.id]?.date);
+ if (date) dateFrom = "citation";
+ }
+ out.push({ id: e.id, index, quote: String(e.quote ?? "").trim(), claim, section, date, dateFrom });
+ }
+ return out;
+}
+
+/** A clip's evidence line for a prompt (its quote and claim cut to `max` characters each). */
+export function clipLine(c: ClipFact, { max = 160, date = true }: { max?: number; date?: boolean } = {}): string {
+ const cut = (s: string) => (s.length > max ? `${s.slice(0, max - 1)}…` : s);
+ return (
+ `- ${c.id}` +
+ (date ? ` [${c.date ?? "date unknown"}]` : "") +
+ (c.section ? ` (chapter: ${c.section})` : "") +
+ (c.quote ? `: "${cut(c.quote)}"` : "") +
+ (c.claim?.text ? ` — claim: ${cut(c.claim.text)}` : "")
+ );
+}
+
+/** Lines that fit a character budget, in order; the rest counted. */
+export function fitLines(lines: string[], budget: number): { text: string; omitted: number } {
+ const kept: string[] = [];
+ let used = 0;
+ for (const l of lines) {
+ if (used + l.length + 1 > budget) break;
+ kept.push(l);
+ used += l.length + 1;
+ }
+ return { text: kept.join("\n"), omitted: lines.length - kept.length };
+}
+
+const QUOTED = /“([^”]+)”|"([^"]+)"/g;
+
+/**
+ * A short line's problems (a topic, a label, a title or a summary), by the
+ * narration's grounding (./grounding.ts): every name and number in the
+ * report, no stock phrase, no first person, no tag. With `quotes`, words in
+ * quotation marks are allowed only when a cited quote says them verbatim
+ * (they are then left out of the other checks); without, any quotation marks
+ * or a run of a quote's words is refused, as in narration.
+ */
+export function checkLine(text: string, g: GroundingInput, { quotes = false }: { quotes?: boolean } = {}): GroundingResult {
+ if (!quotes) return checkNarration(text, g);
+ const hard: string[] = [];
+ const said = g.quotes.map((q) => ` ${strictNormalize(q)} `);
+ const stripped = text.replace(QUOTED, (_m, a: string | undefined, b: string | undefined) => {
+ const words = strictNormalize(a ?? b ?? "");
+ if (!words || !said.some((q) => q.includes(` ${words} `))) hard.push(`“${(a ?? b ?? "").slice(0, 80)}” is not what a cited clip says, word for word`);
+ return " ";
+ });
+ const r = checkNarration(stripped, { ...g, quotes: [] });
+ return { hard: [...new Set([...hard, ...r.hard])].sort(), soft: r.soft };
+}
+
+/** The clips in a manifest by id (the first entry with each id). */
+export function clipsById(manifest: VideoManifest): Map<string, ManifestEntry> {
+ const m = new Map<string, ManifestEntry>();
+ for (const e of manifest.timeline) if (e.type === "clip" && !m.has(e.id)) m.set(e.id, e);
+ return m;
+}
diff --git a/common/lib/report/draft/tasks/flips.ts b/common/lib/report/draft/tasks/flips.ts
@@ -0,0 +1,363 @@
+// TASK flips — THEN/NOW pairs over the cut's clips (release 28, M4): the
+// `render.chrome.flips` panel (umtool/report-to-video/flips.mjs). A STEP on a
+// done iteration, on the media task scaffold (./media.ts): one unit, the
+// whole field.
+//
+// The model proposes pairs — a topic and two clip ids, and optionally a part
+// of each clip's quote. CODE does the rest and checks it all:
+// - the ids name clips of the cut, no clip is in two pairs, 1 to
+// FLIPS_LIMITS.pairs[1] pairs (and no more than the dated clips allow);
+// - the dates are the recordings' (./clipEvidence.ts), never the model's:
+// the earlier clip is THEN, the later NOW, and two clips of one day are
+// no pair; each side's `when` is written from its date ("Jan 2026");
+// - a side's `words` are its clip's quote, verbatim — the model's part of
+// it only when the quote says exactly that — cut to the limit by code;
+// - the topic is one line of at most FLIPS_LIMITS.topic characters, its
+// names and numbers the report's (grounding);
+// - THEN plays before NOW: a pair the other way round is refused, unless
+// the cut's order is a draft itself (`drafted.timeline`) and the flips
+// will be applied — then code swaps the two clips' places in the
+// timeline, written through applyDraft with this task's provenance;
+// - the result passes the build's own validateFlips and validateFlipEntries
+// (common's panels.mjs).
+// A pair failing a check is dropped when the others stand (the repair); the
+// better of two attempts is kept.
+//
+// ONE LEFT PANEL: flips and threads share it. A cut with threads is refused —
+// unless `force` and the threads are a draft: then the flips replace them
+// (the list, each clip's `thread` and their mark go) and the log says so.
+// A cut with no on-screen deck (`render.chrome`) has no panel: refused.
+
+import { applyDraft, clearDrafted, entriesWithId, ownerOf } from "../../drafted.mjs";
+import { FLIPS_LIMITS, threadsOn, validateFlipEntries, validateFlips } from "../../panels.mjs";
+import type { GroundingInput } from "../grounding";
+import type { ManifestEntry, VideoManifest } from "../videoOps";
+import { checkLine, clipFacts, clipLine, fitLines, whenOf, type ClipFact } from "./clipEvidence";
+import { runMediaTask, type MediaAttempt, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media";
+import { TaskInputError } from "./run";
+import type { TaskDeps, TaskResult } from "./types";
+
+export type FlipsInput = MediaTaskInput;
+
+/** A pair as the model proposes it. */
+export type ProposedPair = { topic: string; then: string; now: string; thenWords?: string; nowWords?: string };
+export type FlipsValue = { pairs: ProposedPair[] };
+
+type Side = { entry: string; when: string; words: string };
+export type FlipPair = { id: string; topic: string; then: Side; now: Side };
+
+/** What code makes of a proposal: the field, the swaps it needs, and what is wrong (per pair, and overall). */
+export type FlipsPlan = {
+ flips: { pairs: FlipPair[] };
+ swaps: [string, string][];
+ pairProblems: string[][];
+ problems: string[];
+ soft: string[];
+};
+
+type FlipsUnit = MediaUnit & {
+ // The cut as read (what every plan is made over).
+ manifest: VideoManifest;
+ clips: ClipFact[];
+ g: GroundingInput;
+ // The cut's order is a draft and the flips will be applied: a pair may swap its clips.
+ reorderable: boolean;
+ // The threads are a draft and `force` is set: the flips replace them.
+ dropThreads: boolean;
+ maxPairs: number;
+ // The kept value's plan (set by toField, read by apply).
+ chosen?: FlipsPlan;
+};
+
+// The evidence's share of a prompt (characters), well under the local 8k tokens.
+const EVIDENCE_BUDGET = 14_000;
+
+const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim();
+
+/** A pair id from its topic: letters, digits and `-`; unique among `taken`. */
+export function pairId(topic: string, i: number, taken: Set<string>): string {
+ let base = topic.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "");
+ if (!/^[a-z0-9]/.test(base)) base = `pair-${i + 1}`;
+ let id = base;
+ for (let k = 2; taken.has(id); k++) id = `${base}-${k}`;
+ taken.add(id);
+ return id;
+}
+
+/**
+ * A side's words: the clip's quote, verbatim — or the part of it the model
+ * named, when the quote says exactly that — cut to `max` characters at a word
+ * (with `…`). `soft` when the model's part was not the quote's.
+ */
+export function sideWords(quote: string, part: string | undefined, max: number = FLIPS_LIMITS.words): { words: string; soft?: string } {
+ const q = oneLine(quote);
+ let w = q;
+ let soft: string | undefined;
+ const p = oneLine(part).replace(/^["“'…\s]+|["”'…\s]+$/g, "");
+ if (p) {
+ const at = q.toLowerCase().indexOf(p.toLowerCase());
+ if (at >= 0) w = q.slice(at, at + p.length);
+ else soft = "its words are not the clip's quote: the quote is used";
+ }
+ if (w.length > max) {
+ const cut = w.slice(0, max - 1);
+ const sp = cut.lastIndexOf(" ");
+ w = `${(sp > max / 2 ? cut.slice(0, sp) : cut).replace(/[\s,;:.]+$/, "")}…`;
+ }
+ return { words: w, ...(soft ? { soft } : {}) };
+}
+
+/** The timeline with each pair of ids' places swapped. */
+export function swapEntries(timeline: ManifestEntry[], swaps: readonly [string, string][]): ManifestEntry[] {
+ const out = [...timeline];
+ for (const [a, b] of swaps) {
+ const i = out.findIndex((e) => e.id === a);
+ const j = out.findIndex((e) => e.id === b);
+ if (i < 0 || j < 0) continue;
+ [out[i], out[j]] = [out[j]!, out[i]!];
+ }
+ return out;
+}
+
+const twins = (m: VideoManifest, id: string) => entriesWithId(m, id).length > 1;
+
+/** Code's reading of a proposal over this cut (pure). */
+export function planFlips(value: FlipsValue, unit: Pick<FlipsUnit, "clips" | "g" | "reorderable" | "dropThreads" | "maxPairs">, manifest: VideoManifest): FlipsPlan {
+ const byId = new Map(unit.clips.map((c) => [c.id, c]));
+ const problems: string[] = [];
+ const soft: string[] = [];
+ const [lo] = FLIPS_LIMITS.pairs;
+ const n = value.pairs.length;
+ if (n < lo) problems.push("no pair: propose at least one");
+ if (n > unit.maxPairs) problems.push(`${n} pairs: at most ${unit.maxPairs}`);
+ const used = new Set<string>();
+ const taken = new Set<string>();
+ const pairs: FlipPair[] = [];
+ const pairProblems: string[][] = [];
+ const swaps: [string, string][] = [];
+ value.pairs.forEach((p, i) => {
+ const bad: string[] = [];
+ const w = `pair ${i + 1}`;
+ const topic = oneLine(p.topic);
+ if (!topic) bad.push(`${w}: no topic`);
+ else if (topic.length > FLIPS_LIMITS.topic) bad.push(`${w}: the topic is ${topic.length} characters (at most ${FLIPS_LIMITS.topic})`);
+ else for (const h of checkLine(topic, unit.g).hard) bad.push(`${w}: the topic: ${h}`);
+ let a = byId.get(p.then);
+ let b = byId.get(p.now);
+ if (!a) bad.push(`${w}: ${p.then || "(none)"} is not a clip of the cut`);
+ if (!b) bad.push(`${w}: ${p.now || "(none)"} is not a clip of the cut`);
+ let side = { then: p.thenWords, now: p.nowWords };
+ if (a && b) {
+ if (a.id === b.id) bad.push(`${w}: THEN and NOW are the same clip`);
+ for (const c of [a, b]) {
+ if (used.has(c.id)) bad.push(`${w}: ${c.id} is already in a pair`);
+ if (!c.date) bad.push(`${w}: ${c.id}'s recording has no date`);
+ if (!c.quote) bad.push(`${w}: ${c.id} has no quote`);
+ }
+ if (a.date && b.date) {
+ if (a.date === b.date) bad.push(`${w}: ${a.id} and ${b.id} are of the same day (${a.date})`);
+ else if (a.date > b.date) {
+ // THEN is the earlier recording: the dates are code's.
+ [a, b] = [b, a];
+ side = { then: p.nowWords, now: p.thenWords };
+ }
+ }
+ if (a.id !== b.id && a.index > b.index) {
+ if (!unit.reorderable) bad.push(`${w}: THEN ${a.id} (${a.date}) plays after NOW ${b.id} (${b.date}) and the cut's order is not a draft — pick another pair, or reorder the cut by hand`);
+ else if (twins(manifest, a.id) || twins(manifest, b.id)) bad.push(`${w}: ${a.id} or ${b.id} has variant twins — reorder the cut by hand`);
+ }
+ }
+ if (a && b && !bad.length) {
+ const tw = sideWords(a.quote, side.then);
+ const nw = sideWords(b.quote, side.now);
+ if (tw.soft) soft.push(`${w}: ${a.id} ${tw.soft}`);
+ if (nw.soft) soft.push(`${w}: ${b.id} ${nw.soft}`);
+ if (a.index > b.index) swaps.push([a.id, b.id]);
+ pairs.push({
+ id: pairId(topic, i, taken),
+ topic,
+ then: { entry: a.id, when: whenOf(a.date!), words: tw.words },
+ now: { entry: b.id, when: whenOf(b.date!), words: nw.words },
+ });
+ }
+ // Only a pair that stands takes its clips: a refused one leaves them free.
+ if (a && b && !bad.length) for (const c of [a, b]) used.add(c.id);
+ pairProblems.push(bad);
+ });
+ const flips = { pairs };
+ if (pairs.length && !pairProblems.some((x) => x.length) && !problems.length) {
+ // The build's own checks, on the cut as it will be.
+ const after = JSON.parse(JSON.stringify(manifest)) as VideoManifest & { render?: { chrome?: Record<string, unknown> } };
+ after.timeline = swapEntries(after.timeline, swaps);
+ if (after.render?.chrome) {
+ if (unit.dropThreads) delete after.render.chrome.threads;
+ after.render.chrome.flips = flips;
+ }
+ problems.push(...validateFlips(flips), ...validateFlipEntries(after));
+ }
+ return { flips, swaps, pairProblems, problems, soft };
+}
+
+const allProblems = (p: FlipsPlan) => [...p.problems, ...p.pairProblems.flat()];
+
+export function flipsSystem(maxPairs: number): string {
+ return (
+ "You pick THEN/NOW pairs for a short evidence video: two clips of the same speaker on one topic, where what was said " +
+ "at the earlier date is reversed or contradicted by what was said at the later one. Rules: (1) use only clip ids from " +
+ "the list; (2) a clip is in one pair at most; (3) propose only pairs that really reverse, at most " +
+ `${maxPairs}, best first; (4) the topic names what the pair is about in plain words, at most ${FLIPS_LIMITS.topic} ` +
+ "characters, no quotation marks, no first person, nothing the evidence does not say; (5) the dates are given and " +
+ "decide which clip is THEN — you never write a date; (6) thenWords and nowWords are optional: a part of that clip's " +
+ `quote copied word for word, when the whole quote is longer than ${FLIPS_LIMITS.words} characters; leave them out ` +
+ "otherwise."
+ );
+}
+
+export const FLIPS_SPEC: MediaTaskSpec<FlipsUnit, FlipsValue, FlipsInput> = {
+ task: "flips",
+ noun: "flips panel",
+ async units(ctx: MediaContext<FlipsInput>) {
+ const m = ctx.manifest as VideoManifest & { render?: { chrome?: unknown } };
+ const chrome = m.render?.chrome;
+ if (!chrome || typeof chrome !== "object") {
+ throw new TaskInputError("flips are drawn by the on-screen deck (render.chrome), and this cut has none — turn the deck on first");
+ }
+ let dropThreads = false;
+ if (threadsOn(m.render)) {
+ const owner = ownerOf(m, { field: "render.chrome.threads" });
+ if (!ctx.input.force || owner === "operator") {
+ throw new TaskInputError(
+ "this cut has threads (render.chrome.threads), and flips and threads share the left panel" +
+ (owner === "operator" ? ": the threads are the operator's — remove them first" : ": force replaces drafted threads"),
+ );
+ }
+ dropThreads = true;
+ }
+ const clips = await clipFacts(m, ctx.report, ctx.handle.deps.corpus ?? null);
+ const dated = clips.filter((c) => c.date && c.quote);
+ const days = new Set(dated.map((c) => c.date));
+ if (dated.length < 2 || days.size < 2) {
+ return [{ id: "flips", skipped: `a pair needs two clips of different dates: ${dated.length} dated clip(s), ${days.size} date(s)` }];
+ }
+ const flipsOwner = ownerOf(m, { field: "render.chrome.flips" });
+ return [
+ {
+ id: "flips",
+ target: { field: "render.chrome.flips" },
+ label: "THEN/NOW pairs",
+ manifest: m,
+ clips,
+ g: ctx.grounding,
+ reorderable: ownerOf(m, { field: "timeline" }) === "drafted" && flipsOwner !== "operator",
+ dropThreads,
+ maxPairs: Math.min(FLIPS_LIMITS.pairs[1], Math.floor(dated.length / 2)),
+ },
+ ];
+ },
+ schema: () => ({
+ type: "object",
+ properties: {
+ pairs: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ topic: { type: "string" },
+ then: { type: "string" },
+ now: { type: "string" },
+ thenWords: { type: "string" },
+ nowWords: { type: "string" },
+ },
+ required: ["topic", "then", "now"],
+ },
+ },
+ },
+ required: ["pairs"],
+ }),
+ system: (u) => flipsSystem(u.maxPairs),
+ user(u, ctx) {
+ const r = ctx.report as { title?: string; summary?: string | null };
+ const ev = fitLines(u.clips.map((c) => clipLine(c)), EVIDENCE_BUDGET);
+ return (
+ `Report: ${r.title ?? ""}` +
+ (r.summary ? `\n${String(r.summary).slice(0, 600)}` : "") +
+ `\n\nThe cut's clips (id [recording date] (chapter): "quote" — the claim it stands for):\n${ev.text}` +
+ (ev.omitted ? `\n(${ev.omitted} more clip(s) not shown)` : "") +
+ "\n\nPropose the pairs."
+ );
+ },
+ parse(answer) {
+ const list = (answer as { pairs?: unknown } | null)?.pairs;
+ if (!Array.isArray(list)) throw new Error("no pairs list in the answer");
+ return {
+ pairs: list
+ .filter((p): p is Record<string, unknown> => !!p && typeof p === "object")
+ .map((p) => ({
+ topic: oneLine(p.topic),
+ then: oneLine(p.then),
+ now: oneLine(p.now),
+ ...(typeof p.thenWords === "string" && p.thenWords.trim() ? { thenWords: p.thenWords } : {}),
+ ...(typeof p.nowWords === "string" && p.nowWords.trim() ? { nowWords: p.nowWords } : {}),
+ })),
+ };
+ },
+ check(value, u) {
+ const plan = planFlips(value, u, u.manifest);
+ return { hard: allProblems(plan), soft: plan.soft };
+ },
+ // The best attempt's pairs that pass, when there is one (never a new pair).
+ repair(attempts, u) {
+ let best: MediaAttempt<FlipsValue> | null = null;
+ for (const a of attempts) {
+ if (!a.value) continue;
+ const plan = planFlips(a.value, u, u.manifest);
+ const good = a.value.pairs.filter((_, i) => !plan.pairProblems[i]?.length).slice(0, u.maxPairs);
+ if (!good.length) continue;
+ const v = { pairs: good };
+ const again = planFlips(v, u, u.manifest);
+ const hard = allProblems(again);
+ if (hard.length) continue;
+ if (!best || good.length > best.value!.pairs.length) {
+ best = { value: v, hard: [], soft: [...again.soft, `${a.value.pairs.length - good.length} refused pair(s) dropped`] };
+ }
+ }
+ return best;
+ },
+ toField(value, u) {
+ u.chosen = planFlips(value, u, u.manifest);
+ return u.chosen.flips;
+ },
+ apply(manifest, u, value, provenance, force, ctx) {
+ const res = applyDraft(manifest, { field: "render.chrome.flips", value, provenance, force });
+ if (!res.applied) return res;
+ const m = manifest as VideoManifest & { render?: { chrome?: Record<string, unknown> } };
+ if (u.dropThreads && m.render?.chrome) {
+ delete m.render.chrome.threads;
+ for (const e of m.timeline) delete e.thread;
+ clearDrafted(m, { field: "render.chrome.threads" });
+ ctx.handle.log(" the drafted threads were removed: flips and threads share the left panel");
+ }
+ const swaps = u.chosen?.swaps ?? [];
+ if (swaps.length) {
+ const t = applyDraft(m, { field: "timeline", value: swapEntries(m.timeline, swaps), provenance, force: true });
+ ctx.handle.log(
+ t.applied
+ ? ` the cut's order changed so THEN plays first: ${swaps.map(([a, b]) => `${a} ⇄ ${b}`).join(", ")}`
+ : ` the cut's order could not be changed (${t.reason}): THEN plays after NOW`,
+ );
+ }
+ return res;
+ },
+ describe: (v, u) => {
+ const pairs = planFlips(v, u, u.manifest).flips.pairs;
+ return (
+ `${pairs.length} pair(s): ` +
+ pairs.map((p) => `${p.topic} (${p.then.entry} ${p.then.when} → ${p.now.entry} ${p.now.when})`).join("; ") +
+ (u.dropThreads ? " — replaces the drafted threads" : "")
+ );
+ },
+};
+
+export async function flips(input: FlipsInput, deps: TaskDeps): Promise<TaskResult> {
+ return runMediaTask(FLIPS_SPEC, input, deps);
+}
diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts
@@ -4,6 +4,7 @@
import type { MediaStepTask } from "../../../generationSettings";
import type { MediaTaskInput } from "./media";
import { cut, type CutInput } from "./cut";
+import { flips } from "./flips";
import { narrate, type NarrateInput } from "./narrate";
import { onscreen, type OnscreenInput } from "./onscreen";
import { teaser, type TeaserInput } from "./teaser";
@@ -13,7 +14,9 @@ import { reviseVideo, type ReviseVideoInput } from "./revise-video";
import { sweepAgent, type SweepAgentInput } from "./sweep-agent";
import { sweepPipeline, type SweepPipelineInput } from "./sweep-pipeline";
import { TaskInputError, runOnIteration } from "./run";
+import { threads } from "./threads";
import { TASK_NAMES, type TaskDeps, type TaskName, type TaskResult } from "./types";
+import { youtube } from "./youtube";
export * from "./types";
export { TaskInputError, runOnIteration, usageOf } from "./run";
@@ -47,6 +50,11 @@ export {
type MediaTaskSpec,
type MediaUnit,
} from "./media";
+// Release 28 M4–M6: the left panel (flips or threads) and the upload's text.
+export { flips, FLIPS_SPEC, planFlips, sideWords, swapEntries, type FlipsInput, type FlipsPlan, type FlipsValue } from "./flips";
+export { threads, THREADS_SPEC, THREADS_TASK_COUNT, planThreads, type ThreadsInput, type ThreadsPlan, type ThreadsValue } from "./threads";
+export { youtube, YOUTUBE_SPEC, YOUTUBE_SUMMARY_MAX, type YoutubeInput, type YoutubeValue } from "./youtube";
+export { checkLine, clipFacts, whenOf, type ClipFact } from "./clipEvidence";
export { research, RESEARCH_READ_TOOLS, type ResearchInput } from "./research";
export { pickCorpusBuild, listCorpusBuilds, siteOriginOf, NoCorpusBuildError, type CorpusBuild } from "./corpusSource";
export { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
@@ -65,17 +73,6 @@ export type TaskInput =
| ({ task: "teaser" } & TeaserInput)
| ({ task: Exclude<MediaStepTask, "narrate" | "cut" | "onscreen" | "teaser"> } & MediaTaskInput);
-// A media task this build does not have: the step is recorded on the
-// iteration as failed, saying so (release 28 lanes D and E replace these).
-export function notImplementedTask(input: { task: string } & MediaTaskInput, deps: TaskDeps): Promise<TaskResult> {
- return runOnIteration(
- { article: input.article, n: input.n, deps, step: { task: input.task, model: input.model, ...(input.jobId ? { jobId: input.jobId } : {}) } },
- async () => {
- throw new TaskInputError(`${input.task} is not implemented in this build`);
- },
- );
-}
-
export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> {
switch (input.task) {
case "sweep-agent":
@@ -90,16 +87,18 @@ export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> {
return narrate(input, deps);
case "research":
return research(input, deps);
+ case "flips":
+ return flips(input, deps);
+ case "threads":
+ return threads(input, deps);
+ case "youtube":
+ return youtube(input, deps);
case "cut":
return cut(input, deps);
case "onscreen":
return onscreen(input, deps);
case "teaser":
return teaser(input, deps);
- case "flips":
- case "threads":
- case "youtube":
- return notImplementedTask(input, deps);
}
}
diff --git a/common/lib/report/draft/tasks/panelTasks.test.ts b/common/lib/report/draft/tasks/panelTasks.test.ts
@@ -0,0 +1,365 @@
+// The flips, threads and youtube drafts (release 28, M4–M6): every code check
+// refuses what it should — dates, order, counts, lengths, ids, grounding — the
+// better of two attempts, the repair, the one left panel, and the operator's
+// field kept with the draft as an alternative. The fake ollama answers; the
+// corpus is the synthetic one's records (their upload dates).
+
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs";
+import { recordOf } from "../../../../testing/draft/corpus.mjs";
+import { createIteration, projectOf, updateIteration, writeIterationFile } from "../../iterations";
+import { groundingInputOf } from "../grounding";
+import { validateFlipEntries, validateFlips, validateThreadEntries, validateThreads } from "../../panels.mjs";
+import type { VideoManifest } from "../videoOps";
+import { isoDay, whenOf, type ClipFact } from "./clipEvidence";
+import { flips, planFlips, sideWords, swapEntries } from "./flips";
+import { planThreads, threads } from "./threads";
+import { summaryProblems, titleProblems, youtube, YOUTUBE_SUMMARY_MAX } from "./youtube";
+import type { DraftFile } from "./media";
+import type { TaskDeps } from "./types";
+
+const DRAFT = new URL("../../../../testing/draft/", import.meta.url);
+const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8"));
+
+let tmp: string;
+let ol: FakeOllama;
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "panel-tasks-"));
+ ol = await startFakeOllama();
+});
+after(async () => {
+ await ol.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+// The full manifest with no left panel (its threads taken off).
+async function deckManifest() {
+ const m = await kit("manifests/full.video.manifest.json");
+ delete m.render.chrome.threads;
+ for (const e of m.timeline) delete e.thread;
+ return m;
+}
+
+// The corpus as the tasks read it: get_video_metadata answers a record (no cues).
+const corpus = {
+ source: "fake",
+ tools: [],
+ call: async (name: string, args: Record<string, unknown> = {}) => {
+ if (name !== "get_video_metadata") return "";
+ const r = recordOf(String(args.channel), String(args.video_id));
+ if (!r) throw new Error("video not found");
+ const { cues: _c, ...meta } = r;
+ return JSON.stringify(meta);
+ },
+};
+
+let caseN = 0;
+async function project(manifest: unknown) {
+ caseN++;
+ const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) };
+ const projectsRoot = path.join(tmp, `projects-${caseN}`);
+ await mkdir(paths.articlesDir, { recursive: true });
+ await createIteration("synth-basic", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["synth-kitchen"] } }, paths);
+ const report = await kit("reports/basic.report.json");
+ await writeIterationFile("synth-basic", 1, "report.json", report, paths);
+ const dir = projectOf(projectsRoot, "synth-basic", 1);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
+ await writeFile(path.join(dir, "report.json"), JSON.stringify(report));
+ await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths);
+ const lines: string[] = [];
+ const deps: TaskDeps = {
+ llm: { ollama: { baseUrl: ol.url } },
+ corpus,
+ cuesOf: async () => null,
+ paths,
+ log: (l) => lines.push(l),
+ now: () => new Date("2026-10-13T12:00:00.000Z"),
+ };
+ const input = (o: { force?: boolean } = {}) => ({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot, ...o });
+ const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+ const draftNow = async (task: string) => JSON.parse(await readFile(path.join(dir, `${task}-draft.json`), "utf8")) as DraftFile;
+ return { dir, deps, lines, input, manifestNow, draftNow, report };
+}
+
+const P = { task: "cut", model: "qwen3:8b", at: "2026-10-13T11:00:00.000Z", iteration: 1, attempt: 1 };
+
+// ─── pure ───
+
+test("dates and words are code's: isoDay, whenOf, sideWords verbatim and cut at a word", () => {
+ assert.equal(isoDay("20260105"), "2026-01-05");
+ assert.equal(isoDay("2026-03-01T10:00:00Z"), "2026-03-01");
+ assert.equal(isoDay("March"), null);
+ assert.equal(whenOf("2026-01-05"), "Jan 2026");
+ assert.deepEqual(sideWords("I would never sell the bakery to a chain", "Never sell the BAKERY"), { words: "never sell the bakery" });
+ assert.deepEqual(sideWords("I would never sell the bakery to a chain", "I'd never sell it"), {
+ words: "I would never sell the bakery to a chain",
+ soft: "its words are not the clip's quote: the quote is used",
+ });
+ const long = Array.from({ length: 40 }, (_, i) => `word${i}`).join(" ");
+ const cut = sideWords(long, undefined).words;
+ assert.ok(cut.length <= 110 && cut.endsWith("…") && long.startsWith(cut.slice(0, -1)), cut);
+ assert.deepEqual(
+ swapEntries([{ type: "clip", id: "a" }, { type: "card", id: "x" }, { type: "clip", id: "b" }], [["a", "b"]]).map((e) => e.id),
+ ["b", "x", "a"],
+ );
+});
+
+const clip = (id: string, index: number, date: string | null, quote = `the words of ${id}`, verdict?: string): ClipFact => ({
+ id,
+ index,
+ quote,
+ claim: verdict ? { text: "", verdict } : null,
+ section: null,
+ date,
+ dateFrom: date ? "record" : null,
+});
+
+test("planFlips: ids, one pair per clip, dates (the earlier is THEN; one day is no pair), order, the topic's length and grounding", async () => {
+ const m = (await deckManifest()) as VideoManifest;
+ const g = groundingInputOf(await kit("reports/basic.report.json"));
+ const clips = [clip("c01", 2, "2026-01-05"), clip("c02", 3, "2026-01-05"), clip("c04", 6, "2026-02-10"), clip("c07", 9, "2026-03-01"), clip("c05", 7, null)];
+ const unit = { clips, g, reorderable: false, dropThreads: false, maxPairs: 2 };
+ // The model's THEN is the later recording: code turns it round.
+ const ok = planFlips({ pairs: [{ topic: "The bakery", then: "c07", now: "c01" }] }, unit, m);
+ assert.deepEqual(ok.problems, []);
+ assert.deepEqual(ok.flips.pairs[0], {
+ id: "the-bakery",
+ topic: "The bakery",
+ then: { entry: "c01", when: "Jan 2026", words: "the words of c01" },
+ now: { entry: "c07", when: "Mar 2026", words: "the words of c07" },
+ });
+ const bad = planFlips(
+ {
+ pairs: [
+ { topic: "The oven", then: "c01", now: "c02" },
+ { topic: "The contest", then: "c99", now: "c04" },
+ { topic: "The contest", then: "c05", now: "c04" },
+ { topic: "A topic that is far too long for the panel", then: "c04", now: "c07" },
+ ],
+ },
+ unit,
+ m,
+ );
+ const all = [...bad.problems, ...bad.pairProblems.flat()].join(" | ");
+ assert.match(all, /4 pairs: at most 2/);
+ assert.match(all, /c01 and c02 are of the same day \(2026-01-05\)/);
+ assert.match(all, /c99 is not a clip of the cut/);
+ assert.match(all, /c05's recording has no date/);
+ assert.match(all, /the topic is 42 characters \(at most 32\)/);
+ // A name the report does not have; a clip in two pairs.
+ const two = planFlips({ pairs: [{ topic: "The bakery of Gordon", then: "c01", now: "c07" }, { topic: "The oven", then: "c04", now: "c07" }] }, unit, m);
+ assert.match(two.pairProblems[0]!.join(" "), /name “Gordon” is not in the report/);
+ assert.equal(two.pairProblems[1]!.length, 0, "a refused pair leaves its clips free");
+ const three = planFlips({ pairs: [{ topic: "The bakery", then: "c01", now: "c07" }, { topic: "The oven", then: "c04", now: "c07" }] }, unit, m);
+ assert.match(three.pairProblems[1]!.join(" "), /c07 is already in a pair/);
+});
+
+test("planFlips: THEN after NOW in the cut is refused when the order is the operator's, swapped when it is a draft; the build's validators pass", async () => {
+ const m = (await deckManifest()) as VideoManifest;
+ // c07 (Mar) before c01 (Jan) in the cut.
+ m.timeline = swapEntries(m.timeline, [["c01", "c07"]]);
+ const g = groundingInputOf(await kit("reports/basic.report.json"));
+ const at = (id: string) => m.timeline.findIndex((e) => e.id === id);
+ const clips = [clip("c01", at("c01"), "2026-01-05"), clip("c07", at("c07"), "2026-03-01")];
+ const v = { pairs: [{ topic: "The bakery", then: "c01", now: "c07" }] };
+ const refused = planFlips(v, { clips, g, reorderable: false, dropThreads: false, maxPairs: 1 }, m);
+ assert.match(refused.pairProblems[0]!.join(" "), /THEN c01 \(2026-01-05\) plays after NOW c07 \(2026-03-01\) and the cut's order is not a draft/);
+ const swapped = planFlips(v, { clips, g, reorderable: true, dropThreads: false, maxPairs: 1 }, m);
+ assert.deepEqual([...swapped.problems, ...swapped.pairProblems.flat()], []);
+ assert.deepEqual(swapped.swaps, [["c01", "c07"]]);
+ const after = JSON.parse(JSON.stringify(m));
+ after.timeline = swapEntries(after.timeline, swapped.swaps);
+ after.render.chrome.flips = swapped.flips;
+ assert.deepEqual([...validateFlips(swapped.flips), ...validateFlipEntries(after)], []);
+});
+
+test("planThreads: 2 to 4, labels, ids, assignments, every thread a clip; the outcome is the last clip's verdict in the manifest", async () => {
+ const m = (await deckManifest()) as VideoManifest;
+ const g = groundingInputOf(await kit("reports/basic.report.json"));
+ const at = (id: string) => m.timeline.findIndex((e) => e.id === id);
+ const clips = ["c01", "c02", "c03", "c04", "c05", "c06", "c07"].map((id) => clip(id, at(id), null));
+ const unit = { clips, g, dropFlips: false };
+ const one = planThreads({ threads: [{ id: "a", label: "The bakery" }], assign: [{ clip: "c01", thread: "a" }] }, unit, m);
+ assert.match(one.problems.join(" "), /1 thread\(s\): 2 to 4/);
+ const bad = planThreads(
+ {
+ threads: [
+ { id: "bakery", label: "The bakery" },
+ { id: "bakery", label: "The bakery again" },
+ { id: "x y!", label: "A label that is much too long for the rail" },
+ ],
+ assign: [
+ { clip: "c01", thread: "bakery" },
+ { clip: "c99", thread: "bakery" },
+ { clip: "c02", thread: "nowhere" },
+ { clip: "c03", thread: "bakery" },
+ { clip: "c03", thread: "x y!" },
+ ],
+ },
+ unit,
+ m,
+ );
+ const all = [...bad.problems, ...bad.threadProblems.flat()].join(" | ");
+ assert.match(all, /the id bakery is listed twice/);
+ assert.match(all, /the label is 42 characters \(at most 32\)/);
+ assert.match(all, /c99 is not a clip of the cut/);
+ assert.match(all, /c02 is put in nowhere, which is not a listed thread/);
+ assert.match(all, /c03 is put in two threads \(bakery, x-y\)/);
+ // The outcome: code's, from the manifest — c07 (CONTRADICTED) is the bakery's last clip; c06 (NOT_FOUND) the contest's.
+ const good = planThreads(
+ {
+ threads: [{ id: "bakery", label: "The bakery" }, { id: "contest", label: "The contest" }],
+ assign: ["c01", "c02", "c03", "c07"].map((c) => ({ clip: c, thread: "bakery" })).concat(["c04", "c05"].map((c) => ({ clip: c, thread: "contest" }))),
+ },
+ unit,
+ m,
+ );
+ assert.deepEqual(good.problems, []);
+ assert.deepEqual(good.list, [
+ { id: "bakery", label: "The bakery", outcome: { verdict: "CONTRADICTED" } },
+ { id: "contest", label: "The contest", outcome: { verdict: "PARTLY" } },
+ ]);
+ const after = JSON.parse(JSON.stringify(m));
+ after.render.chrome.threads = { list: good.list };
+ for (const e of after.timeline) if (good.clips[e.id]) e.thread = good.clips[e.id];
+ assert.deepEqual([...validateThreads({ list: good.list }), ...validateThreadEntries(after)], []);
+});
+
+test("youtube's checks: lengths, one line, links, third person, names and numbers, quotes word for word", async () => {
+ const g = groundingInputOf(await kit("reports/basic.report.json"));
+ assert.deepEqual(titleProblems("What the baker of Synth Kitchen says about the bakery", g).hard, []);
+ assert.match(titleProblems("x".repeat(101), g).hard.join(" "), /101 characters \(at most 100\)/);
+ assert.match(titleProblems("Synth Kitchen in 2027", g).hard.join(" "), /number 2027 is not in the report/);
+ assert.match(titleProblems("What Gordon says about the bakery", g).hard.join(" "), /name “Gordon” is not in the report/);
+ assert.match(summaryProblems("I would never sell it, she says.", g).hard.join(" "), /the narrator is third person/);
+ assert.deepEqual(summaryProblems('She says "I would never sell the bakery to a chain" on the bread day.', g).hard, []);
+ assert.match(summaryProblems('She says "I will sell the bakery".', g).hard.join(" "), /is not what a cited clip says, word for word/);
+ assert.match(summaryProblems("See 0:15 for the bakery.", g).hard.join(" "), /no links, timestamps/);
+ assert.match(summaryProblems("a ".repeat(YOUTUBE_SUMMARY_MAX), g).hard.join(" "), /at most 900/);
+});
+
+// ─── the tasks, over the fake ollama ───
+
+test("flips refuses a cut with no deck, and one with threads unless forced over drafted threads — which it then replaces, and says so", async () => {
+ const basic = await project(await kit("manifests/basic.video.manifest.json"));
+ const none = await flips(basic.input(), basic.deps);
+ assert.equal(none.status, "failed");
+ assert.match(none.summary, /drawn by the on-screen deck \(render\.chrome\), and this cut has none/);
+
+ // The full manifest's threads are hand-written: the operator's, refused even forced.
+ const full = await project(await kit("manifests/full.video.manifest.json"));
+ assert.match((await flips(full.input(), full.deps)).summary, /share the left panel: the threads are the operator's/);
+ assert.match((await flips(full.input({ force: true }), full.deps)).summary, /the threads are the operator's — remove them first/);
+
+ // Drafted threads: refused unforced, replaced forced.
+ const m = await kit("manifests/full.video.manifest.json");
+ m.drafted = { "render.chrome.threads": P };
+ const drafted = await project(m);
+ assert.match((await flips(drafted.input(), drafted.deps)).summary, /force replaces drafted threads/);
+ ol.push(jsonReply({ pairs: [{ topic: "The bakery's size", then: "c01", now: "c07" }] }));
+ const out = await flips(drafted.input({ force: true }), drafted.deps);
+ assert.equal(out.status, "done", `${out.summary}\n${drafted.lines.join("\n")}`);
+ const now = await drafted.manifestNow();
+ assert.equal(now.render.chrome.threads, undefined);
+ assert.ok(now.timeline.every((e: { thread?: string }) => e.thread === undefined), "every clip's thread goes with the list");
+ assert.equal(now.drafted["render.chrome.threads"], undefined);
+ assert.equal(now.drafted["render.chrome.flips"].task, "flips");
+ assert.ok(drafted.lines.some((l) => /the drafted threads were removed/.test(l)));
+});
+
+test("flips: a pair the other way round in a drafted cut swaps the clips (the timeline re-marked); a refused pair dropped when the rest stand", async () => {
+ const m = await deckManifest();
+ m.timeline = swapEntries(m.timeline, [["c01", "c07"]]);
+ m.drafted = { timeline: { ...P, model: "code" } };
+ const p = await project(m);
+ const bad = { pairs: [{ topic: "The bakery's size", then: "c01", now: "c07" }, { topic: "The lease and Gordon", then: "c04", now: "c02" }] };
+ ol.push(jsonReply(bad), jsonReply(bad));
+ const out = await flips(p.input(), p.deps);
+ assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`);
+ assert.equal(ol.remaining(), 0, "both attempts asked");
+ const now = await p.manifestNow();
+ assert.deepEqual(now.render.chrome.flips.pairs.map((x: { then: { entry: string }; now: { entry: string } }) => [x.then.entry, x.now.entry]), [["c01", "c07"]]);
+ assert.ok(now.timeline.findIndex((e: { id: string }) => e.id === "c01") < now.timeline.findIndex((e: { id: string }) => e.id === "c07"));
+ assert.equal(now.drafted.timeline.task, "flips", "the order is this draft's now");
+ assert.deepEqual([...validateFlips(now.render.chrome.flips), ...validateFlipEntries(now)], []);
+ const file = await p.draftNow("flips");
+ assert.match(JSON.stringify(file.units.flips!.chosen), /1 refused pair\(s\) dropped/);
+ assert.ok(p.lines.some((l) => /the cut's order changed so THEN plays first: c01 ⇄ c07/.test(l)));
+});
+
+test("flips: the operator's flips stand, forced or not; a forced draft is kept as an alternative", async () => {
+ const p = await project(await kit("manifests/flips.video.manifest.json"));
+ const skipped = await flips(p.input(), p.deps);
+ assert.equal(skipped.status, "failed");
+ assert.match(String((await p.draftNow("flips")).units.flips!.skipped), /the operator's/);
+ ol.push(jsonReply({ pairs: [{ topic: "The contest", then: "c04", now: "c07" }] }));
+ const out = await flips(p.input({ force: true }), p.deps);
+ assert.equal(out.status, "done", out.summary);
+ const now = await p.manifestNow();
+ assert.equal(now.render.chrome.flips.pairs[0].id, "chain", "the operator's pairs stand");
+ const alt = (await p.draftNow("flips")).alternatives;
+ assert.equal(alt.length, 1);
+ assert.equal(alt[0]!.reason, "operator");
+ assert.deepEqual((alt[0]!.value as { pairs: { topic: string }[] }).pairs.map((x) => x.topic), ["The contest"]);
+});
+
+test("threads: refused with operator's flips; forced over drafted flips replaces them; a refused thread dropped when two stand", async () => {
+ const op = await project(await kit("manifests/flips.video.manifest.json"));
+ assert.match((await threads(op.input({ force: true }), op.deps)).summary, /the flips are the operator's — remove them first/);
+ const m = await kit("manifests/flips.video.manifest.json");
+ m.drafted = { "render.chrome.flips": { ...P, task: "flips" } };
+ const p = await project(m);
+ const answer = {
+ threads: [{ id: "bakery", label: "The bakery" }, { id: "contest", label: "The contest" }, { id: "lease", label: "The lease and Gordon" }],
+ clips: [
+ { clip: "c01", thread: "bakery" },
+ { clip: "c02", thread: "bakery" },
+ { clip: "c04", thread: "contest" },
+ { clip: "c06", thread: "lease" },
+ { clip: "c07", thread: "bakery" },
+ ],
+ };
+ ol.push(jsonReply(answer), jsonReply(answer));
+ const out = await threads(p.input({ force: true }), p.deps);
+ assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`);
+ const now = await p.manifestNow();
+ assert.equal(now.render.chrome.flips, undefined);
+ assert.equal(now.drafted["render.chrome.flips"], undefined);
+ assert.deepEqual(now.render.chrome.threads.list.map((t: { id: string }) => t.id), ["bakery", "contest"]);
+ const thread = (id: string) => now.timeline.find((e: { id: string }) => e.id === id).thread;
+ assert.equal(thread("c06"), undefined, "the dropped thread's clip is in none");
+ assert.equal(thread("c07"), "bakery");
+ assert.deepEqual([...validateThreads(now.render.chrome.threads), ...validateThreadEntries(now)], []);
+ assert.ok(p.lines.some((l) => /the drafted flips were removed/.test(l)));
+});
+
+test("youtube: the better of two attempts, the summary's failing sentence removed; the operator's field kept and the draft an alternative", async () => {
+ const p = await project(await kit("manifests/basic.video.manifest.json"));
+ const title = "What the baker of Synth Kitchen says about the bakery";
+ ol.push(
+ jsonReply({ title, description: "Synth Kitchen's baker will not sell the bakery. We think she is right." }),
+ jsonReply({ title: `${title} in 2027`, description: "She will not sell." }),
+ );
+ const out = await youtube(p.input(), p.deps);
+ assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`);
+ const now = await p.manifestNow();
+ assert.deepEqual(now.publish.youtube, { title, description: "Synth Kitchen's baker will not sell the bakery." });
+ assert.equal(now.drafted["publish.youtube"].attempt, 2);
+
+ // The operator edits it (the mark goes): a forced re-draft is an alternative.
+ now.publish.youtube.title = "The baker on the bakery";
+ delete now.drafted;
+ await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(now));
+ ol.push(jsonReply({ title, description: "Synth Kitchen's baker will not sell the bakery." }));
+ const again = await youtube(p.input({ force: true }), p.deps);
+ assert.equal(again.status, "done", again.summary);
+ assert.equal((await p.manifestNow()).publish.youtube.title, "The baker on the bakery");
+ const alt = (await p.draftNow("youtube")).alternatives;
+ assert.equal(alt.at(-1)!.reason, "operator");
+ assert.equal((alt.at(-1)!.value as { title: string }).title, title);
+});
diff --git a/common/lib/report/draft/tasks/threads.ts b/common/lib/report/draft/tasks/threads.ts
@@ -0,0 +1,280 @@
+// TASK threads — the cut's clips grouped into the few lines of argument they
+// make (release 28, M5): `render.chrome.threads.list` and each clip's
+// `thread` key, drawn as the rail down the frame's left
+// (umtool/report-to-video/threads.mjs). A STEP on a done iteration, on the
+// media task scaffold (./media.ts): one unit, the whole field.
+//
+// The model names the threads (an id and a label) and puts each clip in one,
+// or in none. CODE checks it all:
+// - 2 to 4 threads (THREADS_TASK_COUNT; the rail takes up to
+// THREADS_LIMITS.threads[1]), ids that are ids and not listed twice,
+// labels of one line of at most THREADS_LIMITS.label characters whose
+// names and numbers are the report's (grounding);
+// - every assignment names a clip of the cut and a listed thread, a clip
+// is in one thread at most, every thread has a clip;
+// - a thread's OUTCOME is code's: the claim verdict its last clip carries in
+// the manifest (`claim.verdict`), when it carries one — the model never
+// sets a verdict;
+// - the result passes the build's own validateThreads and
+// validateThreadEntries (common's panels.mjs).
+// A thread failing a check is dropped with its clips when at least two stand
+// (the repair); the better of two attempts is kept. Applied: the list through
+// applyDraft, then every clip's `thread` set (or removed: a clip in no thread
+// has none) — the mark covers both.
+//
+// ONE LEFT PANEL: flips and threads share it. A cut with flips is refused —
+// unless `force` and the flips are a draft: then the threads replace them and
+// the log says so. A cut with no on-screen deck (`render.chrome`) is refused.
+
+import { applyDraft, clearDrafted, ownerOf } from "../../drafted.mjs";
+import { THREADS_LIMITS, flipsOn, validateThreadEntries, validateThreads } from "../../panels.mjs";
+import { VERDICTS } from "../../verdicts.mjs";
+import type { GroundingInput } from "../grounding";
+import type { VideoManifest } from "../videoOps";
+import { checkLine, clipFacts, clipLine, fitLines, type ClipFact } from "./clipEvidence";
+import { runMediaTask, type MediaAttempt, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media";
+import { TaskInputError } from "./run";
+import type { TaskDeps, TaskResult } from "./types";
+
+export type ThreadsInput = MediaTaskInput;
+
+/** How many threads a draft makes. */
+export const THREADS_TASK_COUNT = Object.freeze([2, 4] as const);
+
+export type ProposedThread = { id: string; label: string };
+export type ThreadsValue = { threads: ProposedThread[]; assign: { clip: string; thread: string }[] };
+
+export type Thread = { id: string; label: string; outcome?: { verdict: string } };
+export type ThreadsPlan = {
+ list: Thread[];
+ // clip id → thread id, for every clip in a thread.
+ clips: Record<string, string>;
+ threadProblems: string[][];
+ problems: string[];
+ soft: string[];
+};
+
+type ThreadsUnit = MediaUnit & {
+ manifest: VideoManifest;
+ clips: ClipFact[];
+ g: GroundingInput;
+ dropFlips: boolean;
+ chosen?: ThreadsPlan;
+};
+
+const EVIDENCE_BUDGET = 14_000;
+const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;
+const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim();
+
+/** A thread id as code keeps it: the model's, else made from its label. */
+export function threadId(raw: string, label: string, i: number): string {
+ const id = oneLine(raw);
+ if (ID_RE.test(id)) return id;
+ const base = (id || label).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, "");
+ return /^[a-z0-9]/.test(base) ? base : `thread-${i + 1}`;
+}
+
+/** A clip's verdict as the manifest has it (`claim.verdict`), or null. */
+const manifestVerdict = (m: VideoManifest, id: string): string | null => {
+ const v = (m.timeline.find((e) => e.type === "clip" && e.id === id)?.claim as { verdict?: unknown } | undefined)?.verdict;
+ return typeof v === "string" && (VERDICTS as readonly string[]).includes(v) ? v : null;
+};
+
+/** Code's reading of a proposal over this cut (pure). */
+export function planThreads(value: ThreadsValue, unit: Pick<ThreadsUnit, "clips" | "g" | "dropFlips">, manifest: VideoManifest): ThreadsPlan {
+ const [lo, hi] = THREADS_TASK_COUNT;
+ const problems: string[] = [];
+ const soft: string[] = [];
+ const n = value.threads.length;
+ if (n < lo || n > hi) problems.push(`${n} thread(s): ${lo} to ${hi}`);
+ const byClip = new Map(unit.clips.map((c) => [c.id, c]));
+ // The model's id → code's, and each thread's problems.
+ const ids = new Map<string, string>();
+ const seen = new Set<string>();
+ const threadProblems: string[][] = value.threads.map((t, i) => {
+ const bad: string[] = [];
+ const label = oneLine(t.label);
+ const id = threadId(t.id, label, i);
+ const w = `thread ${i + 1} (${id})`;
+ if (seen.has(id)) bad.push(`${w}: the id ${id} is listed twice`);
+ seen.add(id);
+ if (!ids.has(oneLine(t.id))) ids.set(oneLine(t.id), id);
+ if (!label) bad.push(`${w}: no label`);
+ else if (label.length > THREADS_LIMITS.label) bad.push(`${w}: the label is ${label.length} characters (at most ${THREADS_LIMITS.label})`);
+ else for (const h of checkLine(label, unit.g).hard) bad.push(`${w}: the label: ${h}`);
+ return bad;
+ });
+ const listed = value.threads.map((t, i) => threadId(t.id, oneLine(t.label), i));
+ const clips: Record<string, string> = {};
+ for (const a of value.assign) {
+ const clip = oneLine(a.clip);
+ const raw = oneLine(a.thread);
+ if (!raw) continue; // in no thread
+ const t = ids.get(raw) ?? (listed.includes(raw) ? raw : null);
+ if (!byClip.has(clip)) problems.push(`${clip || "(none)"} is not a clip of the cut`);
+ else if (!t) problems.push(`${clip} is put in ${raw}, which is not a listed thread`);
+ else if (clips[clip] !== undefined && clips[clip] !== t) problems.push(`${clip} is put in two threads (${clips[clip]}, ${t})`);
+ else clips[clip] = t;
+ }
+ listed.forEach((id, i) => {
+ if (!Object.values(clips).includes(id)) threadProblems[i]!.push(`thread ${i + 1} (${id}) has no clip`);
+ });
+ // The outcome: the verdict its last clip (in the cut's order) carries.
+ const list: Thread[] = value.threads.map((t, i) => {
+ const id = listed[i]!;
+ const mine = unit.clips.filter((c) => clips[c.id] === id).sort((a, b) => a.index - b.index);
+ const verdict = mine.length ? manifestVerdict(manifest, mine.at(-1)!.id) : null;
+ return { id, label: oneLine(t.label), ...(verdict ? { outcome: { verdict } } : {}) };
+ });
+ if (!problems.length && !threadProblems.some((x) => x.length)) {
+ // The build's own checks, on the cut as it will be.
+ const after = JSON.parse(JSON.stringify(manifest)) as VideoManifest & { render?: { chrome?: Record<string, unknown> } };
+ if (after.render?.chrome) {
+ if (unit.dropFlips) delete after.render.chrome.flips;
+ after.render.chrome.threads = { list };
+ }
+ setClipThreads(after, clips);
+ problems.push(...validateThreads({ list }), ...validateThreadEntries(after));
+ }
+ return { list, clips, threadProblems, problems, soft };
+}
+
+/** Every clip's `thread`: the one it is in, or none. */
+export function setClipThreads(m: VideoManifest, clips: Record<string, string>) {
+ for (const e of m.timeline) {
+ if (e.type !== "clip") continue;
+ if (clips[e.id]) e.thread = clips[e.id];
+ else delete e.thread;
+ }
+}
+
+const allProblems = (p: ThreadsPlan) => [...p.problems, ...p.threadProblems.flat()];
+
+export function threadsSystem(): string {
+ const [lo, hi] = THREADS_TASK_COUNT;
+ return (
+ "You group the clips of a short evidence video into threads: the few lines of argument the clips make, drawn as a " +
+ `rail of cards beside the footage. Rules: (1) ${lo} to ${hi} threads; (2) each thread has an id (letters, digits ` +
+ `and -) and a label of at most ${THREADS_LIMITS.label} characters in plain words, no quotation marks, no first ` +
+ "person, nothing the evidence does not say; (3) put each clip in at most one thread, by its id from the list; a " +
+ "clip that fits none is left out; (4) every thread has at least one clip; (5) you never write a verdict or an " +
+ "outcome."
+ );
+}
+
+export const THREADS_SPEC: MediaTaskSpec<ThreadsUnit, ThreadsValue, ThreadsInput> = {
+ task: "threads",
+ noun: "thread rail",
+ async units(ctx: MediaContext<ThreadsInput>) {
+ const m = ctx.manifest as VideoManifest & { render?: { chrome?: unknown } };
+ if (!m.render?.chrome || typeof m.render.chrome !== "object") {
+ throw new TaskInputError("threads are drawn by the on-screen deck (render.chrome), and this cut has none — turn the deck on first");
+ }
+ let dropFlips = false;
+ if (flipsOn(m.render)) {
+ const owner = ownerOf(m, { field: "render.chrome.flips" });
+ if (!ctx.input.force || owner === "operator") {
+ throw new TaskInputError(
+ "this cut has flips (render.chrome.flips), and flips and threads share the left panel" +
+ (owner === "operator" ? ": the flips are the operator's — remove them first" : ": force replaces drafted flips"),
+ );
+ }
+ dropFlips = true;
+ }
+ const clips = await clipFacts(m, ctx.report, null, { dates: false });
+ if (clips.length < THREADS_TASK_COUNT[0]) {
+ return [{ id: "threads", skipped: `${clips.length} clip(s): ${THREADS_TASK_COUNT[0]} threads need at least ${THREADS_TASK_COUNT[0]}` }];
+ }
+ return [{ id: "threads", target: { field: "render.chrome.threads" }, label: "Threads", manifest: m, clips, g: ctx.grounding, dropFlips }];
+ },
+ schema: () => ({
+ type: "object",
+ properties: {
+ threads: {
+ type: "array",
+ items: { type: "object", properties: { id: { type: "string" }, label: { type: "string" } }, required: ["id", "label"] },
+ },
+ clips: {
+ type: "array",
+ items: { type: "object", properties: { clip: { type: "string" }, thread: { type: "string" } }, required: ["clip", "thread"] },
+ },
+ },
+ required: ["threads", "clips"],
+ }),
+ system: () => threadsSystem(),
+ user(u, ctx) {
+ const r = ctx.report as { title?: string; summary?: string | null };
+ const ev = fitLines(u.clips.map((c) => clipLine(c, { date: false })), EVIDENCE_BUDGET);
+ return (
+ `Report: ${r.title ?? ""}` +
+ (r.summary ? `\n${String(r.summary).slice(0, 600)}` : "") +
+ `\n\nThe cut's clips, in order (id (chapter): "quote" — the claim it stands for):\n${ev.text}` +
+ (ev.omitted ? `\n(${ev.omitted} more clip(s) not shown)` : "") +
+ '\n\nName the threads, then give every clip its thread ("" for none).'
+ );
+ },
+ parse(answer) {
+ const a = answer as { threads?: unknown; clips?: unknown } | null;
+ if (!Array.isArray(a?.threads)) throw new Error("no threads list in the answer");
+ const objs = (v: unknown) => (Array.isArray(v) ? v : []).filter((x): x is Record<string, unknown> => !!x && typeof x === "object");
+ return {
+ threads: objs(a.threads).map((t) => ({ id: oneLine(t.id), label: oneLine(t.label) })),
+ assign: objs(a.clips).map((c) => ({ clip: oneLine(c.clip), thread: oneLine(c.thread) })),
+ };
+ },
+ check(value, u) {
+ const plan = planThreads(value, u, u.manifest);
+ return { hard: allProblems(plan), soft: plan.soft };
+ },
+ // The best attempt's threads that pass, with their clips, when at least two stand.
+ repair(attempts, u) {
+ let best: MediaAttempt<ThreadsValue> | null = null;
+ for (const a of attempts) {
+ if (!a.value) continue;
+ const plan = planThreads(a.value, u, u.manifest);
+ const keepIdx = plan.list.map((_, i) => i).filter((i) => !plan.threadProblems[i]?.length).slice(0, THREADS_TASK_COUNT[1]);
+ const keep = new Set(keepIdx.map((i) => plan.list[i]!.id));
+ const v: ThreadsValue = {
+ threads: keepIdx.map((i) => ({ id: plan.list[i]!.id, label: plan.list[i]!.label })),
+ assign: Object.entries(plan.clips)
+ .filter(([, t]) => keep.has(t))
+ .map(([clip, thread]) => ({ clip, thread })),
+ };
+ if (v.threads.length < THREADS_TASK_COUNT[0]) continue;
+ const again = planThreads(v, u, u.manifest);
+ if (allProblems(again).length) continue;
+ if (!best || v.threads.length > best.value!.threads.length) {
+ best = { value: v, hard: [], soft: [...again.soft, `${a.value.threads.length - v.threads.length} refused thread(s) dropped`] };
+ }
+ }
+ return best;
+ },
+ toField(value, u) {
+ u.chosen = planThreads(value, u, u.manifest);
+ return { list: u.chosen.list };
+ },
+ apply(manifest, u, value, provenance, force, ctx) {
+ const res = applyDraft(manifest, { field: "render.chrome.threads", value, provenance, force });
+ if (!res.applied) return res;
+ setClipThreads(manifest, u.chosen?.clips ?? {});
+ const m = manifest as VideoManifest & { render?: { chrome?: Record<string, unknown> } };
+ if (u.dropFlips && m.render?.chrome) {
+ delete m.render.chrome.flips;
+ clearDrafted(m, { field: "render.chrome.flips" });
+ ctx.handle.log(" the drafted flips were removed: flips and threads share the left panel");
+ }
+ return res;
+ },
+ describe(v, u) {
+ const plan = planThreads(v, u, u.manifest);
+ const count = (id: string) => Object.values(plan.clips).filter((t) => t === id).length;
+ return (
+ plan.list.map((t) => `${t.label} (${count(t.id)} clip(s)${t.outcome ? `, ${t.outcome.verdict}` : ""})`).join("; ") +
+ (u.dropFlips ? " — replaces the drafted flips" : "")
+ );
+ },
+};
+
+export async function threads(input: ThreadsInput, deps: TaskDeps): Promise<TaskResult> {
+ return runMediaTask(THREADS_SPEC, input, deps);
+}
diff --git a/common/lib/report/draft/tasks/youtube.ts b/common/lib/report/draft/tasks/youtube.ts
@@ -0,0 +1,160 @@
+// TASK youtube — the upload's title and summary (release 28, M6):
+// `publish.youtube { title, description }`. A STEP on a done iteration, on the
+// media task scaffold (./media.ts): one unit, the whole field.
+//
+// The model writes the title and ONE summary paragraph; the build composes
+// out/youtube.txt from them (umtool/report-to-video/youtube.mjs: the chapters
+// from its own chapter list, a moment link per cited clip), so the summary
+// leaves room for those under YouTube's 5000. CODE checks:
+// - the title is one line of at most PUBLISH_YOUTUBE_LIMITS.title
+// characters; the summary one paragraph of at most YOUTUBE_SUMMARY_MAX;
+// - grounded (./grounding.ts, ./clipEvidence.ts checkLine): every name and
+// number is the evidence's (the report's title, summary, sections, claims
+// and quotes, the cut's title and subtitle); no stock phrase; third person
+// (Q1: a first-person word outside quotation marks is refused); words in
+// quotation marks only when a cited quote says them word for word;
+// - no links, timestamps or chapter list: those are code's.
+// A summary failing a check loses its failing sentences when what is left
+// stands (the repair); the better of two attempts is kept.
+
+import { PUBLISH_YOUTUBE_LIMITS } from "../../drafted.mjs";
+import { sentencesOf, type GroundingInput } from "../grounding";
+import type { VideoManifest } from "../videoOps";
+import { checkLine, fitLines } from "./clipEvidence";
+import { runMediaTask, type MediaAttempt, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media";
+import type { TaskDeps, TaskResult } from "./types";
+
+export type YoutubeInput = MediaTaskInput;
+export type YoutubeValue = { title: string; description: string };
+
+/** The summary's limit: room under YouTube's 5000 for the chapters and the sources. */
+export const YOUTUBE_SUMMARY_MAX = 900;
+
+type YoutubeUnit = MediaUnit & { g: GroundingInput; evidence: string };
+
+const EVIDENCE_BUDGET = 12_000;
+const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim();
+const stripCites = (s: string) => s.replace(/\[([^\]]*)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "");
+
+const LINK = /https?:\/\/|www\.|\b\d{1,2}:\d{2}\b|#\w/;
+
+/** The title's problems. */
+export function titleProblems(title: string, g: GroundingInput): { hard: string[]; soft: string[] } {
+ const hard: string[] = [];
+ if (!title) hard.push("the title: empty");
+ else if (title.length > PUBLISH_YOUTUBE_LIMITS.title) hard.push(`the title is ${title.length} characters (at most ${PUBLISH_YOUTUBE_LIMITS.title})`);
+ if (LINK.test(title)) hard.push("the title: no links, timestamps or hashtags");
+ const r = title ? checkLine(title, g, { quotes: true }) : { hard: [], soft: [] };
+ return { hard: [...hard, ...r.hard.map((h) => `the title: ${h}`)], soft: r.soft.map((s) => `the title: ${s}`) };
+}
+
+/** The summary's problems. */
+export function summaryProblems(text: string, g: GroundingInput): { hard: string[]; soft: string[] } {
+ const hard: string[] = [];
+ if (!text) hard.push("the summary: empty");
+ else if (text.length > YOUTUBE_SUMMARY_MAX) hard.push(`the summary is ${text.length} characters (at most ${YOUTUBE_SUMMARY_MAX})`);
+ if (LINK.test(text)) hard.push("the summary: no links, timestamps, chapters or hashtags — the build adds the chapters and the sources");
+ const r = text ? checkLine(text, g, { quotes: true }) : { hard: [], soft: [] };
+ return { hard: [...hard, ...r.hard.map((h) => `the summary: ${h}`)], soft: r.soft.map((s) => `the summary: ${s}`) };
+}
+
+export function youtubeSystem(): string {
+ return (
+ "You write the YouTube title and the summary paragraph of the description for a short evidence video made from a " +
+ `cited report. Rules: (1) the title is one line of at most ${PUBLISH_YOUTUBE_LIMITS.title} characters: plain and ` +
+ "specific, no clickbait, no all-caps, no emoji; (2) the summary is one paragraph of at most " +
+ `${YOUTUBE_SUMMARY_MAX} characters saying what the video shows and what the evidence found; (3) third person: you ` +
+ "describe what the speaker said, never as the speaker (no I, me, my, we, us or our outside quotation marks); (4) every " +
+ "name and number comes from the evidence, and nothing goes beyond it; (5) words in quotation marks only when a quote " +
+ "below says them word for word; (6) no links, timestamps, chapter list or hashtags: the chapters and the sources are " +
+ "added after it."
+ );
+}
+
+/** The evidence a title and summary may draw on, and its grounding (the cut's title and subtitle added). */
+function evidenceOf(ctx: MediaContext<YoutubeInput>): { text: string; g: GroundingInput } {
+ const r = ctx.report as {
+ title?: string;
+ summary?: string | null;
+ sections?: { title?: string; claims?: { text?: string; verdict?: string }[] | null }[];
+ citations?: Record<string, { quote?: string; label?: string; date?: string } | undefined> | null;
+ };
+ const m = ctx.manifest as VideoManifest;
+ const head = [`Report title: ${r.title ?? ""}`];
+ if (m.title && m.title !== r.title) head.push(`Video title: ${m.title}`);
+ if (m.subtitle) head.push(`Video subtitle: ${m.subtitle}`);
+ if (r.summary) head.push(`Report summary: ${oneLine(r.summary).slice(0, 1200)}`);
+ const lines: string[] = [];
+ for (const s of r.sections ?? []) {
+ const claims = (s.claims ?? []).map((c) => ` - ${oneLine(stripCites(c.text ?? "")).slice(0, 220)}${c.verdict ? ` [${c.verdict}]` : ""}`);
+ if (!claims.length) continue;
+ lines.push(`Section: ${s.title ?? ""}`, ...claims);
+ }
+ const ev = fitLines(lines, EVIDENCE_BUDGET);
+ const quotes = [...new Set(Object.values(r.citations ?? {}).map((c) => oneLine(c?.quote)).filter(Boolean))];
+ const q = fitLines(quotes.map((x) => `- "${x.slice(0, 200)}"`), 4000);
+ return {
+ text:
+ `${head.join("\n")}\n\nWhat it found:\n${ev.text}` +
+ (ev.omitted ? `\n(${ev.omitted} more line(s) not shown)` : "") +
+ (q.text ? `\n\nQuotes (the only words you may put in quotation marks):\n${q.text}` : ""),
+ g: { ...ctx.grounding, reference: [ctx.grounding.reference, m.title ?? "", m.subtitle ?? ""].join("\n") },
+ };
+}
+
+export const YOUTUBE_SPEC: MediaTaskSpec<YoutubeUnit, YoutubeValue, YoutubeInput> = {
+ task: "youtube",
+ noun: "YouTube text",
+ units(ctx) {
+ const { text, g } = evidenceOf(ctx);
+ return [{ id: "youtube", target: { field: "publish.youtube" }, label: "YouTube title and summary", g, evidence: text }];
+ },
+ schema: () => ({
+ type: "object",
+ properties: { title: { type: "string" }, description: { type: "string" } },
+ required: ["title", "description"],
+ }),
+ system: () => youtubeSystem(),
+ user: (u) => `${u.evidence}\n\nWrite the title and the summary.`,
+ parse(answer) {
+ const a = answer as { title?: unknown; description?: unknown } | null;
+ return {
+ title: oneLine(a?.title).replace(/^["“]+|["”]+$/g, ""),
+ // One paragraph: line breaks are spaces.
+ description: oneLine(a?.description),
+ };
+ },
+ check(v, u) {
+ const t = titleProblems(v.title, u.g);
+ const d = summaryProblems(v.description, u.g);
+ return { hard: [...t.hard, ...d.hard], soft: [...t.soft, ...d.soft] };
+ },
+ // A clean title, with the summary's failing sentences removed (never
+ // rewritten) and cut to the limit at a sentence.
+ repair(attempts, u) {
+ let best: MediaAttempt<YoutubeValue> | null = null;
+ for (const a of attempts) {
+ if (!a.value || titleProblems(a.value.title, u.g).hard.length) continue;
+ const kept: string[] = [];
+ for (const s of sentencesOf(a.value.description)) {
+ if (summaryProblems(s, u.g).hard.length) continue;
+ if ([...kept, s].join(" ").length > YOUTUBE_SUMMARY_MAX) break;
+ kept.push(s);
+ }
+ const description = kept.join(" ");
+ if (!description) continue;
+ const v = { title: a.value.title, description };
+ const again = summaryProblems(description, u.g);
+ if (again.hard.length) continue;
+ if (!best || description.length > best.value!.description.length) {
+ best = { value: v, hard: [], soft: [...titleProblems(v.title, u.g).soft, ...again.soft, "trimmed: failing or overlong sentences removed"] };
+ }
+ }
+ return best;
+ },
+ describe: (v) => `${v.title} — ${v.description.slice(0, 120)}${v.description.length > 120 ? "…" : ""}`,
+};
+
+export async function youtube(input: YoutubeInput, deps: TaskDeps): Promise<TaskResult> {
+ return runMediaTask(YOUTUBE_SPEC, input, deps);
+}
diff --git a/common/lib/report/panels.d.mts b/common/lib/report/panels.d.mts
@@ -0,0 +1,20 @@
+// Types for ./panels.mjs (release 28, M4/M5): the flips' and the threads'
+// limits and validators. See the module's header.
+
+export type FlipSide = { entry: string; when: string; words: string };
+export type FlipPair = { id: string; topic: string; then: FlipSide; now: FlipSide };
+export type Flips = { pairs: FlipPair[] };
+export type ThreadOutcome = { verdict: string; label?: string };
+export type Thread = { id: string; label: string; outcome?: ThreadOutcome };
+export type Threads = { list: Thread[] };
+
+export const FLIPS_LIMITS: Readonly<{ pairs: readonly [number, number]; topic: number; when: number; words: number }>;
+export const THREADS_LIMITS: Readonly<{ threads: readonly [number, number]; label: number; outcome: number }>;
+
+export function flipsOn(render: unknown): boolean;
+export function validateFlips(f: unknown, where?: string): string[];
+export function validateFlipEntries(manifest: unknown): string[];
+export function threadsOn(render: unknown): boolean;
+export function validateThreads(t: unknown, where?: string): string[];
+export function threadOf(entry: unknown): string | null;
+export function validateThreadEntries(manifest: unknown): string[];
diff --git a/common/lib/report/panels.mjs b/common/lib/report/panels.mjs
@@ -0,0 +1,180 @@
+// THE LEFT PANEL'S RULES — THE one copy of what a cut's flips
+// (`render.chrome.flips`) and threads (`render.chrome.threads`, each clip's
+// `thread`) may be: their limits and their validators (release 28, M4/M5:
+// moved here from umtool/report-to-video/flips.mjs and threads.mjs, which
+// re-export them unchanged, so the flips and threads draft tasks check
+// exactly what the build refuses).
+//
+// Plain JS (with ./panels.d.mts for TypeScript) for the reason
+// ./verdicts.mjs is: umtool's report-to-video scripts are `.mjs` run by bare
+// `node`, and the draft tasks are TypeScript. PURE: no fs.
+//
+// The two share the frame's left side: a cut has one or the other
+// (umtool's deck.mjs validateChrome refuses both).
+
+import { VERDICTS } from "./verdicts.mjs";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+// ─── flips ───
+
+/** The limits: pairs, a topic's, a `when`'s and a side's words' characters. */
+export const FLIPS_LIMITS = Object.freeze({ pairs: Object.freeze([1, 24]), topic: 32, when: 18, words: 110 });
+
+const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;
+const oneLineMax = (v, max) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v) && v.length <= max;
+
+/** Is the flips panel on: a `render.chrome.flips` with at least one pair. */
+export function flipsOn(render) {
+ const f = render?.chrome?.flips;
+ return isObj(f) && Array.isArray(f.pairs) && f.pairs.length > 0;
+}
+
+/**
+ * Every reason `render.chrome.flips` cannot be built, as sentences. Shape
+ * only; `validateFlipEntries` checks the pairs against the timeline.
+ *
+ * @returns {string[]}
+ */
+export function validateFlips(f, where = "render.chrome.flips") {
+ if (f === undefined) return [];
+ if (!isObj(f)) return [`${where} must be an object`];
+ const errors = [];
+ for (const k of Object.keys(f)) if (k !== "pairs") errors.push(`${where}.${k} is not a flips setting`);
+ const [lo, hi] = FLIPS_LIMITS.pairs;
+ if (!Array.isArray(f.pairs) || f.pairs.length < lo || f.pairs.length > hi) return [...errors, `${where}.pairs must be ${lo} to ${hi} pairs`];
+ const ids = new Set();
+ f.pairs.forEach((p, i) => {
+ const w = `${where}.pairs[${i}]`;
+ if (!isObj(p)) { errors.push(`${w} must be an object`); return; }
+ for (const k of Object.keys(p)) if (!["id", "topic", "then", "now"].includes(k)) errors.push(`${w}.${k} is not a pair key`);
+ if (typeof p.id !== "string" || !ID_RE.test(p.id)) errors.push(`${w}.id must be letters, digits, _ or -`);
+ else if (ids.has(p.id)) errors.push(`${w}.id ${p.id} is listed twice`);
+ else ids.add(p.id);
+ if (!oneLineMax(p.topic, FLIPS_LIMITS.topic)) errors.push(`${w}.topic must be one line of at most ${FLIPS_LIMITS.topic} characters`);
+ for (const side of ["then", "now"]) {
+ const s = p[side];
+ const ws = `${w}.${side}`;
+ if (!isObj(s)) { errors.push(`${ws} must be an object`); continue; }
+ for (const k of Object.keys(s)) if (!["entry", "when", "words"].includes(k)) errors.push(`${ws}.${k} is not a side key`);
+ if (typeof s.entry !== "string" || !s.entry) errors.push(`${ws}.entry must name a timeline entry`);
+ if (!oneLineMax(s.when, FLIPS_LIMITS.when)) errors.push(`${ws}.when must be one line of at most ${FLIPS_LIMITS.when} characters`);
+ if (!oneLineMax(s.words, FLIPS_LIMITS.words)) errors.push(`${ws}.words must be one line of at most ${FLIPS_LIMITS.words} characters`);
+ }
+ });
+ return errors;
+}
+
+/**
+ * The pairs against the timeline: each side names an entry of the cut, a clip
+ * (not a teaser), the THEN side before the NOW side, and no entry in two pairs.
+ *
+ * @returns {string[]}
+ */
+export function validateFlipEntries(manifest) {
+ const render = manifest?.render ?? {};
+ if (!flipsOn(render)) return [];
+ const errors = [];
+ const at = new Map((manifest.timeline ?? []).map((e, i) => [e?.id, { e, i }]));
+ const used = new Map();
+ render.chrome.flips.pairs.forEach((p, i) => {
+ const w = `render.chrome.flips.pairs[${i}] (${p?.id ?? "?"})`;
+ const idx = {};
+ for (const side of ["then", "now"]) {
+ const id = p?.[side]?.entry;
+ const hit = at.get(id);
+ if (!hit) { errors.push(`${w}.${side}.entry ${id} is not in the timeline`); continue; }
+ if (hit.e.type === "teaser") errors.push(`${w}.${side}.entry ${id} is a teaser, not a clip`);
+ if (used.has(id)) errors.push(`${w}.${side}.entry ${id} is already in pair ${used.get(id)}`);
+ used.set(id, p.id);
+ idx[side] = hit.i;
+ }
+ if (idx.then !== undefined && idx.now !== undefined && idx.then >= idx.now) errors.push(`${w}: its THEN entry must come before its NOW entry`);
+ });
+ return errors;
+}
+
+// ─── threads ───
+
+/** The limits: how many threads, a label's and an outcome label's characters. */
+export const THREADS_LIMITS = Object.freeze({ threads: Object.freeze([1, 8]), label: 32, outcome: 24 });
+
+/** A thread id: letters, digits and `_ -`. */
+const THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;
+
+const oneLine = (v) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v);
+
+/** Is the rail on: a `render.chrome.threads` with at least one thread. */
+export function threadsOn(render) {
+ const t = render?.chrome?.threads;
+ return isObj(t) && Array.isArray(t.list) && t.list.length > 0;
+}
+
+/**
+ * Every reason `render.chrome.threads` cannot be built, as sentences (empty:
+ * it can). validateChrome calls this, so umtool's writer and the build refuse
+ * the same things.
+ *
+ * @returns {string[]}
+ */
+export function validateThreads(t, where = "render.chrome.threads") {
+ if (t === undefined) return [];
+ if (!isObj(t)) return [`${where} must be an object`];
+ const errors = [];
+ for (const k of Object.keys(t)) if (k !== "list") errors.push(`${where}.${k} is not a threads setting`);
+ const [lo, hi] = THREADS_LIMITS.threads;
+ if (!Array.isArray(t.list) || t.list.length < lo || t.list.length > hi) {
+ return [...errors, `${where}.list must be ${lo} to ${hi} threads`];
+ }
+ const seen = new Set();
+ t.list.forEach((th, i) => {
+ const w = `${where}.list[${i}]`;
+ if (!isObj(th)) { errors.push(`${w} must be an object`); return; }
+ for (const k of Object.keys(th)) if (!["id", "label", "outcome"].includes(k)) errors.push(`${w}.${k} is not a thread key`);
+ if (typeof th.id !== "string" || !THREAD_ID_RE.test(th.id)) errors.push(`${w}.id must be letters, digits, _ or -`);
+ else if (seen.has(th.id)) errors.push(`${w}.id ${th.id} is listed twice`);
+ else seen.add(th.id);
+ if (!oneLine(th.label) || th.label.length > THREADS_LIMITS.label) {
+ errors.push(`${w}.label must be one line of at most ${THREADS_LIMITS.label} characters`);
+ }
+ if (th.outcome !== undefined) {
+ const o = th.outcome;
+ if (!isObj(o)) { errors.push(`${w}.outcome must be an object`); return; }
+ for (const k of Object.keys(o)) if (!["verdict", "label"].includes(k)) errors.push(`${w}.outcome.${k} is not an outcome key`);
+ if (!VERDICTS.includes(o.verdict)) errors.push(`${w}.outcome.verdict must be one of ${VERDICTS.join(", ")}`);
+ if (o.label !== undefined && (!oneLine(o.label) || o.label.length > THREADS_LIMITS.outcome)) {
+ errors.push(`${w}.outcome.label must be one line of at most ${THREADS_LIMITS.outcome} characters`);
+ }
+ }
+ });
+ return errors;
+}
+
+/** The thread an entry belongs to, or null. */
+export function threadOf(entry) {
+ return typeof entry?.thread === "string" && entry.thread ? entry.thread : null;
+}
+
+/**
+ * Every `thread` in the timeline, checked against the list: it names a listed
+ * thread, it is not on a teaser, and every listed thread has a clip. The
+ * build refuses with these before it fetches.
+ *
+ * @returns {string[]}
+ */
+export function validateThreadEntries(manifest) {
+ const errors = [];
+ const render = manifest?.render ?? {};
+ const listed = threadsOn(render) ? new Set(render.chrome.threads.list.map((t) => t?.id)) : new Set();
+ const used = new Set();
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.thread === undefined || e?.thread === null) return;
+ const where = `timeline[${i}] (${e.id ?? "?"}).thread`;
+ if (typeof e.thread !== "string" || !e.thread) { errors.push(`${where} must be a thread id`); return; }
+ if (e.type === "teaser") { errors.push(`${where}: a teaser belongs to no thread`); return; }
+ if (!listed.has(e.thread)) { errors.push(`${where} ${e.thread} is not in render.chrome.threads.list`); return; }
+ used.add(e.thread);
+ });
+ for (const id of listed) if (!used.has(id)) errors.push(`render.chrome.threads: thread ${id} has no clip`);
+ return errors;
+}
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -31,6 +31,8 @@ import {
GENERATION_CUT_FIELD_DOCS,
GENERATION_SETTINGS_FIELD_DOCS,
GENERATION_WEB_FIELD_DOCS,
+ GENERATION_VERDICTS_FIELD_DOCS,
+ GENERATION_VERDICT_BAR_FIELD_DOCS,
SOCIAL_LINK_FIELD_DOCS,
SOCIAL_SETTINGS_FIELD_DOCS,
X_SOCIAL_SETTINGS_FIELD_DOCS,
@@ -289,6 +291,8 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
{ path: "generation.web", docs: GENERATION_WEB_FIELD_DOCS, defaults: fromObject(d.generation.web) },
{ path: "generation.research", docs: GENERATION_RESEARCH_FIELD_DOCS, defaults: fromObject(d.generation.research) },
{ path: "generation.cut", docs: GENERATION_CUT_FIELD_DOCS, defaults: fromObject(d.generation.cut) },
+ { path: "generation.verdicts", docs: GENERATION_VERDICTS_FIELD_DOCS, defaults: fromObject(d.generation.verdicts) },
+ { path: "generation.verdicts.bar", docs: GENERATION_VERDICT_BAR_FIELD_DOCS, defaults: fromObject(d.generation.verdicts.bar) },
],
};
}
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -88,6 +88,8 @@ export {
GENERATION_ROUTES_FIELD_DOCS,
GENERATION_SETTINGS_FIELD_DOCS,
GENERATION_WEB_FIELD_DOCS,
+ GENERATION_VERDICTS_FIELD_DOCS,
+ GENERATION_VERDICT_BAR_FIELD_DOCS,
type GenerationSettings,
} from "./generationSettings";
export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings";
diff --git a/common/package.json b/common/package.json
@@ -36,6 +36,7 @@
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
"./lib/ports.mjs": "./lib/ports.mjs",
"./lib/report/drafted.mjs": "./lib/report/drafted.mjs",
+ "./lib/report/panels.mjs": "./lib/report/panels.mjs",
"./lib/report/verdicts.mjs": "./lib/report/verdicts.mjs",
"./lib/toolProbe.mjs": "./lib/toolProbe.mjs",
"./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs",
diff --git a/common/publish/siteDelete.test.ts b/common/publish/siteDelete.test.ts
@@ -0,0 +1,152 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, symlink, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { acquirePublishLock } from "./stageLock";
+import { deleteSiteByPlan, formatSiteDeletePlan, planSiteDelete, siteDeleteBlocked, SiteDeleteRefusedError } from "./siteDelete";
+
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/siteDelete.test.ts
+//
+// Release 28 H5: a site's delete over a temp transcripts/ and export/ — never
+// the real ones.
+
+async function tree() {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "site-delete-"));
+ const paths = {
+ sitesDir: path.join(dir, "transcripts", "sites"),
+ channelsDir: path.join(dir, "transcripts", "channels"),
+ exportDir: path.join(dir, "export"),
+ exportBuildsDir: path.join(dir, "export", ".export-builds"),
+ exportSitesIndexDir: path.join(dir, "export", ".export-index", "sites"),
+ };
+ const site = async (id: string, json: Record<string, unknown> = {}, o: { reports?: string[]; builds?: boolean; deployed?: unknown } = {}) => {
+ const d = path.join(paths.sitesDir, id);
+ await mkdir(d, { recursive: true });
+ await writeFile(path.join(d, "site.json"), JSON.stringify({ siteId: id, siteTitle: id, channels: ["demo-channel"], audience: "private", ...json }));
+ await writeFile(path.join(d, "tags.json"), "{}");
+ for (const r of o.reports ?? []) {
+ await mkdir(path.join(d, "reports", r), { recursive: true });
+ await writeFile(path.join(d, "reports", r, "report.json"), "{}");
+ }
+ if (o.builds !== false) {
+ const b = path.join(paths.exportBuildsDir, id);
+ await mkdir(path.join(b, "out"), { recursive: true });
+ await writeFile(path.join(b, "built.json"), "{}");
+ await writeFile(path.join(b, "out", "index.html"), "<html></html>");
+ if (o.deployed) await writeFile(path.join(b, "deployed.json"), JSON.stringify(o.deployed));
+ await mkdir(path.join(paths.exportSitesIndexDir, id, "report-media"), { recursive: true });
+ await writeFile(path.join(paths.exportSitesIndexDir, id, "summary.json"), "{}");
+ }
+ };
+ // A channel the site's pool names: never touched.
+ await mkdir(path.join(paths.channelsDir, "demo-channel", "data", "v1"), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, "demo-channel", "config.json"), "{}");
+ await writeFile(path.join(paths.channelsDir, "demo-channel", "data", "v1", "transcript.json"), "{}");
+ return { dir, paths, site, done: () => rm(dir, { recursive: true, force: true }) };
+}
+
+test("a private site with nothing deployed: the plan, then its three directories go, and nothing else", async () => {
+ const t = await tree();
+ try {
+ await t.site("doomed");
+ await t.site("keeper");
+ const plan = await planSiteDelete("doomed", t.paths);
+ assert.equal(plan.exists, true);
+ assert.deepEqual(plan.refusals, []);
+ assert.deepEqual(plan.remove.map((e) => e.label), ["sites/doomed/", "export/.export-builds/doomed/", "export/.export-index/sites/doomed/"]);
+ assert.equal(plan.files, 5);
+ assert.ok(plan.kept.some((k) => k.what === "every channel's data"));
+ assert.match(formatSiteDeletePlan(plan)[0]!, /^delete site "doomed": 3 path\(s\)/);
+ const r = await deleteSiteByPlan("doomed", t.paths);
+ assert.equal(r.removed.length, 3);
+ assert.deepEqual(r.failed, []);
+ for (const e of plan.remove) assert.equal(existsSync(e.path), false, e.label);
+ // No park left behind; the other site and the channel untouched.
+ assert.deepEqual(await readdir(t.paths.sitesDir), ["keeper"]);
+ assert.deepEqual((await readdir(t.paths.exportBuildsDir)).filter((n) => !n.startsWith(".publish")), ["keeper"]);
+ assert.ok(existsSync(path.join(t.paths.exportSitesIndexDir, "keeper", "summary.json")));
+ assert.equal(await readFile(path.join(t.paths.channelsDir, "demo-channel", "data", "v1", "transcript.json"), "utf8"), "{}");
+ // Gone means gone: a second delete has no site to delete.
+ await assert.rejects(deleteSiteByPlan("doomed", t.paths), (e: unknown) => e instanceof SiteDeleteRefusedError && /no site "doomed"/.test(e.message));
+ } finally {
+ await t.done();
+ }
+});
+
+test("a deploy target, a recorded deploy or reports of its own refuse unless force; force deletes and keeps the remote", async () => {
+ const t = await tree();
+ try {
+ await t.site("public-one", { audience: "public", cloudflareProject: "demo-pages", siteUrl: "https://demo.example" }, {
+ reports: ["a-report"],
+ deployed: { v: 1, target: "public-one", previews: {}, production: { builtStampId: "x", builtAt: 1, kind: "production", url: "https://demo.example", at: 2, liveCheck: null } },
+ });
+ const plan = await planSiteDelete("public-one", t.paths);
+ assert.deepEqual(
+ plan.refusals.map((r) => [r.reason, r.forceable]),
+ [
+ ['it deploys to the Cloudflare Pages project "demo-pages"', true],
+ ["it holds 1 report (a-report), which go with it", true],
+ ["the publish state records a deploy: production (https://demo.example)", true],
+ ],
+ );
+ assert.equal(siteDeleteBlocked(plan), true);
+ assert.equal(siteDeleteBlocked(plan, true), false);
+ await assert.rejects(deleteSiteByPlan("public-one", t.paths), SiteDeleteRefusedError);
+ assert.ok(existsSync(path.join(t.paths.sitesDir, "public-one", "site.json")), "a refusal writes nothing");
+ assert.ok(plan.kept.some((k) => k.what === 'the Pages project "demo-pages"'));
+ const r = await deleteSiteByPlan("public-one", t.paths, { force: true });
+ assert.equal(r.removed.length, 3);
+ assert.equal(existsSync(path.join(t.paths.sitesDir, "public-one")), false);
+ } finally {
+ await t.done();
+ }
+});
+
+test("never forceable: no such site, a site dir that is a link, a publish stage running", async () => {
+ const t = await tree();
+ try {
+ const none = await planSiteDelete("ghost", t.paths);
+ assert.equal(none.exists, false);
+ assert.deepEqual(none.refusals, [{ reason: 'no site "ghost" (sites/ghost/site.json)', forceable: false }]);
+ // A link: refused, never followed.
+ await t.site("real", {}, { builds: false });
+ await symlink(path.join(t.paths.sitesDir, "real"), path.join(t.paths.sitesDir, "alias"));
+ const link = await planSiteDelete("alias", t.paths);
+ assert.equal(siteDeleteBlocked(link, true), true);
+ assert.match(link.refusals[0]!.reason, /sites\/alias is a link/);
+ // A publish stage holds the lock (this process, alive): refused, force or not.
+ await t.site("busy");
+ const lock = await acquirePublishLock(t.paths, { kind: "build-site", target: "other" });
+ try {
+ const busy = await planSiteDelete("busy", t.paths);
+ assert.deepEqual(busy.refusals.map((r) => r.forceable), [false]);
+ assert.match(busy.refusals[0]!.reason, /a publish stage is running: build-site other/);
+ await assert.rejects(deleteSiteByPlan("busy", t.paths, { force: true }), SiteDeleteRefusedError);
+ } finally {
+ await lock.release();
+ }
+ assert.ok(existsSync(path.join(t.paths.sitesDir, "busy", "site.json")));
+ assert.equal((await deleteSiteByPlan("busy", t.paths)).removed.length, 3);
+ assert.ok((await lstat(path.join(t.paths.sitesDir, "real"))).isDirectory(), "the link's target is kept");
+ } finally {
+ await t.done();
+ }
+});
+
+test("export/out linking into the site's bundle is named and kept", async () => {
+ const t = await tree();
+ try {
+ await t.site("linked");
+ await mkdir(t.paths.exportDir, { recursive: true });
+ const out = path.join(t.paths.exportDir, "out");
+ await symlink(path.join(t.paths.exportBuildsDir, "linked", "out"), out);
+ const plan = await planSiteDelete("linked", t.paths);
+ assert.ok(plan.kept.some((k) => k.what === "export/out" && /next build makes it again/.test(k.why)));
+ await deleteSiteByPlan("linked", t.paths);
+ assert.equal(await readlink(out), path.join(t.paths.exportBuildsDir, "linked", "out"));
+ } finally {
+ await t.done();
+ }
+});
diff --git a/common/publish/siteDelete.ts b/common/publish/siteDelete.ts
@@ -0,0 +1,250 @@
+// DELETE A SITE — a plan, then the delete (release 28 H5; `pnpm ops
+// delete-site`). The editor's Danger → Delete (`deleteSiteAction` →
+// lib/site.ts `deleteSite`) removes `sites/<id>/` and nothing else; this is
+// the scripted path, and it says first what goes, what stays and what refuses.
+//
+// WHAT A SITE IS ON DISK (the survey, 2026-10-13):
+// sites/<id>/ site.json (the pool: `channels`,
+// `citedChannels`), tags.json, charts,
+// its reports/ (each with history-git/)
+// export/.export-builds/<id>/ built.json, deployed.json (the publish
+// state), out/ (the last bundle),
+// public/ and .r2-staging/ (docker builds)
+// export/.export-index/sites/<id>/ compose's staging: report-media/,
+// report-exports/, summaries, stats
+// Nothing else names a site by id on disk: channel membership is site.json's
+// own pool (a channel's config holds no site list), the hub lists the sites
+// that are on disk with a siteUrl (its next build drops this one), and curated
+// tags' site scoping is read against the sites that exist.
+//
+// REMOVED: the three directories. KEPT, always: every channel's data (never
+// touched), the Cloudflare Pages project and anything already deployed to it
+// or to R2 (remote: a deploy, not a delete, takes a site off the edge), a
+// deployed hub until it is rebuilt, `export/out` when it links into this
+// site's bundle (the next build makes it again).
+//
+// REFUSED — forceable: a deploy target (`cloudflareProject`), a deploy the
+// publish state records (production, preview or local), a site that holds
+// reports (they go with it). Never forceable: no such site; its directory is a
+// link; a publish stage running (the publish lock held by a live holder).
+//
+// THE DELETE: under the site.json lock and the publish lock (taken without
+// waiting: a stage running refuses), the plan is made again, then each
+// directory is renamed aside to `.deleting-<id>-<stamp>` (not a site id, so no
+// reader lists it); the bulk is removed after the locks are let go.
+
+import type { Dirent } from "node:fs";
+import { lstat, readdir, readlink, rename, rm } from "node:fs/promises";
+import path from "node:path";
+import { withJsonFileLock } from "../lib/jsonFile-server";
+import type { Paths } from "../lib/paths";
+import { getSite, siteConfigFile, siteDir } from "../lib/site";
+import { isValidSiteId } from "../lib/siteSchema";
+import { exportOutPath } from "./build";
+import { holderIsGone, LockWaitCancelled, acquirePublishLock, describeHolder, readLockHolder, type LockHolder } from "./stageLock";
+import { readDeployedFile, targetDir } from "./stamps";
+
+export type SiteDeletePaths = Pick<Paths, "sitesDir" | "exportBuildsDir" | "exportSitesIndexDir" | "exportDir">;
+
+export type SiteDeleteEntry = { path: string; label: string; what: string; kind: "dir" | "link" | "file"; bytes: number; files: number };
+export type SiteDeleteKept = { what: string; why: string };
+export type SiteDeleteRefusal = { reason: string; forceable: boolean };
+
+export type SiteDeletePlan = {
+ siteId: string;
+ exists: boolean;
+ refusals: SiteDeleteRefusal[];
+ remove: SiteDeleteEntry[];
+ kept: SiteDeleteKept[];
+ bytes: number;
+ files: number;
+};
+
+export type SiteDeleteResult = { plan: SiteDeletePlan; removed: string[]; failed: { path: string; error: string }[] };
+
+export class SiteDeleteRefusedError extends Error {
+ constructor(
+ message: string,
+ readonly plan: SiteDeletePlan,
+ ) {
+ super(message);
+ this.name = "SiteDeleteRefusedError";
+ }
+}
+
+export function siteDeleteBlocked(plan: Pick<SiteDeletePlan, "refusals">, force = false): boolean {
+ return plan.refusals.some((r) => !force || !r.forceable);
+}
+
+async function measure(p: string): Promise<{ bytes: number; files: number }> {
+ let bytes = 0;
+ let files = 0;
+ const walk = async (dir: string) => {
+ let entries: Dirent[];
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const e of entries) {
+ const child = path.join(dir, e.name);
+ if (e.isDirectory()) await walk(child);
+ else {
+ const s = await lstat(child).catch(() => null);
+ if (s) {
+ bytes += s.isSymbolicLink() ? 0 : s.size;
+ files += 1;
+ }
+ }
+ }
+ };
+ await walk(p);
+ return { bytes, files };
+}
+
+async function lstatOrNull(p: string) {
+ return lstat(p).catch(() => null);
+}
+
+export async function planSiteDelete(
+ siteId: string,
+ paths: SiteDeletePaths,
+ o: { measure?: boolean; ownLock?: LockHolder } = {},
+): Promise<SiteDeletePlan> {
+ if (!isValidSiteId(siteId)) throw new Error(`Invalid site id: ${String(siteId)}`);
+ const sizes = o.measure !== false;
+ const refusals: SiteDeleteRefusal[] = [];
+ const remove: SiteDeleteEntry[] = [];
+ const kept: SiteDeleteKept[] = [{ what: "every channel's data", why: "a site's delete never touches a channel" }];
+ const dir = siteDir(paths as Paths, siteId);
+ const st = await lstatOrNull(dir);
+ const exists = !!st && (st.isSymbolicLink() || (st.isDirectory() && !!(await lstatOrNull(siteConfigFile(paths as Paths, siteId)))));
+ if (!exists) refusals.push({ reason: `no site "${siteId}" (sites/${siteId}/site.json)`, forceable: false });
+ else if (st!.isSymbolicLink()) refusals.push({ reason: `sites/${siteId} is a link (to ${await readlink(dir).catch(() => "?")}): refused, never followed`, forceable: false });
+
+ const add = async (p: string, label: string, what: string) => {
+ const s = await lstatOrNull(p);
+ if (!s) return;
+ if (s.isSymbolicLink()) {
+ remove.push({ path: p, label, what, kind: "link", bytes: 0, files: 0 });
+ return;
+ }
+ const m = sizes && s.isDirectory() ? await measure(p) : { bytes: s.isDirectory() ? 0 : s.size, files: s.isDirectory() ? 0 : 1 };
+ remove.push({ path: p, label, what, kind: s.isDirectory() ? "dir" : "file", ...m });
+ };
+
+ if (exists && !st!.isSymbolicLink()) {
+ const site = getSite(siteId, paths as Paths);
+ await add(dir, `sites/${siteId}/`, "the site: site.json, its pool and pages, tags, charts, reports");
+ if (site.cloudflareProject?.trim()) {
+ refusals.push({ reason: `it deploys to the Cloudflare Pages project "${site.cloudflareProject.trim()}"`, forceable: true });
+ kept.push({ what: `the Pages project "${site.cloudflareProject.trim()}"`, why: "remote: what it serves stays until the project is changed there" });
+ }
+ const reports = (await readdir(path.join(dir, "reports"), { withFileTypes: true }).catch(() => [] as Dirent[])).filter((e) => e.isDirectory()).map((e) => e.name);
+ if (reports.length) {
+ refusals.push({ reason: `it holds ${reports.length} report${reports.length === 1 ? "" : "s"} (${reports.slice(0, 5).join(", ")}${reports.length > 5 ? ", …" : ""}), which go with it`, forceable: true });
+ }
+ }
+ // The publish state and the last bundle.
+ const builds = targetDir(paths, siteId);
+ const deployed = await readDeployedFile(paths, siteId).catch(() => null);
+ if (deployed) {
+ const kinds = [
+ ...(deployed.production ? [`production (${deployed.production.url ?? "no url"})`] : []),
+ ...Object.keys(deployed.previews ?? {}).map((b) => `preview ${b}`),
+ ...(deployed.local ? ["local"] : []),
+ ];
+ if (kinds.length) {
+ refusals.push({ reason: `the publish state records a deploy: ${kinds.join(", ")}`, forceable: true });
+ kept.push({ what: "what was deployed", why: "remote (or the local site volume): a delete does not undeploy" });
+ }
+ }
+ await add(builds, `export/.export-builds/${siteId}/`, "its publish state (built.json, deployed.json) and last bundle");
+ await add(path.join(paths.exportSitesIndexDir, siteId), `export/.export-index/sites/${siteId}/`, "compose's staging for it (report media and exports, summaries, stats)");
+ // export/out linking into this site's bundle: named, kept.
+ const out = exportOutPath(paths);
+ const outLink = await readlink(out).catch(() => null);
+ if (outLink) {
+ const target = path.resolve(path.dirname(out), outLink);
+ if (target === builds || target.startsWith(builds + path.sep)) {
+ kept.push({ what: "export/out", why: `it links to this site's bundle (${target}); the next build makes it again` });
+ }
+ }
+ kept.push({ what: "a deployed hub", why: "it lists the site until it is rebuilt (the next hub build drops it)" });
+ // A publish stage running: never forceable.
+ const holder = await readLockHolder(paths);
+ const mine = o.ownLock && holder && holder.pid === o.ownLock.pid && holder.since === o.ownLock.since && holder.host === o.ownLock.host;
+ if (holder && !mine && !holderIsGone(holder)) refusals.push({ reason: `a publish stage is running: ${describeHolder(holder)}`, forceable: false });
+
+ return {
+ siteId,
+ exists,
+ refusals,
+ remove,
+ kept,
+ bytes: remove.reduce((s, e) => s + e.bytes, 0),
+ files: remove.reduce((s, e) => s + e.files, 0),
+ };
+}
+
+export async function deleteSiteByPlan(siteId: string, paths: SiteDeletePaths, o: { force?: boolean; now?: Date } = {}): Promise<SiteDeleteResult> {
+ const first = await planSiteDelete(siteId, paths);
+ if (siteDeleteBlocked(first, o.force)) {
+ throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: ${first.refusals.map((r) => r.reason).join("; ")}`, first);
+ }
+ const stamp = (o.now ?? new Date()).toISOString().replace(/[-:.]/g, "");
+ const parked: string[] = [];
+ // The publish lock, without waiting: a stage that started since the plan refuses.
+ let lock: Awaited<ReturnType<typeof acquirePublishLock>>;
+ try {
+ lock = await acquirePublishLock(paths, { kind: "delete-site", target: siteId }, { signal: AbortSignal.timeout(1500), pollMs: 250 });
+ } catch (e) {
+ if (e instanceof LockWaitCancelled) {
+ const again = await planSiteDelete(siteId, paths, { measure: false });
+ throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: a publish stage is running`, again);
+ }
+ throw e;
+ }
+ try {
+ await withJsonFileLock(siteConfigFile(paths as Paths, siteId), async () => {
+ const plan = await planSiteDelete(siteId, paths, { measure: false, ownLock: lock.holder });
+ if (siteDeleteBlocked(plan, o.force)) {
+ throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: ${plan.refusals.map((r) => r.reason).join("; ")}`, plan);
+ }
+ for (const e of plan.remove) {
+ if (e.kind === "link") {
+ await rm(e.path, { force: true });
+ parked.push(e.path);
+ continue;
+ }
+ const aside = path.join(path.dirname(e.path), `.deleting-${siteId}-${stamp}`);
+ await rename(e.path, aside);
+ parked.push(aside);
+ }
+ });
+ } finally {
+ await lock.release();
+ }
+ const removed: string[] = [];
+ const failed: { path: string; error: string }[] = [];
+ for (const p of parked) {
+ try {
+ await rm(p, { recursive: true, force: true });
+ removed.push(p);
+ } catch (e) {
+ failed.push({ path: p, error: (e as Error).message });
+ }
+ }
+ return { plan: first, removed, failed };
+}
+
+const fmt = (n: number) => (n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KiB` : n < 1024 ** 3 ? `${(n / 1024 ** 2).toFixed(1)} MiB` : `${(n / 1024 ** 3).toFixed(1)} GiB`);
+
+export function formatSiteDeletePlan(plan: SiteDeletePlan, o: { force?: boolean } = {}): string[] {
+ const blocked = siteDeleteBlocked(plan, o.force);
+ const out = [`delete site "${plan.siteId}": ${plan.remove.length} path(s), ${fmt(plan.bytes)} in ${plan.files} file(s)${blocked ? " — REFUSED" : ""}`];
+ for (const r of plan.refusals) out.push(` refused${r.forceable ? (o.force ? " (force answers it)" : " (unless force)") : ""}: ${r.reason}`);
+ for (const e of plan.remove) out.push(` remove ${e.label} ${e.what}, ${e.kind === "link" ? "a link" : `${fmt(e.bytes)} in ${e.files} file(s)`}`);
+ for (const k of plan.kept) out.push(` keep ${k.what}: ${k.why}`);
+ return out;
+}
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -20,7 +20,7 @@ transcript, channel or person goes in these fixtures, ever.
| `archiveOrg/fakeArchiveOrg.mjs` | A fake archive.org on loopback: `/advancedsearch.php` (every word of `q` in an item's identifier, title or subject; `*` all) and `/metadata/<id>` over invented items (`ITEMS`: a show's episodes with an original, a derivative and a JSON file, a restricted item, an audio tape). `ia.fetch` sends `https://archive.org/…` to it, for `new ArchiveOrgClient({ fetch: ia.fetch })`; `busyTimes` answers 429 first. |
| `draft/manifests/full`, `flips` | Release 28: every media field a draft task writes, as the build accepts it today — per-entry `onscreen`, a narrated card, a teaser, `claim` verdicts, `render.chrome.threads` with a `thread` per clip (`full`), or `render.chrome.flips` (`flips`: one THEN/NOW pair over clips of different dates). Hand-written, not derived; `umtool/report-to-video/fixtures-r28.test.mjs` keeps them lint-clean. |
| `draft/reports/ruled.report.json` | Release 28: a synthetic fact-check whose claims carry verdicts standing for operator rulings — every verdict at least once, each cited quote a cue of the corpus. The verdict bench's tests read it. |
-| `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. |
+| `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`; release 28's `flips`, `threads` and `youtube`, each with a `note` saying what it is run over and why its first answer is refused), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. |
| `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 at S0, the `paragraphs` manifest showed two owed bugs: the title card had no `foot`, and
diff --git a/common/testing/draft/runs/flips.json b/common/testing/draft/runs/flips.json
@@ -0,0 +1,21 @@
+{
+ "task": "flips",
+ "model": "qwen3:8b",
+ "note": "Over the full manifest with its threads taken off (a deck, no left panel) and the basic report. The first answer is refused (a pair of one day; a number the report does not have) and re-asked; the second is the S0 flips manifest's pair.",
+ "turns": [
+ {
+ "message": {
+ "role": "assistant",
+ "content": "{\"pairs\": [{\"topic\": \"The bakery's size\", \"then\": \"c07\", \"now\": \"c01\"}, {\"topic\": \"The contest in 2027\", \"then\": \"c04\", \"now\": \"c05\"}]}"
+ },
+ "done": true
+ },
+ {
+ "message": {
+ "role": "assistant",
+ "content": "{\"pairs\": [{\"topic\": \"The bakery's size\", \"then\": \"c01\", \"now\": \"c07\"}]}"
+ },
+ "done": true
+ }
+ ]
+}
diff --git a/common/testing/draft/runs/threads.json b/common/testing/draft/runs/threads.json
@@ -0,0 +1,21 @@
+{
+ "task": "threads",
+ "model": "qwen3:8b",
+ "note": "Over the full manifest with its threads taken off and the basic report. The first answer is refused (a label naming someone the report does not; a thread with no clip) and re-asked; the second groups the clips as the S0 full manifest does, the lease clip in the contest thread.",
+ "turns": [
+ {
+ "message": {
+ "role": "assistant",
+ "content": "{\"threads\": [{\"id\": \"bakery\", \"label\": \"The bakery\"}, {\"id\": \"contest\", \"label\": \"The contest\"}, {\"id\": \"gordon\", \"label\": \"Talks with Gordon\"}], \"clips\": [{\"clip\": \"c01\", \"thread\": \"bakery\"}, {\"clip\": \"c02\", \"thread\": \"bakery\"}, {\"clip\": \"c03\", \"thread\": \"bakery\"}, {\"clip\": \"c04\", \"thread\": \"contest\"}, {\"clip\": \"c05\", \"thread\": \"contest\"}, {\"clip\": \"c06\", \"thread\": \"\"}, {\"clip\": \"c07\", \"thread\": \"bakery\"}]}"
+ },
+ "done": true
+ },
+ {
+ "message": {
+ "role": "assistant",
+ "content": "{\"threads\": [{\"id\": \"bakery\", \"label\": \"The bakery\"}, {\"id\": \"contest\", \"label\": \"The contest\"}], \"clips\": [{\"clip\": \"c01\", \"thread\": \"bakery\"}, {\"clip\": \"c02\", \"thread\": \"bakery\"}, {\"clip\": \"c03\", \"thread\": \"bakery\"}, {\"clip\": \"c04\", \"thread\": \"contest\"}, {\"clip\": \"c05\", \"thread\": \"contest\"}, {\"clip\": \"c06\", \"thread\": \"contest\"}, {\"clip\": \"c07\", \"thread\": \"bakery\"}]}"
+ },
+ "done": true
+ }
+ ]
+}
diff --git a/common/testing/draft/runs/youtube.json b/common/testing/draft/runs/youtube.json
@@ -0,0 +1,21 @@
+{
+ "task": "youtube",
+ "model": "qwen3:8b",
+ "note": "Over the basic manifest and report. The first answer is refused (the summary speaks as the speaker; a link) and re-asked; the second is kept.",
+ "turns": [
+ {
+ "message": {
+ "role": "assistant",
+ "content": "{\"title\": \"What the baker of Synth Kitchen says about the bakery\", \"description\": \"She told us the bakery is not for sale. Watch it at https://synth.example.\"}"
+ },
+ "done": true
+ },
+ {
+ "message": {
+ "role": "assistant",
+ "content": "{\"title\": \"What the baker of Synth Kitchen says about the bakery\", \"description\": \"Synth Kitchen's baker says \\\"I would never sell the bakery to a chain\\\" and that she paid for the new mixer herself. In a later stream she says she did not enter the contest this year, and she will not talk about the lease.\"}"
+ },
+ "done": true
+ }
+ ]
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,9 @@
# Changelog
## [Unreleased]
+- **A research run on `auto` continues into its sweep by itself.** Once its acquisitions settle — every job it started has ended and nothing waits for your yes or no — the editor runs the same sweep **Continue into a sweep** would, on the run's own model, and the run's queue in umtool says **continued automatically by i<n>**. The caps hold: the sweep's per-job cap applies, and past the day's API total it is not started; the queue says so, and it is tried again the next day (UTC). A channel the run acquired into that is in no site build yet is left out of the sweep, with the warning "not in any build yet: <slug> — rebuild the site and continue again" on the queue and on the sweep; a run with nothing it could sweep waits for a newer build. `propose` and `limits` runs are still continued by you, and an editor booted idle (`ARCHILYZER_IDLE_BOOT`) continues nothing. Needs a restart of the editor and umtool.
+- **The editor drafts a report video's flips, threads and YouTube text.** `pnpm ops report-draft --json '{"task": "flips" | "threads" | "youtube", "article", "iteration", "model"?, "force"?}'` runs on a done iteration's video project. **Flips** pairs a clip with a later one on the same topic: the model picks the clips and names the topic, and the dates (the recordings'), the THEN/NOW order, the `when` lines and the words (the clip's own quote, word for word) are set by code. **Threads** groups the clips into 2 to 4 labelled threads; a thread's verdict stamp is its last clip's ruling, never the model's. **YouTube** writes `publish.youtube`'s title and a one-paragraph summary, with every name and number from the report, in the third person, quoting only what a clip says. Flips and threads share the left panel, so each refuses a cut that has the other unless forced over a draft of it, which it then replaces. Each drafted field carries its `drafted` mark and goes through the drafts review.
+- **A build writes the YouTube text: `out/youtube.txt`.** When the manifest has `publish.youtube`, the build writes the title, the summary, the chapters from its own chapter list, and a moment link for each cited clip, in cut order, each once. The chapters follow YouTube's rules: they start at 0:00, there are at least three, and each lasts ten seconds or more. A shorter one is folded into the one before it; when the list still falls short it is left out, and the build says why. umtool's project page shows the text with **Copy**. Before a build, it shows the same text without the chapters.
- **A drafted field of a report video says it was drafted, and a final build refuses it until it is approved.** A field a generation task writes (a card's narration today; on-screen text, a teaser's lines, the cut's order, the flips, the threads and the YouTube text as their tasks land) carries `drafted` — who drafted it, on which model, when — in the manifest. umtool shows **drafted by <model>** and its review state beside the field (the On-screen table, the teaser editor, the narration page) with **Approve** and **Reject** (with a note), and `/browse/<project>/review` (**Review drafts — N** on the project page) lists every drafted field of the cut and what a final build would refuse. Verdicts are kept in `drafts.review.json` beside the manifest, each on the value it was given on, so a re-draft or an edit needs approving again. A **final** build refuses a drafted field not approved (`--drafts-unreviewed` builds the unapproved anyway, never a rejected one); preview and fast builds only warn. A narration written by hand keeps the rule it had, and existing `narration.review.json` verdicts read as they were (new ones are written to `drafts.review.json`).
- **A draft never overwrites what you wrote.** A field with words in it and no `drafted` mark is yours: no generation task replaces it, even when asked to redraft. Its draft is kept aside in `<task>-draft.json` and shown under the field in umtool with **Use this**, which writes it as your own edit. Editing a drafted field in umtool makes it yours (its mark goes).
- **A report video manifest may carry `publish.youtube { title, description }`** — two strings, a title of at most 100 characters — for the YouTube text a later task drafts.
@@ -9,6 +12,11 @@
- **Report and video revisions on the local model are one request.** A revision on the local model no longer runs a tool conversation: it asks once for the whole batch of edits, over the report or cut trimmed to fit the model's 8k-token prompt (the sections or chapters the feedback names first; long quotes shortened and links cut to their labels in what the model reads, never in the report). Revisions on the Claude API are unchanged. Needs a restart of the editor.
- **A sweep can name its own extractor.** `pnpm ops report-draft --json '{"task": "sweep", …, "extractorModel": "claude-haiku-5-5"}'` reads that sweep's batches with the named Claude model instead of `settings.generation.models.extractor`; the MCP's `generate` takes it too. In umtool, a sweep on a Claude model shows an **extractor** choice on `/articles/new`, beside **Copy with model**, and beside a research run's **Continue into a sweep**. A sweep on the local model has no extractor and says so. Needs a restart of the editor and umtool.
- **Report draft jobs show their progress.** A **Report draft** job's row on /jobs now shows the model turns taken against the task's turn limit (a sweep, a revision, a research run; the repair round counted on), or the recordings read of the worklist for a sweep on the local model. `pnpm ops get job <id>` carries the same as `progress`. Needs a restart of the editor.
+- **The verdict bench: could a model propose a fact-check verdict well enough to review?** `archilyzer reports bench-verdicts --models claude-sonnet-5-5,claude-opus-5-5,qwen3:8b` asks each model about every claim of the fact-check articles that carries your verdict and a citation with a transcript — one claim per call, shown the claim, its quotes and the transcript a minute either side, never your findings or your verdict — and scores the answers against your rulings: agreement, CONTRADICTED and NOT_FOUND recall, PARTLY counted strictly and as close to CORROBORATED, beside a model that always says CORROBORATED, with the cost and the time each took. `--dry` lists the claims it would ask and what the run would cost, asking nothing. The run goes through the editor (`pnpm ops bench-verdicts`; a local model takes its turn on the GPU and is unloaded after), stops at `--max-usd` (default $5, the whole run), and a run with the same `--run` id carries on where it stopped. The results stay on this machine, in `.generation/bench/verdicts/`.
+- **umtool: `/bench` shows a bench run, and is where you set the bar.** Per model its agreement and recalls against the always-CORROBORATED baseline and its cost, the confusion matrix (your verdict against the model's), and every claim with each model's verdict and reason, disagreements first, filtered by model or by your verdict. The bar — the least agreement, CONTRADICTED recall and NOT_FOUND recall a model must reach — is saved into the editor's settings (`settings.generation.verdicts`), each model reads as passing or failing it, and verdict proposals will run only on the passing models you tick. Linked from `/articles` ("verdict bench").
+- **`pnpm ops delete-site {"id", "dryRun"?, "force"?}` deletes a site, plan first.** It removes the site's directory (its settings, pages, tags, charts and reports), its last build and publish state, and its export staging, and says what it keeps: every channel's data (never touched), the Pages project and anything already deployed (a delete does not undeploy), a deployed hub until it is rebuilt. A site with a Pages project, a recorded deploy or reports of its own is refused unless `force`; a missing site, a linked site directory or a publish stage running is refused whatever.
+- **A paused parakeet transcription no longer leaves its working files in the temp directory**, and each run clears what a crashed or killed run left there more than a day ago (unless another run still owns it).
+- **New settings key `generation.verdicts`** (SETTINGS.md): the verdict bench's bar (`agreement`, `contradictedRecall`, `notFoundRecall`, fractions) and the passing models you ticked (`models`, never set automatically).
- **Articles, iterations, report-video projects and takes can be deleted, and every delete shows its plan first.** `archilyzer reports delete <id>` prints what would go — each path with its size, what is kept and why, and anything that stops it — and deletes nothing until `--apply`; `--iteration <n>` deletes one iteration. Deleting an article removes its directory (report, video, history, notes, iterations), each iteration's video project under `settings.generation.projectsRoot` and its staged exports. A published article is refused unless `--force`, which unpublishes it first; an article with a running iteration is always refused. An iteration is refused while it is the current article or video, the one the article's report came from, running, or the parent or original of another iteration, and its number is never given out again. The usage ledger, the shared prepared-media cache and the corpus's git history are kept. The same deletes run over HTTP as `pnpm ops delete-article {id, force?, dryRun?}` and `pnpm ops delete-iteration {id, n, dryRun?}`, which answer a refusal as a 409 with the plan.
- **umtool: Delete article, `Delete i<n>`, Delete project and `Delete take <id>`.** Each button reads the plan, shows it (what goes with sizes, what is kept, what refuses) and deletes only on **Confirm delete**; **Keep it** closes it. **Delete article** is on an article's page (one in the making too) and returns to `/articles`, which says what went; `Delete i<n>` is on each iteration of the Iterations tab. **Delete project** on a report-video project removes its directory, and its `out/` or deliverables on the media drive when they are its own copy; it is refused while a job works in the project, for an article's current video, and — unless you tick **delete anyway** — for a project whose manifest names an article with a video attached. `Delete take <id>` removes `takes/<id>/`; the take whose manifest is the project's own needs **delete anyway**, and its verdict and notes are kept.
- **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor.
diff --git a/editor/app/api/ops/_autoContinue.ts b/editor/app/api/ops/_autoContinue.ts
@@ -0,0 +1,16 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { armResearchAutoContinue } from "yt-dlp-transcript-common/controller/researchAutoContinue";
+import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
+import { researchEditor } from "./_researchEditor";
+
+// AN `auto` RESEARCH RUN CONTINUES BY ITSELF (release 28 F1), armed by
+// instrumentation.ts below the idle gate: the job-end listener and a boot
+// scan now, the heartbeat's scan from then on. The deps are the report-draft
+// route's own, so a continuation is the job "Continue into a sweep" posts.
+// See common/controller/researchAutoContinue.ts.
+export function armAutoContinue(): boolean {
+ return armResearchAutoContinue(
+ { paths: getPaths(), corpusTools: (source) => createCorpusTools({ source }), researchEditor },
+ { log: (line) => console.log(line) },
+ );
+}
diff --git a/editor/app/api/ops/_benchVerdicts.test.ts b/editor/app/api/ops/_benchVerdicts.test.ts
@@ -0,0 +1,124 @@
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { CHANNELS } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+import { FAKE_KEY, startFakeAnthropic, toolTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs";
+import { jsonReply, startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs";
+import { enqueueVerdictBench, parseBenchVerdictsBody } from "yt-dlp-transcript-common/controller/benchVerdicts";
+import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { appendGenerationUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage";
+import { readBenchRun } from "yt-dlp-transcript-common/lib/report/draft/bench/index";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_benchVerdicts.test.ts"
+//
+// The `bench-verdicts` job (release 28 M7) end to end in this process: the
+// controller the route adapts, the ruled synthetic fact-check in a temp
+// article store, the synthetic recordings' cues on disk, the fake Anthropic
+// and ollama servers, a temp jobs dir, usage ledger and runs root.
+
+const RULED = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../common/testing/draft/reports/ruled.report.json");
+let tmp: string;
+let api: FakeAnthropic;
+let ol: FakeOllama;
+let paths: Paths;
+let gen: GenerationSettings;
+let root: string;
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "bench-verdicts-"));
+ api = await startFakeAnthropic();
+ ol = await startFakeOllama();
+ const keyFile = path.join(tmp, "anthropic.env");
+ await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`);
+ await chmod(keyFile, 0o600);
+ const report = JSON.parse(await readFile(RULED, "utf8"));
+ await mkdir(path.join(tmp, "reports", report.id), { recursive: true });
+ await writeFile(path.join(tmp, "reports", report.id, "report.json"), JSON.stringify(report));
+ for (const ch of CHANNELS) {
+ for (const r of ch.records) {
+ const rec = path.join(tmp, "channels", ch.slug, "data", r.id);
+ await mkdir(rec, { recursive: true });
+ await writeFile(path.join(rec, "transcript.cues.json"), JSON.stringify({ cues: r.cues }));
+ }
+ }
+ paths = {
+ jobsDir: path.join(tmp, ".jobs"),
+ articlesDir: path.join(tmp, "reports"),
+ exportIndexDir: path.join(tmp, ".export-index"),
+ channelsDir: path.join(tmp, "channels"),
+ generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"),
+ ollamaUrl: ol.url,
+ } as Paths;
+ root = path.join(tmp, ".generation", "bench", "verdicts");
+ gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20 } });
+});
+
+after(async () => {
+ await api.close();
+ await ol.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+const deps = (g: Partial<GenerationSettings> = {}) => ({ paths, root, settings: () => ({ generation: { ...gen, ...g } }) });
+
+test("the body: models required, the run id and reports checked, numbers as numbers", () => {
+ assert.throws(() => parseBenchVerdictsBody({}), /"models" is a list/);
+ assert.throws(() => parseBenchVerdictsBody({ models: [] }), /at least one model/);
+ assert.throws(() => parseBenchVerdictsBody({ models: ["m"], run: "../x" }), /"run" is a run id/);
+ assert.throws(() => parseBenchVerdictsBody({ models: ["m"], reports: ["Bad Id"] }), /"reports" is a list of article ids/);
+ assert.throws(() => parseBenchVerdictsBody({ models: ["m"], window: "60" }), /"window" is a number/);
+ assert.deepEqual(parseBenchVerdictsBody({ models: "a, b", maxUsd: 2, limit: 3 }), { models: ["a", "b"], maxUsd: 2, limit: 3 });
+});
+
+test("an API and a local model: a bench-verdicts job on draft:local, every answer on disk, the API spend in the ledger, ollama unloaded", async () => {
+ for (let i = 0; i < 7; i++) api.push(toolTurn("answer", { verdict: "CORROBORATED", reason: "she says so" }));
+ for (let i = 0; i < 7; i++) ol.push(jsonReply({ verdict: "NOT_FOUND", reason: "not in the window" }));
+ const out = await enqueueVerdictBench({ models: ["claude-sonnet-5-5", "qwen3:8b"], run: "vb-editor" }, deps());
+ assert.ok(out.result.ok && "run" in out, (out.result as { error?: string }).error);
+ assert.equal(out.run, "vb-editor");
+ const job = getRegistry().get(out.result.jobId)!;
+ assert.equal(job.kind, "bench-verdicts");
+ assert.equal(job.queueKey, "draft:local");
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ const log = await readFile(job.logPath, "utf8");
+ assert.equal(done.status, "done", log);
+ assert.match(log, /@@bench-verdicts \{"run":"vb-editor","status":"done","items":7,"skipped":1/);
+ assert.match(log, /unloaded qwen3:8b from ollama/);
+ assert.ok(!log.includes(FAKE_KEY), "the key is never in the log");
+ assert.deepEqual(ol.unloads, ["qwen3:8b"]);
+ const run = (await readBenchRun(root, "vb-editor"))!;
+ assert.equal(run.results.length, 14);
+ const [sonnet, qwen] = run.summary.score.models;
+ assert.equal(sonnet!.agreed, 2); // the two CORROBORATED
+ assert.equal(qwen!.agreed, 1); // the one NOT_FOUND
+ const rows = await readGenerationUsage(paths.generationUsageFile);
+ assert.deepEqual(rows.map((r) => [r.model, r.task, r.jobId]), [["claude-sonnet-5-5", "bench-verdicts", out.result.jobId]]);
+ assert.ok(rows[0]!.usd > 0);
+ assert.equal(api.requestHeaders.at(-1)!["x-api-key"], FAKE_KEY, "the key file's key");
+});
+
+test("API models only run on draft:api; past the day's cap an API run is refused, a local one is not", async () => {
+ api.push(toolTurn("answer", { verdict: "CORROBORATED", reason: "ok" }));
+ const one = await enqueueVerdictBench({ models: ["claude-haiku-4-5"], run: "vb-api", limit: 1 }, deps());
+ assert.ok(one.result.ok && "run" in one);
+ assert.equal(getRegistry().get(one.result.jobId)!.queueKey, "draft:api");
+ void one.result.stream.cancel();
+ assert.equal((await one.result.done).status, "done");
+ await appendGenerationUsage(paths.generationUsageFile, [
+ { at: new Date().toISOString(), day: utcDay(), jobId: "x", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 25 },
+ ]);
+ const refused = await enqueueVerdictBench({ models: ["claude-sonnet-5-5"], run: "vb-late" }, deps());
+ assert.equal(refused.result.ok, false);
+ assert.match((refused.result as { error: string }).error, /daily cap/);
+ ol.push(jsonReply({ verdict: "CORROBORATED", reason: "ok" }));
+ const local = await enqueueVerdictBench({ models: ["qwen3:8b"], run: "vb-local", limit: 1 }, deps());
+ assert.ok(local.result.ok && "run" in local);
+ void local.result.stream.cancel();
+ assert.equal((await local.result.done).status, "done");
+});
diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts
@@ -235,19 +235,24 @@ test("a local narration: draft:local, a step on the iteration, ollama unloaded w
assert.ok(m.timeline.find((e: { id: string }) => e.id === "the-bakery").narration.text);
});
-test("a media draft this build does not have: a step on the done iteration, failed at the job, saying so", async () => {
+test("a media draft (youtube, release 28 M6): a step on the done iteration, through the job, its field written", async () => {
// synth-basic i1 is done (the narration test above).
- const out = await enqueueReportDraft({ task: "youtube", article: "synth-basic", iteration: 1, model: "qwen3:8b", source }, deps());
+ const r = await run("youtube");
+ ol.push(...r.turns);
+ const out = await enqueueReportDraft({ task: "youtube", article: "synth-basic", iteration: 1, model: r.model, source }, deps());
assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error);
assert.equal(out.iteration, 1);
+ assert.equal(getRegistry().get(out.result.jobId)!.queueKey, "draft:local");
void out.result.stream.cancel();
const done = await out.result.done;
- assert.equal(done.status, "failed");
+ assert.equal(done.status, "done", await readFile(getRegistry().get(out.result.jobId)!.logPath, "utf8"));
const it = (await readIteration("synth-basic", 1, paths))!;
assert.equal(it.status, "done", "the iteration is left as it was");
const step = it.steps.find((s) => s.task === "youtube")!;
- assert.equal(step.status, "failed");
- assert.match(step.detail ?? "", /youtube is not implemented in this build/);
+ assert.equal(step.status, "done");
+ const m = JSON.parse(await readFile(path.join(projectOf(gen.projectsRoot, "synth-basic", 1), "video.manifest.json"), "utf8"));
+ assert.equal(m.publish.youtube.title, "What the baker of Synth Kitchen says about the bakery");
+ assert.equal(m.drafted["publish.youtube"].task, "youtube");
const notDone = await enqueueReportDraft({ task: "cut", article: "synth-basic", iteration: 9, model: "qwen3:8b", source }, deps());
assert.match((notDone.result as { error: string }).error, /has no iteration i9/);
});
diff --git a/editor/app/api/ops/bench-verdicts/route.ts b/editor/app/api/ops/bench-verdicts/route.ts
@@ -0,0 +1,29 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { BENCH_VERDICTS_BODY_KEYS, enqueueVerdictBench } from "yt-dlp-transcript-common/controller/benchVerdicts";
+import { jobResponse, ops } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { models, run?, reports?, window?, maxUsd?, limit? }
+// -> { ok: true, jobId, run }
+//
+// The verdict bench (release 28 M7), as a `bench-verdicts` job: every ruled
+// claim of the registry's fact-checks (or of `reports`) asked of each of
+// `models`, one claim per call, scored against the operator's rulings. On
+// `draft:local` when any model is local — every ollama call through the GPU
+// arbiter, ollama unloaded at the end — else `draft:api`. `maxUsd` caps the
+// whole run (default 5); an API run is refused past the day's cap. `run`
+// names a run to continue (its answered pairs are skipped). The results are
+// local-only: `.generation/bench/verdicts/<run>/` (umtool's /bench reads
+// them). `job cancel` stops it; the log ends `@@bench-verdicts {json}`.
+//
+// AN ADAPTER: the refusals are the controller's (controller/benchVerdicts.ts).
+export async function POST(request: Request) {
+ return ops(request, BENCH_VERDICTS_BODY_KEYS, async (body) => {
+ const out = await enqueueVerdictBench(body, { paths: getPaths() });
+ if (!out.result.ok || !("run" in out)) return jobResponse(out.result);
+ void out.result.stream.cancel();
+ return NextResponse.json({ ok: true, jobId: out.result.jobId, run: out.run });
+ });
+}
diff --git a/editor/app/api/ops/delete-site/route.ts b/editor/app/api/ops/delete-site/route.ts
@@ -0,0 +1,51 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { isValidSiteId } from "yt-dlp-transcript-common/lib/siteSchema";
+import {
+ SiteDeleteRefusedError,
+ deleteSiteByPlan,
+ planSiteDelete,
+ siteDeleteBlocked,
+} from "yt-dlp-transcript-common/publish/siteDelete";
+import { OpsInputError, ops, opsFail, optBool, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { id: string, force?: boolean, dryRun?: boolean }
+// -> { ok, applied, plan, removed?, failed? }
+//
+// DELETE A SITE (release 28 H5), plan first: `sites/<id>/` (site.json, its
+// pool and pages, tags, charts, reports), its publish state and last bundle
+// (`export/.export-builds/<id>/`) and compose's staging for it
+// (`export/.export-index/sites/<id>/`) — through publish/siteDelete.ts,
+// under the site.json lock and the publish lock. Channel data is never
+// touched; the Pages project, what was deployed and a deployed hub are kept
+// (remote: a delete does not undeploy). `dryRun` answers the plan and writes
+// nothing. Refused (409, with the plan): a site with a deploy target
+// (`cloudflareProject`), a deploy in its publish state, or reports of its own
+// — unless `force`; no such site, a site dir that is a link, or a publish
+// stage running — force or not.
+//
+// There is no undo, and transcripts/ is its own git repo — the only way back
+// for sites/<id>/ is a commit there.
+export async function POST(request: Request) {
+ return ops(request, ["id", "force", "dryRun"], async (body) => {
+ const id = reqString(body, "id");
+ if (!isValidSiteId(id)) throw new OpsInputError(`"${id}" is not a site id`);
+ const force = optBool(body, "force") === true;
+ const paths = getPaths();
+ try {
+ const plan = await planSiteDelete(id, paths);
+ if (siteDeleteBlocked(plan, force)) {
+ const why = plan.refusals.filter((r) => !force || !r.forceable).map((r) => r.reason);
+ return opsFail(`refused: ${why.join("; ")}`, plan.exists ? 409 : 404, { plan });
+ }
+ if (optBool(body, "dryRun") === true) return NextResponse.json({ ok: true, applied: false, plan });
+ const r = await deleteSiteByPlan(id, paths, { force });
+ return NextResponse.json({ ok: r.failed.length === 0, applied: true, plan: r.plan, removed: r.removed, failed: r.failed });
+ } catch (err) {
+ if (err instanceof SiteDeleteRefusedError) return opsFail(err.message, 409, { plan: err.plan });
+ throw err;
+ }
+ });
+}
diff --git a/editor/app/api/ops/research-approve/route.ts b/editor/app/api/ops/research-approve/route.ts
@@ -19,9 +19,10 @@ export const dynamic = "force-dynamic";
// their doors and queues; `approve: false` rejects them (`note`: why);
// - no `ids`: the run's state now (the umtool queue polls this).
// `research` is {article, iteration, status, phase, autonomy, limits, spent,
-// proposals, waitingOn: {approval, jobs}, continuedBy}. A run whose job is
-// still going is refused. The CONTINUATION is report-draft {task: "sweep",
-// iteration: <this run>}.
+// proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}. A run
+// whose job is still going is refused. The CONTINUATION is report-draft
+// {task: "sweep", iteration: <this run>}; an `auto` run's is asked by the
+// editor itself (release 28 F1, controller/researchAutoContinue.ts).
//
// AN ADAPTER: the rules are the controller's (controller/researchRuns.ts).
export async function POST(request: Request) {
diff --git a/editor/app/scheduler/heartbeat.ts b/editor/app/scheduler/heartbeat.ts
@@ -73,6 +73,18 @@ async function fire(generation: number): Promise<void> {
// already records its own outcome; the heartbeat just keeps beating.
}
+ // An `auto` research run whose acquisitions settled continues into its
+ // sweep (release 28 F1). A no-op unless instrumentation armed it (never on
+ // an idle boot). See common/controller/researchAutoContinue.ts.
+ try {
+ const { researchAutoContinueTick } = await import(
+ "yt-dlp-transcript-common/controller/researchAutoContinue"
+ );
+ await researchAutoContinueTick();
+ } catch {
+ // the scan records its own outcomes on the runs it reads
+ }
+
// Re-read the cadence each fire so a live settings change is honored without a
// restart. If it has been turned off (0), the loop simply stops here.
if (generation !== state.generation) return;
diff --git a/editor/e2e/backfill.spec.ts b/editor/e2e/backfill.spec.ts
@@ -512,9 +512,22 @@ test("a lane can be scoped to one operation from its console, and the scope is a
)
.toEqual({ enabled: true, operations: ["diarization"] });
- // Switch it back off so an armed lane does not bleed into the next spec.
- await lane.getByLabel("Enable auto-backfill").uncheck();
+ // Switch it back off so an armed lane does not bleed into the next spec —
+ // once the first save has SETTLED on the page (its "Saved.", the button
+ // back, nothing unsaved). Unchecking while it was still settling was the
+ // release 28 flake: the form could adopt the saved copy after the uncheck,
+ // and the second save then wrote the lane on again.
+ const enable = lane.getByLabel("Enable auto-backfill");
+ await expect(lane.getByRole("status")).toHaveText("Saved.");
+ await expect(lane.getByRole("button", { name: "Save policy" })).toBeEnabled();
+ await expect(lane.getByText("Unsaved changes")).toHaveCount(0);
+ await expect(enable).toBeChecked();
+ await enable.uncheck();
+ await expect(enable).not.toBeChecked();
+ await expect(lane.getByText("Unsaved changes")).toBeVisible();
await lane.getByRole("button", { name: "Save policy" }).click();
+ await expect(lane.getByRole("button", { name: "Save policy" })).toBeEnabled();
+ await expect(lane.getByText("Unsaved changes")).toHaveCount(0);
await expect.poll(laneArmed, { timeout: 30_000 }).toBe(false);
});
diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts
@@ -236,6 +236,17 @@ export async function register() {
/* a runner that fails to start must not block server readiness */
}
+ // AN `auto` RESEARCH RUN CONTINUES BY ITSELF (release 28 F1): the job-end
+ // listener and one scan of the research runs now; the heartbeat scans again
+ // on each beat. Below the idle gate: a continuation is a generation job.
+ // See common/controller/researchAutoContinue.ts.
+ try {
+ const { armAutoContinue } = await import("./app/api/ops/_autoContinue");
+ armAutoContinue();
+ } catch {
+ /* auto-continue that fails to arm must not block server readiness */
+ }
+
// NO SECOND RESUME HOOK. There used to be two more here, one per sweep, and
// each re-launched a corpus-wide pass from its own persisted flag. Both lanes
// are runner lanes now, so `startAutoRunnersIfEnabled` above resumes all four
diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts
@@ -456,3 +456,84 @@ test("revise-video on a local model: one ops batch over the trimmed cut", async
const m = JSON.parse(await readFile(path.join(projectOf(projectsRoot, "synth-basic", it.n), "video.manifest.json"), "utf8"));
assert.equal(m.timeline.find((e: { id: string }) => e.id === "the-bakery").heading, "About the bakery");
});
+
+// ─── release 28 M4–M6: flips, threads, youtube (lane E) ───
+
+// i1 done with the basic report and the FULL manifest with its threads taken
+// off: an on-screen deck with no left panel, seven clips over three recordings.
+async function deckCut(article = "synth-basic") {
+ const { projectDir } = await doneSweep(article, "basic", { manifest: true });
+ const m = JSON.parse(await readFile(path.join(DRAFT, "manifests", "full.video.manifest.json"), "utf8"));
+ delete m.render.chrome.threads;
+ for (const e of m.timeline) delete e.thread;
+ await writeFile(path.join(projectDir!, "video.manifest.json"), `${JSON.stringify(m, null, 2)}\n`);
+ return projectDir!;
+}
+
+const manifestOf = async (dir: string) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+
+test("flips: the pairs are code's — dates from the records, THEN before NOW, the quotes verbatim; the S0 flips shape (release 28 M4)", async () => {
+ await drainFake();
+ const r = await run("flips");
+ ol.push(...r.turns);
+ const dir = await deckCut();
+ const d = deps();
+ const out = await runTask({ task: "flips", article: "synth-basic", n: 1, model: r.model, projectsRoot }, d);
+ assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`);
+ const m = await manifestOf(dir);
+ const expected = JSON.parse(await readFile(path.join(DRAFT, "manifests", "flips.video.manifest.json"), "utf8")).render.chrome.flips;
+ const strip = (f: { pairs: { id: string }[] }) => f.pairs.map(({ id: _id, ...p }) => p);
+ assert.deepEqual(strip(m.render.chrome.flips), strip(expected), "one pair, c01 Jan 2026 → c07 Mar 2026, the quotes word for word");
+ assert.equal(m.drafted["render.chrome.flips"].task, "flips");
+ assert.equal(m.drafted["render.chrome.flips"].attempt, 2);
+ const draft = JSON.parse(await readFile(path.join(dir, "flips-draft.json"), "utf8"));
+ const first = draft.units.flips.attempts[0].hard.join(" | ");
+ assert.match(first, /c04 and c05 are of the same day \(2026-02-10\)/);
+ assert.match(first, /number 2027 is not in the report/);
+ // The dates came from the corpus records: the prompt shows them, the clips carry none.
+ const user = ol.requests.at(-1).messages[1].content as string;
+ assert.match(user, /- c01 \[2026-01-05\] \(chapter: The bakery\): "I would never sell the bakery to a chain"/);
+ assert.match(user, /- c07 \[2026-03-01\]/);
+ const step = (await readIteration("synth-basic", 1, paths))!.steps.find((s) => s.task === "flips")!;
+ assert.equal(step.status, "done");
+});
+
+test("threads: 2 to 4 threads, every clip's thread set, the outcomes from the manifest's verdicts (release 28 M5)", async () => {
+ await drainFake();
+ const r = await run("threads");
+ ol.push(...r.turns);
+ const dir = await deckCut();
+ const d = deps();
+ const out = await runTask({ task: "threads", article: "synth-basic", n: 1, model: r.model, projectsRoot }, d);
+ assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`);
+ const m = await manifestOf(dir);
+ assert.deepEqual(m.render.chrome.threads.list, [
+ { id: "bakery", label: "The bakery", outcome: { verdict: "CONTRADICTED" } },
+ { id: "contest", label: "The contest", outcome: { verdict: "NOT_FOUND" } },
+ ]);
+ const byId = Object.fromEntries(m.timeline.filter((e: { type: string }) => e.type === "clip").map((e: { id: string; thread?: string }) => [e.id, e.thread]));
+ assert.deepEqual(byId, { c01: "bakery", c02: "bakery", c03: "bakery", c04: "contest", c05: "contest", c06: "contest", c07: "bakery" });
+ assert.equal(m.drafted["render.chrome.threads"].task, "threads");
+ const draft = JSON.parse(await readFile(path.join(dir, "threads-draft.json"), "utf8"));
+ const first = draft.units.threads.attempts[0].hard.join(" | ");
+ assert.match(first, /name “Gordon” is not in the report/);
+ assert.match(first, /thread 3 \(gordon\) has no clip/);
+});
+
+test("youtube: the title and one summary paragraph, grounded and third person (release 28 M6)", async () => {
+ await drainFake();
+ const r = await run("youtube");
+ ol.push(...r.turns);
+ const { projectDir } = await doneSweep("synth-basic", "basic", { manifest: true });
+ const d = deps();
+ const out = await runTask({ task: "youtube", article: "synth-basic", n: 1, model: r.model, projectsRoot }, d);
+ assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`);
+ const m = await manifestOf(projectDir!);
+ assert.equal(m.publish.youtube.title, "What the baker of Synth Kitchen says about the bakery");
+ assert.match(m.publish.youtube.description, /^Synth Kitchen's baker says "I would never sell the bakery to a chain"/);
+ assert.equal(m.drafted["publish.youtube"].task, "youtube");
+ const draft = JSON.parse(await readFile(path.join(projectDir!, "youtube-draft.json"), "utf8"));
+ const first = draft.units.youtube.attempts[0].hard.join(" | ");
+ assert.match(first, /the summary: the narrator is third person \(“us”\)/);
+ assert.match(first, /no links, timestamps, chapters or hashtags/);
+});
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -9240,3 +9240,88 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
- **`report-draft {extractorModel}`** is a sweep's, a Claude id `isKnownApiModel` accepts; it replaces `generation.models.extractor` for that job.
- **A report-draft job's progress** is the task's: `TaskDeps.progress?({metric: "turns" | "cards" | "entries", current, total?})` → `JobProgress {metric, initial: 0, target, current}`. A task calls `h.progress(...)` (TaskHandle; a throwing listener is swallowed). Media tasks report `cards` / `entries` the same way.
+## Release 28 lane C: the verdict bench, site delete (verified 2026-10-13, branch `r28/bench-house`)
+
+- **A verdict bench run** lives in `<repo>/.generation/bench/verdicts/<run>/` (`benchRootOf(paths)` = the usage ledger's
+ directory + `bench/verdicts`; gitignored, local-only): `items.jsonl` (one `BenchItem` per ruled claim — key
+ `<article>/<claim>`, the claim text, quotes, windows, and the operator's `verdict`, the answer key), `results.jsonl`
+ (one `BenchResult` per (item, model): `verdict` or null with `failure` `parse`|`error`, `reason` ≤ 300 chars, ms, usd,
+ tokens) and `summary.json` (format `archilyzer-verdict-bench`, status `running|done|capped|cancelled|failed`,
+ `stopped`, params, `spentUsd`, `skipped`, `score`). Every file is rewritten whole, atomically; the same run id
+ resumes (answered pairs skipped, failures asked again). Readers re-score from items + results (`scoreBench`), never
+ trust `summary.score` alone. Code: `common/lib/report/draft/bench/` (`index.ts`; import `…/bench/index`, a directory
+ import does not resolve through the package exports).
+- **The bench runs as job kind `bench-verdicts`** (`controller/benchVerdicts.ts`, `POST /api/ops/bench-verdicts`): on
+ `draft:local` when any model is local (the GPU arbiter's `gpuGatedFetch`, ollama unloaded at the end), else
+ `draft:api`; refused past `caps.daily`; its API spend goes to the usage ledger as rows with `task: "bench-verdicts"`,
+ `article: ""`, `iteration: 0`. The cues are the local corpus's (`diskCuesOf`), not a build's. `archilyzer reports
+ bench-verdicts` is `--dry` (read only), through the editor (default), or `--here` (API models only).
+- **`settings.generation.verdicts` = `{bar: {agreement, contradictedRecall, notFoundRecall}, models: string[]}`**:
+ fractions 0..1 (all 0 = no bar), and the passing models the operator ticked on umtool's `/bench` (never set
+ automatically). umtool writes the whole block through the editor's settings action (a nested object replaces).
+ `passesBar(score, bar)` (`bench/score.ts`) is the one pass rule: strict agreement and the two recalls; a recall with
+ nothing ruled that way is not a miss.
+- **A site's delete** (`publish/siteDelete.ts`, `pnpm ops delete-site`) removes `sites/<id>/`,
+ `export/.export-builds/<id>/` and `export/.export-index/sites/<id>/`; nothing else on disk names a site by id
+ (channel membership is site.json's own pool). The editor's Danger → Delete (`deleteSiteAction` → `deleteSite`) still
+ removes `sites/<id>/` alone.
+## Release 28 F1: an `auto` research run continues by itself (verified 2026-10-14, branch `r28/research-f`)
+
+- **`maybeAutoContinue(article, n, deps)`** (`common/controller/researchAutoContinue.ts`, `deps` = `ReportDraftDeps`)
+ is the one function; it answers `{outcome: "continued", by, jobId?, warnings} | {outcome: "held" | "refused",
+ reason} | {outcome: "not-now", why, final?}` and is idempotent. Only `auto` continues by itself; `propose` and
+ `limits` are final not-nows. The continuation is `enqueueReportDraft({task: "sweep", article, iteration: n,
+ model: <the research run's own model>, channels: <the kept ones>})` — Continue's own path, so `markContinued`,
+ caps.sweep and the daily cap at the ask and at the job's turn are unchanged.
+- **The record** is `research.autoContinue` in the run's `iteration.json` (`AutoContinueRecord`,
+ `lib/report/draft/research/state.ts`): `{status: "claimed" | "continued" | "refused" | "held", at, by?, reason?,
+ warnings?, day?, buildsAt?}`, mirrored as `ResearchView.autoContinue` (research-approve's answer), plus a
+ `{kind: "auto-continue", outcome, …}` line in the run's `turns.jsonl`. **The claim is the once-only mark**, taken by
+ `updateIteration`'s function patch under the article store's lock; a claim is fresh for `CLAIM_STALE_MS` (10 min),
+ and a stale one with a sweep made after it (`parent` n) is recorded as the continuation. `refused` is retried
+ only on a later UTC day than `day`; `held` (nothing it would sweep is in any composed build) on a build newer than
+ `buildsAt` or a later day. A channel in no build (`listCorpusBuilds`) is left out with the warning `not in any
+ build yet: <slug> — rebuild the site and continue again`, also a failed `unbuilt channels` check on the sweep.
+- **The triggers.** `onJobEnd(listener)` (`common/jobs/registry.ts`, new): every job's end, once, on a later turn
+ (`setImmediate`) after `finalize`. `settle` in `researchRuns.ts` watches an `auto` run's pending job ids
+ (`watchResearchJobs` / `takeWatchedRun`, in-process, bounded at 2000); the listener continues a watched job's
+ run, and the end of a `report-draft` job or a site build (`SCAN_ON_END`) runs the scan. `scanAutoContinue(deps)` reads every article's iteration
+ dirs holding a `proposals.json` (a run finished with is remembered, not re-read), one scan at a time.
+ `armResearchAutoContinue(deps, {log?, env?, bootScan?})` arms the listener and a boot scan and refuses an idle
+ boot (false); `researchAutoContinueTick()` is the heartbeat's call (`editor/app/scheduler/heartbeat.ts` `fire`)
+ and returns null unarmed. The editor arms it in `instrumentation.ts` BELOW the idle gate, through
+ `editor/app/api/ops/_autoContinue.ts` (the report-draft route's deps).
+- **The heartbeat is off by default** (`syncScheduler.heartbeatSeconds` 0; the live `settings.json` has 0, verified
+ 2026-10-14): live, the job-end listener and the boot scan are the triggers, and a `refused` or `held` run is
+ retried only at the next end of a report-draft job or a site build, the next boot, or a heartbeat if one is
+ configured.
+
+## Release 28 lane E: flips, threads, the YouTube text (verified 2026-10-14, branch `r28/media-e`)
+
+- **The left panel's rules are common's** — `common/lib/report/panels.mjs` (+ `.d.mts`, exported as
+ `yt-dlp-transcript-common/lib/report/panels.mjs`): `FLIPS_LIMITS`, `flipsOn`, `validateFlips`,
+ `validateFlipEntries`, `THREADS_LIMITS`, `threadsOn`, `threadOf`, `validateThreads`, `validateThreadEntries`.
+ umtool's `report-to-video/flips.mjs` and `threads.mjs` re-export them unchanged; never copy them back.
+- **A flips pair is code's but for its clips and topic.** The `flips` task (`tasks/flips.ts`) dates each clip
+ (`tasks/clipEvidence.ts` `clipFacts`): the entry's `date`, else the corpus record's `uploadDate`
+ (`get_video_metadata` through `deps.corpus`), else the report citation's `date`. The earlier is THEN; one day is
+ no pair; `when` is `Mon YYYY`; `words` is the clip's quote (or the model's part of it, when the quote says exactly
+ that), cut at a word to `FLIPS_LIMITS.words` with `…`; the pair id is the topic slugged. A THEN that plays after its
+ NOW swaps the two clips' places only when `ownerOf(timeline)` is `"drafted"` and the flips will be applied (the
+ timeline is rewritten through `applyDraft` with the flips provenance), else the pair is refused.
+- **A thread's outcome is its last clip's `claim.verdict` in the manifest** (by timeline order), when it has one; the
+ `threads` task (`tasks/threads.ts`) makes 2 to 4 threads (`THREADS_TASK_COUNT`) and, once the list is applied, sets
+ every clip's `thread` (a clip in none has the key removed).
+- **One left panel:** `flips` refuses a cut with threads and `threads` one with flips, unless `force` and the other is
+ a draft: then the other's field, its clips' `thread` keys (for threads) and its mark are removed, and the log says
+ so. Both refuse a cut with no `render.chrome`.
+- **`publish.youtube` is drafted by `youtube`** (`tasks/youtube.ts`): title ≤ 100, one summary paragraph ≤
+ `YOUTUBE_SUMMARY_MAX` (900), `checkLine(…, {quotes: true})` grounding (words in quotation marks must be a cited
+ quote's, word for word), no links, timestamps or hashtags. **`checkLine` does not check a line's FIRST word as a
+ name** (it is the narration grounding, which skips each sentence's first word), so a topic, label or title that
+ starts with an unknown name passes that check.
+- **`out/youtube.txt`** (`youtube-<variant>.txt` for a variant other than `sourced`) is written by build-video after
+ every chapter mux (the full build, the deck build, `--rail-only`, `--chapters-only`; also under `--no-chapters`,
+ without chapters) when the manifest has a `publish.youtube` title. `muxChapters` returns `{chapters: [{start, end,
+ title}], total}`. The composition is `report-to-video/youtube.mjs` (`composeYoutubeText`, `youtubeChapters`,
+ `youtubeSources`, `momentLinkOf`, `youtubePreview`, `youtubeTextName`), exported as `umtool-report-to-video/youtube`.
diff --git a/plans/release-28.md b/plans/release-28.md
@@ -377,6 +377,319 @@ Gates: in the lane's totals below.
Not done here: the MCP's `sweep_plan` / `ask_plan` text (Claude Code's own /sweep) does not state `WHOLE_SENTENCE_QUOTE_RULE` (`mcp/src/instructions.ts` is not this lane's; one line where the claim-quotes and verbatim rules are).
+### Phase 1 merges (2026-10-13, orchestrator)
+
+`r28/framework` (M0) merged `172d07ae`; `r28/quality` (Q1–Q3, F2, F3) merged `900671ae`; `7e14a060` adds lane B's
+`WHOLE_SENTENCE_QUOTE_RULE` to the `/sweep` plan's extractor directive (`mcp/src/instructions.ts`). Gates at
+`7e14a060`: tsc clean; common 4041/4042 — `fetchPosts.test.ts` "a drain mid-page waits for the page's cursor…" failed
+once under load and passes 3/3 alone (a flake candidate); mcp 346/346; editor 290/290; `test:scripts` 871 + 3 skipped.
+### M7, as shipped (2026-10-13, lane C, `r28/bench-house`)
+
+The verdict bench: ruled fact-check claims asked of models one claim per call, scored against the operator's rulings.
+
+| Commit | What |
+| --- | --- |
+| `dc21f2c8` | `common/lib/report/draft/bench/` (`items.ts`, `prompt.ts`, `score.ts`, `store.ts`, `run.ts`, `index.ts`, `bench.test.ts`); `controller/benchVerdicts.ts`; job kind `bench-verdicts`; `POST /api/ops/bench-verdicts` (+ `_benchVerdicts.test.ts`); the ops ACTIONS row and help; `archilyzer reports bench-verdicts` (`bin/reports-bench-verdicts.ts` + test); `settings.generation.verdicts`; COMMANDS.md, SETTINGS.md, settings.json.example |
+| `c31bedd0` | umtool `/bench` (`app/bench/page.tsx`, `components/bench/BarForm.tsx`, `lib/bench.ts`, `/api/bench/bar`), the `/articles` link; e2e `verdict-bench.spec.ts` + `fixtures/bench-fixture.mjs` |
+| (this commit) | the records, FACTS, CHANGELOG |
+
+- **Items:** every claim of a `kind: "factcheck"` article (the registry's `listArticleDirs` / `articleFile` / `parseReport`)
+ with an operator `verdict` and a span citation whose recording has cues within ±`window` s (default 60) of the cited
+ span; overlapping windows of one recording merged. The rest are `skipped` with a reason (`no operator verdict`, `no
+ citation`, `no video or audio citation`, `no cited recording has cues around the cited seconds`). An item carries the
+ claim text, its quotes and windows, and the verdict (the answer key); `findings`, `gist`, `flag` and `title` are
+ never copied, and the prompt never reads the verdict.
+- **The call:** `structuredAnswer` with `{verdict: VERDICTS enum, reason}`; the system prompt is the five verdicts'
+ meanings and "judge only the transcript shown" (no example); the reason is cut at 300 chars in code. A local prompt
+ is held under 7 800 estimated tokens (the client's 8k less a margin) by dropping the cues farthest from a cited span
+ first; the claim and quotes are never trimmed.
+- **Where it runs (decided here):** not a `report-draft` (no iteration, no task) — a job of its own, `bench-verdicts`,
+ in the editor, because the GPU arbiter's holds are in-process there: any local model puts the run on `draft:local`
+ with `llmConfigOf(…, {onLog, signal})` (every ollama call through `gpuGatedFetch`) and ollama is unloaded at the end;
+ API-only runs go on `draft:api`. Calls are sequential. The day's cap refuses an API run at the ask and at its turn;
+ its spend is appended to the usage ledger (`task: "bench-verdicts"`). The CLI is `--dry` (offline, read only),
+ through the editor (`pnpm ops bench-verdicts`, the default), or `--here` (in process, API models only).
+- **The cap:** `maxUsd` (default 5, refused above 50) for the whole run, resumed spend included, checked before each
+ API call against the spend so far plus that call's estimate; past it the run ends `capped` with what it did. A model
+ with three errors in a row is stopped and the run goes on.
+- **Scoring (pure):** agreement (a failure counts as a miss), agreement with PARTLY ~ CORROBORATED, the 5×5 matrix (rows
+ operator) plus each row's unanswered, recall for CONTRADICTED, NOT_FOUND, PARTLY strict and adjacent, cost, latency
+ (mean, median, p90), parse failures and errors; the always-CORROBORATED baseline scored the same way. `passesBar`:
+ strict agreement and the two recalls (a recall with nothing ruled that way is not a miss).
+- **Results:** `.generation/bench/verdicts/<run>/{items.jsonl, results.jsonl, summary.json}`, gitignored (`/.generation/`),
+ every write atomic and whole; the same `--run` resumes (answered pairs skipped, failures asked again).
+- **umtool `/bench`:** the run picker; a tile per model and the baseline; the bar form (writes
+ `settings.generation.verdicts {bar, models}` whole through the editor's settings action; a model failing the typed bar
+ cannot be ticked); the confusion matrices; the items, disagreements first, filtered by model and by the operator's
+ verdict; the skipped list. Zero client JS but the form. Linked from `/articles` ("verdict bench"), the nav unchanged.
+- **Labels (contracts):** link `verdict bench`; regions `models`, `the bar`, `confusion`, `items`; tables `confusion
+ <model>`; form `bar` with spinbuttons `minimum agreement`, `minimum CONTRADICTED recall`, `minimum NOT_FOUND
+ recall`, checkboxes `use <model>`, button `Save the bar`, status `Saved.`; attributes `data-bench-run`,
+ `data-status`, `data-model`, `data-pass`, `data-metric`, `data-cell`, `data-item`, `data-disagree`, `data-run`.
+
+**The real run (the orchestrator's):**
+
+```
+pnpm archilyzer reports bench-verdicts --models claude-sonnet-5-5,claude-opus-5-5,qwen3:8b --max-usd 5 --run vb-r28 --wait
+```
+
+through an editor that has this branch (the route is new). Its `--dry` over the registry (read only, 2026-10-13): 147
+items from 2 fact-checks, 44 claims skipped (23 no operator verdict, 12 no citation, 9 no video or audio citation);
+ruled CORROBORATED 78, PARTLY 58, NOT_FOUND 6, CONTRADICTED 4, UNTESTABLE 1; estimate Sonnet 5.5 ~$1.29, Opus 5.5
+~$2.57, qwen $0 — ~$3.86 in all. With 4 CONTRADICTED and 6 NOT_FOUND items the two recalls move in steps of 25% and
+17%.
+
+### H1, as shipped (2026-10-13, lane C, `r28/bench-house`)
+
+| Commit | What |
+| --- | --- |
+| `66fd4a04` | `scripts/parakeet-stitch.mjs`: the pause path breaks out of the window loop and exits after the `finally`; the start-up sweep; `main()` only as a program; `scripts/parakeet-stitch.test.mjs` (3) |
+
+- **The sweep:** a `parakeet-stitch-*` dir in the tmpdir older than 24 h (its mtime; a running run's dir changes with
+ every window) is removed unless held. **Chosen: an owner file** (`owner.json`: pid and that process's start time from
+ `/proc/<pid>/stat`, so a reused pid is not the owner), written at creation. A `/proc` scan of open files and cwds alone
+ would not do: a run holds nothing in its tmp dir between two windows. A dir with no owner file (today's stale ones) is
+ held while any other parakeet-stitch process runs (its cmdline), or while any process has a file or its cwd in it.
+- Unit: the pause path (a fake parakeet-cli sends the SIGTERM mid-window) exits 0 with the window kept and no temp dir
+ left — red against the old script; the sweep removes an old unheld dir and keeps an owned, a held and a young one.
+- The 21 live stale dirs in `/tmp` are the orchestrator's to remove after merge.
+
+### H2, as shipped (2026-10-13, lane C, `r28/bench-house`)
+
+| Commit | What |
+| --- | --- |
+| `4e941835` | the three flakes |
+
+- **`relocateChannelMedia.test.ts` "reconcile: an extra and a changed file":** each test already has its own
+ `mkdtemp`; the cause was a directory mtime. Writing `stale.json` moved the target's `v1/` mtime, and when the setup
+ crossed a second boundary rsync (whole seconds) itemized `.d..t v1/` as a third difference. Both trees' directory
+ mtimes are pinned now. Proved with a forced 1.1 s delay: red before, green after.
+ - Found, not changed (not this lane's file): `relocateDir.ts` `diffTrees` reports a directory-mtime-only line as
+ "changed" in the reconcile sentence, which the verify (`DIR_MTIME_ONLY`) already ignores.
+- **`queue-lock.test.mjs` `--with` (:792), and "two weighted jobs" (:632), red in this branch's first run:** fixed holds
+ (700 ms, 1500 ms) raced the next run's start under parallel test files. The holding runs wait on a gate file the test
+ opens once what it checks has happened (capped at 20 s, so a wrong admission still fails the order assertion).
+- **`backfill.spec.ts` (:516):** the lane is unchecked only once the first save has settled on the page ("Saved.", the
+ button back, nothing unsaved, still checked), and the second save is seen to settle before the lane is polled.
+- Five runs each: `relocateChannelMedia.test.ts` 44/44 ×5; `queue-lock.test.mjs` 37/37 ×5; `backfill.spec.ts` 22/22 ×5
+ (1.8, 1.8, 2.0, 1.3 and 0.7 min).
+
+### H5, as shipped (code) (2026-10-13, lane C, `r28/bench-house`)
+
+| Commit | What |
+| --- | --- |
+| `8b11cb7d` | the plan and the delete, `POST /api/ops/delete-site`, the ACTIONS row and help, COMMANDS.md, the unit test |
+| `ebf9e60d` | moved to `common/publish/siteDelete.ts` (the architecture test: controller/ may not import publish/) |
+
+- **The survey — what a site leaves on disk:** `sites/<id>/` (site.json with its pool, tags.json, charts, reports with
+ their history-git), `export/.export-builds/<id>/` (built.json, deployed.json, out/, a docker build's public/ and
+ .r2-staging/) and `export/.export-index/sites/<id>/` (report media and exports, summaries, stats). Nothing else names
+ a site by id: channel membership is site.json's own pool, the hub lists the sites on disk with a siteUrl, and curated
+ tags' per-site file is in the site dir.
+- **Plan, then apply** (as release 27's `reports delete`): `dryRun` answers the plan. Removed: the three directories.
+ Kept: every channel's data, the Pages project and what was deployed (a delete does not undeploy), a deployed hub until
+ rebuilt, `export/out` when it links into the site's bundle. Refused unless `force`: a `cloudflareProject`, a deploy
+ in deployed.json (production, a preview, local), reports of its own. Refused, force or not: no such site (404), a
+ site dir that is a link, a publish stage running (a live publish-lock holder).
+- **The delete:** the publish lock taken without waiting (1.5 s; a stage that started refuses), the site.json lock,
+ the plan made again, each directory renamed aside to `.deleting-<id>-<stamp>`; the bulk removed after the locks.
+- The editor's Danger → Delete (`deleteSiteAction` → `deleteSite`) is unchanged: it still removes `sites/<id>/` alone.
+- **The candalyzer plan** (read only, 2026-10-13): not refused, 3 paths, 7 772 files, about 2.7 GiB. The orchestrator
+ runs `pnpm ops delete-site --json '{"id":"candalyzer"}'` after merge (a `dryRun` first).
+
+### Lane C gates (2026-10-13)
+
+- tsc clean (all packages) at every commit.
+- Unit, at the branch's start → at its tip:
+ - common 4017 of 4018 (1 red: "a drain mid-page waits for the page's cursor", not this lane's; green since) →
+ 4034/4034 (16 new: `bench.test.ts` 8, `reports-bench-verdicts.test.ts` 3, `siteDelete.test.ts` 4, the verdicts
+ settings 1);
+ - editor 288 of 289 (1 red: `whisperFromContainer.test.ts`, not this lane's; green since) → 291/291 (3 new: `_benchVerdicts.test.ts`);
+ - `test:scripts` 858 pass, 2 red (the queue-lock pair H2 fixed), 3 skipped → 864 pass, 0 red, 2 skipped (3 new:
+ `parakeet-stitch.test.mjs`);
+ - mcp 343/343 (not touched).
+- `docs env|files|cli --check`, `settings example --check`: clean.
+- Builds (heavy slot, 5 GB cap): umtool 31 s with the corpus linked for the build only and removed (`/bench`,
+ `/api/bench/bar`); umtool's e2e start build 29 s; the editor's e2e start build 57 s at `66fd4a04`
+ (`/api/ops/bench-verdicts`); the editor at `ebf9e60d`, 123 s (`/api/ops/bench-verdicts`, `/api/ops/delete-site`).
+- e2e: umtool `verdict-bench.spec.ts` 2/2, 14.2 s; editor `backfill.spec.ts` 22/22 five times (above).
+
+### Lane C merge and H1's clean-up (2026-10-13, orchestrator)
+
+`r28/bench-house` merged `8cd383dd`. Gates there: tsc clean; common 4058/4058; mcp 346/346; editor 293/293;
+`test:scripts` 874 + 3 skipped, 0 failed. H1's leftovers: the 16 `parakeet-stitch-*` dirs left in `/tmp` (176 MB of the
+RAM tmpfs; 5 had gone since the survey's 21) were removed with no parakeet-stitch process running and no process holding
+a file in them. The real verdict bench runs once, after the rollout, through the live editor (`bench-verdicts` is a new
+route, and qwen needs the editor's GPU arbiter); its results land in the primary checkout's `.generation/`.
+Lane C's leftovers: `relocateDir.ts` reports a directory-mtime-only difference as "changed"; the editor's Danger →
+Delete still removes only `sites/<id>/` (M9 routes it through the plan-first delete).
+### F1, as shipped (2026-10-14, lane F, `r28/research-f`)
+
+An `auto` research run continues into its sweep by itself once its acquisitions settle.
+
+| Commit | What |
+| --- | --- |
+| `7739bce5` | `controller/researchAutoContinue.ts`: `maybeAutoContinue`, `scanAutoContinue`, `armResearchAutoContinue` / `researchAutoContinueTick`; `onJobEnd` in `jobs/registry.ts`; `researchRuns.ts` watches an `auto` run's pending jobs (`watchResearchJobs`, `takeWatchedRun`) and its view carries `autoContinue`; `AutoContinueRecord` in `research/state.ts`; the heartbeat's call; the editor arms it below the idle gate (`_autoContinue.ts`); 6 tests |
+| `526261f1` | umtool: the research queue says "continued automatically by iN", or why not; the editor stub continues an `auto` run as the editor does; `article-research.spec` asserts it |
+| `a3084416` | OPERATING.md's research section, the `autonomy` field doc and SETTINGS.md, research-approve's help and COMMANDS.md |
+| `62f732d3` | a site build's end runs the scan too (`SCAN_ON_END`), so a held run continues after the rebuild; 1 test |
+| (this commit) | this record, FACTS "Release 28 F1", CHANGELOG |
+
+- **Who continues by itself:** autonomy `auto` only. `propose` and `limits` are continued by the operator, as in r27.
+- **When:** the run is done; nothing waits for a yes or no; every acquisition job has ended (done, failed or
+ cancelled); it is not continued already.
+- **The once-only mark** is a claim taken under the article store's lock (`updateIteration`'s function patch), so a
+ heartbeat and a job end racing continue once. A claim is fresh for 10 minutes. A stale claim whose sweep exists is
+ recorded as the continuation, not made again.
+- **What it asks:** Continue's own path, `report-draft {task: "sweep", iteration: n, model, channels}`.
+ - The model is the research run's own (the brief's "the run's model/route"). The umtool button still defaults to the
+ sweep route's.
+ - The per-job cap is `caps.sweep`; the daily cap is checked first, again at the ask, and again at the job's turn.
+ - A daily-cap refusal, like any refusal of the ask, is recorded as `refused` and tried again only on a later UTC
+ day.
+- **Builds:** a channel in no composed build is left out. The warning `not in any build yet: <slug> — rebuild the site
+ and continue again` is on the run's record and is a failed `unbuilt channels` check on the sweep. With nothing left,
+ the run is `held` (nothing enqueued) until a build newer than the hold, or a later day.
+- **Triggers:**
+ - the registry's new `onJobEnd`: a watched acquisition job's end continues its run; the end of a `report-draft` job
+ (the research job's own) or a site build runs the scan;
+ - the scan: on the heartbeat (`fire`, after the tick) and once at boot.
+ - The editor arms both in `instrumentation.ts` below the idle gate, and `armResearchAutoContinue` refuses an idle
+ boot itself.
+- **On the run:** `research.autoContinue` (status, at, by, reason, warnings, day, buildsAt) in `iteration.json`, an
+ `auto-continue` line in `turns.jsonl`, `ResearchView.autoContinue` in research-approve's answer, and umtool's
+ queue line.
+- **Found:** the editor's heartbeat is off by default (`syncScheduler.heartbeatSeconds` 0; the live `settings.json`
+ says 0). Live, the triggers are the job ends and the boot scan. A refused run is retried the next day only when a
+ report-draft or site-build job ends, the editor restarts, or a heartbeat is configured.
+- **No change to `reportDraft.ts`:** the continuation is asked from code through `enqueueReportDraft`, and the daily
+ cap is pre-checked with `generationUsage`'s exports. No settings key was added; the `autonomy` doc says what `auto`
+ now does.
+
+Gates (from the worktree root; counts at the branch start → the tip):
+- tsc clean (all packages) before every commit.
+- common 4042 → 4049/4049 (7 new, `controller/researchAutoContinue.test.ts`, five runs each clean); editor unit
+ 290 → 290/290; mcp 345 of 346 at the start (1 failure, "a real editor that stops answering a poll hands back the
+ job", not reproduced since) → 346/346; `test:scripts` 870 + 3 skipped, 1 failure at the start (`queue-lock`, H2's
+ flake) → 871 + 3 skipped, 0 failed (874; the count unchanged, the failure not reproduced).
+- `settings example --check`, `docs env|files|cli --check`: clean.
+- Editor build (heavy slot, 5 GB cap): clean in 52 s.
+- e2e, single specs in the foreground:
+ - umtool `article-research.spec.ts` 3/3 (31.2 s; its prebuild's capped build 29 s), the new auto-continue test included;
+ - umtool `article-iterations.spec.ts` + `article-new.spec.ts` 7/7 (40.6 s);
+ - editor `report-draft.spec.ts` 3/3 (19.2 s; its prebuild's capped build 48 s), with the new boot arming in its server.
+### M4, as shipped (2026-10-14, lane E, `r28/media-e`)
+
+The flips draft (`flips`): THEN/NOW pairs over the cut's clips, `render.chrome.flips`. A step on a done iteration on
+M0's scaffold, one unit (the whole field), replacing step 0's "not implemented" refusal.
+- **The model** proposes pairs: a topic, two clip ids, and optionally a part of each clip's quote. Rules, no example.
+- **Code** does the rest. It dates each clip: the entry's `date` (the operator's, what the header shows), else the
+ corpus record's `uploadDate` (`get_video_metadata`), else the citation's `date`. The earlier is THEN, whichever
+ way the model named them, and a pair of one day is refused. Each `when` is written from the date (`Jan 2026`).
+ A side's `words` is the clip's quote verbatim, or the model's part of it only when the quote says exactly that,
+ cut at a word to 110 with `…`. The pair id is the topic slugged. Code refuses unknown ids, a clip in two pairs, and
+ more pairs than `min(24, dated clips / 2)`. The topic is one line of at most 32 characters, grounded by
+ `checkLine`.
+- **Order:** a THEN that plays after its NOW is refused, unless `ownerOf(timeline)` is `"drafted"` and the flips
+ will be applied. In that case the two clips swap places, and the timeline is written through `applyDraft` with the
+ flips provenance. A twin id refuses the swap.
+- **The build's validators:** `validateFlips` and `validateFlipEntries` run on the cut as it will be, swaps
+ included. To make that possible they moved to common, as `common/lib/report/panels.mjs` (see M5). The repair keeps
+ the attempt's pairs that pass when one fails.
+- **One left panel (the simplest correct rule):** a cut with threads is refused, unless `force` and the threads are
+ a draft. In that case the flips replace them: the list, every clip's `thread` and the mark are removed, and the log
+ says so. Operator's threads are refused even with `force`. A cut with no `render.chrome` is refused.
+- Test kit: `draft/runs/flips.json`. Run over the full manifest with its threads taken off: the first answer is
+ refused (a pair of one day, a number the report lacks) and re-asked. The kept answer reproduces S0's flips manifest
+ pair, id aside.
+
+### M5, as shipped (2026-10-14, lane E, `r28/media-e`)
+
+The threads draft (`threads`): `render.chrome.threads.list` and each clip's `thread`.
+- **The model** names the threads (`{id, label}`) and gives each clip a thread or `""`.
+- **Code** checks the result:
+ - 2 to 4 threads (`THREADS_TASK_COUNT`);
+ - ids are slugged when invalid, and none is listed twice;
+ - labels are one line of at most 32 characters, grounded;
+ - every assignment names a clip of the cut and a listed thread, and no clip is in two threads;
+ - every thread has a clip;
+ - `validateThreads` and `validateThreadEntries` pass on the cut as it will be.
+- **The outcome is code's:** the `claim.verdict` that the thread's last clip (in timeline order) carries in the
+ manifest, when it has one. The model never writes a verdict.
+- **Applied:** `applyDraft(render.chrome.threads, {list})`, then every clip's `thread` is set, and removed from a
+ clip in no thread. The repair drops failing threads with their clips when two still stand.
+- **Mirror of M4:** a cut with flips is refused unless `force` and the flips are a draft, which the threads then
+ replace.
+- **`common/lib/report/panels.mjs`** is now the one copy of the flips' and the threads' limits and validators.
+ umtool's `flips.mjs` and `threads.mjs` re-export them unchanged (their tests, deck, lint and fixtures-r28 pass
+ unchanged).
+- Test kit: `draft/runs/threads.json`. The first answer is refused (a label naming someone the report does not, a
+ thread with no clip). The kept answer: bakery CONTRADICTED (c07), contest NOT_FOUND (c06).
+
+### M6, as shipped (2026-10-14, lane E, `r28/media-e`)
+
+The YouTube draft (`youtube`), `out/youtube.txt`, and umtool's panel.
+- **The task** writes `publish.youtube {title, description}`: a title of one line, at most 100 characters, and one
+ summary paragraph of at most 900 (`YOUTUBE_SUMMARY_MAX`, room under `validatePublish`'s 5000). Both are grounded
+ by `checkLine(…, {quotes: true})`:
+ - names and numbers come from the report and the cut's title and subtitle;
+ - no stock phrase;
+ - third person (Q1's `firstPersonProblems`);
+ - words in quotation marks only when a cited quote says them word for word;
+ - no links, timestamps or hashtags.
+ The repair drops a failing sentence of the summary when the title is clean and something is left.
+- **`out/youtube.txt`** is composed by code (`umtool/report-to-video/youtube.mjs`, pure; exported
+ `umtool-report-to-video/youtube`):
+ - the title, a blank line, the summary;
+ - `Chapters` from the build's own chapter list: `muxChapters` now returns `{chapters, total}`, the list it muxed;
+ - `Sources`: a moment link per cited clip, in cut order, each once — `citeUrl`, else the archive's page at
+ `cite`.
+- **Chapters follow YouTube's rules** (ruled here): the first at 0:00, at least three, each at least ten seconds. A
+ shorter one is folded into the one before it. A list that still falls short, or does not start at 0:00, is left
+ out, and the build's `youtube` event names why.
+- **When it is written:** after every chapter mux (the full build, the deck build, `--rail-only`,
+ `--chapters-only`), and under `--no-chapters` without the block, whenever the manifest has a `publish.youtube`
+ title. The file is `youtube-<variant>.txt` for a variant other than `sourced`, as the mp4 is named.
+- **umtool:** `YoutubeSection` on the project page shows `out/youtube.txt` (its age; a note when `publish.youtube`
+ changed since), else the same text composed without chapters (`youtubePreview`), with **Copy** and "drafted by
+ <model>". Nothing when neither exists. M9 does "Draft with".
+- Test kit: `draft/runs/youtube.json`. The first answer is refused (speaks as the speaker, a link). The editor's
+ `_reportDraft.test.ts` runs a youtube step through the job (step 0's "not implemented" case is now this).
+
+| Commit | What |
+| --- | --- |
+| `e4dff898` | `common/lib/report/panels.mjs` (+ `.d.mts`, package export), flips.mjs and threads.mjs re-export it; `report-to-video/youtube.mjs` + `youtube.test.mjs` (6); `muxChapters` returns its list; `writeYoutubeText` after every chapter mux; the `youtube` event |
+| `2d97a52c` | `tasks/clipEvidence.ts` (`clipFacts`, `isoDay`, `whenOf`, `checkLine`), `tasks/flips.ts`, `tasks/threads.ts`, `tasks/youtube.ts`, the dispatcher; `panelTasks.test.ts` (10); runs `flips` / `threads` / `youtube`; the MCP's end-to-end tests (3); the editor's report-draft youtube step; the kit README |
+| `f4884f7f` | umtool `YoutubeSection` on the project page; e2e `media-draft-e.spec.ts`, `fixtures/youtube-fixture.mjs` |
+| `45355fb8` | report-to-video README: the drafted panels, `publish.youtube` and `out/youtube.txt` |
+| (this commit) | these records, FACTS "Release 28 lane E", CHANGELOG |
+
+Lane E's gates (from the worktree root, at `45355fb8`; counts at the branch's start `381156ae` → its tip):
+- tsc clean (all packages) before every commit.
+- common 4059 → 4069 (+10, `panelTasks.test.ts`); 4068 passed, 1 failed: `fetchPosts.test.ts` "a drain mid-page
+ waits for the page's cursor…", the phase-1 flake candidate, 8/8 alone.
+- mcp 346 → 349/349 (+3); editor 295/295 (one test rewritten, none added); `test:scripts` 874 + 3 skipped →
+ 880 + 3 skipped (+6, `youtube.test.mjs`).
+- `docs env|files|cli --check`, `settings example --check`: clean (nothing regenerated).
+- umtool e2e, single specs in the foreground:
+ - `media-draft-e.spec.ts` 1/1 (5.0 s; a real offline fast build: three chapters, two folded, and the sources);
+ - `draft-review.spec.ts` + `report-narration.spec.ts` 6/6;
+ - `projects.spec.ts` + `build.spec.ts` 29/29.
+ - Each run's prebuild was umtool's capped `next build`, 29 s.
+- umtool capped build, corpus linked, through the heavy slot (5 GB): ok, 29 s with 8.5 GB available; the link removed.
+
+Found and left:
+- `checkLine` does not check a line's FIRST word as a name. It is the narration grounding, which skips each
+ sentence's first word, so a topic, label or title starting with an unknown name passes that check. The tests use a
+ name mid-line.
+- "Use this" on a threads alternative writes the list alone (M0's `writeDraftedField`), not the clips' `thread`
+ keys the draft assigned. A threads alternative arises only when the operator's threads are forced over, and its
+ Use this may then leave clips naming the operator's old ids, which the build refuses.
+- The media tasks report no progress in this branch. Lane D's scaffold change (`h.progress` per unit,
+ `progressMetric`) covers these three once merged; they set no `progressMetric` (default `entries`).
+- umtool's editor stub answers a media step only for `narrate` (any other task makes a new iteration in the stub).
+ That is M9's to extend with its buttons.
+
## Not in this release
Comment and thread generation for social posts (X/Bluesky promotion); auto-publishing to YouTube (r28 writes the text
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -58,6 +58,7 @@
// pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'
// pnpm ops delete-article --json '{"id":"demo-article","force":true}'
// pnpm ops delete-iteration --json '{"id":"demo-article","n":3}'
+// pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'
// pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'
// pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'
// pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'
@@ -108,6 +109,7 @@
// pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait
// pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'
// pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'
+// pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
// four-thousand-id tag-videos body is written by a script, not typed by a model
@@ -270,6 +272,9 @@ const ACTIONS = [
// Synchronous; no job.
"delete-article",
"delete-iteration",
+ // Delete a site ({id, force?, dryRun?}): the plan, then sites/<id>/, its
+ // publish state and its staging. Channel data is never touched. Synchronous.
+ "delete-site",
// The channel's lifecycle: the New channel form, and the channel page's
// Danger → Rename and Danger → Delete. Synchronous; no job.
"create-channel",
@@ -404,6 +409,10 @@ const ACTIONS = [
// job — refreshed from their jobs, then approved (run through the editor) or
// rejected ({article, iteration, ids?, approve?, note?}). Synchronous.
"research-approve",
+ // THE VERDICT BENCH (release 28 M7): ruled fact-check claims asked of each
+ // model, one per call ({models, run?, reports?, window?, maxUsd?, limit?}),
+ // as a bench-verdicts job on draft:local (any local model) or draft:api.
+ "bench-verdicts",
];
// The log line a transcribe job ends with: this marker, then the result as
@@ -416,6 +425,9 @@ export const TTS_RESULT_MARKER = "@@tts-result ";
// The same for a generation (REPORT_DRAFT_RESULT_MARKER in
// common/controller/reportDraft.ts).
export const REPORT_DRAFT_RESULT_MARKER = "@@report-draft ";
+// The same for the verdict bench (BENCH_VERDICTS_RESULT_MARKER in
+// common/controller/benchVerdicts.ts).
+export const BENCH_VERDICTS_RESULT_MARKER = "@@bench-verdicts ";
// The same for a remote listing (REMOTE_LISTING_RESULT_MARKER in
// common/controller/remoteListing.ts).
export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing ";
@@ -643,6 +655,7 @@ export function parseArgs(argv) {
...(action === "tts" ? { resultMarker: TTS_RESULT_MARKER } : {}),
...(action === "remote-listing" ? { resultMarker: REMOTE_LISTING_RESULT_MARKER } : {}),
...(action === "report-draft" ? { resultMarker: REPORT_DRAFT_RESULT_MARKER } : {}),
+ ...(action === "bench-verdicts" ? { resultMarker: BENCH_VERDICTS_RESULT_MARKER } : {}),
wait,
quiet,
waitTimeout,
@@ -981,6 +994,18 @@ export function usage() {
' from, the current video, a queued or running one, one another revises',
' or copies.',
"",
+ 'delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan',
+ " — every path with its size, what is kept and why — and write nothing),",
+ ' "force"? It removes sites/<id>/ (site.json, its pool and pages, tags,',
+ " charts, its reports), its publish state and last bundle",
+ " (export/.export-builds/<id>/) and compose's staging for it",
+ " (export/.export-index/sites/<id>/). Channel data is never touched; the",
+ " Pages project, what was deployed and a deployed hub are kept (a delete",
+ ' does not undeploy). Refused with the plan (409) unless "force": a deploy',
+ " target (cloudflareProject), a deploy in its publish state, reports of its",
+ " own. Refused, force or not: no such site (404), a site dir that is a link,",
+ " a publish stage running.",
+ "",
'create-channel is the New channel form: {"fields": {"name", "handling":',
' "youtube"|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?,',
' "socialHandle"?, …}} with channel-config\'s patch keys; "slug"? (else',
@@ -1225,13 +1250,28 @@ export function usage() {
' "iteration", "ids"?: ["p01", …], "approve"?: true | false, "note"?} ->',
" {outcomes: [{id, status?, jobId?, note?, error?}], research: {phase,",
" autonomy, limits, spent, proposals, waitingOn: {approval, jobs},",
- " continuedBy}}. It first refreshes every enqueued acquisition from its",
+ " continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its",
" jobs (all done: done; one failed: failed, naming it). approve: true runs",
" each proposal through the editor's own action (past the run's autonomy and",
" caps, never past a standing rule); false rejects it, note saying why. No",
" ids: the run's state now. The phase is wait (approvals or jobs pending),",
' ready (nothing pending: continue with report-draft {"task": "sweep",',
- ' "iteration": N}) or continued. Refused while the run\'s job is going.',
+ ' "iteration": N}) or continued. An `auto` run is continued by the editor',
+ " itself once ready; autoContinue says how (continued by, held for a build,",
+ " refused by a cap, and why). Refused while the run's job is going.",
+ "",
+ 'bench-verdicts runs the verdict bench as a bench-verdicts job: {"models":',
+ ' ["…"], "run"?, "reports"?: ["<article>"], "window"? (seconds, default 60),',
+ ' "maxUsd"? (default 5), "limit"?} -> {jobId, run}. Every claim of the',
+ " registry's fact-checks (or of \"reports\") with the operator's verdict and a",
+ " citation with cues is asked of each model, one claim per call (the claim,",
+ " its quotes, the transcript within the window; never the findings or the",
+ " verdict), and scored against the rulings. On draft:local when any model is",
+ " local (through the GPU arbiter; unloaded at the end), else draft:api; the",
+ " run stops at maxUsd, and an API run is refused past caps.daily. A \"run\"",
+ " that exists continues (answered pairs are skipped). Results stay local, in",
+ " .generation/bench/verdicts/<run>/ (umtool's /bench). The log ends with",
+ " @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}.",
"",
"Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,",
" ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").",
diff --git a/scripts/parakeet-stitch.mjs b/scripts/parakeet-stitch.mjs
@@ -55,10 +55,11 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
-import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
-import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, writeFile } from "node:fs/promises";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
import os from "node:os";
import path from "node:path";
+import { fileURLToPath } from "node:url";
const execFileP = promisify(execFile);
@@ -266,6 +267,150 @@ function workDirFor(absAudio) {
const PARTIAL_PAUSE_CODE = 0;
+// ─── The temp dir: removed on every exit; a stale one swept at start-up ───
+//
+// Each run slices its windows into a `parakeet-stitch-*` dir under the
+// tmpdir (a RAM tmpfs on some hosts). It is removed in a `finally`, and the
+// pause path leaves the loop rather than exiting inside it, so the `finally`
+// runs there too. What a kill -9 or a crash leaves behind is swept by the next
+// run: a dir older than STALE_MS that no running process holds.
+//
+// "Holds" is decided by an OWNER FILE written into the dir at creation — the
+// pid and that process's start time (/proc/<pid>/stat, field 22), so a reused
+// pid is not taken for the owner. A scan of /proc for open files or a cwd in
+// the dir would not do: a run holds nothing in it between two windows. A dir
+// with no owner file (from before this change) is held while any other
+// parakeet-stitch process is running (its cmdline), or while any process has a
+// file or its cwd in it — the conservative reading.
+
+export const TMP_PREFIX = "parakeet-stitch-";
+export const OWNER_FILE = "owner.json";
+export const STALE_MS = 24 * 60 * 60 * 1000;
+
+// A process's start time in clock ticks since boot, or null (no such pid, no /proc).
+export function procStartTime(pid) {
+ try {
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
+ const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
+ // rest[0] is field 3 (state); field 22 (starttime) is rest[19].
+ return rest[19] ?? null;
+ } catch {
+ return null;
+ }
+}
+
+function pidAlive(pid) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (e) {
+ return e?.code === "EPERM";
+ }
+}
+
+async function procPids() {
+ try {
+ return (await readdir("/proc")).filter((n) => /^\d+$/.test(n)).map(Number);
+ } catch {
+ return [];
+ }
+}
+
+// The live system's answers; tests pass their own.
+export const liveProc = {
+ // The owner file's process is the same process, still running.
+ ownerAlive(owner) {
+ if (!owner || !Number.isInteger(owner.pid) || !pidAlive(owner.pid)) return false;
+ const start = procStartTime(owner.pid);
+ return owner.start == null || start == null || String(start) === String(owner.start);
+ },
+ // Some process has its cwd or an open file inside `dir`.
+ async holds(dir) {
+ const inside = (p) => p === dir || p.startsWith(dir + path.sep);
+ for (const pid of await procPids()) {
+ try {
+ if (inside(await readlink(`/proc/${pid}/cwd`))) return true;
+ } catch {
+ // gone, or not ours to read
+ }
+ let fds = [];
+ try {
+ fds = await readdir(`/proc/${pid}/fd`);
+ } catch {
+ continue;
+ }
+ for (const fd of fds) {
+ try {
+ if (inside(await readlink(`/proc/${pid}/fd/${fd}`))) return true;
+ } catch {
+ // closed meanwhile
+ }
+ }
+ }
+ return false;
+ },
+ // Another parakeet-stitch process is running.
+ async stitchRunning() {
+ for (const pid of await procPids()) {
+ if (pid === process.pid) continue;
+ try {
+ if (readFileSync(`/proc/${pid}/cmdline`, "utf8").includes("parakeet-stitch")) return true;
+ } catch {
+ // gone
+ }
+ }
+ return false;
+ },
+};
+
+export async function writeOwnerFile(dir, pid = process.pid) {
+ await writeFile(path.join(dir, OWNER_FILE), JSON.stringify({ pid, start: procStartTime(pid) }));
+}
+
+// Remove every stale, unheld `parakeet-stitch-*` dir under `tmpdir`.
+// Answers what was removed and what was kept, with why.
+export async function sweepStaleTempDirs({ tmpdir = os.tmpdir(), now = Date.now(), staleMs = STALE_MS, proc = liveProc } = {}) {
+ const removed = [];
+ const kept = [];
+ let names = [];
+ try {
+ names = (await readdir(tmpdir, { withFileTypes: true })).filter((e) => e.isDirectory() && e.name.startsWith(TMP_PREFIX)).map((e) => e.name);
+ } catch {
+ return { removed, kept };
+ }
+ for (const name of names) {
+ const dir = path.join(tmpdir, name);
+ let st;
+ try {
+ st = await stat(dir);
+ } catch {
+ continue;
+ }
+ if (now - st.mtimeMs < staleMs) {
+ kept.push({ dir, why: "young" });
+ continue;
+ }
+ let owner = null;
+ try {
+ owner = JSON.parse(await readFile(path.join(dir, OWNER_FILE), "utf8"));
+ } catch {
+ owner = null;
+ }
+ const held = owner ? proc.ownerAlive(owner) : (await proc.stitchRunning()) || (await proc.holds(dir));
+ if (held) {
+ kept.push({ dir, why: "held" });
+ continue;
+ }
+ try {
+ await rm(dir, { recursive: true, force: true });
+ removed.push(dir);
+ } catch {
+ kept.push({ dir, why: "not removable" });
+ }
+ }
+ return { removed, kept };
+}
+
async function main() {
const opts = parseArgs(process.argv.slice(2));
if (!opts.audio) fail("missing <audioFile>\n\n" + HELP);
@@ -343,7 +488,12 @@ async function main() {
process.on("SIGTERM", onStop);
process.on("SIGINT", onStop);
- const tmp = await mkdtemp(path.join(os.tmpdir(), "parakeet-stitch-"));
+ // What a crashed or killed run left in the tmpdir goes first.
+ const swept = await sweepStaleTempDirs().catch(() => ({ removed: [] }));
+ if (swept.removed.length) progress(`removed ${swept.removed.length} stale temp dir(s) from earlier runs`);
+ const tmp = await mkdtemp(path.join(os.tmpdir(), TMP_PREFIX));
+ await writeOwnerFile(tmp);
+ let paused = false;
const segTimes = []; // measured wall-time (ms) per freshly-transcribed window, for ETA
let done = 0; // windows present (cached or freshly done)
try {
@@ -356,8 +506,9 @@ async function main() {
continue;
}
if (stopRequested) {
- progress(`paused after ${done}/${N} window(s) — re-run to resume`);
- process.exit(PARTIAL_PAUSE_CODE);
+ // Leave the loop, never exit inside it: the `finally` removes the temp dir.
+ paused = true;
+ break;
}
const isLast = i === N - 1;
// Last window runs to EOF (no -t) so we never miss a trailing fragment.
@@ -380,6 +531,10 @@ async function main() {
} finally {
if (!opts.keepTemp) await rm(tmp, { recursive: true, force: true });
}
+ if (paused) {
+ progress(`paused after ${done}/${N} window(s) — re-run to resume`);
+ process.exit(PARTIAL_PAUSE_CODE);
+ }
// All windows present — load the raw payloads and stitch the final transcript.
const windowWords = [];
@@ -435,6 +590,16 @@ async function main() {
if (!opts.keepTemp) await rm(workDir, { recursive: true, force: true });
}
-main().catch((err) => {
- fail(err?.stack || String(err), 1);
-});
+// Run as a program (the app's binary, or the CLI), not when a test imports it.
+const isMain = (() => {
+ try {
+ return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return false;
+ }
+})();
+if (isMain) {
+ main().catch((err) => {
+ fail(err?.stack || String(err), 1);
+ });
+}
diff --git a/scripts/parakeet-stitch.test.mjs b/scripts/parakeet-stitch.test.mjs
@@ -0,0 +1,118 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { OWNER_FILE, STALE_MS, TMP_PREFIX, sweepStaleTempDirs, writeOwnerFile } from "./parakeet-stitch.mjs";
+
+// Run with: node --test scripts/parakeet-stitch.test.mjs
+//
+// Release 28 H1: the temp dir a run slices its windows into is removed on the
+// pause path too, and a run sweeps the stale ones a crash or a kill left.
+
+const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "parakeet-stitch.mjs");
+
+function sh(file, body) {
+ writeFileSync(file, `#!/bin/sh\n${body}\n`);
+ chmodSync(file, 0o755);
+ return file;
+}
+
+test("the pause path: a SIGTERM mid-run finishes the window, keeps it, exits 0 — and leaves no temp dir", () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), "stitch-pause-"));
+ try {
+ const tmpdir = path.join(root, "tmp");
+ const bin = path.join(root, "bin");
+ const work = path.join(root, "video");
+ mkdirSync(tmpdir);
+ mkdirSync(bin);
+ mkdirSync(work);
+ writeFileSync(path.join(work, "audio.wav"), "not audio");
+ writeFileSync(path.join(root, "model.gguf"), "not a model");
+ sh(path.join(bin, "ffprobe"), "echo 1000");
+ // ffmpeg: write the window wav (its last argument).
+ sh(path.join(bin, "ffmpeg"), 'for a; do last="$a"; done; echo wav > "$last"');
+ // parakeet-cli: the operator pauses during the first window (a SIGTERM to
+ // the script, its parent), and the window still completes.
+ sh(path.join(bin, "parakeet-cli"), 'kill -TERM $PPID; echo \'{"words":[{"w":"hello","start":1,"end":1.5}]}\'');
+ const r = spawnSync(
+ process.execPath,
+ [SCRIPT, "--model", path.join(root, "model.gguf"), "--cli", path.join(bin, "parakeet-cli"), "--ffmpeg", path.join(bin, "ffmpeg"), path.join(work, "audio.wav"), path.join(work, "out.json")],
+ { env: { ...process.env, TMPDIR: tmpdir }, encoding: "utf8", timeout: 30_000 },
+ );
+ assert.equal(r.status, 0, r.stderr);
+ assert.match(r.stderr, /paused after 1\/3 window\(s\)/);
+ assert.deepEqual(readdirSync(tmpdir).filter((n) => n.startsWith(TMP_PREFIX)), [], "no temp dir left");
+ // The completed window is kept for the resume; nothing was stitched.
+ assert.ok(existsSync(path.join(work, ".audio.wav.parakeet", "win-0000.json")));
+ assert.ok(!existsSync(path.join(work, "out.json")));
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("the sweep: an old unheld dir goes; a held one (its owner alive, or a process in it) and a young one stay", async () => {
+ const tmpdir = mkdtempSync(path.join(os.tmpdir(), "stitch-sweep-"));
+ try {
+ const now = Date.now();
+ const make = (name, ageMs) => {
+ const d = path.join(tmpdir, name);
+ mkdirSync(d);
+ writeFileSync(path.join(d, "win-0000.wav"), "wav");
+ const t = (now - ageMs) / 1000;
+ utimesSync(d, t, t);
+ return d;
+ };
+ const old = make(`${TMP_PREFIX}old`, STALE_MS + 60_000);
+ const owned = path.join(tmpdir, `${TMP_PREFIX}owned`);
+ mkdirSync(owned);
+ await writeOwnerFile(owned, 4242);
+ utimesSync(owned, (now - STALE_MS * 2) / 1000, (now - STALE_MS * 2) / 1000);
+ const legacyHeld = make(`${TMP_PREFIX}legacy-held`, STALE_MS * 3);
+ const young = make(`${TMP_PREFIX}young`, 60_000);
+ const other = make("something-else", STALE_MS * 5);
+ const proc = {
+ ownerAlive: (o) => o.pid === 4242,
+ holds: async (dir) => dir === legacyHeld,
+ stitchRunning: async () => false,
+ };
+ const out = await sweepStaleTempDirs({ tmpdir, now, proc });
+ assert.deepEqual(out.removed, [old]);
+ assert.deepEqual(
+ out.kept.map((k) => [path.basename(k.dir), k.why]).sort(),
+ [
+ [`${TMP_PREFIX}legacy-held`, "held"],
+ [`${TMP_PREFIX}owned`, "held"],
+ [`${TMP_PREFIX}young`, "young"],
+ ],
+ );
+ assert.ok(existsSync(owned) && existsSync(legacyHeld) && existsSync(young) && existsSync(other));
+ assert.ok(existsSync(path.join(owned, OWNER_FILE)));
+ // The owner gone: the dir goes. A dir with no owner file waits while
+ // another parakeet-stitch runs.
+ const later = await sweepStaleTempDirs({ tmpdir, now, proc: { ...proc, ownerAlive: () => false, stitchRunning: async () => true } });
+ assert.deepEqual(later.removed, [owned]);
+ assert.ok(existsSync(legacyHeld));
+ } finally {
+ rmSync(tmpdir, { recursive: true, force: true });
+ }
+});
+
+test("the live owner check: this process owns a dir it marked; a dead pid does not", async () => {
+ const { liveProc } = await import("./parakeet-stitch.mjs");
+ const dir = mkdtempSync(path.join(os.tmpdir(), "stitch-owner-"));
+ try {
+ await writeOwnerFile(dir);
+ const mine = JSON.parse((await import("node:fs")).readFileSync(path.join(dir, OWNER_FILE), "utf8"));
+ assert.equal(mine.pid, process.pid);
+ assert.equal(liveProc.ownerAlive(mine), true);
+ // The same pid with another start time is a reused pid, not the owner.
+ assert.equal(liveProc.ownerAlive({ pid: process.pid, start: "1" }), mine.start === null);
+ const child = spawnSync(process.execPath, ["-e", "console.log(process.pid)"], { encoding: "utf8" });
+ assert.equal(liveProc.ownerAlive({ pid: Number(child.stdout.trim()), start: null }), false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs
@@ -97,6 +97,26 @@ function markerCmd(logFile, id, holdMs) {
];
}
+// The same, held until `gateFile` exists (or `maxMs` passes) rather than for a
+// fixed time: a test opens the gate once what it means to see has happened, so
+// a loaded machine's slow start of the NEXT run cannot outlast the hold. (A
+// fixed hold was the release 28 flake: under `test:scripts`' parallel files,
+// the second run sometimes started after the first had already ended.) The
+// cap keeps a run that should have been admitted, and was not, from hanging
+// the test: it ends, and the order assertion names what went wrong.
+function gateCmd(logFile, id, gateFile, maxMs = 20_000) {
+ return [
+ process.execPath,
+ "-e",
+ `const fs=require("fs");` +
+ `fs.appendFileSync(${JSON.stringify(logFile)},"S${id}");` +
+ `const t0=Date.now();` +
+ `const tick=()=>{if(fs.existsSync(${JSON.stringify(gateFile)})||Date.now()-t0>${maxMs}){fs.appendFileSync(${JSON.stringify(logFile)},"E${id}");}else setTimeout(tick,20);};` +
+ `tick();`,
+ ];
+}
+const openGate = (gateFile) => fs.writeFileSync(gateFile, "");
+
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
test("serializes concurrent invocations", async () => {
@@ -636,12 +656,16 @@ test("two weighted jobs run side by side; a third waits for headroom, named in t
meminfo(env.HEAVY_MEMINFO_FILE, 8000);
const jobs = path.join(dir, "heavy.lock.jobs");
const tickets = () => (fs.existsSync(jobs) ? fs.readdirSync(jobs).filter((n) => n.endsWith(".json")).length : 0);
- const a = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "a", 1500)], env);
+ // a and b hold until c has been seen waiting: their overlap, and c's wait,
+ // are then by the gate, not by how fast this machine starts a process.
+ const gate = path.join(dir, "gate-ab");
+ const a = startLock(["--heavy", "--estimate", "1500", "--", ...gateCmd(log, "a", gate)], env);
await until(() => tickets() === 1);
- const b = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "b", 1500)], env);
+ const b = startLock(["--heavy", "--estimate", "1500", "--", ...gateCmd(log, "b", gate)], env);
await until(() => tickets() === 2);
const c = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "c", 50)], env);
await c.waitFor(/waiting for memory — 8000 MB available, 3000 MB promised to 2 running jobs, the floor is 6000 MB/);
+ openGate(gate);
const [ra, rb, rc] = await Promise.all([a.done, b.done, c.done]);
assert.equal(ra.code, 0, ra.stderr);
assert.equal(rb.code, 0, rb.stderr);
@@ -793,11 +817,15 @@ test("--with: a suite that shares a tree holds the other suite's queue too", asy
const dir = tmpDir();
const log = path.join(dir, "order.log");
const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock") });
- const editor = startLock(["--name", "e2e-editor", "--with", "e2e-export", "--estimate", "100", "--", ...markerCmd(log, "e", 700)], env);
+ // The editor holds until umtool has run: umtool's start "beside the editor"
+ // is then the lock's doing, not a race against a 700 ms hold.
+ const gate = path.join(dir, "gate-e");
+ const editor = startLock(["--name", "e2e-editor", "--with", "e2e-export", "--estimate", "100", "--", ...gateCmd(log, "e", gate)], env);
await until(() => fs.existsSync(path.join(dir, "q.lock.e2e-export.holder.json")));
const exp = startLock(["--name", "e2e-export", "--estimate", "100", "--", ...markerCmd(log, "x", 50)], env);
await exp.waitFor(/waiting for the e2e queue — held by .*pid \d+/);
const umtool = await runLock(["--name", "e2e-umtool", "--estimate", "100", "--", ...markerCmd(log, "u", 50)], env);
+ openGate(gate);
for (const r of [await editor.done, await exp.done, umtool]) assert.equal(r.code, 0, r.stderr);
const order = fs.readFileSync(log, "utf8");
assert.ok(order.indexOf("Sx") > order.indexOf("Ee"), `export ran beside the editor: ${order}`);
diff --git a/settings.json.example b/settings.json.example
@@ -284,6 +284,14 @@
"maxTranscribeHours": 6,
"newChannelsNeedApproval": true,
"postWalksNeedApproval": true
+ },
+ "verdicts": {
+ "bar": {
+ "agreement": 0,
+ "contradictedRecall": 0,
+ "notFoundRecall": 0
+ },
+ "models": []
}
}
}
diff --git a/umtool/app/api/bench/bar/route.ts b/umtool/app/api/bench/bar/route.ts
@@ -0,0 +1,27 @@
+import { errorResponse } from "@/lib/articles/generation";
+import { readVerdictsPolicy, writeVerdictsPolicy } from "@/lib/bench";
+
+export const dynamic = "force-dynamic";
+
+// THE VERDICT BENCH'S BAR (release 28 M7): settings.generation.verdicts — the
+// operator's bar and the passing models they ticked — read from and written
+// through the editor's settings action (POST /api/ops/settings), whole.
+//
+// GET -> { verdicts }
+// POST { bar: {agreement, contradictedRecall, notFoundRecall}, models } -> { ok, verdicts }
+export async function GET() {
+ try {
+ return Response.json({ verdicts: await readVerdictsPolicy() }, { headers: { "cache-control": "no-store" } });
+ } catch (err) {
+ return errorResponse(err);
+ }
+}
+
+export async function POST(request: Request) {
+ try {
+ const body = await request.json().catch(() => null);
+ return Response.json({ ok: true, verdicts: await writeVerdictsPolicy(body) }, { headers: { "cache-control": "no-store" } });
+ } catch (err) {
+ return errorResponse(err);
+ }
+}
diff --git a/umtool/app/articles/page.tsx b/umtool/app/articles/page.tsx
@@ -63,6 +63,9 @@ export default async function ArticlesPage({ searchParams }: { searchParams: Pro
<Link href="/sites" className="ml-2 text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]">
site pages
</Link>
+ <Link href="/bench" className="ml-2 text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]">
+ verdict bench
+ </Link>
</div>
{pending.length > 0 && (
<section aria-label="in the making" className="mb-4">
diff --git a/umtool/app/bench/page.tsx b/umtool/app/bench/page.tsx
@@ -0,0 +1,305 @@
+import Link from "next/link";
+import BrowseHeader from "@/components/BrowseHeader";
+import BarForm from "@/components/bench/BarForm";
+import { badgeVariants } from "@/components/ui/badge";
+import {
+ BASELINE_MODEL,
+ VERDICTS,
+ filterBenchRows,
+ passesBar,
+ readBenchRuns,
+ readBenchView,
+ readVerdictsPolicy,
+} from "@/lib/bench";
+import type { ModelScore } from "yt-dlp-transcript-common/lib/report/draft/bench/index";
+import type { GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings";
+
+export const dynamic = "force-dynamic";
+
+// THE VERDICT BENCH (release 28 M7): could a model propose a fact-check
+// verdict well enough to be worth a review? One run at a time: per model its
+// agreement with the operator's rulings and its CONTRADICTED and NOT_FOUND
+// recall beside the always-CORROBORATED baseline, its cost; the confusion
+// matrix; every item with each model's verdict and reason, disagreements
+// first. The bar (settings.generation.verdicts) is set here, and each model's
+// pass or fail read against it — the handoff for the verdict proposals. The
+// runs are local-only (`archilyzer reports bench-verdicts`); zero client JS
+// but the bar's form.
+
+type Search = { run?: string; model?: string; verdict?: string };
+
+const pct = (v: number | null) => (v === null ? "—" : `${Math.round(v * 1000) / 10}%`);
+
+export default async function BenchPage({ searchParams }: { searchParams: Promise<Search> }) {
+ const sp = await searchParams;
+ const runs = await readBenchRuns();
+ const id = sp.run && runs.some((r) => r.id === sp.run) ? sp.run : runs[0]?.id;
+ const view = id ? await readBenchView(id) : null;
+ let policy: GenerationVerdicts | null = null;
+ let policyError: string | null = null;
+ try {
+ policy = await readVerdictsPolicy();
+ } catch (e) {
+ policyError = (e as Error).message;
+ }
+ const qs = (next: Partial<Search>) => {
+ const p = new URLSearchParams();
+ for (const [k, v] of Object.entries({ ...sp, run: id, ...next })) if (v) p.set(k, String(v));
+ return `/bench?${p.toString()}`;
+ };
+
+ return (
+ <div className="flex h-full flex-col">
+ <BrowseHeader
+ active="articles"
+ crumbs={[{ label: "articles", href: "/articles" }, { label: "verdict bench" }]}
+ note={`${runs.length} run${runs.length === 1 ? "" : "s"}`}
+ />
+ <main className="deck-main flex-1 p-4 text-[12px]">
+ {runs.length === 0 ? (
+ <p className="text-[var(--color-dim)]">
+ no bench runs — <code className="font-mono">archilyzer reports bench-verdicts --models …</code>
+ </p>
+ ) : (
+ <>
+ <nav aria-label="runs" className="mb-3 flex flex-wrap items-center gap-1.5">
+ <span className="micro">run</span>
+ {runs.map((r) => (
+ <Link
+ key={r.id}
+ href={`/bench?run=${r.id}`}
+ data-run={r.id}
+ aria-current={r.id === id ? "true" : undefined}
+ className={badgeVariants({ variant: r.id === id ? "on" : "neutral" })}
+ >
+ {r.id} · {r.status} · {r.items}
+ </Link>
+ ))}
+ </nav>
+ {!view ? (
+ <p role="alert" className="text-[var(--color-bad)]">
+ run {id} cannot be read
+ </p>
+ ) : (
+ <RunView view={view} policy={policy} policyError={policyError} sp={sp} qs={qs} />
+ )}
+ </>
+ )}
+ </main>
+ </div>
+ );
+}
+
+function RunView({
+ view,
+ policy,
+ policyError,
+ sp,
+ qs,
+}: {
+ view: NonNullable<Awaited<ReturnType<typeof readBenchView>>>;
+ policy: GenerationVerdicts | null;
+ policyError: string | null;
+ sp: Search;
+ qs: (n: Partial<Search>) => string;
+}) {
+ const { summary: s, score } = view;
+ const bar = policy?.bar ?? null;
+ const rows = filterBenchRows(view.items, { model: sp.model, verdict: sp.verdict });
+ const models = sp.model ? s.models.filter((m) => m === sp.model) : s.models;
+ return (
+ <div data-bench-run={s.id} data-status={s.status} className="flex flex-col gap-4">
+ <p role="status" className="text-[var(--color-dim)]">
+ {s.status} · {s.items} items · {s.skipped.length} skipped · a {s.windowS} s window · ${s.spentUsd.toFixed(4)} of ${s.maxUsd} ·{" "}
+ {new Date(s.createdAt).toISOString().slice(0, 16).replace("T", " ")} UTC
+ {s.stopped?.length ? ` · stopped: ${s.stopped.join("; ")}` : ""}
+ </p>
+ <section aria-label="models" className="flex flex-wrap gap-2">
+ {[...score.models, score.baseline].map((m) => (
+ <ModelTile key={m.model} m={m} baseline={m.model === BASELINE_MODEL ? null : score.baseline} pass={bar && m.model !== BASELINE_MODEL ? passesBar(m, bar) : null} />
+ ))}
+ </section>
+ <section aria-label="the bar" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3">
+ {policy ? (
+ <BarForm initial={policy} models={score.models} />
+ ) : (
+ <p role="alert" className="text-[var(--color-bad)]">
+ the bar cannot be read: {policyError}
+ </p>
+ )}
+ </section>
+ <section aria-label="confusion" className="flex flex-wrap gap-4">
+ {score.models.map((m) => (
+ <Matrix key={m.model} m={m} />
+ ))}
+ </section>
+ <section aria-label="items">
+ <div className="mb-2 flex flex-wrap items-center gap-1.5">
+ <span className="micro">model</span>
+ <Chip href={qs({ model: "" })} on={!sp.model} label="all" />
+ {s.models.map((m) => (
+ <Chip key={m} href={qs({ model: m })} on={sp.model === m} label={m} />
+ ))}
+ <span className="micro ml-3">operator</span>
+ <Chip href={qs({ verdict: "" })} on={!sp.verdict} label="all" />
+ {VERDICTS.filter((v) => score.ruled[v] > 0).map((v) => (
+ <Chip key={v} href={qs({ verdict: v })} on={sp.verdict === v} label={`${v} ${score.ruled[v]}`} />
+ ))}
+ </div>
+ <table className="w-full border-collapse">
+ <thead>
+ <tr className="micro text-left">
+ <th className="py-1 pr-2">claim</th>
+ <th className="py-1 pr-2">operator</th>
+ {models.map((m) => (
+ <th key={m} className="py-1 pr-2 font-mono">
+ {m}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((r) => (
+ <tr key={r.key} data-item={r.key} data-disagree={r.disagree.length ? r.disagree.join(" ") : undefined} className="border-t border-[var(--color-line)] align-top">
+ <td className="max-w-[28rem] py-1.5 pr-2">
+ <div className="font-mono text-[10px] text-[var(--color-dim)]">{r.key}</div>
+ {r.text}
+ </td>
+ <td className="py-1.5 pr-2 font-mono">{r.verdict}</td>
+ {models.map((m) => {
+ const a = r.answers[m];
+ return (
+ <td key={m} data-model={m} data-verdict={a?.verdict ?? "none"} className="max-w-[20rem] py-1.5 pr-2">
+ {!a ? (
+ <span className="text-[var(--color-dim)]">not asked</span>
+ ) : a.verdict ? (
+ <>
+ <span className={`font-mono ${a.verdict === r.verdict ? "text-[var(--color-good)]" : "text-[var(--color-bad)]"}`}>{a.verdict}</span>
+ {a.reason && <div className="text-[var(--color-dim)]">{a.reason}</div>}
+ </>
+ ) : (
+ <span className="text-[var(--color-bad)]">
+ {a.failure}: {a.error}
+ </span>
+ )}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </section>
+ {s.skipped.length > 0 && (
+ <details>
+ <summary className="micro cursor-pointer">skipped {s.skipped.length}</summary>
+ <ul aria-label="skipped" className="mt-1 flex flex-col gap-0.5">
+ {s.skipped.map((k) => (
+ <li key={k.key} className="font-mono text-[var(--color-dim)]">
+ {k.key} — {k.reason}
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+ </div>
+ );
+}
+
+function ModelTile({ m, baseline, pass }: { m: ModelScore; baseline: ModelScore | null; pass: { pass: boolean; misses: string[] } | null }) {
+ const vs = (v: number | null, b: number | null | undefined) => (baseline ? `${pct(v)} (baseline ${pct(b ?? null)})` : pct(v));
+ return (
+ <div
+ data-model={m.model}
+ data-pass={pass ? String(pass.pass) : undefined}
+ className="min-w-[15rem] rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2"
+ >
+ <div className="mb-1 flex items-center gap-2">
+ <span className="font-mono text-[var(--color-text)]">{m.model}</span>
+ {pass && (
+ <span className={badgeVariants({ variant: pass.pass ? "on" : "blocking", size: "sm" })} title={pass.misses.join("; ") || undefined}>
+ {pass.pass ? "passes" : "fails"} the bar
+ </span>
+ )}
+ </div>
+ <dl className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5">
+ <dt className="text-[var(--color-dim)]">agreement</dt>
+ <dd data-metric="agreement">{vs(m.agreement, baseline?.agreement)}</dd>
+ <dt className="text-[var(--color-dim)]">with PARTLY ~ CORROBORATED</dt>
+ <dd>{vs(m.agreementAdjacent, baseline?.agreementAdjacent)}</dd>
+ <dt className="text-[var(--color-dim)]">CONTRADICTED recall</dt>
+ <dd data-metric="contradicted">
+ {vs(m.recall.CONTRADICTED.recall, baseline?.recall.CONTRADICTED.recall)} of {m.recall.CONTRADICTED.ruled}
+ </dd>
+ <dt className="text-[var(--color-dim)]">NOT_FOUND recall</dt>
+ <dd data-metric="not-found">
+ {vs(m.recall.NOT_FOUND.recall, baseline?.recall.NOT_FOUND.recall)} of {m.recall.NOT_FOUND.ruled}
+ </dd>
+ <dt className="text-[var(--color-dim)]">PARTLY recall</dt>
+ <dd>
+ {pct(m.recall.PARTLY.recall)} · adjacent {pct(m.recall.PARTLY_ADJACENT.recall)}
+ </dd>
+ {baseline && (
+ <>
+ <dt className="text-[var(--color-dim)]">cost</dt>
+ <dd data-metric="cost">${m.usd.toFixed(4)}</dd>
+ <dt className="text-[var(--color-dim)]">latency</dt>
+ <dd>{m.latency.medianMs === null ? "—" : `${(m.latency.medianMs / 1000).toFixed(1)} s median, ${((m.latency.p90Ms ?? 0) / 1000).toFixed(1)} s p90`}</dd>
+ <dt className="text-[var(--color-dim)]">answered</dt>
+ <dd>
+ {m.answered} of {m.asked}
+ {m.parseFailures ? ` · ${m.parseFailures} parse failures` : ""}
+ {m.errors ? ` · ${m.errors} errors` : ""}
+ </dd>
+ </>
+ )}
+ </dl>
+ </div>
+ );
+}
+
+function Matrix({ m }: { m: ModelScore }) {
+ return (
+ <table aria-label={`confusion ${m.model}`} className="border-collapse font-mono text-[11px]">
+ <caption className="micro mb-1 text-left">
+ {m.model} — rows: operator, columns: model
+ </caption>
+ <thead>
+ <tr>
+ <th />
+ {VERDICTS.map((v) => (
+ <th key={v} className="px-1.5 py-0.5 text-[var(--color-dim)]" title={v}>
+ {v.slice(0, 4)}
+ </th>
+ ))}
+ <th className="px-1.5 py-0.5 text-[var(--color-dim)]">none</th>
+ </tr>
+ </thead>
+ <tbody>
+ {VERDICTS.map((op, i) => (
+ <tr key={op}>
+ <th className="pr-1.5 text-left text-[var(--color-dim)]">{op}</th>
+ {VERDICTS.map((v, j) => (
+ <td
+ key={v}
+ data-cell={`${op}:${v}`}
+ className={`border border-[var(--color-line)] px-1.5 py-0.5 text-right ${i === j && m.matrix[i]![j]! > 0 ? "text-[var(--color-good)]" : m.matrix[i]![j]! > 0 ? "text-[var(--color-text)]" : "text-[var(--color-dim)]"}`}
+ >
+ {m.matrix[i]![j]}
+ </td>
+ ))}
+ <td className="border border-[var(--color-line)] px-1.5 py-0.5 text-right text-[var(--color-dim)]">{m.unanswered[i]}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ );
+}
+
+function Chip({ href, on, label }: { href: string; on: boolean; label: string }) {
+ return (
+ <Link href={href} aria-current={on ? "true" : undefined} className={badgeVariants({ variant: on ? "on" : "neutral" })}>
+ {label}
+ </Link>
+ );
+}
diff --git a/umtool/components/articles/ResearchSlot.tsx b/umtool/components/articles/ResearchSlot.tsx
@@ -19,6 +19,11 @@ import type { ResearchProposal, ResearchView } from "@/lib/articles/research";
// /api/articles/research), which refreshes the enqueued acquisitions from
// their jobs; it is re-read every 4 s while the run's job or an acquisition's
// is going.
+//
+// An `auto` run continues by itself once its acquisitions settle (release 28
+// F1, the editor's researchAutoContinue): the queue says "continued
+// automatically" with the channels it left out, or why it has not (held for
+// a build, refused by a cap).
const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]";
@@ -38,6 +43,29 @@ const PHASE_SAYS: Record<ResearchView["phase"], string> = {
continued: "continued",
};
+// An `auto` run's own continuation: done (by which sweep, and what it left
+// out), or why not yet.
+function AutoContinued({ ac }: { ac: NonNullable<ResearchView["autoContinue"]> }) {
+ if (ac.status === "continued") {
+ return (
+ <div data-auto-continued={ac.by ?? ""} className="flex flex-col gap-0.5">
+ <span className="text-[var(--color-text)]">continued automatically{ac.by ? ` by i${ac.by}` : ""}</span>
+ {(ac.warnings ?? []).map((w, i) => (
+ <span key={i} className="text-[var(--color-dirty)]">
+ {w}
+ </span>
+ ))}
+ </div>
+ );
+ }
+ if (ac.status === "claimed") return <span data-auto-continue="claimed">continuing automatically…</span>;
+ return (
+ <p data-auto-continue={ac.status} className="text-[var(--color-dirty)]">
+ {ac.status === "held" ? "not continued automatically yet" : "not continued automatically today"}: {ac.reason}
+ </p>
+ );
+}
+
// What an acquisition is for, in one line: its channel and what it fetches.
function target(p: ResearchProposal): string {
const a = p.args;
@@ -273,6 +301,7 @@ export default function ResearchSlot({
</>
)}
</div>
+ {view?.autoContinue && <AutoContinued ac={view.autoContinue} />}
{view?.notes && <p className="whitespace-pre-wrap text-[13px] text-[var(--color-text)]">{view.notes}</p>}
{view && view.proposals.length === 0 && !active && <p className="text-[var(--color-dim)]">no acquisitions proposed</p>}
{view && view.proposals.length > 0 && (
diff --git a/umtool/components/bench/BarForm.tsx b/umtool/components/bench/BarForm.tsx
@@ -0,0 +1,103 @@
+"use client";
+
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { passesBar, type ModelScore, type VerdictBar } from "yt-dlp-transcript-common/lib/report/draft/bench/score";
+import type { GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings";
+
+// THE BAR (release 28 M7): the least agreement, CONTRADICTED recall and
+// NOT_FOUND recall a model must reach on this run, and the passing models the
+// operator ticks for the verdict proposals — settings.generation.verdicts,
+// written whole through /api/bench/bar (the editor's settings action). A
+// model is never ticked automatically, and one that fails the bar as typed
+// cannot be ticked.
+
+const KEYS: { key: keyof VerdictBar; label: string }[] = [
+ { key: "agreement", label: "minimum agreement" },
+ { key: "contradictedRecall", label: "minimum CONTRADICTED recall" },
+ { key: "notFoundRecall", label: "minimum NOT_FOUND recall" },
+];
+const field = "w-16 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]";
+const toPct = (v: number) => String(Math.round(v * 1000) / 10);
+
+export default function BarForm({ initial, models }: { initial: GenerationVerdicts; models: ModelScore[] }) {
+ const [typed, setTyped] = useState(() => Object.fromEntries(KEYS.map((k) => [k.key, toPct(initial.bar[k.key])])) as Record<keyof VerdictBar, string>);
+ const [ticked, setTicked] = useState<string[]>(initial.models);
+ const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null);
+ const [busy, setBusy] = useState(false);
+ const bar = Object.fromEntries(KEYS.map((k) => [k.key, Math.min(100, Math.max(0, Number(typed[k.key]) || 0)) / 100])) as VerdictBar;
+ // A model ticked in settings but not in this run is kept as it is.
+ const here = new Set(models.map((m) => m.model));
+
+ async function save(e: React.FormEvent) {
+ e.preventDefault();
+ setBusy(true);
+ setStatus(null);
+ const keep = ticked.filter((m) => !here.has(m) || passesBar(models.find((x) => x.model === m)!, bar).pass);
+ try {
+ const r = await fetch("/api/bench/bar", { method: "POST", body: JSON.stringify({ bar, models: keep }) });
+ const body = await r.json();
+ if (!r.ok) throw new Error(body.error ?? `HTTP ${r.status}`);
+ const v = body.verdicts as GenerationVerdicts;
+ setTyped(Object.fromEntries(KEYS.map((k) => [k.key, toPct(v.bar[k.key])])) as Record<keyof VerdictBar, string>);
+ setTicked(v.models);
+ setStatus({ ok: true, text: "Saved." });
+ } catch (err) {
+ setStatus({ ok: false, text: (err as Error).message });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <form aria-label="bar" onSubmit={save} className="flex flex-col gap-2 text-[12px]">
+ <div className="flex flex-wrap items-center gap-3">
+ <span className="micro">the bar</span>
+ {KEYS.map((k) => (
+ <label key={k.key} className="flex items-center gap-1">
+ <span className="text-[var(--color-dim)]">{k.label}</span>
+ <input
+ aria-label={k.label}
+ className={field}
+ type="number"
+ min={0}
+ max={100}
+ step={0.1}
+ value={typed[k.key]}
+ onChange={(e) => setTyped({ ...typed, [k.key]: e.target.value })}
+ />
+ <span className="text-[var(--color-dim)]">%</span>
+ </label>
+ ))}
+ </div>
+ <div className="flex flex-wrap items-center gap-3">
+ <span className="micro">verdict proposals on</span>
+ {models.map((m) => {
+ const check = passesBar(m, bar);
+ const on = ticked.includes(m.model) && check.pass;
+ return (
+ <label key={m.model} data-model={m.model} data-pass={String(check.pass)} className="flex items-center gap-1" title={check.misses.join("; ") || undefined}>
+ <input
+ type="checkbox"
+ aria-label={`use ${m.model}`}
+ checked={on}
+ disabled={!check.pass}
+ onChange={(e) => setTicked(e.target.checked ? [...new Set([...ticked, m.model])] : ticked.filter((x) => x !== m.model))}
+ />
+ <span className="font-mono">{m.model}</span>
+ <span className={check.pass ? "text-[var(--color-good)]" : "text-[var(--color-bad)]"}>{check.pass ? "passes" : "fails"}</span>
+ </label>
+ );
+ })}
+ <Button type="submit" size="sm" disabled={busy}>
+ Save the bar
+ </Button>
+ {status && (
+ <span role="status" className={status.ok ? "text-[var(--color-dim)]" : "text-[var(--color-bad)]"}>
+ {status.text}
+ </span>
+ )}
+ </div>
+ </form>
+ );
+}
diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx
@@ -30,6 +30,7 @@ import ReportBuildChain from "./ReportBuildChain";
import SnapshotButton from "./SnapshotButton";
import DeleteProject from "./DeleteProject";
import TagCitedButton from "./TagCitedButton";
+import YoutubeSection from "./YoutubeSection";
import { RowControls, RowNotes, TimelineList } from "./TimelineEditor";
import GeneratedBanner from "@/components/notes/GeneratedBanner";
import { NotesProvider } from "@/components/notes/NotesProvider";
@@ -760,6 +761,9 @@ export default async function ReportProject({
)}
</section>
+ {/* --- the upload's text (out/youtube.txt, or its preview) --------- */}
+ <YoutubeSection dir={project.dir} manifest={m as Record<string, unknown>} />
+
{/* --- exports --------------------------------------------------- */}
<section data-exports="" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2">
<h2 className="micro mb-1">export</h2>
diff --git a/umtool/components/projects/YoutubeSection.tsx b/umtool/components/projects/YoutubeSection.tsx
@@ -0,0 +1,53 @@
+import { readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import CopyButton from "@/components/CopyButton";
+import { fmtAgo } from "@/lib/format";
+import { youtubePreview, youtubeTextName } from "umtool-report-to-video/youtube";
+
+// The upload's text (release 28 M6): what the build wrote to
+// out/youtube.txt — the title, the summary, the chapters and the sources —
+// or, before a build, the same text composed from the manifest without the
+// chapters. Shown with Copy. Nothing when the cut has no publish.youtube and
+// no built text.
+
+type Props = { dir: string; manifest: Record<string, unknown> };
+
+export default async function YoutubeSection({ dir, manifest }: Props) {
+ const file = path.join(dir, "out", youtubeTextName("sourced"));
+ const built = await readFile(file, "utf8").catch(() => null);
+ const mtimeMs = built === null ? null : await stat(file).then((s) => s.mtimeMs, () => null);
+ const preview = youtubePreview(manifest);
+ const text = built ?? preview.text;
+ if (!text) return null;
+ const yt = (manifest.publish as { youtube?: { title?: string; description?: string } } | undefined)?.youtube;
+ // The built text starts with the title and the summary as they were then.
+ const head = [yt?.title?.trim(), yt?.description?.trim()].filter(Boolean).join("\n\n");
+ const stale = built !== null && !!head && !built.startsWith(head);
+ const drafted = (manifest.drafted as Record<string, { model?: string }> | undefined)?.["publish.youtube"];
+ return (
+ <section
+ data-youtube={built !== null ? "built" : "preview"}
+ aria-label="YouTube text"
+ className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"
+ >
+ <div className="mb-1 flex flex-wrap items-baseline gap-3">
+ <h2 className="micro">youtube</h2>
+ <span className="num text-[11px] text-[var(--color-dim)]" data-youtube-status="">
+ {built !== null
+ ? `out/${youtubeTextName("sourced")}${mtimeMs ? `, built ${fmtAgo(mtimeMs)}` : ""}${stale ? " — the title or summary has changed since: rebuild" : ""}`
+ : `preview — ${preview.note}`}
+ {drafted ? ` · drafted by ${drafted.model ?? "a model"}` : ""}
+ </span>
+ <span className="ml-auto">
+ <CopyButton text={text} label="Copy" title="copy the YouTube title and description" />
+ </span>
+ </div>
+ <pre
+ data-youtube-text=""
+ className="max-h-[40vh] overflow-y-auto whitespace-pre-wrap break-words font-mono text-[11px] text-[var(--color-text)]"
+ >
+ {text}
+ </pre>
+ </section>
+ );
+}
diff --git a/umtool/e2e/article-research.spec.ts b/umtool/e2e/article-research.spec.ts
@@ -25,7 +25,10 @@ test.beforeAll(async ({ playwright }) => {
test.setTimeout(WARM_TIMEOUT);
await warm(playwright, ["/articles/new", "/api/articles/policy", "/api/articles/channels", "/articles/zeta?tab=iterations"]);
});
-test.afterAll(() => rmSync(path.join(FIXTURE, "articles", ARTICLE), { recursive: true, force: true }));
+const AUTO = "research-auto-e2e";
+test.afterAll(() => {
+ for (const a of [ARTICLE, AUTO]) rmSync(path.join(FIXTURE, "articles", a), { recursive: true, force: true });
+});
test("research: started with an autonomy, its queue answered yes and no, its job followed, then continued into a sweep", async ({ page }) => {
test.setTimeout(120_000);
@@ -110,6 +113,33 @@ test("research: started with an autonomy, its queue answered yes and no, its job
await expect(page.locator("[data-iteration='1'] [data-continued-by]")).toHaveAttribute("data-continued-by", "2");
});
+// Release 28 F1: an `auto` run whose acquisitions settled is continued by the
+// editor itself — umtool asks for nothing, and its queue says so.
+test("research: an auto run continues into its sweep by itself, and the queue says so", async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.goto("/articles/new");
+ const form = page.getByRole("form", { name: "new article" });
+ await form.getByRole("radio", { name: /^research/ }).check();
+ await form.getByRole("combobox", { name: "autonomy" }).selectOption("auto");
+ await form.getByRole("textbox", { name: "question" }).fill("Where did the recount story start?");
+ await form.getByRole("textbox", { name: "article id" }).fill(AUTO);
+ await form.getByRole("button", { name: "Start" }).click();
+ await expect(page).toHaveURL(new RegExp(`/articles/${AUTO}\\?tab=iterations$`));
+ expect(stubAsked("report-draft").at(-1)).toMatchObject({ task: "research", article: AUTO, autonomy: "auto" });
+
+ const slot = page.locator("[data-iteration='1']").getByRole("region", { name: "i1 research" });
+ await expect(slot.locator("[data-auto-continued]")).toHaveAttribute("data-auto-continued", "2", { timeout: 20_000 });
+ await expect(slot.locator("[data-auto-continued]")).toContainText("continued automatically by i2");
+ await expect(slot.locator("[data-auto-continued]")).toContainText("not in any build yet: radio-tape");
+ await expect(slot).toHaveAttribute("data-research-phase", "continued");
+ const sweep = page.locator("[data-iteration='2']");
+ await expect(sweep).toHaveAttribute("data-kind", "sweep");
+ await expect(sweep).toContainText("of i1");
+ await expect(sweep).toContainText("unbuilt channels: not in any build yet: radio-tape");
+ // Umtool posted no sweep: the editor made it.
+ expect(stubAsked("report-draft").filter((r) => r.article === AUTO).map((r) => r.task)).toEqual(["research"]);
+});
+
test("the research route refuses what is not a decision", async ({ request }) => {
const bad = await request.post("/api/articles/research", { data: { article: ARTICLE, n: 1, ids: ["p01"] } });
expect(bad.status()).toBe(400);
diff --git a/umtool/e2e/fixtures/bench-fixture.mjs b/umtool/e2e/fixtures/bench-fixture.mjs
@@ -0,0 +1,79 @@
+// A verdict bench run, synthetic (release 28 M7), for verdict-bench.spec.ts:
+// four invented claims ruled CORROBORATED, PARTLY, CONTRADICTED and
+// NOT_FOUND, asked of two models — one right on three (it calls the PARTLY
+// one CORROBORATED), one that always says CORROBORATED and fails to parse
+// once. Written as `archilyzer reports bench-verdicts` writes a run
+// (common/lib/report/draft/bench/store.ts); the page scores it again.
+
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const BENCH_RUN = "vb-e2e";
+export const SONNET = "claude-sonnet-5-5";
+export const QWEN = "qwen3:8b";
+
+const claims = [
+ ["c1", "The article says she opened the shop in spring.", "CORROBORATED"],
+ ["c2", "The article says the oven was broken for a month.", "PARTLY"],
+ ["c3", "The article says she sold the van.", "CONTRADICTED"],
+ ["c4", "The article says she named the supplier.", "NOT_FOUND"],
+];
+const said = {
+ [SONNET]: ["CORROBORATED", "CORROBORATED", "CONTRADICTED", "NOT_FOUND"],
+ [QWEN]: ["CORROBORATED", "CORROBORATED", "CORROBORATED", null],
+};
+
+export function makeBenchRun(root) {
+ const dir = path.join(root, BENCH_RUN);
+ rmSync(dir, { recursive: true, force: true });
+ mkdirSync(dir, { recursive: true });
+ const items = claims.map(([id, text, verdict], i) => ({
+ key: `synth-bench/${id}`,
+ report: "synth-bench",
+ claim: id,
+ text,
+ verdict,
+ quotes: [{ citation: `q${i}`, channel: "synth-kitchen", id: "bread-day-01", start: 10 + i * 15, end: 14 + i * 15, quote: "a line" }],
+ windows: [{ channel: "synth-kitchen", id: "bread-day-01", from: 0, to: 80, cited: [{ start: 10 + i * 15, end: 14 + i * 15 }], cues: [{ start: 10 + i * 15, end: 14 + i * 15, text: "a line" }] }],
+ }));
+ const results = [];
+ for (const [model, verdicts] of Object.entries(said)) {
+ items.forEach((it, i) => {
+ const v = verdicts[i];
+ results.push({
+ key: it.key,
+ model,
+ verdict: v,
+ ...(v ? { reason: `${model} read the window for ${it.claim}` } : { failure: "parse", error: "the answer is not JSON" }),
+ ms: 1200 + i * 100,
+ usd: model === SONNET ? 0.004 : 0,
+ inputTokens: 900,
+ outputTokens: 60,
+ at: "2026-10-13T12:00:00.000Z",
+ });
+ });
+ }
+ const jsonl = (rows) => rows.map((r) => `${JSON.stringify(r)}\n`).join("");
+ writeFileSync(path.join(dir, "items.jsonl"), jsonl(items));
+ writeFileSync(path.join(dir, "results.jsonl"), jsonl(results));
+ writeFileSync(
+ path.join(dir, "summary.json"),
+ JSON.stringify({
+ format: "archilyzer-verdict-bench",
+ version: 1,
+ id: BENCH_RUN,
+ createdAt: "2026-10-13T12:00:00.000Z",
+ updatedAt: "2026-10-13T12:05:00.000Z",
+ status: "done",
+ models: [SONNET, QWEN],
+ windowS: 60,
+ maxUsd: 5,
+ reports: [],
+ spentUsd: 0.016,
+ items: items.length,
+ skipped: [{ key: "synth-bench/c5", report: "synth-bench", claim: "c5", reason: "no citation" }],
+ score: {},
+ }),
+ );
+ return dir;
+}
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -186,11 +186,12 @@ function finishDraft(job) {
}
const claude = it.model.startsWith("claude-");
const usage = claude ? { [it.model]: { usd: 0.37, inputTokens: 41000, outputTokens: 2100, calls: 6 } } : {};
- const patch = { status: "done", usage, minutes: 0.1, endedAt: now, checks: [{ name: "strict-quotes", ok: true }] };
+ // A check written beside the job (auto-continue's) is kept, as the task's own merge does.
+ const patch = { status: "done", usage, minutes: 0.1, endedAt: now, checks: [...(it.checks ?? []).filter((c) => c.name !== "strict-quotes"), { name: "strict-quotes", ok: true }] };
if (it.kind === "research") {
const autonomy = job.autonomy ?? "propose";
writeFileSync(path.join(itDir(article, n), "proposals.json"), JSON.stringify(stubProposals(autonomy), null, 2) + "\n");
- patch.research = { autonomy, phase: "wait", notes: "The archive holds one stream on it. I asked for the episode and a channel for the radio tape." };
+ patch.research = { autonomy, phase: autonomy === "auto" ? "ready" : "wait", notes: "The archive holds one stream on it. I asked for the episode and a channel for the radio tape." };
delete patch.checks;
} else if (it.kind === "sweep") {
writeFileSync(path.join(itDir(article, n), "report.json"), JSON.stringify(stubReport(article, `Sweep: ${it.question ?? "a copy"}`), null, 2) + "\n");
@@ -213,6 +214,20 @@ function finishDraft(job) {
patchIt(article, n, patch);
job.status = "done";
job.log.push("stub: wrote the iteration", `@@report-draft ${JSON.stringify({ article, iteration: n, task, status: "done" })}`);
+ if (it.kind === "research" && job.autonomy === "auto") autoContinue(article, n);
+}
+
+// An `auto` run's acquisitions have settled: the editor continues it by
+// itself (release 28 F1, controller/researchAutoContinue.ts) — a sweep on the
+// run's model over the channels in a build (the new channel is in none: left
+// out, with the warning), recorded on the run and as a failed check on the sweep.
+function autoContinue(article, n) {
+ const r = readIt(article, n);
+ const warning = "not in any build yet: radio-tape — rebuild the site and continue again";
+ const { iteration: by } = startDraft({ task: "sweep", article, iteration: n, model: r.model, channels: ["sitechan"] });
+ patchIt(article, by, { checks: [{ name: "unbuilt channels", ok: false, detail: warning }] });
+ const now = readIt(article, n);
+ patchIt(article, n, { research: { ...now.research, autoContinue: { status: "continued", at: new Date().toISOString(), by, warnings: [warning] } } });
}
// ─── research (release 27 S11) ───
@@ -220,6 +235,18 @@ function finishDraft(job) {
// What the stub's research run proposes: as the real run under `propose`
// (every acquisition waits; the Twitch VOD refused by the standing rule).
function stubProposals(autonomy) {
+ // Under `auto` (release 28 F1): the import ran and the channel was made;
+ // the Twitch VOD is refused in every mode.
+ if (autonomy === "auto") {
+ const base = stubProposals("propose");
+ const doneAt = new Date().toISOString();
+ base.autonomy = "auto";
+ base.spent = { items: 1, gb: 0.2, transcribeHours: 0 };
+ base.proposals[0] = { ...base.proposals[0], status: "done", jobId: "stub-acq-auto", doneAt };
+ base.proposals[1] = { ...base.proposals[1], status: "done", channel: "radio-tape", doneAt };
+ for (const p of base.proposals.slice(0, 2)) delete p.note;
+ return base;
+ }
return {
format: "archilyzer-research-proposals",
version: 1,
@@ -296,6 +323,7 @@ function researchView(article, n, st) {
},
continuedBy: rec.continuedBy ?? [],
...(rec.notes ? { notes: rec.notes } : {}),
+ ...(rec.autoContinue ? { autoContinue: rec.autoContinue } : {}),
};
}
@@ -343,7 +371,7 @@ function settleResearch(body) {
// A sweep continuing research run `rn`: its question, its channels widened by
// what was acquired (refused while it waits, unless force).
-function continuation(article, rn, force) {
+function continuation(article, rn, force, given) {
const r = readIt(article, rn);
if (r.kind !== "research") throw new Error(`a sweep with "iteration" continues a research run; "${article}" i${rn} is a ${r.kind} iteration`);
if (r.status !== "done") throw new Error(`"${article}" i${rn} is ${r.status}: only a done research run is continued`);
@@ -356,7 +384,7 @@ function continuation(article, rn, force) {
if (p.status !== "done") continue;
for (const c of [p.channel, p.args?.slug]) if (typeof c === "string" && !channels.includes(c)) channels.push(c);
}
- return { kind: "sweep", parent: rn, copyOf: null, question: r.question, scope: { channels } };
+ return { kind: "sweep", parent: rn, copyOf: null, question: r.question, scope: { channels: given ?? channels } };
}
// The media drafts (release 28) run FOR REAL: the common task over the
@@ -424,7 +452,7 @@ function startDraft(body) {
} else if (task === "research") {
base = { kind: "research", parent: null, copyOf: null, question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}) } };
} else if (task === "sweep" && body.iteration) {
- base = continuation(article, body.iteration, body.force === true);
+ base = continuation(article, body.iteration, body.force === true, Array.isArray(body.channels) ? body.channels : undefined);
} else if (task === "sweep") {
base = { kind: "sweep", parent: null, copyOf: null, question: body.question, scope: { channels: body.channels, ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } };
} else {
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -27,6 +27,7 @@ import { makeIterationsFixture } from "./iterations-fixture.mjs";
import { makeMediaDraftFixture } from "./media-draft-fixture.mjs";
import { makeDeleteFixture } from "./delete-fixture.mjs";
import { makeDraftReviewFixture } from "./draft-review-fixture.mjs";
+import { makeYoutubeFixture } from "./youtube-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -1657,6 +1658,8 @@ for (const dir of [BENCH, BUILD, ONSCREEN, ONSCREEN_BUILD, ONSCREEN_POSTS, ONSCR
// Release 28: drafted fields to review, and a final build they hold
// (draft-review.spec.ts).
makeDraftReviewFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
+// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
+makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// TWO MORE cached windows for vid1, and they are the regression rather than
// decoration.
@@ -1961,4 +1964,5 @@ console.log(` takes-fixture (writable: takes/ with 4 takes over 2 gro
console.log(` narration-fixture (writable: a narrated card, voiced by the editor stub's tone)`);
console.log(` narration-review-fixture (writable: two narrated cards, nothing judged)`);
console.log(` draft-review-fixture (writable: drafted on-screen, narration, teaser; an alternative), draft-review-build-fixture`);
+console.log(` youtube-fixture (writable: a drafted publish.youtube, built fast to out/youtube.txt)`);
console.log(` ${taken} candidate files copied, 2 mix tracks synthesised`);
diff --git a/umtool/e2e/fixtures/youtube-fixture.mjs b/umtool/e2e/fixtures/youtube-fixture.mjs
@@ -0,0 +1,32 @@
+// What media-draft-e.spec.ts reads (release 28, M6): a cut whose
+// publish.youtube was drafted, three cards long enough to make YouTube
+// chapters, and two clips over the cached window the build fixtures share —
+// so the project page previews the YouTube text, and a fast build writes
+// out/youtube.txt with its chapters and sources. Its own, so the other specs'
+// projects are never touched. Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+const P = (task, model = "qwen3:8b") => ({ task, model, at: "2026-10-13T10:00:00.000Z", iteration: 1, attempt: 1 });
+
+/**
+ * @param {{ reports: string, manifest: Function, cachedWindow: string }} o
+ * `manifest` is make-fixture's manifest(slug, title, provenance, timeline);
+ * `cachedWindow` the vid1 0-9 s window the build fixtures share.
+ */
+export function makeYoutubeFixture({ reports, manifest, cachedWindow }) {
+ const dir = path.join(reports, "youtube-fixture");
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ const m = manifest("youtube-fixture", "The YouTube Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "card", id: "title", style: "title", seconds: 10, heading: "The YouTube Fixture" },
+ { type: "clip", id: "c01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "and because" },
+ { type: "card", id: "k01", style: "chapter", seconds: 10, heading: "The county" },
+ { type: "clip", id: "c02", video: "vid1", start: 9.0, end: 12.0, cite: 9, section: 0, lock: true, quote: "another whole sentence" },
+ { type: "card", id: "k02", style: "chapter", seconds: 10, heading: "Then" },
+ ]);
+ m.publish = { youtube: { title: "The county said yes", description: "Half a year on, the county said yes, and the fixture says so." } };
+ m.drafted = { "publish.youtube": P("youtube") };
+ writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
+ copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", path.basename(cachedWindow)));
+ return { dir };
+}
diff --git a/umtool/e2e/media-draft-e.spec.ts b/umtool/e2e/media-draft-e.spec.ts
@@ -0,0 +1,69 @@
+import { test, expect } from "@playwright/test";
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// ---------------------------------------------------------------------------
+// Release 28 lane E's media drafts, as umtool shows them (M6): the project
+// page's YouTube text — previewed from publish.youtube before a build (the
+// sources, no chapters), copied with Copy, then as a fast build writes it to
+// out/youtube.txt with the build's own chapters (YouTube's rules) and a moment
+// link per cited clip. The flips, threads and youtube tasks themselves run
+// over the fake LLM in common's and the MCP's suites; umtool's "Draft with"
+// buttons are M9's. Fixture: e2e/fixtures/youtube-fixture.mjs.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/youtube-fixture";
+const DIR = path.join(FIXTURE, "reports", "youtube-fixture");
+const TITLE = "The county said yes";
+const SUMMARY = "Half a year on, the county said yes, and the fixture says so.";
+const SOURCES = ["https://archive.example/?v=testchan%2Fvid1&t=3", "https://archive.example/?v=testchan%2Fvid1&t=9"];
+
+test("the YouTube text: a preview before the build, Copy, then out/youtube.txt with chapters and sources", async ({ page, request, context }) => {
+ test.setTimeout(300_000);
+ await context.grantPermissions(["clipboard-read", "clipboard-write"]);
+ await page.goto(`/browse/${PROJECT}`);
+ const section = page.locator("[data-youtube]");
+ await expect(section).toHaveAttribute("data-youtube", "preview");
+ await expect(section.locator("[data-youtube-status]")).toContainText("chapters are added by the build");
+ await expect(section.locator("[data-youtube-status]")).toContainText("drafted by qwen3:8b");
+ const preview = await section.locator("[data-youtube-text]").textContent();
+ expect(preview).toBe(`${TITLE}\n\n${SUMMARY}\n\nSources\n${SOURCES.join("\n")}\n`);
+ await section.getByRole("button", { name: "Copy" }).click();
+ await expect(section.locator("[data-copy]")).toHaveAttribute("data-state", "done");
+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(preview);
+
+ // A fast build (hard cuts) writes the text with the build's chapters.
+ const start = await request.post("/api/report/build", { data: { project: PROJECT, preset: "fast" } });
+ expect(start.ok(), await start.text()).toBeTruthy();
+ const { job } = (await start.json()) as { job: { id: string } };
+ let done: { state: string; error: string | null } = { state: "running", error: null };
+ const until = Date.now() + 240_000;
+ while (Date.now() < until) {
+ done = (await (await request.get(`/api/report/build?job=${job.id}`)).json()) as typeof done;
+ if (done.state !== "running") break;
+ await new Promise((r) => setTimeout(r, 400));
+ }
+ expect(done.state, done.error ?? "").toBe("done");
+ const file = path.join(DIR, "out", "youtube.txt");
+ expect(existsSync(file)).toBe(true);
+ const text = readFileSync(file, "utf8");
+ const [title, , summary, , chaptersHead, ...rest] = text.split("\n");
+ expect([title, summary, chaptersHead]).toEqual([TITLE, SUMMARY, "Chapters"]);
+ // Five entries; the two under ten seconds after a chapter are folded: three
+ // chapters, the first at 0:00 (the title card), the clips' at 0:10 and 0:2x.
+ const chapters = rest.slice(0, rest.indexOf(""));
+ expect(chapters.length).toBe(3);
+ expect(chapters[0]).toBe("0:00 The YouTube Fixture");
+ expect(chapters[1]).toMatch(/^0:1\d /);
+ expect(chapters[2]).toMatch(/^0:2\d /);
+ expect(text.endsWith(`\n\nSources\n${SOURCES.join("\n")}\n`)).toBe(true);
+
+ // The page shows the built text now.
+ await page.reload();
+ await expect(section).toHaveAttribute("data-youtube", "built");
+ await expect(section.locator("[data-youtube-status]")).toContainText("out/youtube.txt, built");
+ expect(await section.locator("[data-youtube-text]").textContent()).toBe(text);
+});
diff --git a/umtool/e2e/verdict-bench.spec.ts b/umtool/e2e/verdict-bench.spec.ts
@@ -0,0 +1,97 @@
+import { test, expect } from "@playwright/test";
+import { readFileSync, rmSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { WARM_TIMEOUT, warm } from "./warm";
+import { BENCH_RUN, QWEN, SONNET, makeBenchRun } from "./fixtures/bench-fixture.mjs";
+
+// ---------------------------------------------------------------------------
+// The verdict bench's page (release 28 M7) over a synthetic run in the
+// fixture's `.generation`-style root (GENERATION_USAGE_FILE is the fixture's,
+// so the runs root is <fixture>/bench/verdicts): the tiles against the
+// baseline, the confusion matrix, the items with disagreements first and the
+// filters, and the bar — written through the (stubbed) editor's settings
+// action, each model's pass or fail read against it, and a failing model
+// never tickable.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const ROOT = path.join(FIXTURE, "bench", "verdicts");
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+const stubAsked = (route: string) =>
+ (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; [k: string]: unknown }[]).filter((r) => r.route === route);
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ makeBenchRun(ROOT);
+ await warm(playwright, ["/bench", "/api/bench/bar"]);
+});
+test.afterAll(async ({ request }) => {
+ await request.post("/api/bench/bar", { data: { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] } });
+ rmSync(path.join(ROOT, BENCH_RUN), { recursive: true, force: true });
+});
+
+test("the run: each model's tile against the baseline, the matrix, the items with disagreements first, the filters", async ({ page }) => {
+ await page.goto("/articles");
+ await page.getByRole("link", { name: "verdict bench" }).click();
+ await expect(page).toHaveURL(/\/bench$/);
+ await expect(page.locator(`[data-bench-run="${BENCH_RUN}"]`)).toHaveAttribute("data-status", "done");
+ const models = page.getByRole("region", { name: "models" });
+ const sonnet = models.locator(`[data-model="${SONNET}"]`);
+ await expect(sonnet.locator('[data-metric="agreement"]')).toHaveText("75% (baseline 25%)");
+ await expect(sonnet.locator('[data-metric="contradicted"]')).toHaveText("100% (baseline 0%) of 1");
+ await expect(sonnet.locator('[data-metric="not-found"]')).toHaveText("100% (baseline 0%) of 1");
+ await expect(sonnet.locator('[data-metric="cost"]')).toHaveText("$0.0160");
+ const qwen = models.locator(`[data-model="${QWEN}"]`);
+ await expect(qwen.locator('[data-metric="agreement"]')).toHaveText("25% (baseline 25%)");
+ await expect(qwen).toContainText("3 of 4 · 1 parse failures");
+ await expect(models.locator('[data-model="always-CORROBORATED"]')).toBeVisible();
+ // The matrix: rows the operator, columns the model.
+ const m = page.getByRole("table", { name: `confusion ${SONNET}` });
+ await expect(m.locator('[data-cell="PARTLY:CORROBORATED"]')).toHaveText("1");
+ await expect(m.locator('[data-cell="CONTRADICTED:CONTRADICTED"]')).toHaveText("1");
+ // The items: every disagreement first.
+ const rows = page.getByRole("region", { name: "items" }).locator("tbody tr");
+ await expect(rows).toHaveCount(4);
+ await expect(rows.nth(0)).toHaveAttribute("data-item", "synth-bench/c2");
+ await expect(rows.nth(3)).toHaveAttribute("data-item", "synth-bench/c1");
+ await expect(rows.nth(0).locator(`[data-model="${SONNET}"]`)).toContainText("read the window for c2");
+ await expect(rows.nth(2).locator(`[data-model="${QWEN}"]`)).toContainText("parse: the answer is not JSON");
+ // By model: that model's disagreements first, its column alone.
+ await page.getByRole("region", { name: "items" }).getByRole("link", { name: SONNET, exact: true }).click();
+ await expect(rows.nth(0)).toHaveAttribute("data-item", "synth-bench/c2");
+ await expect(rows.nth(1)).toHaveAttribute("data-item", "synth-bench/c1");
+ await expect(page.getByRole("region", { name: "items" }).locator(`thead th`)).toHaveCount(3);
+ // By the operator's verdict.
+ await page.getByRole("region", { name: "items" }).getByRole("link", { name: "CONTRADICTED 1" }).click();
+ await expect(rows).toHaveCount(1);
+ await expect(rows.nth(0)).toHaveAttribute("data-item", "synth-bench/c3");
+ await expect(page.getByText("skipped 1")).toBeVisible();
+});
+
+test("the bar: saved through the editor's settings action; a passing model ticked, a failing one never", async ({ page }) => {
+ await page.goto(`/bench?run=${BENCH_RUN}`);
+ const form = page.getByRole("form", { name: "bar" });
+ await form.getByRole("spinbutton", { name: "minimum agreement" }).fill("50");
+ await form.getByRole("spinbutton", { name: "minimum CONTRADICTED recall" }).fill("50");
+ await form.getByRole("spinbutton", { name: "minimum NOT_FOUND recall" }).fill("50");
+ await expect(form.getByRole("checkbox", { name: `use ${QWEN}` })).toBeDisabled();
+ await expect(form.locator(`[data-model="${QWEN}"]`)).toHaveAttribute("data-pass", "false");
+ const use = form.getByRole("checkbox", { name: `use ${SONNET}` });
+ await expect(use).toBeEnabled();
+ await use.check();
+ await form.getByRole("button", { name: "Save the bar" }).click();
+ await expect(form.getByRole("status")).toHaveText("Saved.");
+ expect(stubAsked("settings").at(-1)).toMatchObject({
+ patch: { generation: { verdicts: { bar: { agreement: 0.5, contradictedRecall: 0.5, notFoundRecall: 0.5 }, models: [SONNET] } } },
+ authorization: "Bearer umtool-e2e-token",
+ });
+ // Read back: the tiles say who passes the saved bar.
+ await page.reload();
+ const models = page.getByRole("region", { name: "models" });
+ await expect(models.locator(`[data-model="${SONNET}"]`)).toHaveAttribute("data-pass", "true");
+ await expect(models.locator(`[data-model="${QWEN}"]`)).toHaveAttribute("data-pass", "false");
+ await expect(page.getByRole("form", { name: "bar" }).getByRole("checkbox", { name: `use ${SONNET}` })).toBeChecked();
+ await expect(page.getByRole("form", { name: "bar" }).getByRole("spinbutton", { name: "minimum agreement" })).toHaveValue("50");
+});
diff --git a/umtool/lib/bench.ts b/umtool/lib/bench.ts
@@ -0,0 +1,118 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ benchRootOf,
+ listBenchRuns,
+ passesBar,
+ readBenchRun,
+ scoreBench,
+ BASELINE_MODEL,
+ type BenchItem,
+ type BenchResult,
+ type BenchScore,
+ type BenchSummary,
+ type VerdictBar,
+} from "yt-dlp-transcript-common/lib/report/draft/bench/index";
+import { VERDICTS, type Verdict } from "yt-dlp-transcript-common/lib/report/verdicts";
+import { sanitizeGeneration, type GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings";
+import { askEditor, EditorError } from "@/lib/articles/generation";
+
+// THE VERDICT BENCH, AS UMTOOL SEES IT (release 28 M7): the runs `archilyzer
+// reports bench-verdicts` wrote under the checkout's `.generation/bench/
+// verdicts/` (local-only; read here, never written), scored again from their
+// items and results so the page and the files cannot disagree, and the
+// operator's bar — settings.generation.verdicts — read from and written
+// through the editor's settings action, as the generation policy is.
+//
+// SERVER-ONLY.
+
+export type BenchRunRow = Pick<BenchSummary, "id" | "createdAt" | "status" | "models" | "items" | "spentUsd" | "maxUsd">;
+
+export type BenchItemRow = {
+ key: string;
+ report: string;
+ claim: string;
+ text: string;
+ verdict: Verdict;
+ answers: Record<string, { verdict: Verdict | null; reason?: string; failure?: string; error?: string }>;
+ // A model whose answer is not the operator's (failures included).
+ disagree: string[];
+};
+
+export type BenchView = {
+ summary: BenchSummary;
+ score: BenchScore;
+ items: BenchItemRow[];
+};
+
+export function benchRoot(): string {
+ return benchRootOf(getPaths());
+}
+
+export async function readBenchRuns(): Promise<BenchRunRow[]> {
+ return (await listBenchRuns(benchRoot())).map((s) => ({
+ id: s.id,
+ createdAt: s.createdAt,
+ status: s.status,
+ models: s.models,
+ items: s.items,
+ spentUsd: s.spentUsd,
+ maxUsd: s.maxUsd,
+ }));
+}
+
+function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], models: readonly string[]): BenchItemRow[] {
+ const by = new Map<string, BenchResult>();
+ for (const r of results) by.set(`${r.model}\u0000${r.key}`, r);
+ return items.map((it) => {
+ const answers: BenchItemRow["answers"] = {};
+ const disagree: string[] = [];
+ for (const m of models) {
+ const r = by.get(`${m}\u0000${it.key}`);
+ if (!r) continue;
+ answers[m] = { verdict: r.verdict, ...(r.reason ? { reason: r.reason } : {}), ...(r.failure ? { failure: r.failure } : {}), ...(r.error ? { error: r.error } : {}) };
+ if (r.verdict !== it.verdict) disagree.push(m);
+ }
+ return { key: it.key, report: it.report, claim: it.claim, text: it.text, verdict: it.verdict, answers, disagree };
+ });
+}
+
+export async function readBenchView(id: string): Promise<BenchView | null> {
+ const run = await readBenchRun(benchRoot(), id).catch(() => null);
+ if (!run) return null;
+ const score = scoreBench(run.items, run.results, run.summary.models);
+ return { summary: run.summary, score, items: rowsOf(run.items, run.results, run.summary.models) };
+}
+
+// The rows a filter keeps, disagreements first (then in item order).
+export function filterBenchRows(rows: readonly BenchItemRow[], f: { model?: string; verdict?: string }): BenchItemRow[] {
+ const kept = rows.filter(
+ (r) => (!f.verdict || r.verdict === f.verdict) && (!f.model || f.model in r.answers),
+ );
+ const disagrees = (r: BenchItemRow) => (f.model ? r.disagree.includes(f.model) : r.disagree.length > 0);
+ return [...kept.filter(disagrees), ...kept.filter((r) => !disagrees(r))];
+}
+
+export { passesBar, BASELINE_MODEL, VERDICTS };
+export type { VerdictBar };
+
+// ─── The bar (settings.generation.verdicts) ───
+
+export async function readVerdictsPolicy(): Promise<GenerationVerdicts> {
+ const answer = await askEditor<{ value?: unknown }>("/api/ops/settings?key=generation");
+ return sanitizeGeneration(answer.value ?? {}).verdicts;
+}
+
+/** Write the bar and the ticked models whole (a nested block replaces). Answers it as read back. */
+export async function writeVerdictsPolicy(v: unknown): Promise<GenerationVerdicts> {
+ if (!v || typeof v !== "object" || Array.isArray(v)) throw new EditorError("send {bar, models}", 400);
+ const o = v as Record<string, unknown>;
+ const b = (o.bar ?? {}) as Record<string, unknown>;
+ for (const k of ["agreement", "contradictedRecall", "notFoundRecall"]) {
+ const x = b[k];
+ if (typeof x !== "number" || !Number.isFinite(x) || x < 0 || x > 1) throw new EditorError(`bar.${k} is a fraction from 0 to 1`, 400);
+ }
+ if (!Array.isArray(o.models) || !o.models.every((m) => typeof m === "string")) throw new EditorError("models is a list of model names", 400);
+ const verdicts = sanitizeGeneration({ verdicts: { bar: b, models: o.models } }).verdicts;
+ await askEditor("/api/ops/settings", { method: "POST", body: { patch: { generation: { verdicts } } } });
+ return readVerdictsPolicy();
+}
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -675,6 +675,39 @@ holds one pair while it plays.
- **Punch.** The panel is built for short clips — the line and nothing else —
and near-hard cuts (`transition` 0.12); a smaller `footageScale` gives it room.
+The flips and the threads can be drafted (release 28): the `flips` and
+`threads` tasks (`common/lib/report/draft/tasks/`) write these fields with a
+`drafted` mark, through the checks this section describes — the limits and
+validators are one copy, `common/lib/report/panels.mjs`, which `flips.mjs` and
+`threads.mjs` re-export. A pair's dates, `when`s and words are code's (the
+recordings' dates; the quote, verbatim); a thread's outcome is its last clip's
+`claim.verdict`. Each task refuses a cut that has the other panel, unless
+forced over a draft of it, which it then replaces.
+
+### `publish.youtube` — the upload's text (`out/youtube.txt`)
+
+```jsonc
+"publish": { "youtube": { "title": "…", // one line, ≤ 100 characters
+ "description": "…" } } // the summary paragraph (≤ 5000; the youtube task keeps it ≤ 900)
+```
+
+Every build that muxes chapters (or would have, under `--no-chapters`) writes
+`out/youtube.txt` (`youtube-<variant>.txt` for another variant) when the
+manifest has `publish.youtube`, composed by code (`youtube.mjs`):
+
+- the title, a blank line, the description;
+- `Chapters`: the build's own chapter list as `m:ss Title`, on YouTube's rules —
+ the first at 0:00, at least three, each at least ten seconds (a shorter one is
+ folded into the one before it). A list that still falls short is left out,
+ and the build's `youtube` event says why;
+- `Sources`: a moment link per cited clip, in cut order, each once — its
+ `citeUrl`, else the archive's page at its `cite` second (a `src` clip without
+ a `citeUrl` has none).
+
+umtool's project page shows the text with **Copy** — the built file, or before
+a build the same text without the chapters. The `youtube` task drafts the title
+and the summary (grounded, third person, quotes only word for word).
+
### The `image` entry type
A still: the receipts a clip cannot say out loud — a post, a thread, a DM, a
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -143,6 +143,8 @@ import {
import { validateClaims } from "./factcheck.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
+// The upload's text (release 28 M6): composed by code, written beside the cut.
+import { composeYoutubeText, youtubeChapters, youtubeSources, youtubeTextName } from "./youtube.mjs";
// A card's `narration` (release 25): validated, resolved and levelled in
// narration.mjs (pure); its synthesized sound is kept in out/narration/
// (narration-store.mjs) by asking the editor (narrate-via-editor.mjs).
@@ -408,7 +410,7 @@ export function variantPaths(outRoot, slug, variant) {
// printed -- this is a formatting switch, not new instrumentation.
//
// Events: start, card, clip, fetch, snap, segment, entry-failed, concat,
-// chapters, chrome, narrate, note, done.
+// chapters, youtube, chrome, narrate, note, done.
const HUMAN = {
start: (e) => `${e.title} — ${e.entries} entr(ies)`,
card: (e) => `card ${e.id}`,
@@ -432,6 +434,7 @@ const HUMAN = {
"entry-failed": (e) => ` ** ${e.id} failed: ${e.message}`,
concat: (e) => `${e.mode === "xfade" ? "crossfading" : "hard-cutting"} ${e.n} segments…`,
chapters: (e) => `chapters: ${e.n} marker(s) -> ${e.file}`,
+ youtube: (e) => `youtube: ${e.file}${e.chapters ? ` (${e.chapters} chapter(s))` : ""}${e.note ? ` — ${e.note}` : ""}`,
// The deck's steps. `phase` is schedule | compose | render | cached | overlay.
chrome: (e) =>
`chrome ${e.phase}` +
@@ -3947,23 +3950,29 @@ export async function measureChromeSchedule({ manifest, entries, segments, D })
return deckSchedule({ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [] });
}
+// Returns the chapters it muxed (`{ chapters: [{ start, end, title }], total }`,
+// seconds) -- the list out/youtube.txt's Chapters are made from -- or null
+// when the cut is one segment and gets none.
async function muxChapters(finalPath, entries, segments, D, outDir, provenance, fps, deck = false, joins = null, { disclosure = null } = {}) {
- if (segments.length < 2) return;
+ if (segments.length < 2) return null;
// The cut's own offsets: under the deck a held clip is longer in the cut
// than its file, and every chapter after it starts that much later.
const { starts, total } = await cutOffsets(segments, D, fps, joins);
const lines = [";FFMETADATA1", ""];
+ const chapters = [];
for (let i = 0; i < entries.length; i += 1) {
// Land just PAST the crossfade, so the marker opens on the incoming clip
// rather than on the outgoing one mid-dissolve.
const start = i === 0 ? 0 : starts[i] + D;
const end = i === entries.length - 1 ? total : starts[i + 1] + D;
+ const title = await chapterTitle(entries[i], i, provenance, { deck });
+ chapters.push({ start, end, title });
lines.push(
"[CHAPTER]",
"TIMEBASE=1/1000",
`START=${Math.round(start * 1000)}`,
`END=${Math.round(end * 1000)}`,
- `title=${ffmetaEscape(await chapterTitle(entries[i], i, provenance, { deck }))}`,
+ `title=${ffmetaEscape(title)}`,
"",
);
}
@@ -3984,6 +3993,28 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance,
);
await rename(tmp, finalPath);
EMIT("chapters", { n: entries.length, file: path.basename(metaPath) });
+ return { chapters, total };
+}
+
+/**
+ * `out/youtube.txt` (youtube.mjs): the cut's `publish.youtube` title and
+ * description, the chapters the build just muxed (YouTube's rules, else left
+ * out with a note) and a moment link per cited clip. Written by every build
+ * that muxes chapters -- or would have, under --no-chapters -- when the
+ * manifest has `publish.youtube`; nothing otherwise.
+ *
+ * @param {{ chapters: Array<{ start: number, end: number, title: string }>, total: number } | null} muxed
+ * @param {string | null} [why] why there are no chapters (`--no-chapters`)
+ */
+async function writeYoutubeText(manifest, entries, outRoot, variant, muxed, why = null) {
+ const youtube = manifest.publish?.youtube;
+ if (!youtube?.title) return null;
+ const { chapters, note } = muxed ? youtubeChapters(muxed.chapters, muxed.total) : { chapters: null, note: `no chapters: ${why ?? "the cut is one segment"}` };
+ const text = composeYoutubeText({ youtube, chapters, sources: youtubeSources(entries, manifest.provenance) });
+ const file = path.join(outRoot, youtubeTextName(variant));
+ await writeFile(file, text, "utf8");
+ EMIT("youtube", { file: path.basename(file), chapters: chapters?.length ?? 0, note });
+ return file;
}
/**
@@ -4452,7 +4483,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
}
// Under the deck the cut's offsets include the holds: measured, not written.
const joins = deck ? segmentJoins(await measureChromeSchedule({ manifest, entries, segments: segs, D })) : null;
- await muxChapters(finalPath, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
+ const muxed = await muxChapters(finalPath, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
+ await writeYoutubeText(manifest, entries, outRoot, variant, muxed);
return { out: finalPath, failures: [] };
}
@@ -4486,9 +4518,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
await assertConcatLength(out, railPlan.total, render.fps, "rail build");
// applyRail re-encodes, so the chapters muxed onto the previous final are
// gone. Put them back, or --rail-only quietly ships a chapterless cut.
- if (!opts.noChapters) {
- await muxChapters(out, entries, segs, D, outDir, provenance, render.fps, deckOn(render), null, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
- }
+ const muxed = opts.noChapters
+ ? null
+ : await muxChapters(out, entries, segs, D, outDir, provenance, render.fps, deckOn(render), null, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
+ await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null);
}
EMIT("done", { out, failures: [] });
return { out, failures: [] };
@@ -4594,7 +4627,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
}
await assertConcatLength(dirs.final, schedule.total, render.fps, "deck build");
// The overlay re-encodes, so the chapters on the previous final are gone.
- if (!opts.noChapters) await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
+ const muxed = opts.noChapters
+ ? null
+ : await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
+ await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null);
await pruneFrames();
EMIT("done", { out: dirs.final, failures: [] });
return { out: dirs.final, failures: [] };
@@ -4717,7 +4753,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// shortest=1), and a hang means an unbounded -loop 1.
if (railPlan) await assertConcatLength(final, railPlan.total, render.fps, "rail build");
- if (!opts.noChapters) await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
+ const muxed = opts.noChapters
+ ? null
+ : await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
+ await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null);
// A branded cut with a `thumbnail` gets one beside it. The cut is already
// done, so a thumbnail that cannot be made is said, not thrown.
diff --git a/umtool/report-to-video/flips.mjs b/umtool/report-to-video/flips.mjs
@@ -15,10 +15,12 @@
// threadsGeometry); the two are one region and a cut has one or the other.
//
// PURE, like threads.mjs. chrome-flips.mjs draws the panel.
+// The limits and the validators are common's (lib/report/panels.mjs, release
+// 28): the flips draft task checks exactly what the build refuses.
+import { FLIPS_LIMITS, flipsOn, validateFlipEntries, validateFlips } from "yt-dlp-transcript-common/lib/report/panels.mjs";
import { planCues } from "./threads.mjs";
-/** The limits: pairs, a topic's, a `when`'s and a side's words' characters. */
-export const FLIPS_LIMITS = Object.freeze({ pairs: Object.freeze([1, 24]), topic: 32, when: 18, words: 110 });
+export { FLIPS_LIMITS, flipsOn, validateFlipEntries, validateFlips };
/**
* The panel's motion, in seconds: a pair rises in over `enter`, its NOW card
@@ -32,80 +34,6 @@ export const FLIP_MOTION = Object.freeze({
/** How bright the THEN card rests once NOW has landed. */
export const THEN_DIM = 0.5;
-const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;
-const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
-const oneLine = (v, max) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v) && v.length <= max;
-
-/** Is the flips panel on: a `render.chrome.flips` with at least one pair. */
-export function flipsOn(render) {
- const f = render?.chrome?.flips;
- return isObj(f) && Array.isArray(f.pairs) && f.pairs.length > 0;
-}
-
-/**
- * Every reason `render.chrome.flips` cannot be built, as sentences. Shape
- * only; `validateFlipEntries` checks the pairs against the timeline.
- *
- * @returns {string[]}
- */
-export function validateFlips(f, where = "render.chrome.flips") {
- if (f === undefined) return [];
- if (!isObj(f)) return [`${where} must be an object`];
- const errors = [];
- for (const k of Object.keys(f)) if (k !== "pairs") errors.push(`${where}.${k} is not a flips setting`);
- const [lo, hi] = FLIPS_LIMITS.pairs;
- if (!Array.isArray(f.pairs) || f.pairs.length < lo || f.pairs.length > hi) return [...errors, `${where}.pairs must be ${lo} to ${hi} pairs`];
- const ids = new Set();
- f.pairs.forEach((p, i) => {
- const w = `${where}.pairs[${i}]`;
- if (!isObj(p)) { errors.push(`${w} must be an object`); return; }
- for (const k of Object.keys(p)) if (!["id", "topic", "then", "now"].includes(k)) errors.push(`${w}.${k} is not a pair key`);
- if (typeof p.id !== "string" || !ID_RE.test(p.id)) errors.push(`${w}.id must be letters, digits, _ or -`);
- else if (ids.has(p.id)) errors.push(`${w}.id ${p.id} is listed twice`);
- else ids.add(p.id);
- if (!oneLine(p.topic, FLIPS_LIMITS.topic)) errors.push(`${w}.topic must be one line of at most ${FLIPS_LIMITS.topic} characters`);
- for (const side of ["then", "now"]) {
- const s = p[side];
- const ws = `${w}.${side}`;
- if (!isObj(s)) { errors.push(`${ws} must be an object`); continue; }
- for (const k of Object.keys(s)) if (!["entry", "when", "words"].includes(k)) errors.push(`${ws}.${k} is not a side key`);
- if (typeof s.entry !== "string" || !s.entry) errors.push(`${ws}.entry must name a timeline entry`);
- if (!oneLine(s.when, FLIPS_LIMITS.when)) errors.push(`${ws}.when must be one line of at most ${FLIPS_LIMITS.when} characters`);
- if (!oneLine(s.words, FLIPS_LIMITS.words)) errors.push(`${ws}.words must be one line of at most ${FLIPS_LIMITS.words} characters`);
- }
- });
- return errors;
-}
-
-/**
- * The pairs against the timeline: each side names an entry of the cut, a clip
- * (not a teaser), the THEN side before the NOW side, and no entry in two pairs.
- *
- * @returns {string[]}
- */
-export function validateFlipEntries(manifest) {
- const render = manifest?.render ?? {};
- if (!flipsOn(render)) return [];
- const errors = [];
- const at = new Map((manifest.timeline ?? []).map((e, i) => [e?.id, { e, i }]));
- const used = new Map();
- render.chrome.flips.pairs.forEach((p, i) => {
- const w = `render.chrome.flips.pairs[${i}] (${p?.id ?? "?"})`;
- const idx = {};
- for (const side of ["then", "now"]) {
- const id = p?.[side]?.entry;
- const hit = at.get(id);
- if (!hit) { errors.push(`${w}.${side}.entry ${id} is not in the timeline`); continue; }
- if (hit.e.type === "teaser") errors.push(`${w}.${side}.entry ${id} is a teaser, not a clip`);
- if (used.has(id)) errors.push(`${w}.${side}.entry ${id} is already in pair ${used.get(id)}`);
- used.set(id, p.id);
- idx[side] = hit.i;
- }
- if (idx.then !== undefined && idx.now !== undefined && idx.then >= idx.now) errors.push(`${w}: its THEN entry must come before its NOW entry`);
- });
- return errors;
-}
-
/** The years between two `when`s, when both carry one (`2019`, `May 2019`): else null. */
export function yearsBetween(a, b) {
const y = (s) => {
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -40,6 +40,7 @@
"./resolve-windows": "./resolve-windows.mjs",
"./shoot-page": "./shoot-page.mjs",
"./sources": "./sources.mjs",
- "./verify-build": "./verify-build.mjs"
+ "./verify-build": "./verify-build.mjs",
+ "./youtube": "./youtube.mjs"
}
}
diff --git a/umtool/report-to-video/threads.mjs b/umtool/report-to-video/threads.mjs
@@ -19,10 +19,12 @@
// PURE, like factcheck.mjs: the settings, their validation, the schedule and
// the cues. No fs. deck.mjs imports this file -- never the other way round.
// chrome-threads.mjs draws the rail.
-import { resolveFactcheck, VERDICTS } from "./factcheck.mjs";
+import { resolveFactcheck } from "./factcheck.mjs";
+// The limits and the validators are common's (lib/report/panels.mjs, release
+// 28): the threads draft task checks exactly what the build refuses.
+import { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads } from "yt-dlp-transcript-common/lib/report/panels.mjs";
-/** The limits: how many threads, a label's and an outcome label's characters. */
-export const THREADS_LIMITS = Object.freeze({ threads: Object.freeze([1, 8]), label: 32, outcome: 24 });
+export { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads };
/**
* The rail's motion, in seconds: a card lights over `light` and its string
@@ -37,17 +39,7 @@ export const THREAD_MOTION = Object.freeze({
/** How long before its thread's last clip ends the outcome lands, at most. */
export const OUTCOME_LEAD = 1.8;
-/** A thread id: letters, digits and `_ -`. */
-const THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/;
-
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
-const oneLine = (v) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v);
-
-/** Is the rail on: a `render.chrome.threads` with at least one thread. */
-export function threadsOn(render) {
- const t = render?.chrome?.threads;
- return isObj(t) && Array.isArray(t.list) && t.list.length > 0;
-}
/**
* The threads with their outcomes resolved: `[{ id, label, outcome: { verdict,
@@ -68,75 +60,6 @@ export function resolveThreads(render) {
}
/**
- * Every reason `render.chrome.threads` cannot be built, as sentences (empty:
- * it can). validateChrome calls this, so umtool's writer and the build refuse
- * the same things.
- *
- * @returns {string[]}
- */
-export function validateThreads(t, where = "render.chrome.threads") {
- if (t === undefined) return [];
- if (!isObj(t)) return [`${where} must be an object`];
- const errors = [];
- for (const k of Object.keys(t)) if (k !== "list") errors.push(`${where}.${k} is not a threads setting`);
- const [lo, hi] = THREADS_LIMITS.threads;
- if (!Array.isArray(t.list) || t.list.length < lo || t.list.length > hi) {
- return [...errors, `${where}.list must be ${lo} to ${hi} threads`];
- }
- const seen = new Set();
- t.list.forEach((th, i) => {
- const w = `${where}.list[${i}]`;
- if (!isObj(th)) { errors.push(`${w} must be an object`); return; }
- for (const k of Object.keys(th)) if (!["id", "label", "outcome"].includes(k)) errors.push(`${w}.${k} is not a thread key`);
- if (typeof th.id !== "string" || !THREAD_ID_RE.test(th.id)) errors.push(`${w}.id must be letters, digits, _ or -`);
- else if (seen.has(th.id)) errors.push(`${w}.id ${th.id} is listed twice`);
- else seen.add(th.id);
- if (!oneLine(th.label) || th.label.length > THREADS_LIMITS.label) {
- errors.push(`${w}.label must be one line of at most ${THREADS_LIMITS.label} characters`);
- }
- if (th.outcome !== undefined) {
- const o = th.outcome;
- if (!isObj(o)) { errors.push(`${w}.outcome must be an object`); return; }
- for (const k of Object.keys(o)) if (!["verdict", "label"].includes(k)) errors.push(`${w}.outcome.${k} is not an outcome key`);
- if (!VERDICTS.includes(o.verdict)) errors.push(`${w}.outcome.verdict must be one of ${VERDICTS.join(", ")}`);
- if (o.label !== undefined && (!oneLine(o.label) || o.label.length > THREADS_LIMITS.outcome)) {
- errors.push(`${w}.outcome.label must be one line of at most ${THREADS_LIMITS.outcome} characters`);
- }
- }
- });
- return errors;
-}
-
-/** The thread an entry belongs to, or null. */
-export function threadOf(entry) {
- return typeof entry?.thread === "string" && entry.thread ? entry.thread : null;
-}
-
-/**
- * Every `thread` in the timeline, checked against the list: it names a listed
- * thread, it is not on a teaser, and every listed thread has a clip. The
- * build refuses with these before it fetches.
- *
- * @returns {string[]}
- */
-export function validateThreadEntries(manifest) {
- const errors = [];
- const render = manifest?.render ?? {};
- const listed = threadsOn(render) ? new Set(render.chrome.threads.list.map((t) => t?.id)) : new Set();
- const used = new Set();
- (manifest?.timeline ?? []).forEach((e, i) => {
- if (e?.thread === undefined || e?.thread === null) return;
- const where = `timeline[${i}] (${e.id ?? "?"}).thread`;
- if (typeof e.thread !== "string" || !e.thread) { errors.push(`${where} must be a thread id`); return; }
- if (e.type === "teaser") { errors.push(`${where}: a teaser belongs to no thread`); return; }
- if (!listed.has(e.thread)) { errors.push(`${where} ${e.thread} is not in render.chrome.threads.list`); return; }
- used.add(e.thread);
- });
- for (const id of listed) if (!used.has(id)) errors.push(`render.chrome.threads: thread ${id} has no clip`);
- return errors;
-}
-
-/**
* The rail's schedule, in the cut's clock. `segments` are the schedule's, in
* order, each `{ id, start, duration, thread }`; `moves` are the footage's
* moves for popup posts (deck.mjs footageMoves).
diff --git a/umtool/report-to-video/youtube.mjs b/umtool/report-to-video/youtube.mjs
@@ -0,0 +1,147 @@
+// THE YOUTUBE TEXT (release 28, M6): what a cut's upload says, composed by
+// CODE from `publish.youtube { title, description }` (drafted by the youtube
+// task or written by hand), the build's own chapter list and the cut's
+// citations. The build writes it to `out/youtube.txt` (`out/youtube-<variant>.txt`
+// for a variant other than `sourced`, as the cut's mp4 is named); umtool shows
+// and copies it, and previews it the same way, without chapters, before a build.
+//
+// <title>
+//
+// <description>
+//
+// Chapters
+// 0:00 <chapter>
+// …
+//
+// Sources
+// <a moment link per cited clip, in cut order, each once>
+//
+// The chapters are YouTube's: the first at 0:00, at least three, each at
+// least ten seconds. A chapter shorter than that is folded into the one
+// before it (a first one shorter than that takes the next one's span). A list
+// that is still too short, or does not start at 0:00, is left out -- and the
+// result's `notes` say why.
+//
+// PURE: no fs. build-video.mjs writes the file.
+
+/** YouTube's rules for a description's chapters. */
+export const YOUTUBE_CHAPTERS = Object.freeze({ min: 3, minSeconds: 10 });
+
+/** `m:ss`, or `h:mm:ss` from an hour. */
+export function chapterStamp(seconds) {
+ const s = Math.max(0, Math.floor(seconds));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const ss = String(s % 60).padStart(2, "0");
+ return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
+}
+
+const oneLine = (s) => String(s ?? "").replace(/\s+/g, " ").trim();
+
+/**
+ * The chapters as YouTube takes them, from the build's list (`{ start, end?,
+ * title }`, seconds, in order; `total` the cut's length for the last one's
+ * span): `{ chapters, note }` -- `chapters` null when the block is left out,
+ * `note` saying what was folded or why the block is left out.
+ *
+ * @param {Array<{ start: number, end?: number, title: string }> | null | undefined} list
+ * @param {number | null} [total]
+ */
+export function youtubeChapters(list, total = null) {
+ if (!Array.isArray(list) || !list.length) return { chapters: null, note: "no chapters: the build made none" };
+ const all = list.map((c) => ({ start: Math.floor(Number(c.start)), title: oneLine(c.title) || "Chapter" }));
+ if (all[0].start !== 0) return { chapters: null, note: `no chapters: the first starts at ${chapterStamp(all[0].start)}, not 0:00` };
+ const end = Number.isFinite(Number(total)) && total !== null
+ ? Math.floor(Number(total))
+ : Math.floor(Number(list.at(-1).end ?? all.at(-1).start + YOUTUBE_CHAPTERS.minSeconds));
+ const kept = [all[0]];
+ let folded = 0;
+ for (const c of all.slice(1)) {
+ if (c.start - kept.at(-1).start < YOUTUBE_CHAPTERS.minSeconds) {
+ folded++;
+ // A first chapter too short to stand takes the next one's span under its own 0:00.
+ continue;
+ }
+ kept.push(c);
+ }
+ // The last must run ten seconds too.
+ while (kept.length > 1 && end - kept.at(-1).start < YOUTUBE_CHAPTERS.minSeconds) {
+ kept.pop();
+ folded++;
+ }
+ const foldNote = folded ? `${folded} chapter(s) under ${YOUTUBE_CHAPTERS.minSeconds} s folded into the one before` : "";
+ if (kept.length < YOUTUBE_CHAPTERS.min) {
+ return {
+ chapters: null,
+ note: `no chapters: ${kept.length} of at least ${YOUTUBE_CHAPTERS.min}` + (foldNote ? ` (${foldNote})` : ""),
+ };
+ }
+ return { chapters: kept, note: foldNote };
+}
+
+/**
+ * A clip's moment link: its `citeUrl` when it has one, else the archive's page
+ * at the cited second (`cite`, else `start`) -- the link the citation makes
+ * (`<origin>/?v=<channel>%2F<video>&t=<s>`). A clip from a file beside the
+ * manifest (`src`) with no `citeUrl` has none; nor has any other entry.
+ */
+export function momentLinkOf(entry, provenance = {}) {
+ if (entry?.type !== "clip") return null;
+ if (entry.citeUrl) return entry.citeUrl;
+ if (entry.src != null) return null;
+ const origin = String(provenance?.siteOrigin ?? "").replace(/\/+$/, "");
+ const channel = entry.channel ?? provenance?.channelSlug;
+ if (!origin || !channel || !entry.video) return null;
+ const at = Number.isFinite(Number(entry.cite)) ? Number(entry.cite) : Number(entry.start);
+ return `${origin}/?v=${encodeURIComponent(`${channel}/${entry.video}`)}&t=${Math.floor(Number.isFinite(at) ? at : 0)}`;
+}
+
+/** The cut's moment links, in cut order, each once. */
+export function youtubeSources(entries, provenance = {}) {
+ const out = [];
+ const seen = new Set();
+ for (const e of entries ?? []) {
+ const href = momentLinkOf(e, provenance);
+ if (!href || seen.has(href)) continue;
+ seen.add(href);
+ out.push(href);
+ }
+ return out;
+}
+
+/**
+ * The text. `chapters` is youtubeChapters' (null: no block); `sources` the
+ * links. Null when the manifest has no `publish.youtube` title.
+ *
+ * @param {{ youtube?: { title?: string, description?: string } | null, chapters?: Array<{ start: number, title: string }> | null, sources?: string[] }} o
+ * @returns {string | null}
+ */
+export function composeYoutubeText({ youtube, chapters = null, sources = [] }) {
+ const title = oneLine(youtube?.title);
+ if (!title) return null;
+ const parts = [title];
+ const description = String(youtube?.description ?? "").trim();
+ if (description) parts.push(description);
+ if (chapters?.length) parts.push(["Chapters", ...chapters.map((c) => `${chapterStamp(c.start)} ${oneLine(c.title)}`)].join("\n"));
+ if (sources.length) parts.push(["Sources", ...sources].join("\n"));
+ return `${parts.join("\n\n")}\n`;
+}
+
+/** The file a variant's text is written to, in the project's `out/`. */
+export function youtubeTextName(variant = "sourced") {
+ return variant === "sourced" ? "youtube.txt" : `youtube-${variant}.txt`;
+}
+
+/**
+ * The preview umtool shows before a build: composed the same way, without
+ * chapters (the build makes them), over the default cut's entries -- an entry
+ * tagged with another `variant` is left out, as build-video's selectVariant
+ * leaves it out of `sourced`.
+ *
+ * @returns {{ text: string | null, note: string }}
+ */
+export function youtubePreview(manifest) {
+ const entries = (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => !e?.variant || e.variant === "sourced");
+ const text = composeYoutubeText({ youtube: manifest?.publish?.youtube, chapters: null, sources: youtubeSources(entries, manifest?.provenance) });
+ return { text, note: "chapters are added by the build" };
+}
diff --git a/umtool/report-to-video/youtube.test.mjs b/umtool/report-to-video/youtube.test.mjs
@@ -0,0 +1,91 @@
+// out/youtube.txt's composition (release 28 M6): the title, the summary, the
+// chapters on YouTube's rules (0:00 first, at least three, ten seconds each),
+// the sources in cut order, each once.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import {
+ chapterStamp, composeYoutubeText, momentLinkOf, youtubeChapters, youtubePreview, youtubeSources, youtubeTextName, YOUTUBE_CHAPTERS,
+} from "./youtube.mjs";
+
+const FULL = new URL("../../common/testing/draft/manifests/full.video.manifest.json", import.meta.url);
+const YT = { title: "What the baker says about the bakery", description: "Synth Kitchen on the bakery and the contest." };
+
+test("stamps: m:ss, h:mm:ss from an hour", () => {
+ assert.equal(chapterStamp(0), "0:00");
+ assert.equal(chapterStamp(65.9), "1:05");
+ assert.equal(chapterStamp(3725), "1:02:05");
+});
+
+test("chapters: 0:00 first, at least three, each ten seconds — short ones folded into the one before", () => {
+ const list = [
+ { start: 0, title: "Title" },
+ { start: 4, title: "The bakery" }, // 4 s after the first: folded
+ { start: 12.4, title: "Not for sale" },
+ { start: 30, title: "The contest" },
+ { start: 55, title: "Last" }, // 5 s before the end: folded
+ ];
+ const r = youtubeChapters(list, 60);
+ assert.deepEqual(r.chapters.map((c) => [c.start, c.title]), [[0, "Title"], [12, "Not for sale"], [30, "The contest"]]);
+ assert.match(r.note, /2 chapter\(s\) under 10 s folded/);
+ assert.equal(YOUTUBE_CHAPTERS.min, 3);
+});
+
+test("chapters: fewer than three, or not starting at 0:00, are left out — and the note says why", () => {
+ const two = youtubeChapters([{ start: 0, title: "A" }, { start: 20, title: "B" }], 40);
+ assert.equal(two.chapters, null);
+ assert.match(two.note, /^no chapters: 2 of at least 3/);
+ const late = youtubeChapters([{ start: 2, title: "A" }, { start: 20, title: "B" }, { start: 40, title: "C" }], 60);
+ assert.equal(late.chapters, null);
+ assert.match(late.note, /first starts at 0:02, not 0:00/);
+ assert.match(youtubeChapters(null).note, /made none/);
+});
+
+test("sources: a moment link per cited clip in cut order, each once; citeUrl wins; a src clip and a card have none", () => {
+ const prov = { siteOrigin: "https://synth.example/", channelSlug: "synth-kitchen" };
+ const entries = [
+ { type: "card", id: "t" },
+ { type: "clip", id: "c02", video: "bread-day-01", start: 24.2, cite: 25 },
+ { type: "clip", id: "c01", channel: "synth-kitchen", video: "bread-day-01", start: 15 },
+ { type: "clip", id: "c02b", video: "bread-day-01", start: 25, cite: 25.9 }, // the same moment again
+ { type: "clip", id: "x", citeUrl: "https://x.example/post/1" },
+ { type: "clip", id: "local", src: "a.mp4", start: 0 },
+ ];
+ assert.deepEqual(youtubeSources(entries, prov), [
+ "https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=25",
+ "https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=15",
+ "https://x.example/post/1",
+ ]);
+ assert.equal(momentLinkOf({ type: "clip", video: "v" }, {}), null, "no origin: no link");
+});
+
+test("the text: title, a blank, the summary, Chapters, Sources; nothing without a title", () => {
+ const text = composeYoutubeText({
+ youtube: YT,
+ chapters: [{ start: 0, title: "Title" }, { start: 12, title: "Not for sale" }, { start: 75, title: "The contest" }],
+ sources: ["https://a.example/1", "https://a.example/2"],
+ });
+ assert.equal(
+ text,
+ "What the baker says about the bakery\n\nSynth Kitchen on the bakery and the contest.\n\nChapters\n0:00 Title\n0:12 Not for sale\n1:15 The contest\n\nSources\nhttps://a.example/1\nhttps://a.example/2\n",
+ );
+ assert.equal(composeYoutubeText({ youtube: { title: " ", description: "x" } }), null);
+ assert.equal(composeYoutubeText({ youtube: { title: "T" } }), "T\n");
+ assert.equal(youtubeTextName(), "youtube.txt");
+ assert.equal(youtubeTextName("full"), "youtube-full.txt");
+});
+
+test("the preview: the default cut's sources, no chapters", async () => {
+ const m = JSON.parse(await readFile(FULL, "utf8"));
+ m.publish = { youtube: YT };
+ m.timeline.push({ type: "clip", id: "only-full", variant: "full", channel: "synth-kitchen", video: "qa-long-03", start: 5, cite: 5 });
+ const p = youtubePreview(m);
+ const lines = p.text.split("\n");
+ assert.equal(lines[0], YT.title);
+ assert.ok(!p.text.includes("Chapters"));
+ const sources = lines.slice(lines.indexOf("Sources") + 1).filter(Boolean);
+ assert.equal(sources.length, 7, "seven clips, seven moments");
+ assert.ok(!p.text.includes("qa-long-03&t=5"), "an entry of another variant is not in the default cut");
+ assert.equal(youtubePreview({ timeline: [] }).text, null);
+});