commit 1dc5c6e12878eea8d706c3ec084e647cf4aae05e
parent 442926c9db15d745ff1e0942bb08605019e39267
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 21:16:30 -0400
common: the verdict bench — items from ruled fact-checks, one claim per call, scored
lib/report/draft/bench/: items (a ruled claim with a span citation whose
recording has cues, the window ±N s; the rest skipped with a reason), the
prompt (rules only, the window trimmed for a local model's 8k cap), the pure
score (agreement, the 5x5 matrix, CONTRADICTED/NOT_FOUND recall, PARTLY strict
and adjacent, the always-CORROBORATED baseline, the bar), the local-only run
store under .generation/bench/verdicts/ (atomic, resumable) and the runner
(sequential, the whole-run cap checked before each API call).
The job: controller/benchVerdicts.ts, kind bench-verdicts on draft:local
(any local model: the GPU arbiter's gated fetch, ollama unloaded) or
draft:api; the day's cap and the usage ledger. POST /api/ops/bench-verdicts,
the ops ACTIONS row, `archilyzer reports bench-verdicts` (--dry, through the
editor, or --here for API models). settings.generation.verdicts {bar, models}.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
23 files changed, 2108 insertions(+), 0 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) |
@@ -145,6 +146,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" \| "narrate" \| "research", "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 narration takes "iteration" (a done one; "cards"?, "force"?) and is a step on it. "copyOf" N runs iteration N again on "model". "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`
@@ -1013,6 +1014,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
@@ -1054,6 +1070,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/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
@@ -74,3 +74,12 @@ test("research (S11): a route of its own, a file from before it keeps its preset
assert.deepEqual(r, { autonomy: "auto", maxItemsPerRun: 3, maxGbPerRun: 5, maxTranscribeHours: 6, newChannelsNeedApproval: false, postWalksNeedApproval: true });
assert.equal(sanitizeGeneration({ research: { autonomy: "yolo" } }).research.autonomy, "propose");
});
+
+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
@@ -42,6 +42,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;
@@ -55,8 +62,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";
@@ -74,6 +84,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> = {
@@ -93,6 +104,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> = {
@@ -208,9 +232,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/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/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -108,6 +108,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
@@ -403,6 +404,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
@@ -415,6 +420,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 ";
@@ -642,6 +650,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,
@@ -1226,6 +1235,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/settings.json.example b/settings.json.example
@@ -275,6 +275,14 @@
"maxTranscribeHours": 6,
"newChannelsNeedApproval": true,
"postWalksNeedApproval": true
+ },
+ "verdicts": {
+ "bar": {
+ "agreement": 0,
+ "contradictedRecall": 0,
+ "notFoundRecall": 0
+ },
+ "models": []
}
}
}