commit 254bbac30bec0d5a595fd05abd8f7cc624bb544b
parent 969ec546a1bb2841680d9764feb0fc0191cbd6c2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 22:14:00 -0400
Merge r28/integration into r28/media-e (lane C, phase 1 records)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
# common/lib/generationSettings.test.ts
Diffstat:
41 files changed, 3829 insertions(+), 13 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"}'` |
@@ -145,6 +147,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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}'` |
+| `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/SETTINGS.md b/SETTINGS.md
@@ -966,6 +966,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `web` | object — see below | The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart. |
| `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'. |
+| `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`
@@ -1019,6 +1020,21 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `newChannelsNeedApproval` | `true` | Under `limits`, a new channel waits for approval. (A new channel is always created on no site.) |
| `postWalksNeedApproval` | `true` | Under `limits`, a walk over an account's post history (`fetch-posts` full or older) waits for approval. |
+#### `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
@@ -1066,6 +1082,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/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/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts
@@ -104,3 +104,12 @@ test("the media drafts (release 28): steps, each with narrate's route in every p
// One media task routed on its own is custom.
assert.equal(sanitizeGeneration({ routes: { ...GENERATION_PRESETS.api, teaser: "local" } }).preset, "custom");
});
+
+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
@@ -55,6 +55,13 @@ export type GenerationResearch = {
postWalksNeedApproval: boolean;
};
+// 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";
routes: GenerationRoutes;
@@ -68,8 +75,11 @@ export type GenerationSettings = {
web: GenerationWeb;
citationOrigin: string;
research: GenerationResearch;
+ 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";
@@ -87,6 +97,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = {
web: { provider: "duckduckgo", searchUrl: "" },
citationOrigin: "",
research: { ...DEFAULT_GENERATION_RESEARCH },
+ verdicts: { bar: { ...DEFAULT_GENERATION_VERDICTS.bar }, models: [] },
};
export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
@@ -106,6 +117,19 @@ export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
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: "A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'.",
+ 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_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = {
@@ -232,9 +256,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/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -30,6 +30,8 @@ import {
GENERATION_ROUTES_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,
@@ -287,6 +289,8 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
{ path: "generation.caps", docs: GENERATION_CAPS_FIELD_DOCS, defaults: fromObject(d.generation.caps) },
{ 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.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
@@ -87,6 +87,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/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/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -9,6 +9,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/_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/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/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/plans/FACTS.md b/plans/FACTS.md
@@ -9240,3 +9240,28 @@ 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.
diff --git a/plans/release-28.md b/plans/release-28.md
@@ -377,6 +377,143 @@ 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).
+
## 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',
@@ -1233,6 +1258,19 @@ export function usage() {
' ready (nothing pending: continue with report-draft {"task": "sweep",',
' "iteration": N}) or continued. 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\").",
" WORKER_TOKEN and ARCHILYZER_EDITOR_URL, when unset, are read from",
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
@@ -281,6 +281,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/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/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/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();
+}