commit e6a8af9f53c963f435087ad59f340467117c6709
parent 458fbbf518bdae09c1ec17e6e52c33ff58d4934e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 15 Oct 2026 07:26:28 -0400
Merge r29/verdicts V1 (bench v2) into r29/integration
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
32 files changed, 1968 insertions(+), 219 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -36,7 +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 bench-verdicts` | `--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds\|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--run <id>] [--dry] [--here] [--wait] [--json]` | the verdict bench (release 28; release 29 V1): 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 report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT\_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode or --limit with it). The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations 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 with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/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) |
@@ -147,7 +147,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` |
| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. | `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}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait` |
| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -> {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` |
-| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the claim, its quotes, the transcript within the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues (answered pairs are skipped). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` |
+| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode or limit with it)} -> {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 report's title, the claim's section, the claim, its quotes, the transcript in 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 with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/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` |
| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` |
### Usage, flags and environment
diff --git a/REPORT.md b/REPORT.md
@@ -59,7 +59,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `id` | yes | The claim's id (letters, digits, `_ . : -`; at most 64): its anchor on the report page. Unique among the report's section, claim and entry ids, and none of the page's own anchors (`report-head`, `in-brief`, `found`, `claims`, `references`, `downloads`, `report-end`). |
| `title` | no | A short headline for the claim (plain text, e.g. a phrase it turns on), shown above its text. Absent = the text alone. |
| `text` | yes | The claim, as stated by the document under review (plain text). |
-| `verdict` | no | The ruling on the claim: `CORROBORATED`, `PARTLY`, `CONTRADICTED`, `NOT_FOUND`, `UNTESTABLE`. A fact-check's claim may leave it out (not yet ruled); a sweep's carries none. |
+| `verdict` | no | The ruling on the claim: `CORROBORATED`, `PARTLY`, `CONTRADICTED`, `NOT_FOUND`, `UNTESTABLE` (what each means: "The verdicts", below). A fact-check's claim may leave it out (not yet ruled); a sweep's carries none. |
| `gist` | no | The claim's finding in one line (plain text, at most 240 characters), shown beside its title in the overview of what the check found. Absent = the title alone. |
| `flag` | no | A short mark on the claim (plain text, one line, at most 60 characters), shown as a pill on its card: e.g. that the document gives no source for it. Absent = none. |
| `sourceQuote` | no | The document's own sentence making the claim: `{ "citation": "<id>" }`, naming a `source` citation (its still is shown with the claim). |
@@ -108,13 +108,15 @@ A report is also read as slides — its page's **Slides** view (`?rv=slides`), t
The shared vocabulary (`common/lib/report/verdicts.mjs` — the one copy; report-to-video's fact-check stamps read it too), in the order a tally lists them. A report's `verdicts` overrides a label (one line, at most 24 characters) or a colour (`#rgb` or `#rrggbb`), each on its own.
-| Verdict | Default label | Default colour |
-|---|---|---|
-| `CORROBORATED` | Corroborated | `#3fbf7f` |
-| `PARTLY` | Partly true | `#e3b23c` |
-| `CONTRADICTED` | Contradicted | `#e5534b` |
-| `NOT_FOUND` | Not found | `#8b93a7` |
-| `UNTESTABLE` | Untestable | `#7d8fd6` |
+| Verdict | Means | Default label | Default colour |
+|---|---|---|---|
+| `CORROBORATED` | the substance of the claim is shown by the cited words. Framing, emphasis, or a detail the transcript does not show does not demote it. | Corroborated | `#3fbf7f` |
+| `PARTLY` | a part of the claim is shown by the transcript to be overstated or wrong. A part that is only not shown does not make a claim PARTLY. | Partly true | `#e3b23c` |
+| `CONTRADICTED` | the substance of the claim is shown to be wrong: the transcript shows the opposite of it, or something that cannot be true at the same time. | Contradicted | `#e5534b` |
+| `NOT_FOUND` | the claim could be checked against what was said, and its substance is not in the transcript shown: the topic may come up without what the claim says about it. | Not found | `#8b93a7` |
+| `UNTESTABLE` | the claim is an opinion, a judgement, a prediction, or anything else a transcript cannot show to be true or false. | Untestable | `#7d8fd6` |
+
+In doubt between CORROBORATED and PARTLY: CORROBORATED, unless a part of the claim is shown overstated or wrong. The meanings are the operator's standard; the verdict bench's prompt and the verdict proposals read the same sentences.
## Iterations
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -416,8 +416,8 @@ 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" },
+ "--models <a,b,…> [--report <id,…>] [--window <s>] [--window-mode seconds|turn] [--max-usd <n>] [--limit <n>] [--items-from <run>] [--run <id>] [--dry] [--here] [--wait] [--json] the verdict bench (release 28; release 29 V1): 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 report's title, the claim's section, the claim, its quotes (their speaker and the recording's date) and the transcript within --window seconds (default 60) of each cited span, or with --window-mode turn the cited speaker's turn bounded by --window, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT_FOUND recall, not-CORROBORATED precision and recall, against an always-CORROBORATED baseline). --limit takes a stratified sample (by the operator's verdict: every verdict kept); --items-from takes an earlier run's exact items (no --report, --window, --window-mode or --limit with it). The run records its prompt version and its items' hash. --dry lists the items, the skipped claims and the dropped citations 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 with this invocation's --models only (refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench) (exit 1 when the run stopped early or was refused; 2 for usage)",
+ flags: { report: "string", models: "string", window: "string", "window-mode": "string", "max-usd": "string", limit: "string", "items-from": "string", run: "string", dry: "boolean", here: "boolean", wait: "boolean", json: "boolean" },
run: async (ctx) => (await import("./reports-bench-verdicts")).benchRow(ctx),
},
{
diff --git a/common/bin/reports-bench-verdicts.test.ts b/common/bin/reports-bench-verdicts.test.ts
@@ -60,7 +60,8 @@ test("--dry: the items over the local corpus's cues, the skipped claims and the
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.match(cap.logs[0]!, /^7 items from 1 fact-check\(s\), a 60 s window; 1 claims skipped, 0 citations dropped$/);
+ assert.match(cap.logs[1]!, /^ {2}prompt version \d+, items [0-9a-f]{16}$/);
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)));
@@ -82,6 +83,17 @@ test("a run goes through the editor (pnpm ops bench-verdicts); --here refuses a
);
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"]]);
+ // V1: the window mode, the stratified limit and items-from ride along.
+ seen.length = 0;
+ assert.equal(await benchMain({ models: "qwen3:8b", "window-mode": "turn", limit: "20" }, { paths: c.paths, runOps: async (argv) => (seen.push(argv), 0), out: capture().out }), 0);
+ assert.deepEqual(JSON.parse(seen[0]![2]!), { models: ["qwen3:8b"], limit: 20, windowMode: "turn" });
+ seen.length = 0;
+ assert.equal(await benchMain({ models: "qwen3:8b", "items-from": "vb-r28", run: "vb-r29-q1" }, { paths: c.paths, runOps: async (argv) => (seen.push(argv), 0), out: capture().out }), 0);
+ assert.deepEqual(JSON.parse(seen[0]![2]!), { models: ["qwen3:8b"], run: "vb-r29-q1", itemsFrom: "vb-r28" });
+ const bad = capture();
+ assert.equal(await benchMain({ models: "qwen3:8b", "items-from": "vb-r28", limit: "5" }, { paths: c.paths, runOps: async () => 0, out: bad.out }), 2);
+ assert.match(bad.errors.join("\n"), /items as they are: drop the limit/);
+ assert.equal(await benchMain({ models: "qwen3:8b", "window-mode": "sentence" }, { paths: c.paths, runOps: async () => 0, out: capture().out }), 2);
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/);
diff --git a/common/bin/reports-bench-verdicts.ts b/common/bin/reports-bench-verdicts.ts
@@ -1,8 +1,11 @@
// `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/).
+// [--window-mode seconds|turn] [--max-usd 5] [--limit n] [--items-from <run>]
+// [--run <id>] [--dry] [--here] [--wait] [--json]`
+// (release 28 M7; release 29 V1) — 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/). V1: `--window-mode
+// turn` (the cited speaker's turn, bounded by --window), a stratified `--limit`
+// (by the operator's verdict), `--items-from <run>` (that run's exact items).
//
// --dry lists the items (key, the operator's verdict, quotes, cues — no
// claim text unless --json) and the skipped claims with their
@@ -31,6 +34,7 @@ import { diskCuesOf } from "../lib/report/convert-server";
import {
BenchInputError,
isBenchRunId,
+ isWindowMode,
newBenchRunId,
validateBenchOptions,
planVerdictBench,
@@ -38,6 +42,7 @@ import {
type BenchPlan,
} from "../lib/report/draft/bench/index";
import { benchDailyCapRefusal, runBenchWithSettings } from "../controller/benchVerdicts";
+import { diskDateOf, diskTurnsOf } from "../lib/report/draft/bench/disk";
import { runOpsChild } from "./gen";
type Out = { log: (s: string) => void; error: (s: string) => void };
@@ -61,6 +66,11 @@ export function benchOptionsOf(flags: Record<string, FlagValue>): BenchOptions {
if (m !== undefined) o.maxUsd = m;
const l = num(flags.limit, "limit");
if (l !== undefined) o.limit = l;
+ if (typeof flags["window-mode"] === "string") {
+ if (!isWindowMode(flags["window-mode"])) throw new BenchInputError(`--window-mode is "seconds" or "turn"`);
+ o.windowMode = flags["window-mode"];
+ }
+ if (typeof flags["items-from"] === "string") o.itemsFrom = flags["items-from"];
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");
@@ -69,10 +79,17 @@ export function benchOptionsOf(flags: Record<string, FlagValue>): BenchOptions {
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 window = plan.windowMode === "turn" ? `the speaker's turn within ${plan.windowS} s` : `a ${plan.windowS} s window`;
+ lines.push(
+ `${plan.items.length} items from ${plan.reports.length} fact-check(s)${plan.itemsFrom ? ` (run ${plan.itemsFrom}'s items)` : ""}, ${window}; ${plan.skipped.length} claims skipped, ${plan.dropped.length} citations dropped`,
+ );
+ lines.push(` prompt version ${plan.promptVersion}, items ${plan.itemsHash}`);
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 drops = new Map<string, number>();
+ for (const d of plan.dropped) drops.set(d.reason, (drops.get(d.reason) ?? 0) + 1);
+ for (const [r, n] of drops) lines.push(` dropped ${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"}`);
@@ -82,6 +99,7 @@ export function formatBenchPlan(plan: BenchPlan): string[] {
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}`);
+ for (const d of plan.dropped) lines.push(` dropped ${d.key} ${d.citation}: ${d.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)}`);
@@ -102,7 +120,12 @@ export async function benchMain(flags: Record<string, FlagValue>, deps: BenchDep
try {
opts = benchOptionsOf(flags);
if (flags.dry === true) {
- const plan = await planVerdictBench(opts, { paths: deps.paths, cuesOf: diskCuesOf(deps.paths.channelsDir) });
+ const plan = await planVerdictBench(opts, {
+ paths: deps.paths,
+ cuesOf: diskCuesOf(deps.paths.channelsDir),
+ turnsOf: diskTurnsOf(deps.paths.channelsDir),
+ dateOf: diskDateOf(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;
@@ -145,6 +168,8 @@ export async function benchMain(flags: Record<string, FlagValue>, deps: BenchDep
if (opts.windowS !== undefined) body.window = opts.windowS;
if (opts.maxUsd !== undefined) body.maxUsd = opts.maxUsd;
if (opts.limit !== undefined) body.limit = opts.limit;
+ if (opts.windowMode !== undefined) body.windowMode = opts.windowMode;
+ if (opts.itemsFrom !== undefined) body.itemsFrom = opts.itemsFrom;
return deps.runOps(["bench-verdicts", "--json", JSON.stringify(body), ...(flags.wait === true ? ["--wait"] : [])]);
}
diff --git a/common/controller/benchVerdicts.ts b/common/controller/benchVerdicts.ts
@@ -6,8 +6,12 @@
// 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)
+// windowMode "seconds" (the default) or "turn": the cited speaker's turn,
+// bounded by the window (release 29 V1)
// maxUsd the whole run's API cap (default 5, at most 50)
-// limit the first n items only
+// limit a stratified sample of n items, by the operator's verdict (V1)
+// itemsFrom the exact items of an earlier run (V1; no reports, window,
+// windowMode or limit with it)
//
// 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
@@ -36,18 +40,21 @@ import {
BenchInputError,
DEFAULT_BENCH_MAX_USD,
isBenchRunId,
+ isWindowMode,
newBenchRunId,
runVerdictBench,
validateBenchOptions,
type BenchOptions,
+ type WindowMode,
} from "../lib/report/draft/bench/index";
+import { diskDateOf, diskTurnsOf } from "../lib/report/draft/bench/disk";
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;
+export const BENCH_VERDICTS_BODY_KEYS = ["run", "reports", "models", "window", "windowMode", "maxUsd", "limit", "itemsFrom"] as const;
const fail = (msg: string): never => {
throw new BenchInputError(msg);
@@ -79,6 +86,14 @@ export function parseBenchVerdictsBody(b: Record<string, unknown>): BenchOptions
if (typeof b.limit !== "number") fail(`"limit" is a number of items`);
out.limit = b.limit as number;
}
+ if (b.windowMode !== undefined) {
+ if (!isWindowMode(b.windowMode)) fail(`"windowMode" is "seconds" or "turn"`);
+ out.windowMode = b.windowMode as WindowMode;
+ }
+ if (b.itemsFrom !== undefined) {
+ if (!isBenchRunId(b.itemsFrom)) fail(`"itemsFrom" is a run id: lowercase letters, digits and dashes`);
+ out.itemsFrom = b.itemsFrom as string;
+ }
validateBenchOptions(out);
return out;
}
@@ -122,6 +137,8 @@ export async function runBenchWithSettings(
paths,
...(o.root ? { root: o.root } : {}),
cuesOf: diskCuesOf(paths.channelsDir),
+ turnsOf: diskTurnsOf(paths.channelsDir),
+ dateOf: diskDateOf(paths.channelsDir),
llm: llmConfigOf(g, paths, locals.length ? { onLog, ...(o.signal ? { signal: o.signal } : {}) } : undefined),
log: onLog,
...(o.signal ? { signal: o.signal } : {}),
diff --git a/common/lib/report/docs.ts b/common/lib/report/docs.ts
@@ -23,7 +23,7 @@ import {
sectionSchema,
slideSchema,
} from "./schema";
-import { VERDICT_DEFAULTS, VERDICT_LABEL_MAX, VERDICTS } from "./verdicts";
+import { VERDICT_DEFAULTS, VERDICT_LABEL_MAX, VERDICT_MEANINGS, VERDICT_TIE_RULE, VERDICTS } from "./verdicts";
export function renderReportMarkdown(): string {
const out: string[] = [];
@@ -144,13 +144,15 @@ export function renderReportMarkdown(): string {
"characters) or a colour (`#rgb` or `#rrggbb`), each on its own.",
);
out.push("");
- out.push("| Verdict | Default label | Default colour |");
- out.push("|---|---|---|");
+ out.push("| Verdict | Means | Default label | Default colour |");
+ out.push("|---|---|---|---|");
for (const v of VERDICTS) {
const d = VERDICT_DEFAULTS[v];
- out.push(`| \`${v}\` | ${cell(d.label)} | \`${d.color}\` |`);
+ out.push(`| \`${v}\` | ${cell(VERDICT_MEANINGS[v])} | ${cell(d.label)} | \`${d.color}\` |`);
}
out.push("");
+ out.push(`${VERDICT_TIE_RULE} The meanings are the operator's standard; the verdict bench's prompt and the verdict proposals read the same sentences.`);
+ out.push("");
out.push("## Iterations");
out.push("");
out.push(
diff --git a/common/lib/report/draft/bench/bench.test.ts b/common/lib/report/draft/bench/bench.test.ts
@@ -20,9 +20,20 @@ import {
runVerdictBench,
scoreBench,
VERDICT_BENCH_SYSTEM,
+ VERDICT_ANSWER_SCHEMA,
+ PROMPT_VERSION,
+ benchItemsHash,
+ compareBenchRuns,
+ markedScore,
+ stratifiedLimit,
+ turnOf,
+ type BenchAsk,
type BenchItem,
type BenchResult,
} from "./index";
+import { VERDICT_MEANINGS, VERDICT_TIE_RULE } from "../../verdicts";
+import { CLAIM_FIELD_DOCS } from "../../schema";
+import { renderReportMarkdown } from "../../docs";
import { promptEstimate } from "../../../llm/ollama";
const RULED = path.join(import.meta.dirname, "../../../../testing/draft/reports/ruled.report.json");
@@ -345,7 +356,12 @@ test("plan (the dry run): the items, the skipped, an estimate per model; nothing
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);
+ // The limit is stratified: every verdict ruled is kept; the rest are skipped, said so.
+ assert.deepEqual([...new Set(plan.items.map((i) => i.verdict))].sort(), ["CONTRADICTED", "CORROBORATED", "NOT_FOUND", "PARTLY"]);
+ assert.equal(plan.skipped.length, 3);
+ assert.equal(plan.skipped.filter((x) => x.reason === "left out by the limit").length, 2);
+ assert.equal(plan.promptVersion, PROMPT_VERSION);
+ assert.match(plan.itemsHash, /^[0-9a-f]{16}$/);
assert.deepEqual(plan.reports, ["synth-ruled"]);
const [sonnet, opus, qwen] = plan.estimate;
assert.ok(sonnet!.usd > 0 && opus!.usd > sonnet!.usd);
@@ -359,3 +375,238 @@ test("plan (the dry run): the items, the skipped, an estimate per model; nothing
await s.done();
}
});
+
+// ─── release 29 V1: bench v2 ───
+
+// A stubbed model (R6's injected ask): answers each claim from a table, and
+// records what it was asked.
+function stubAsk(answers: (model: string, id: string) => unknown, texts: Record<string, string>) {
+ const asked: { model: string; id: string; system: string; user: string; schema: any }[] = [];
+ const ask: BenchAsk = async <T,>(system: string, user: string, schema: object, model: string) => {
+ const id = texts[claimOf(user)]!;
+ asked.push({ model, id, system, user, schema });
+ const a = answers(model, id);
+ if (a instanceof Error) throw a;
+ return a as T;
+ };
+ return { ask, asked };
+}
+
+test("V1 prompt: the meanings are the shared module's, the tie rule is in, reason before verdict, the context shown, a version", async () => {
+ for (const v of VERDICTS) assert.ok(VERDICT_BENCH_SYSTEM.includes(`- ${v}: ${VERDICT_MEANINGS[v]}`), v);
+ assert.ok(VERDICT_BENCH_SYSTEM.includes(VERDICT_TIE_RULE));
+ assert.match(VERDICT_MEANINGS.CORROBORATED, /substance/);
+ assert.match(VERDICT_MEANINGS.PARTLY, /shown .* overstated or wrong/);
+ assert.ok(!/example|e\.g\./i.test(VERDICT_BENCH_SYSTEM));
+ assert.deepEqual(Object.keys(VERDICT_ANSWER_SCHEMA.properties), ["reason", "verdict"]);
+ assert.deepEqual(VERDICT_ANSWER_SCHEMA.required, ["reason", "verdict"]);
+ assert.equal(typeof PROMPT_VERSION, "string");
+ // The same sentences in REPORT.md and the claim's docs: nowhere else spells them out.
+ const md = renderReportMarkdown();
+ for (const v of VERDICTS) assert.ok(md.includes(VERDICT_MEANINGS[v]), `REPORT.md lacks ${v}'s meaning`);
+ assert.ok(md.includes(VERDICT_TIE_RULE));
+ assert.match(CLAIM_FIELD_DOCS.verdict, /what each means/);
+ // The context: the report's title, the section, each quote's speaker (the channel) and date.
+ const s = await store();
+ try {
+ const { items } = await benchItemsOf(await benchReportsOf(s.paths), {
+ cuesOf,
+ dateOf: async (_c, id) => (id === "bread-day-01" ? "2026-01-05" : null),
+ });
+ const r02 = items.find((i) => i.claim === "r02")!;
+ assert.equal(r02.title, "Synth Kitchen — what an article says about the baker, checked");
+ assert.equal(r02.section, "The bakery");
+ const u = benchPrompt(r02).user;
+ assert.match(u, /^Report: Synth Kitchen/m);
+ assert.match(u, /^Section: The bakery$/m);
+ assert.match(u, /"the oven was fine it just ran hot" \(speaker: synth-kitchen; recorded: 2026-01-05\)/);
+ assert.match(u, /^## Bread day, 0:00 to 1:34 \(channel: synth-kitchen; recorded: 2026-01-05\)$/m);
+ assert.ok(!u.includes(r02.verdict));
+ // A local prompt stays under the 8k cap with the longer system prompt.
+ for (const it of items) assert.ok(benchPrompt(it, { capTokens: LOCAL_PROMPT_CAP }).estimate <= LOCAL_PROMPT_CAP);
+ } finally {
+ await s.done();
+ }
+});
+
+test("V1 items: the turn mode — the speaker's segments, else a pause or a >> change — bounded by the window; drops listed by reason", async () => {
+ const cues = [
+ { start: 0, end: 4, text: "hello" },
+ { start: 4.5, end: 8, text: "the oven" },
+ { start: 9, end: 12, text: "ran hot" },
+ { start: 16, end: 19, text: ">> no it did not" },
+ { start: 19.5, end: 22, text: "it was fine" },
+ ];
+ // No segments: back to the pause at 0 (none: the first cue), on until the >> change.
+ assert.deepEqual(turnOf(cues, null, { start: 5, end: 7 }, 0, 100), { from: 0, to: 12, bound: "pause" });
+ // A >> cue starts its own turn: it runs on, never back.
+ assert.deepEqual(turnOf(cues, null, { start: 17, end: 18 }, 0, 100), { from: 16, to: 22, bound: "pause" });
+ // The bound cuts a turn: `limit`.
+ assert.deepEqual(turnOf(cues, null, { start: 5, end: 7 }, 3, 10), { from: 3, to: 10, bound: "limit" });
+ // Speaker segments win: speaker 1's run around the span.
+ const segs = [
+ { start: 0, end: 4, speaker: 0 },
+ { start: 4, end: 9, speaker: 1 },
+ { start: 9, end: 13, speaker: 1 },
+ { start: 13, end: 22, speaker: 0 },
+ ];
+ assert.deepEqual(turnOf(cues, segs, { start: 5, end: 7 }, 0, 100), { from: 4, to: 13, bound: "speaker" });
+
+ const s = await store((r) => {
+ // r01 cites a missing citation and a post beside its span: both dropped, the claim kept.
+ r.citations.p1 = { kind: "post", channel: "synth-kitchen-posts", id: "p-1", quote: "a post" };
+ r.sections[0].claims[0].citations = ["q01", "p1", "gone"];
+ // r02's second citation is a recording with no cues: dropped.
+ r.citations.q99 = { ...r.citations.q02, id: "no-such-recording" };
+ r.sections[0].claims[1].citations = ["q02", "q99"];
+ });
+ try {
+ const reports = await benchReportsOf(s.paths);
+ const secs = await benchItemsOf(reports, { cuesOf, windowS: 60 });
+ assert.deepEqual(
+ secs.dropped.map((d) => [d.key, d.citation, d.reason]),
+ [
+ ["synth-ruled/r01", "p1", "not a video or audio citation"],
+ ["synth-ruled/r01", "gone", "not in the report's citations"],
+ ["synth-ruled/r02", "q99", "the recording has no cues"],
+ ],
+ );
+ assert.ok(secs.items.every((i) => i.windows.every((w) => w.bound === "seconds")));
+ // Turn mode over the synthetic cues (0.2 s apart: one long turn) is bounded by the window.
+ const turn = await benchItemsOf(reports, { cuesOf, windowS: 10, windowMode: "turn" });
+ const r02 = turn.items.find((i) => i.claim === "r02")!;
+ assert.equal(r02.windows[0]!.bound, "limit");
+ assert.equal(r02.windows[0]!.from, 20);
+ assert.equal(r02.windows[0]!.to, 44.8);
+ // With the speaker's segments: exactly the turn.
+ const turns = await benchItemsOf(reports, {
+ cuesOf,
+ windowS: 60,
+ windowMode: "turn",
+ turnsOf: async (_c, id) => (id === "bread-day-01" ? [{ start: 0, end: 25, speaker: 0 }, { start: 25, end: 40, speaker: 1 }, { start: 40, end: 70, speaker: 0 }] : null),
+ });
+ const w = turns.items.find((i) => i.claim === "r02")!.windows[0]!;
+ assert.deepEqual([w.from, w.to, w.bound], [25, 40, "speaker"]);
+ assert.deepEqual(w.cues.map((c) => c.start), [25, 30, 35, 40]);
+ } finally {
+ await s.done();
+ }
+});
+
+test("V1 stratified limit: every verdict kept, in proportion, the rest by the largest remainder; order kept", () => {
+ const mk = (n: number, v: Verdict) => Array.from({ length: n }, (_, i) => ({ key: `${v}-${i}`, verdict: v }));
+ const items = [...mk(78, "CORROBORATED"), ...mk(58, "PARTLY"), ...mk(6, "NOT_FOUND"), ...mk(4, "CONTRADICTED"), ...mk(1, "UNTESTABLE")];
+ const { kept, left } = stratifiedLimit(items, 20);
+ assert.equal(kept.length, 20);
+ assert.equal(left.length, 127);
+ const count = (v: Verdict) => kept.filter((k) => k.verdict === v).length;
+ assert.deepEqual(VERDICTS.map(count), [10, 7, 1, 1, 1]);
+ assert.deepEqual(kept.slice(0, 2).map((k) => k.key), ["CORROBORATED-0", "CORROBORATED-1"]);
+ // Smaller than the verdicts: the rarest first.
+ assert.deepEqual(stratifiedLimit(items, 2).kept.map((k) => k.verdict), ["CONTRADICTED", "UNTESTABLE"]);
+ assert.equal(stratifiedLimit(items, 500).kept.length, 147);
+});
+
+test("V1 run: the injected ask, reason before verdict, a per-call trace; --items-from takes the exact items; a resume asks only its own models; another prompt version is refused", async () => {
+ const s = await store();
+ const texts = await claimTexts();
+ // Sonnet right everywhere; qwen says PARTLY on r01, right elsewhere.
+ const { ask, asked } = stubAsk((model, id) => ({ reason: `on ${id}`, verdict: model === "qwen3:8b" && id === "r01" ? "PARTLY" : TRUTH[id] }), texts);
+ const root = benchRootOf(s.paths);
+ try {
+ const first = await runVerdictBench({ runId: "vb-one", models: ["claude-sonnet-5-5", "qwen3:8b"] }, { paths: s.paths, cuesOf, llm: {}, ask });
+ assert.equal(first.summary.status, "done");
+ assert.equal(asked.length, 14);
+ assert.equal(first.summary.promptVersion, PROMPT_VERSION);
+ assert.equal(first.summary.windowMode, "seconds");
+ assert.match(first.summary.itemsHash!, /^[0-9a-f]{16}$/);
+ assert.deepEqual(Object.keys(asked[0]!.schema.properties), ["reason", "verdict"]);
+ // The trace: a start line and one line per call with the prompt the model saw and its answer.
+ const trace = (await readFile(path.join(root, "vb-one", "trace.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l));
+ assert.equal(trace[0].t, "start");
+ assert.equal(trace[0].promptVersion, PROMPT_VERSION);
+ const calls = trace.filter((l) => l.t === "call");
+ assert.equal(calls.length, 14);
+ assert.ok(calls[0].user.startsWith("Report: "));
+ assert.deepEqual(calls[0].answer, { reason: "on r01", verdict: "CORROBORATED" });
+
+ // A run from vb-one's items: the same items, the same hash; only qwen asked.
+ asked.length = 0;
+ const two = await runVerdictBench({ runId: "vb-two", models: ["qwen3:8b"], itemsFrom: "vb-one" }, { paths: s.paths, cuesOf, llm: {}, ask });
+ assert.equal(two.summary.itemsFrom, "vb-one");
+ assert.equal(two.summary.itemsHash, first.summary.itemsHash);
+ assert.equal(asked.length, 7);
+ assert.ok(asked.every((a) => a.model === "qwen3:8b"));
+ // Resume with Sonnet too: only Sonnet is asked; qwen's pairs are not re-asked.
+ asked.length = 0;
+ const again = await runVerdictBench({ runId: "vb-two", models: ["claude-sonnet-5-5"] }, { paths: s.paths, cuesOf, llm: {}, ask });
+ assert.equal(asked.length, 7);
+ assert.ok(asked.every((a) => a.model === "claude-sonnet-5-5"));
+ assert.deepEqual(again.summary.models, ["qwen3:8b", "claude-sonnet-5-5"]);
+ // A resume with qwen alone asks nothing.
+ asked.length = 0;
+ await runVerdictBench({ runId: "vb-two", models: ["qwen3:8b"] }, { paths: s.paths, cuesOf, llm: {}, ask });
+ assert.equal(asked.length, 0);
+
+ // items-from refuses what would change the items, and a run that does not exist.
+ await assert.rejects(runVerdictBench({ runId: "vb-x", models: ["m"], itemsFrom: "vb-one", limit: 3 }, { paths: s.paths, cuesOf, llm: {}, ask }), /drop the limit/);
+ await assert.rejects(runVerdictBench({ runId: "vb-x", models: ["m"], itemsFrom: "vb-nope" }, { paths: s.paths, cuesOf, llm: {}, ask }), /no run "vb-nope"/);
+ // An M7 run (no prompt version) is not resumed under this one.
+ const sum = JSON.parse(await readFile(path.join(root, "vb-one", "summary.json"), "utf8"));
+ delete sum.promptVersion;
+ await writeFile(path.join(root, "vb-one", "summary.json"), JSON.stringify(sum));
+ await assert.rejects(runVerdictBench({ runId: "vb-one", models: ["qwen3:8b"] }, { paths: s.paths, cuesOf, llm: {}, ask }), /prompt version 1, and this is version/);
+ // ... but its items are taken as they are, and fill the context M7's items lacked.
+ const m7 = (await readBenchRun(root, "vb-one"))!;
+ const bare = m7.items.map(({ title: _t, section: _s, ...rest }) => rest);
+ await writeFile(path.join(root, "vb-one", "items.jsonl"), bare.map((i) => `${JSON.stringify(i)}\n`).join(""));
+ asked.length = 0;
+ const three = await runVerdictBench({ runId: "vb-three", models: ["qwen3:8b"], itemsFrom: "vb-one" }, { paths: s.paths, cuesOf, llm: {}, ask });
+ assert.equal(three.summary.itemsHash, first.summary.itemsHash);
+ assert.match(asked[0]!.user, /^Section: /m);
+ } finally {
+ await s.done();
+ }
+});
+
+test("V1 score: not-CORROBORATED precision and recall; two runs compared; the operator's marks on disagreements", () => {
+ const items = Object.entries(TRUTH).map(([claim, verdict]) => ({ key: `r/${claim}`, verdict }));
+ const res = (model: string, said: Record<string, Verdict | null>): BenchResult[] =>
+ Object.entries(said).map(([claim, v]) => ({ key: `r/${claim}`, model, verdict: v, ...(v ? {} : { failure: "parse" as const }), ms: 1, usd: 0, inputTokens: 0, outputTokens: 0, at: "" }));
+ // Run A: PARTLY on both CORROBORATED (2 false flags), finds r02 r04 r07, misses r03 (CORROBORATED), r05 (failed).
+ const a = res("m", { r01: "PARTLY", r02: "PARTLY", r03: "CORROBORATED", r04: "CONTRADICTED", r05: null, r06: "PARTLY", r07: "NOT_FOUND" });
+ const sa = scoreBench(items, a, ["m"]).models[0]!;
+ // positives: r01 r02 r04 r06 r07 → tp r02 r04 r07 (3), fp r01 r06 (2); fn r03 r05 (2).
+ assert.deepEqual(sa.notCorroborated, { tp: 3, fp: 2, fn: 2, precision: 0.6, recall: 0.6 });
+ assert.equal(scoreBench(items, a, ["m"]).baseline.notCorroborated.recall, 0);
+ // Run B on the same items: r01 fixed, r04 broken.
+ const b = res("m", { r01: "CORROBORATED", r02: "PARTLY", r03: "CORROBORATED", r04: "PARTLY", r05: null, r06: "PARTLY", r07: "NOT_FOUND" });
+ const cmp = compareBenchRuns({ items, results: a, models: ["m"] }, { items, results: b, models: ["m", "n"] });
+ assert.equal(cmp.items, 7);
+ assert.equal(cmp.models.length, 1);
+ const m = cmp.models[0]!;
+ assert.deepEqual([m.a.agreed, m.b.agreed], [3, 3]);
+ assert.deepEqual(m.changed, [
+ { key: "r/r01", ruled: "CORROBORATED", a: "PARTLY", b: "CORROBORATED" },
+ { key: "r/r04", ruled: "CONTRADICTED", a: "CONTRADICTED", b: "PARTLY" },
+ ]);
+ assert.deepEqual([m.fixed, m.broke], [1, 1]);
+ // Marks: r06's PARTLY marked Right (the model saw what the ruling missed),
+ // r01's marked Wrong, and a stale mark (on an answer since changed) ignored.
+ const marks = {
+ m: {
+ "r/r06": { verdict: "right" as const, answer: "PARTLY" as const, at: "" },
+ "r/r01": { verdict: "wrong" as const, answer: "PARTLY" as const, at: "" },
+ "r/r02": { verdict: "right" as const, answer: "CORROBORATED" as const, at: "" },
+ },
+ };
+ const ms = markedScore(items, a, "m", marks);
+ assert.deepEqual(ms.marks, { marked: 2, right: 1, wrong: 1, precision: 0.5 });
+ assert.equal(ms.agreed, 4);
+ assert.deepEqual(ms.notCorroborated, { tp: 4, fp: 1, fn: 2, precision: 0.8, recall: 0.6667 });
+ // The hash is the items' identity: context lines do not change it.
+ assert.equal(
+ benchItemsHash([{ key: "a", verdict: "PARTLY", windows: [] }]),
+ benchItemsHash([{ key: "a", verdict: "PARTLY", windows: [], title: "t" } as any]),
+ );
+});
diff --git a/common/lib/report/draft/bench/disk.ts b/common/lib/report/draft/bench/disk.ts
@@ -0,0 +1,83 @@
+// The verdict bench's disk half (release 29 V1): what a channels tree tells
+// the items beside the cues (`diskCuesOf`, ../../convert-server.ts) — a
+// recording's speaker segments (its attribution sidecar, for the `turn` window
+// mode) and its own date (metadata.info.json's upload_date, for a quote whose
+// citation names none). Behind the text guard (lib/channelMedia.ts), as the
+// cues are: a channel whose text is not readable answers null. Reads only.
+//
+// SERVER-ONLY (node:fs).
+
+import { open } from "node:fs/promises";
+import path from "node:path";
+import { assertChannelTextReadable } from "../../../channelMedia";
+import { resolveVideoDir } from "../../../videoDir-server.mjs";
+import { isSafeChannelSegment, isSafeIdSegment } from "../../../citations/moments";
+import { loadAttribution } from "../../../attribution-server";
+import type { DateOf, SpeakerTurn, TurnsOf } from "./items";
+
+function guard(channelsDir: string) {
+ const readable = new Map<string, Promise<boolean>>();
+ return (slug: string) => {
+ let p = readable.get(slug);
+ if (!p) {
+ p = assertChannelTextReadable({ channelsDir }, slug).then(
+ () => true,
+ () => false,
+ );
+ readable.set(slug, p);
+ }
+ return p;
+ };
+}
+
+async function videoDirOf(channelsDir: string, ok: (slug: string) => Promise<boolean>, channel: string, id: string): Promise<string | null> {
+ if (!isSafeChannelSegment(channel) || !isSafeIdSegment(id)) return null;
+ if (!(await ok(channel))) return null;
+ return resolveVideoDir(channelsDir, channel, id).catch(() => null);
+}
+
+/** A recording's speaker segments from its attribution sidecar, or null. */
+export function diskTurnsOf(channelsDir: string): TurnsOf {
+ const ok = guard(channelsDir);
+ return async (channel, id) => {
+ const dir = await videoDirOf(channelsDir, ok, channel, id);
+ if (!dir) return null;
+ const rec = await loadAttribution(dir).catch(() => null);
+ if (!rec?.segments.length) return null;
+ return rec.segments.map((s): SpeakerTurn => ({ start: s.start, end: s.end, speaker: s.speaker }));
+ };
+}
+
+const UPLOAD_DATE_RE = /"upload_date":\s*"(\d{4})(\d{2})(\d{2})"/;
+const TAIL_BYTES = 8192;
+
+/**
+ * A recording's own date, `YYYY-MM-DD`, off its metadata.info.json — yt-dlp
+ * writes upload_date near the end, so the file's last 8 KB, then (a file
+ * whose date is not there) the whole file.
+ */
+export function diskDateOf(channelsDir: string): DateOf {
+ const ok = guard(channelsDir);
+ return async (channel, id) => {
+ const dir = await videoDirOf(channelsDir, ok, channel, id);
+ if (!dir) return null;
+ let fh;
+ try {
+ fh = await open(path.join(dir, "metadata.info.json"), "r");
+ const { size } = await fh.stat();
+ const tail = Buffer.alloc(Math.min(size, TAIL_BYTES));
+ await fh.read(tail, 0, tail.length, Math.max(0, size - tail.length));
+ let m = UPLOAD_DATE_RE.exec(tail.toString("utf8"));
+ if (!m && size > TAIL_BYTES) {
+ const all = Buffer.alloc(size);
+ await fh.read(all, 0, size, 0);
+ m = UPLOAD_DATE_RE.exec(all.toString("utf8"));
+ }
+ return m ? `${m[1]}-${m[2]}-${m[3]}` : null;
+ } catch {
+ return null;
+ } finally {
+ await fh?.close().catch(() => {});
+ }
+ };
+}
diff --git a/common/lib/report/draft/bench/items.ts b/common/lib/report/draft/bench/items.ts
@@ -1,32 +1,54 @@
-// THE VERDICT BENCH'S ITEMS (release 28, M7): one per ruled fact-check claim.
+// THE VERDICT BENCH'S ITEMS (release 28 M7; release 29 V1): 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.
+// recording has cues around the cited seconds: the claim's text, its context
+// (the report's title, the claim's section heading; each quote's speaker and
+// date), the cited quotes, and the transcript WINDOW around each cited span —
+// overlapping windows of one recording merged. Every other claim is SKIPPED,
+// and every citation of a kept claim that gives no window is DROPPED, each
+// with its reason, and counted: nothing is left out silently.
+//
+// THE WINDOW MODES (V1):
+// seconds the cues within ±`windowS` of the cited span (M7's, the default)
+// turn the cited speaker's TURN: the recording's speaker segments
+// (`turnsOf`, the attribution sidecar) around the span, else the
+// cues run on until a pause of TURN_GAP_S or a `>>` speaker change —
+// bounded by ±`windowS` either way (a window's `bound` says which)
//
// 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 UNRULED mode (M8's proposals) is the same reading over the claims with
+// NO verdict: a ruled claim is skipped ("ruled by the operator").
+//
// 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 { createHash } from "node:crypto";
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 type { Claim, Report } from "../../schema";
import { parseReport } from "../../validate";
-import { isVerdict, type Verdict } from "../../verdicts";
+import { isVerdict, VERDICTS, type Verdict } from "../../verdicts";
export const DEFAULT_WINDOW_S = 60;
+export const WINDOW_MODES = ["seconds", "turn"] as const;
+export type WindowMode = (typeof WINDOW_MODES)[number];
+export const isWindowMode = (v: unknown): v is WindowMode => typeof v === "string" && (WINDOW_MODES as readonly string[]).includes(v);
+
+// The turn mode with no speaker segments: a pause this long between two cues
+// ends the turn.
+export const TURN_GAP_S = 2;
+
export type BenchCue = { start: number; end: number; text: string };
export type BenchQuote = {
@@ -41,6 +63,11 @@ export type BenchQuote = {
date?: string;
};
+// What ended a window: the seconds either side (`seconds`), the speaker's own
+// segments (`speaker`), a pause or a speaker change in the cues (`pause`), or
+// the ±windowS bound a turn ran into (`limit`).
+export type WindowBound = "seconds" | "speaker" | "pause" | "limit";
+
// One recording's cues around the cited spans in it.
export type BenchWindow = {
channel: string;
@@ -51,6 +78,7 @@ export type BenchWindow = {
// The cited spans in this window (for the trim: the cues nearest them stay).
cited: { start: number; end: number }[];
cues: BenchCue[];
+ bound?: WindowBound;
};
export type BenchItem = {
@@ -63,13 +91,36 @@ export type BenchItem = {
verdict: Verdict;
quotes: BenchQuote[];
windows: BenchWindow[];
+ // Context for the model (V1): the report's title and the claim's section heading.
+ title?: string;
+ section?: string;
};
+// An unruled claim, read the same way (M8's proposals): no answer key.
+export type ClaimItem = Omit<BenchItem, "verdict">;
+
export type BenchSkipped = { key: string; report: string; claim: string; reason: string };
+// A citation of a KEPT claim that gave no window, and why.
+export type BenchDropped = { key: string; citation: string; reason: string };
+
export type BenchReport = { id: string; report: Report };
-export type BenchItems = { items: BenchItem[]; skipped: BenchSkipped[] };
+export type BenchItems = { items: BenchItem[]; skipped: BenchSkipped[]; dropped: BenchDropped[] };
+
+// A recording's speaker segments (the attribution sidecar's), or null.
+export type SpeakerTurn = { start: number; end: number; speaker: number | string };
+export type TurnsOf = (channel: string, id: string) => Promise<readonly SpeakerTurn[] | null>;
+// A recording's own date (`YYYY-MM-DD`), for a quote whose citation names none.
+export type DateOf = (channel: string, id: string) => Promise<string | null>;
+
+export type ItemOptions = {
+ cuesOf: CuesOf;
+ windowS?: number;
+ windowMode?: WindowMode;
+ turnsOf?: TurnsOf;
+ dateOf?: DateOf;
+};
export class BenchInputError extends Error {}
@@ -106,6 +157,8 @@ export async function benchReportsOf(
return out;
}
+const BOUND_RANK: Record<WindowBound, number> = { seconds: 0, speaker: 1, pause: 2, limit: 3 };
+
function mergeWindows(windows: BenchWindow[]): BenchWindow[] {
const byRecord = new Map<string, BenchWindow[]>();
for (const w of windows) {
@@ -123,6 +176,7 @@ function mergeWindows(windows: BenchWindow[]): BenchWindow[] {
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);
+ if (w.bound && (!cur.bound || BOUND_RANK[w.bound] > BOUND_RANK[cur.bound])) cur.bound = w.bound;
} else {
if (cur) out.push(cur);
cur = { ...w, cited: [...w.cited], cues: [...w.cues] };
@@ -133,77 +187,267 @@ function mergeWindows(windows: BenchWindow[]): BenchWindow[] {
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 overlaps = (a: { start: number; end: number }, from: number, to: number) => a.end >= from && a.start <= to;
+const changesSpeaker = (text: string) => /^\s*>>/.test(text);
+
+/**
+ * The cited speaker's turn around `span`, bounded by [lo, hi]: the speaker's
+ * run of segments when `turns` has one over the span, else the cues run on
+ * until a pause of TURN_GAP_S or a `>>` speaker change. The cited span is
+ * always inside; a turn cut by the bound says `limit`. Pure.
+ */
+export function turnOf(
+ cues: readonly BenchCue[],
+ turns: readonly SpeakerTurn[] | null,
+ span: { start: number; end: number },
+ lo: number,
+ hi: number,
+): { from: number; to: number; bound: WindowBound } {
+ const clip = (from: number, to: number, bound: WindowBound) => ({
+ from: Math.max(lo, Math.min(from, span.start)),
+ to: Math.min(hi, Math.max(to, span.end)),
+ bound: from < lo || to > hi ? ("limit" as const) : bound,
+ });
+ const segs = (turns ?? []).filter((s) => Number.isFinite(s.start) && Number.isFinite(s.end) && s.end > s.start).slice().sort((a, b) => a.start - b.start);
+ let best = -1;
+ let most = 0;
+ segs.forEach((s, i) => {
+ const o = Math.min(s.end, span.end) - Math.max(s.start, span.start);
+ if (o > most) {
+ most = o;
+ best = i;
+ }
+ });
+ if (best >= 0) {
+ const who = segs[best]!.speaker;
+ let a = best;
+ let b = best;
+ while (a > 0 && segs[a - 1]!.speaker === who) a--;
+ while (b < segs.length - 1 && segs[b + 1]!.speaker === who) b++;
+ return clip(segs[a]!.start, segs[b]!.end, "speaker");
+ }
+ const sorted = cues.slice().sort((x, y) => x.start - y.start);
+ const hit = sorted.flatMap((c, i) => (overlaps(c, span.start, span.end) ? [i] : []));
+ if (!hit.length) return clip(span.start, span.end, "pause");
+ let a = hit[0]!;
+ let b = hit[hit.length - 1]!;
+ // Back: the cue before joins while there is no pause and the turn did not start here.
+ while (a > 0 && !changesSpeaker(sorted[a]!.text) && sorted[a]!.start - sorted[a - 1]!.end < TURN_GAP_S) a--;
+ // On: the next cue joins while there is no pause and it does not change the speaker.
+ while (b < sorted.length - 1 && !changesSpeaker(sorted[b + 1]!.text) && sorted[b + 1]!.start - sorted[b]!.end < TURN_GAP_S) b++;
+ return clip(sorted[a]!.start, sorted[b]!.end, "pause");
+}
+
+type ReadClaim = { ok: true; item: ClaimItem; dropped: BenchDropped[] } | { ok: false; reason: string };
+
+// One claim's quotes and windows (its verdict is the caller's business).
+async function readClaim(r: BenchReport, sectionTitle: string, claim: Claim, o: ItemOptions): Promise<ReadClaim> {
const windowS = o.windowS ?? DEFAULT_WINDOW_S;
+ const mode = o.windowMode ?? "seconds";
+ const key = `${r.id}/${claim.id}`;
+ const citations = (r.report.citations ?? {}) as Record<string, Citation>;
+ const dropped: BenchDropped[] = [];
+ const ids = claim.citations ?? [];
+ if (!ids.length) return { ok: false, reason: "no citation" };
+ const spans: (readonly [string, Citation])[] = [];
+ for (const id of ids) {
+ const c = citations[id];
+ if (!c) dropped.push({ key, citation: id, reason: "not in the report's citations" });
+ else if (!isSpanCitation(c)) dropped.push({ key, citation: id, reason: "not a video or audio citation" });
+ else spans.push([id, c]);
+ }
+ if (!spans.length) return { ok: false, reason: "no video or audio citation" };
+ 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) {
+ dropped.push({ key, citation: cid, reason: "the recording has no cues" });
+ continue;
+ }
+ const lo = Math.max(0, c.start - windowS);
+ const hi = c.end + windowS;
+ let from = lo;
+ let to = hi;
+ let bound: WindowBound = "seconds";
+ if (mode === "turn") {
+ const turns = o.turnsOf ? await o.turnsOf(c.channel, c.id).catch(() => null) : null;
+ ({ from, to, bound } = turnOf(cues, turns, { start: c.start, end: c.end }, lo, hi));
+ }
+ const inWindow = cues.filter((q) => overlaps(q, from, to)).map((q) => ({ start: q.start, end: q.end, text: q.text }));
+ if (!inWindow.length) {
+ dropped.push({ key, citation: cid, reason: "no cues around the cited seconds" });
+ continue;
+ }
+ const date = c.date ?? (o.dateOf ? await o.dateOf(c.channel, c.id).catch(() => null) : null);
+ 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 } : {}),
+ ...(date ? { 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, bound });
+ }
+ if (!quotes.length) return { ok: false, reason: "no cited recording has cues around the cited seconds" };
+ return {
+ ok: true,
+ item: {
+ key,
+ report: r.id,
+ claim: claim.id,
+ text: claim.text,
+ quotes,
+ windows: mergeWindows(windows),
+ ...(r.report.title ? { title: r.report.title } : {}),
+ ...(sectionTitle ? { section: sectionTitle } : {}),
+ },
+ dropped,
+ };
+}
+
+// The items of one report: its ruled claims with a span citation that has cues.
+export async function benchItemsOfReport(r: BenchReport, o: ItemOptions): Promise<BenchItems> {
const items: BenchItem[] = [];
const skipped: BenchSkipped[] = [];
- const citations = (r.report.citations ?? {}) as Record<string, Citation>;
+ const dropped: BenchDropped[] = [];
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");
+ skipped.push({ key, report: r.id, claim: claim.id, reason: "no operator verdict" });
continue;
}
- const ids = claim.citations ?? [];
- if (!ids.length) {
- skip("no citation");
+ const got = await readClaim(r, section.title, claim, o);
+ if (!got.ok) {
+ skipped.push({ key, report: r.id, claim: claim.id, reason: got.reason });
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");
+ dropped.push(...got.dropped);
+ items.push({ ...got.item, verdict: claim.verdict });
+ }
+ }
+ return { items, skipped, dropped };
+}
+
+// The UNRULED claims of one report (M8's proposals): every claim with no
+// verdict, read as a bench item is; a ruled claim is skipped. `claims` keeps
+// only those ids.
+export async function unruledItemsOfReport(
+ r: BenchReport,
+ o: ItemOptions & { claims?: readonly string[] },
+): Promise<{ items: ClaimItem[]; skipped: BenchSkipped[]; dropped: BenchDropped[] }> {
+ const items: ClaimItem[] = [];
+ const skipped: BenchSkipped[] = [];
+ const dropped: BenchDropped[] = [];
+ const only = o.claims?.length ? new Set(o.claims) : null;
+ for (const section of r.report.sections) {
+ for (const claim of section.claims ?? []) {
+ if (only && !only.has(claim.id)) continue;
+ const key = `${r.id}/${claim.id}`;
+ if (isVerdict(claim.verdict)) {
+ skipped.push({ key, report: r.id, claim: claim.id, reason: "ruled by the operator" });
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");
+ const got = await readClaim(r, section.title, claim, o);
+ if (!got.ok) {
+ skipped.push({ key, report: r.id, claim: claim.id, reason: got.reason });
continue;
}
- items.push({ key, report: r.id, claim: claim.id, text: claim.text, verdict: claim.verdict, quotes, windows: mergeWindows(windows) });
+ dropped.push(...got.dropped);
+ items.push(got.item);
+ }
+ }
+ return { items, skipped, dropped };
+}
+
+export const LIMIT_REASON = "left out by the limit";
+
+/**
+ * A stratified `limit`: the items kept by the operator's verdict in proportion
+ * to how many were ruled each way, at least one of each verdict there is (the
+ * rarest first, when the limit is smaller than the verdicts), the rest by the
+ * largest remainder. Within a verdict the first items are kept; the kept ones
+ * stay in their order. Pure.
+ */
+export function stratifiedLimit<T extends { verdict: Verdict }>(items: readonly T[], limit: number): { kept: T[]; left: T[] } {
+ if (limit >= items.length) return { kept: [...items], left: [] };
+ const by = new Map<Verdict, T[]>();
+ for (const it of items) by.set(it.verdict, [...(by.get(it.verdict) ?? []), it]);
+ const size = (v: Verdict) => by.get(v)!.length;
+ const classes = [...by.keys()].sort((a, b) => size(a) - size(b) || VERDICTS.indexOf(a) - VERDICTS.indexOf(b));
+ const take = new Map<Verdict, number>(classes.map((v) => [v, 0]));
+ let left = limit;
+ for (const v of classes) {
+ if (left <= 0) break;
+ take.set(v, 1);
+ left--;
+ }
+ if (left > 0) {
+ const share = classes.map((v) => {
+ const want = (limit * size(v)) / items.length;
+ return { v, want, rem: want - Math.floor(want) };
+ });
+ for (const s of share) {
+ const e = Math.min(left, Math.max(0, Math.min(size(s.v), Math.floor(s.want)) - take.get(s.v)!));
+ take.set(s.v, take.get(s.v)! + e);
+ left -= e;
+ }
+ const order = share.slice().sort((a, b) => b.rem - a.rem || size(b.v) - size(a.v));
+ while (left > 0) {
+ let moved = false;
+ for (const s of order) {
+ if (left <= 0) break;
+ if (take.get(s.v)! < size(s.v)) {
+ take.set(s.v, take.get(s.v)! + 1);
+ left--;
+ moved = true;
+ }
+ }
+ if (!moved) break;
}
}
- return { items, skipped };
+ const keep = new Set<T>();
+ for (const v of classes) for (const it of by.get(v)!.slice(0, take.get(v)!)) keep.add(it);
+ return { kept: items.filter((it) => keep.has(it)), left: items.filter((it) => !keep.has(it)) };
}
-// 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> {
+// Every item of every report, in report then claim order; `limit` keeps a
+// stratified sample (the rest are skipped, LIMIT_REASON).
+export async function benchItemsOf(reports: readonly BenchReport[], o: ItemOptions & { limit?: number }): Promise<BenchItems> {
const items: BenchItem[] = [];
const skipped: BenchSkipped[] = [];
+ const dropped: BenchDropped[] = [];
for (const r of reports) {
const got = await benchItemsOfReport(r, o);
items.push(...got.items);
skipped.push(...got.skipped);
+ dropped.push(...got.dropped);
}
- return { items: o.limit !== undefined && o.limit >= 0 ? items.slice(0, o.limit) : items, skipped };
+ if (o.limit === undefined || o.limit < 0 || o.limit >= items.length) return { items, skipped, dropped };
+ const { kept, left } = stratifiedLimit(items, o.limit);
+ const keptKeys = new Set(kept.map((i) => i.key));
+ return {
+ items: kept,
+ skipped: [...skipped, ...left.map((i) => ({ key: i.key, report: i.report, claim: i.claim, reason: LIMIT_REASON }))],
+ dropped: dropped.filter((d) => keptKeys.has(d.key)),
+ };
+}
+
+/**
+ * The identity of a run's items, so two runs can be said to be over the SAME
+ * items: each item's key, the operator's verdict and its windows (recording,
+ * from, to, how many cues) — not the context lines, which a run made from an
+ * earlier run's items may add. 16 hex characters of a sha256.
+ */
+export function benchItemsHash(items: readonly Pick<BenchItem, "key" | "verdict" | "windows">[]): string {
+ const canon = items
+ .map((i) => ({ k: i.key, v: i.verdict, w: i.windows.map((w) => [w.channel, w.id, w.from, w.to, w.cues.length]) }))
+ .sort((a, b) => (a.k < b.k ? -1 : a.k > b.k ? 1 : 0));
+ return createHash("sha256").update(JSON.stringify(canon)).digest("hex").slice(0, 16);
}
diff --git a/common/lib/report/draft/bench/prompt.ts b/common/lib/report/draft/bench/prompt.ts
@@ -1,51 +1,66 @@
-// THE VERDICT BENCH'S PROMPT (release 28, M7): one claim per call.
+// THE VERDICT BENCH'S PROMPT (release 28 M7; release 29 V1): 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.
+// Q0: the system prompt is rules only — what each verdict means (the
+// operator's standard, read from ../../verdicts.mjs VERDICT_MEANINGS and its
+// tie rule: the one copy), 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. The answer
+// schema puts `reason` BEFORE `verdict`: the model writes what the transcript
+// shows, then rules on it. 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, its context and the cited quotes are never trimmed.
//
-// The prompt reads an item's claim text, its quotes and its windows — never
+// The user prompt carries the claim's context (V1): the report's title, the
+// claim's section heading, each cited line's speaker (the citation's, else the
+// channel) and the recording's date.
+//
+// PROMPT_VERSION names the prompt: a string, bumped BY HAND with any change to
+// the system prompt, the meanings, the schema or the user prompt's shape. A run
+// records it (summary.promptVersion; a run without one is M7's, "1"), and a
+// run is never resumed under another version (./run.ts).
+//
+// The prompt reads an item's claim text, context, quotes and windows — never
// its `verdict` (the operator's ruling, the answer).
-import { VERDICTS } from "../../verdicts";
+import { VERDICT_MEANINGS, VERDICT_TIE_RULE, VERDICTS } from "../../verdicts";
import { PROMPT_CAP_TOKENS, promptEstimate } from "../../../llm/ollama";
import type { BenchItem, BenchWindow } from "./items";
+export const PROMPT_VERSION = "2";
+// The version a run with no `promptVersion` was made with (release 28 M7).
+export const M7_PROMPT_VERSION = "1";
+
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.`,
+ description: `First: what the transcript shows about the claim, in one or two plain sentences of at most ${REASON_MAX} characters.`,
},
+ verdict: { type: "string", enum: [...VERDICTS], description: "Then: the ruling that reason supports." },
},
- required: ["verdict", "reason"],
+ required: ["reason", "verdict"],
} 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).",
+ "You are shown the report the claim is from, the section it is in, the claim, the lines it cites (who says each and when the recording was made), 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.",
+ "- Rule on the substance of the claim: what it says was said or done.",
"- 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.",
+ "- Write the reason first, naming what the transcript says; then give the verdict that reason supports.",
"",
"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.",
+ ...VERDICTS.map((v) => `- ${v}: ${VERDICT_MEANINGS[v]}`),
+ `- ${VERDICT_TIE_RULE}`,
"",
- `Give the verdict and a reason of at most ${REASON_MAX} characters that names what the transcript says.`,
+ `The reason is at most ${REASON_MAX} characters.`,
].join("\n");
const stamp = (s: number) => {
@@ -56,18 +71,23 @@ const stamp = (s: number) => {
return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
};
-type Prompted = Pick<BenchItem, "text" | "quotes" | "windows">;
+type Prompted = Pick<BenchItem, "text" | "quotes" | "windows" | "title" | "section">;
function render(item: Prompted, windows: BenchWindow[]): string {
- const lines: string[] = [`Claim: ${item.text}`, "", "Cited lines:"];
+ const lines: string[] = [];
+ if (item.title) lines.push(`Report: ${item.title}`);
+ if (item.section) lines.push(`Section: ${item.section}`);
+ lines.push(`Claim: ${item.text}`, "", "Cited lines:");
+ const said = (q: Prompted["quotes"][number]) => [`speaker: ${q.speaker ?? q.channel}`, q.date ? `recorded: ${q.date}` : ""].filter(Boolean).join("; ");
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(`- [${where}] "${q.quote}" (${said(q)})`);
}
lines.push("", "Transcript:");
windows.forEach((w, i) => {
- lines.push("", `## ${w.label ?? `Recording ${i + 1}`}, ${stamp(w.from)} to ${stamp(w.to)}`);
+ const q = item.quotes.find((x) => x.channel === w.channel && x.id === w.id);
+ const of = [`channel: ${w.channel}`, q?.date ? `recorded: ${q.date}` : ""].filter(Boolean).join("; ");
+ lines.push("", `## ${w.label ?? `Recording ${i + 1}`}, ${stamp(w.from)} to ${stamp(w.to)} (${of})`);
if (!w.cues.length) lines.push("(trimmed to fit)");
for (const c of w.cues) lines.push(`[${stamp(c.start)}] ${c.text}`);
});
diff --git a/common/lib/report/draft/bench/run.ts b/common/lib/report/draft/bench/run.ts
@@ -1,14 +1,23 @@
-// THE VERDICT BENCH (release 28, M7): can a model propose a fact-check verdict
-// well enough to be worth an operator's review?
+// THE VERDICT BENCH (release 28 M7; release 29 V1): 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
+// `planVerdictBench` reads only: the items, the skipped claims, the dropped
+// citations, and an estimate of what each model would cost (the `--dry`).
+// `runVerdictBench` asks each model about each item, one claim per call —
+// `structuredAnswer` against {reason, verdict}, or the injected `ask` (tests,
+// R6's shape) — writes every answer as it lands, traces every call
+// (trace.jsonl: the prompt the model saw and its raw answer), 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 ITEMS: read from the registry's fact-checks (./items.ts: the window in
+// seconds or the speaker's turn, a stratified `limit`), or — `itemsFrom` — the
+// EXACT items of an earlier run (its keys, rulings, quotes and windows; the
+// context lines a run before V1 lacked are filled from the registry, which
+// does not change the items' hash). The run records the prompt's version and
+// its items' hash, so two runs can be compared on the same items.
+//
// 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
@@ -17,7 +26,10 @@
//
// 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.
+// failed one is asked again. Only THIS invocation's models are asked (a
+// qwen-only re-run never re-asks an API model's pairs); the summary keeps
+// every model the run has asked. A resume under another PROMPT_VERSION, or
+// with `itemsFrom` naming other items, is REFUSED: start a new run.
import { mkdir } from "node:fs/promises";
import type { Paths } from "../../../paths";
@@ -26,14 +38,29 @@ 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 {
+ benchItemsHash,
+ benchItemsOf,
+ benchReportsOf,
+ BenchInputError,
+ DEFAULT_WINDOW_S,
+ isWindowMode,
+ type BenchDropped,
+ type BenchItem,
+ type BenchSkipped,
+ type DateOf,
+ type TurnsOf,
+ type WindowMode,
+} from "./items";
+import { benchPrompt, LOCAL_PROMPT_CAP, M7_PROMPT_VERSION, PROMPT_VERSION, REASON_MAX, VERDICT_ANSWER_SCHEMA, VERDICT_BENCH_SYSTEM } from "./prompt";
import { scoreBench, type BenchResult } from "./score";
import {
+ appendBenchTrace,
BENCH_FORMAT,
BENCH_VERSION,
benchRootOf,
benchRunDir,
+ isBenchRunId,
newBenchRunId,
readBenchRun,
writeBenchItems,
@@ -61,17 +88,30 @@ export type BenchOptions = {
reports?: string[];
models: string[];
windowS?: number;
+ windowMode?: WindowMode;
maxUsd?: number;
+ // A stratified sample of this many items (by the operator's verdict).
limit?: number;
+ // The exact items of this earlier run (no reports, window or limit with it).
+ itemsFrom?: string;
};
+// The model, injected (R6's shape; tests): a structured answer to the prompt.
+export type BenchAsk = <T>(system: string, user: string, schema: object, model: string) => Promise<T>;
+
export type BenchDeps = {
paths: Pick<Paths, "articlesDir" | "exportIndexDir" | "generationUsageFile">;
// Where runs live (default `.generation/bench/verdicts/`, ./store.ts).
root?: string;
cuesOf: CuesOf;
+ // The turn mode's speaker segments, and a recording's own date.
+ turnsOf?: TurnsOf;
+ dateOf?: DateOf;
// The providers' config (the editor's job gates a local model's calls on the GPU).
llm: LlmConfig;
+ // The model, stubbed (tests): replaces structuredAnswer (and its Meter: an
+ // injected ask costs nothing here).
+ ask?: BenchAsk;
log?: (line: string) => void;
signal?: AbortSignal;
now?: () => Date;
@@ -84,13 +124,20 @@ export type BenchModelEstimate = { model: string; provider: "api" | "local"; cal
export type BenchPlan = {
items: BenchItem[];
skipped: BenchSkipped[];
+ dropped: BenchDropped[];
reports: string[];
windowS: number;
+ windowMode: WindowMode;
+ promptVersion: string;
+ itemsHash: string;
+ itemsFrom?: string;
estimate: BenchModelEstimate[];
estimateUsd: number;
};
-export function validateBenchOptions(o: BenchOptions): { models: string[]; windowS: number; maxUsd: number; limit?: number } {
+export type ValidBenchOptions = { models: string[]; windowS: number; windowMode: WindowMode; maxUsd: number; limit?: number; itemsFrom?: string };
+
+export function validateBenchOptions(o: BenchOptions): ValidBenchOptions {
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) {
@@ -98,11 +145,24 @@ export function validateBenchOptions(o: BenchOptions): { models: string[]; windo
}
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");
+ if (o.windowMode !== undefined && !isWindowMode(o.windowMode)) throw new BenchInputError(`the window mode is "seconds" or "turn"`);
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 } : {}) };
+ if (o.itemsFrom !== undefined) {
+ if (!isBenchRunId(o.itemsFrom)) throw new BenchInputError("items-from is a run id: lowercase letters, digits and dashes");
+ const also = [o.reports?.length ? "reports" : "", o.windowS !== undefined ? "window" : "", o.windowMode !== undefined ? "window mode" : "", o.limit !== undefined ? "limit" : ""].filter(Boolean);
+ if (also.length) throw new BenchInputError(`items-from takes ${o.itemsFrom}'s items as they are: drop the ${also.join(", ")}`);
+ }
+ return {
+ models,
+ windowS,
+ windowMode: o.windowMode ?? "seconds",
+ maxUsd,
+ ...(o.limit !== undefined ? { limit: o.limit } : {}),
+ ...(o.itemsFrom !== undefined ? { itemsFrom: o.itemsFrom } : {}),
+ };
}
// What one call to `model` about `item` would cost, by the prompt's size.
@@ -130,17 +190,100 @@ function estimateOf(items: readonly BenchItem[], models: readonly string[], loca
});
}
-// 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);
+type ItemSet = {
+ items: BenchItem[];
+ skipped: BenchSkipped[];
+ dropped: BenchDropped[];
+ reports: string[];
+ windowS: number;
+ windowMode: WindowMode;
+ limit?: number;
+ itemsFrom?: string;
+};
+
+// The context lines an item made before V1 lacks (the report's title, the
+// claim's section heading, a quote's recording date), filled from the registry
+// as it is now. The items' identity (benchItemsHash) does not change.
+async function withContext(items: BenchItem[], deps: Pick<BenchDeps, "paths" | "dateOf">): Promise<BenchItem[]> {
+ const reports = new Map<string, Awaited<ReturnType<typeof benchReportsOf>>[number] | null>();
+ const out: BenchItem[] = [];
+ for (const it of items) {
+ let next = it;
+ if (it.title === undefined || it.section === undefined) {
+ if (!reports.has(it.report)) reports.set(it.report, (await benchReportsOf(deps.paths, [it.report]).catch(() => []))[0] ?? null);
+ const r = reports.get(it.report);
+ const section = r?.report.sections.find((s) => (s.claims ?? []).some((c) => c.id === it.claim));
+ next = {
+ ...next,
+ ...(it.title === undefined && r?.report.title ? { title: r.report.title } : {}),
+ ...(it.section === undefined && section?.title ? { section: section.title } : {}),
+ };
+ }
+ if (deps.dateOf && next.quotes.some((q) => !q.date)) {
+ const quotes = [];
+ for (const q of next.quotes) {
+ const date = q.date ?? (await deps.dateOf(q.channel, q.id).catch(() => null));
+ quotes.push(date ? { ...q, date } : q);
+ }
+ next = { ...next, quotes };
+ }
+ out.push(next);
+ }
+ return out;
+}
+
+async function itemSetOf(v: ValidBenchOptions, o: BenchOptions, deps: Pick<BenchDeps, "paths" | "cuesOf" | "turnsOf" | "dateOf" | "root">): Promise<ItemSet> {
+ if (v.itemsFrom) {
+ const root = deps.root ?? benchRootOf(deps.paths);
+ const src = await readBenchRun(root, v.itemsFrom);
+ if (!src) throw new BenchInputError(`no run "${v.itemsFrom}" to take the items from`);
+ return {
+ items: await withContext(src.items, deps),
+ skipped: src.summary.skipped,
+ dropped: src.summary.dropped ?? [],
+ reports: src.summary.reports,
+ windowS: src.summary.windowS,
+ windowMode: src.summary.windowMode ?? "seconds",
+ ...(src.summary.limit !== undefined ? { limit: src.summary.limit } : {}),
+ itemsFrom: v.itemsFrom,
+ };
+ }
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);
+ const got = await benchItemsOf(reports, {
+ cuesOf: deps.cuesOf,
+ windowS: v.windowS,
+ windowMode: v.windowMode,
+ ...(deps.turnsOf ? { turnsOf: deps.turnsOf } : {}),
+ ...(deps.dateOf ? { dateOf: deps.dateOf } : {}),
+ ...(v.limit ? { limit: v.limit } : {}),
+ });
return {
- items,
- skipped,
- reports: reports.map((r) => r.id),
+ ...got,
+ reports: o.reports?.length ? [...new Set(o.reports)] : [],
windowS: v.windowS,
+ windowMode: v.windowMode,
+ ...(v.limit !== undefined ? { limit: v.limit } : {}),
+ // (planVerdictBench names the reports it read; a run records what was asked.)
+ };
+}
+
+// The dry run: the items, the skipped claims, the dropped citations and the
+// estimate. Reads only.
+export async function planVerdictBench(o: BenchOptions, deps: Pick<BenchDeps, "paths" | "cuesOf" | "turnsOf" | "dateOf" | "localCapTokens" | "root">): Promise<BenchPlan> {
+ const v = validateBenchOptions(o);
+ const set = await itemSetOf(v, o, deps);
+ const estimate = estimateOf(set.items, v.models, deps.localCapTokens);
+ const reports = v.itemsFrom ? [...new Set(set.items.map((i) => i.report))] : (await benchReportsOf(deps.paths, o.reports)).map((r) => r.id);
+ return {
+ items: set.items,
+ skipped: set.skipped,
+ dropped: set.dropped,
+ reports,
+ windowS: set.windowS,
+ windowMode: set.windowMode,
+ promptVersion: PROMPT_VERSION,
+ itemsHash: benchItemsHash(set.items),
+ ...(set.itemsFrom ? { itemsFrom: set.itemsFrom } : {}),
estimate,
estimateUsd: Math.round(estimate.reduce((s, e) => s + e.usd, 0) * 10_000) / 10_000,
};
@@ -160,43 +303,64 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise
const id = o.runId ?? newBenchRunId(now());
const dir = benchRunDir(root, id);
const localCap = deps.localCapTokens ?? LOCAL_PROMPT_CAP;
+ if (v.itemsFrom === id) throw new BenchInputError(`a run cannot take its items from itself: name the new run`);
// A new run, or the stored one continued.
const prior = await readBenchRun(root, id);
- let items: BenchItem[];
- let skipped: BenchSkipped[];
+ let set: ItemSet;
let results: BenchResult[];
let models: string[];
- let reportsAsked: string[];
let createdAt: string;
+ let itemsHash: string;
if (prior) {
const s = prior.summary;
+ const was = s.promptVersion ?? M7_PROMPT_VERSION;
+ if (was !== PROMPT_VERSION) {
+ throw new BenchInputError(`run ${id} was asked with prompt version ${was}, and this is version ${PROMPT_VERSION}: start a new run (--items-from ${id} keeps its items)`);
+ }
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.windowMode !== undefined && o.windowMode !== (s.windowMode ?? "seconds")) {
+ throw new BenchInputError(`run ${id} was made with the ${s.windowMode ?? "seconds"} window mode: drop the mode, 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;
+ itemsHash = s.itemsHash ?? benchItemsHash(prior.items);
+ if (v.itemsFrom) {
+ const src = await readBenchRun(root, v.itemsFrom);
+ if (!src) throw new BenchInputError(`no run "${v.itemsFrom}" to take the items from`);
+ const theirs = src.summary.itemsHash ?? benchItemsHash(src.items);
+ if (theirs !== itemsHash) throw new BenchInputError(`run ${id} is over other items than ${v.itemsFrom}'s: start a new run`);
+ }
+ set = {
+ items: prior.items,
+ skipped: s.skipped,
+ dropped: s.dropped ?? [],
+ reports: s.reports,
+ windowS: s.windowS,
+ windowMode: s.windowMode ?? "seconds",
+ ...(s.limit !== undefined ? { limit: s.limit } : {}),
+ ...(s.itemsFrom ? { itemsFrom: s.itemsFrom } : {}),
+ };
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`);
+ log(`continuing run ${id}: ${set.items.length} items, ${results.filter((r) => r.verdict !== null).length} answers on disk; asking ${v.models.join(", ")}`);
} 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;
+ set = await itemSetOf(v, o, { ...deps, root });
+ itemsHash = benchItemsHash(set.items);
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`);
+ await writeBenchItems(dir, set.items);
+ log(
+ `run ${id}: ${set.items.length} items${set.itemsFrom ? ` from run ${set.itemsFrom}` : ""}, ${set.skipped.length} claims skipped, ${set.dropped.length} citations dropped; prompt version ${PROMPT_VERSION}, items ${itemsHash}`,
+ );
}
+ const items = set.items;
const priorSpend = round6(results.reduce((s, r) => s + r.usd, 0));
const meter = new Meter();
@@ -211,13 +375,18 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise
status,
...(stopped.length ? { stopped: [...stopped] } : {}),
models,
- windowS: prior?.summary.windowS ?? v.windowS,
+ windowS: set.windowS,
+ windowMode: set.windowMode,
+ promptVersion: PROMPT_VERSION,
+ itemsHash,
+ ...(set.itemsFrom ? { itemsFrom: set.itemsFrom } : {}),
maxUsd: v.maxUsd,
- reports: reportsAsked,
- ...(prior?.summary.limit !== undefined ? { limit: prior.summary.limit } : v.limit !== undefined ? { limit: v.limit } : {}),
+ reports: set.reports,
+ ...(set.limit !== undefined ? { limit: set.limit } : {}),
spentUsd: round6(priorSpend + meter.usd),
items: items.length,
- skipped,
+ skipped: set.skipped,
+ dropped: set.dropped,
score: scoreBench(items, results, models),
});
const save = async () => {
@@ -229,11 +398,27 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise
if (at >= 0) results[at] = r;
else results.push(r);
};
+ let traceBroken = false;
+ const trace = async (line: Record<string, unknown>) => {
+ try {
+ await appendBenchTrace(dir, { at: now().toISOString(), ...line });
+ } catch (e) {
+ if (!traceBroken) log(`trace not kept: ${(e as Error).message}`);
+ traceBroken = true;
+ }
+ };
await save();
+ await trace({ t: "start", run: id, promptVersion: PROMPT_VERSION, itemsHash, models: v.models, system: VERDICT_BENCH_SYSTEM, schema: VERDICT_ANSWER_SCHEMA });
+
+ const ask: BenchAsk =
+ deps.ask ??
+ (<T,>(system: string, user: string, schema: object, model: string) =>
+ structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens: MAX_ANSWER_TOKENS }));
const answered = new Set(results.filter((r) => r.verdict !== null).map((r) => `${r.model}\u0000${r.key}`));
try {
- models: for (const model of models) {
+ // THIS invocation's models only: a resumed run never re-asks another's pairs.
+ models: for (const model of v.models) {
const local = providerOf(model) === "local";
let streak = 0;
for (const item of items) {
@@ -258,17 +443,10 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise
const usdBefore = meter.usd;
const t0 = Date.now();
let r: BenchResult;
+ let raw: unknown = undefined;
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 ans = await ask<{ verdict?: unknown; reason?: unknown }>(prompt.system, prompt.user, VERDICT_ANSWER_SCHEMA, model);
+ raw = ans;
const verdict = isVerdict(ans?.verdict) ? ans.verdict : null;
const reason = typeof ans?.reason === "string" ? ans.reason.trim().slice(0, REASON_MAX) : null;
r = {
@@ -314,6 +492,21 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise
if (prompt.cuesTrimmed) r.cuesTrimmed = prompt.cuesTrimmed;
record(r);
await save();
+ await trace({
+ t: "call",
+ model,
+ key: item.key,
+ promptVersion: PROMPT_VERSION,
+ estimate: prompt.estimate,
+ cuesShown: prompt.cuesShown,
+ cuesTrimmed: prompt.cuesTrimmed,
+ user: prompt.user,
+ ...(raw !== undefined ? { answer: raw } : {}),
+ verdict: r.verdict,
+ ...(r.failure ? { failure: r.failure, error: r.error } : {}),
+ ms: r.ms,
+ usd: r.usd,
+ });
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})`);
diff --git a/common/lib/report/draft/bench/score.ts b/common/lib/report/draft/bench/score.ts
@@ -11,10 +11,22 @@
// - 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.
+// - (V1) "not CORROBORATED" as the positive class — the claims a proposal
+// would put in front of the operator: precision (of the model's
+// not-CORROBORATED answers, the share the operator ruled so too) and
+// recall (of the operator's not-CORROBORATED rulings, the share the model
+// found); a failed answer is a miss, never a positive.
// 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`.
+//
+// V1 adds, also pure: `compareBenchRuns` (two runs on the same items: each
+// model's agreement in each, and the claims whose answers changed) and
+// `markedScore` (the operator's Right/Wrong marks on disagreements — a
+// disagreement marked Right counts as the model agreeing — tallied by the
+// triage marks' `markTally`).
import { VERDICTS, type Verdict } from "../../verdicts";
+import { markTally, type MarkTally } from "../triage/types";
export type BenchResult = {
key: string;
@@ -37,6 +49,9 @@ export type BenchResult = {
export type Recall = { ruled: number; matched: number; recall: number | null };
+// "Not CORROBORATED" as the positive class.
+export type FlagScore = { tp: number; fp: number; fn: number; precision: number | null; recall: number | null };
+
export type ModelScore = {
model: string;
asked: number;
@@ -49,6 +64,7 @@ export type ModelScore = {
matrix: number[][];
unanswered: number[];
recall: { CONTRADICTED: Recall; NOT_FOUND: Recall; PARTLY: Recall; PARTLY_ADJACENT: Recall };
+ notCorroborated: FlagScore;
parseFailures: number;
errors: number;
usd: number;
@@ -97,10 +113,15 @@ export function scoreModel(model: string, truth: ReadonlyMap<string, Verdict>, r
let errors = 0;
let usd = 0;
const ms: number[] = [];
+ const flag = { tp: 0, fp: 0, fn: 0 };
for (const [key, r] of last) {
const op = truth.get(key)!;
usd += r.usd;
if (r.ms > 0) ms.push(r.ms);
+ const pos = r.verdict !== null && r.verdict !== "CORROBORATED";
+ if (pos && op !== "CORROBORATED") flag.tp++;
+ else if (pos) flag.fp++;
+ else if (op !== "CORROBORATED") flag.fn++;
if (r.verdict === null) {
unanswered[idx(op)]! += 1;
if (r.failure === "parse") parseFailures++;
@@ -129,6 +150,7 @@ export function scoreModel(model: string, truth: ReadonlyMap<string, Verdict>, r
PARTLY: recallOf(matrix, unanswered, "PARTLY"),
PARTLY_ADJACENT: recallOf(matrix, unanswered, "PARTLY", "CORROBORATED"),
},
+ notCorroborated: { ...flag, precision: ratio(flag.tp, flag.tp + flag.fp), recall: ratio(flag.tp, flag.tp + flag.fn) },
parseFailures,
errors,
usd: Math.round(usd * 1e6) / 1e6,
@@ -184,3 +206,114 @@ export function passesBar(s: ModelScore, bar: VerdictBar): BarCheck {
if (s.asked === 0) misses.push("no items asked");
return { pass: misses.length === 0, misses };
}
+
+// ─── V1: two runs compared, and the operator's marks ───
+
+type RunLike = { items: readonly { key: string; verdict: Verdict }[]; results: readonly BenchResult[]; models: readonly string[] };
+
+export type AnswerChange = { key: string; ruled: Verdict; a: Verdict | null; b: Verdict | null };
+
+export type ModelCompare = {
+ model: string;
+ a: { agreed: number; asked: number; agreement: number | null };
+ b: { agreed: number; asked: number; agreement: number | null };
+ // The claims whose answer changed, the ones b got right that a did not first.
+ changed: AnswerChange[];
+ // Of the changed: b agrees where a did not (fixed), and the other way (broke).
+ fixed: number;
+ broke: number;
+};
+
+export type RunCompare = {
+ // The item keys both runs have (a comparison reads only these).
+ items: number;
+ onlyA: number;
+ onlyB: number;
+ models: ModelCompare[];
+};
+
+const lastOf = (results: readonly BenchResult[], model: string) => {
+ const m = new Map<string, BenchResult>();
+ for (const r of results) if (r.model === model) m.set(r.key, r);
+ return m;
+};
+
+/**
+ * Two runs on the same items: for each model asked in both, its agreement in
+ * each (over the shared items) and every claim whose answer changed. The
+ * operator's verdict is A's (the same items carry the same rulings). Pure.
+ */
+export function compareBenchRuns(a: RunLike, b: RunLike): RunCompare {
+ const bKeys = new Map(b.items.map((i) => [i.key, i.verdict] as const));
+ const shared = a.items.filter((i) => bKeys.has(i.key));
+ const truth = new Map(shared.map((i) => [i.key, i.verdict] as const));
+ const models: ModelCompare[] = [];
+ for (const model of a.models.filter((m) => b.models.includes(m))) {
+ const ra = lastOf(a.results, model);
+ const rb = lastOf(b.results, model);
+ const changed: AnswerChange[] = [];
+ let fixed = 0;
+ let broke = 0;
+ const tally = (r: Map<string, BenchResult>) => {
+ let agreed = 0;
+ let asked = 0;
+ for (const [k, v] of truth) {
+ const x = r.get(k);
+ if (!x) continue;
+ asked++;
+ if (x.verdict === v) agreed++;
+ }
+ return { agreed, asked, agreement: ratio(agreed, asked) };
+ };
+ for (const [k, ruled] of truth) {
+ const x = ra.get(k);
+ const y = rb.get(k);
+ if (!x || !y || x.verdict === y.verdict) continue;
+ changed.push({ key: k, ruled, a: x.verdict, b: y.verdict });
+ if (y.verdict === ruled) fixed++;
+ else if (x.verdict === ruled) broke++;
+ }
+ const rank = (c: AnswerChange) => (c.b === c.ruled ? 0 : c.a === c.ruled ? 1 : 2);
+ changed.sort((p, q) => rank(p) - rank(q));
+ models.push({ model, a: tally(ra), b: tally(rb), changed, fixed, broke });
+ }
+ return { items: shared.length, onlyA: a.items.length - shared.length, onlyB: b.items.length - shared.length, models };
+}
+
+// An operator's mark on one disagreement: was the MODEL right? `answer` is the
+// answer it marked — a mark whose answer has since changed (a resumed run asked
+// again) no longer applies.
+export type BenchMark = { verdict: "right" | "wrong"; answer: Verdict | null; at: string };
+// model → item key → mark.
+export type BenchMarks = Record<string, Record<string, BenchMark>>;
+
+export type MarkedScore = {
+ model: string;
+ // The marks that apply (on a disagreement, on the answer it still has).
+ marks: MarkTally;
+ // Agreement and the not-CORROBORATED scores with each disagreement marked
+ // Right counted as the model agreeing.
+ agreed: number;
+ agreement: number | null;
+ notCorroborated: FlagScore;
+};
+
+/** One model's score with the operator's marks applied. Pure. */
+export function markedScore(items: readonly { key: string; verdict: Verdict }[], results: readonly BenchResult[], model: string, marks: BenchMarks): MarkedScore {
+ const mine = marks[model] ?? {};
+ const last = lastOf(results, model);
+ const applied: BenchMark[] = [];
+ const truth = new Map<string, Verdict>();
+ for (const it of items) {
+ const r = last.get(it.key);
+ const m = mine[it.key];
+ let v = it.verdict;
+ if (r && m && r.verdict !== it.verdict && m.answer === r.verdict) {
+ applied.push(m);
+ if (m.verdict === "right" && r.verdict !== null) v = r.verdict;
+ }
+ truth.set(it.key, v);
+ }
+ const s = scoreModel(model, truth, results);
+ return { model, marks: markTally(applied), agreed: s.agreed, agreement: s.agreement, notCorroborated: s.notCorroborated };
+}
diff --git a/common/lib/report/draft/bench/store.ts b/common/lib/report/draft/bench/store.ts
@@ -6,18 +6,24 @@
// 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
+// its score; V1: the prompt version, the items hash, the
+// window mode, the dropped citations, `itemsFrom`
+// trace.jsonl (V1) every call as it was made — the prompt the model
+// saw, its raw answer, the verdict kept — appended, one
+// line each, plus a `start` line per invocation
+// marks.json (V1) the operator's Right/Wrong marks on disagreements,
+// umtool's own (one writer: umtool/lib/bench-marks.mjs)
//
// 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 { appendFile, 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";
+import type { BenchDropped, BenchItem, BenchSkipped, WindowMode } from "./items";
+import type { BenchMarks, BenchResult, BenchScore } from "./score";
export const BENCH_FORMAT = "archilyzer-verdict-bench";
export const BENCH_VERSION = 1;
@@ -25,6 +31,9 @@ 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_TRACE_FILE = "trace.jsonl";
+export const BENCH_MARKS_FILE = "marks.json";
+export const BENCH_MARKS_FORMAT = "archilyzer-bench-marks";
export const BENCH_STATUSES = ["running", "done", "capped", "cancelled", "failed"] as const;
export type BenchStatus = (typeof BENCH_STATUSES)[number];
@@ -40,6 +49,14 @@ export type BenchSummary = {
stopped?: string[];
models: string[];
windowS: number;
+ // V1: how each window was cut (absent: M7's, "seconds").
+ windowMode?: WindowMode;
+ // V1: the prompt the run asked with (absent: M7's, "1"), and the identity of
+ // its items (./items.ts benchItemsHash; absent: compute it from the items).
+ promptVersion?: string;
+ itemsHash?: string;
+ // V1: the run whose items this one was made from (`--items-from`).
+ itemsFrom?: string;
maxUsd: number;
// The reports asked for (empty: every fact-check in the registry).
reports: string[];
@@ -47,6 +64,8 @@ export type BenchSummary = {
spentUsd: number;
items: number;
skipped: BenchSkipped[];
+ // V1: the citations of kept claims that gave no window, with their reasons.
+ dropped?: BenchDropped[];
score: BenchScore;
};
@@ -146,3 +165,23 @@ export async function listBenchRuns(root: string): Promise<BenchSummary[]> {
}
export { readJsonl as readBenchJsonl };
+
+// One line of a run's trace, appended (never rewritten). A trace write never
+// fails the run: the caller catches.
+export async function appendBenchTrace(dir: string, line: Record<string, unknown>): Promise<void> {
+ await appendFile(path.join(dir, BENCH_TRACE_FILE), `${JSON.stringify(line)}\n`);
+}
+
+export async function readBenchTrace(root: string, id: string): Promise<Record<string, unknown>[]> {
+ return readJsonl<Record<string, unknown>>(path.join(benchRunDir(root, id), BENCH_TRACE_FILE));
+}
+
+// A run's marks, as umtool wrote them (none, or a file that does not read: empty).
+export async function readBenchMarks(root: string, id: string): Promise<BenchMarks> {
+ try {
+ const v = JSON.parse(await readFile(path.join(benchRunDir(root, id), BENCH_MARKS_FILE), "utf8")) as { format?: string; marks?: BenchMarks };
+ return v?.format === BENCH_MARKS_FORMAT && v.marks && typeof v.marks === "object" ? v.marks : {};
+ } catch {
+ return {};
+ }
+}
diff --git a/common/lib/report/draft/triage/types.ts b/common/lib/report/draft/triage/types.ts
@@ -310,6 +310,21 @@ export type Precision = {
byStrength: { strong: { right: number; wrong: number }; weak: { right: number; wrong: number } };
};
+// An operator's Right/Wrong marks, tallied: the one count triage's flags and
+// the verdict bench's disagreements (release 29 V1) share.
+export type MarkTally = { marked: number; right: number; wrong: number; precision: number | null };
+
+export function markTally(marks: readonly { verdict: "right" | "wrong" }[]): MarkTally {
+ let right = 0;
+ let wrong = 0;
+ for (const m of marks) {
+ if (m.verdict === "right") right++;
+ else wrong++;
+ }
+ const marked = right + wrong;
+ return { marked, right, wrong, precision: marked ? Math.round((right / marked) * 1000) / 1000 : null };
+}
+
export function precisionOf(marks: readonly FlagMark[]): Precision {
const by = { strong: { right: 0, wrong: 0 }, weak: { right: 0, wrong: 0 } };
for (const m of marks) {
@@ -317,10 +332,7 @@ export function precisionOf(marks: readonly FlagMark[]): Precision {
if (m.verdict === "right") s.right++;
else s.wrong++;
}
- const right = by.strong.right + by.weak.right;
- const wrong = by.strong.wrong + by.weak.wrong;
- const marked = right + wrong;
- return { marked, right, wrong, precision: marked ? Math.round((right / marked) * 1000) / 1000 : null, byStrength: by };
+ return { ...markTally(marks), byStrength: by };
}
// The fewest marks of a kind a suggestion is made on.
diff --git a/common/lib/report/schema.ts b/common/lib/report/schema.ts
@@ -205,7 +205,7 @@ export const CLAIM_FIELD_DOCS: FieldDocs<Claim> = {
id: `The claim's id (letters, digits, \`_ . : -\`; at most 64): its anchor on the report page. Unique among the report's section, claim and entry ids, and none of the page's own anchors (${RESERVED_ANCHOR_IDS.map((a) => `\`${a}\``).join(", ")}).`,
title: "A short headline for the claim (plain text, e.g. a phrase it turns on), shown above its text. Absent = the text alone.",
text: "The claim, as stated by the document under review (plain text).",
- verdict: `The ruling on the claim: ${VERDICTS.map((v) => `\`${v}\``).join(", ")}. A fact-check's claim may leave it out (not yet ruled); a sweep's carries none.`,
+ verdict: `The ruling on the claim: ${VERDICTS.map((v) => `\`${v}\``).join(", ")} (what each means: "The verdicts", below). A fact-check's claim may leave it out (not yet ruled); a sweep's carries none.`,
gist: `The claim's finding in one line (plain text, at most ${CLAIM_GIST_MAX} characters), shown beside its title in the overview of what the check found. Absent = the title alone.`,
flag: `A short mark on the claim (plain text, one line, at most ${CLAIM_FLAG_MAX} characters), shown as a pill on its card: e.g. that the document gives no source for it. Absent = none.`,
sourceQuote:
diff --git a/common/lib/report/verdicts.mjs b/common/lib/report/verdicts.mjs
@@ -20,6 +20,30 @@ export const VERDICT_DEFAULTS = Object.freeze({
UNTESTABLE: Object.freeze({ label: "Untestable", color: "#7d8fd6" }),
});
+/**
+ * What each verdict MEANS — the operator's standard (release 29 V1), the one
+ * copy: the verdict bench's prompt (draft/bench/prompt.ts), the verdict
+ * proposals that reuse it, REPORT.md (lib/report/docs.ts) and umtool's bench
+ * page read these sentences; nowhere else spells them out. A change here
+ * changes the bench's prompt: bump its PROMPT_VERSION with it.
+ */
+export const VERDICT_MEANINGS = Object.freeze({
+ CORROBORATED:
+ "the substance of the claim is shown by the cited words. Framing, emphasis, or a detail the transcript does not show does not demote it.",
+ PARTLY:
+ "a part of the claim is shown by the transcript to be overstated or wrong. A part that is only not shown does not make a claim PARTLY.",
+ CONTRADICTED:
+ "the substance of the claim is shown to be wrong: the transcript shows the opposite of it, or something that cannot be true at the same time.",
+ NOT_FOUND:
+ "the claim could be checked against what was said, and its substance is not in the transcript shown: 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.",
+});
+
+/** The rule between the two verdicts a ruling most often falls between. */
+export const VERDICT_TIE_RULE =
+ "In doubt between CORROBORATED and PARTLY: CORROBORATED, unless a part of the claim is shown overstated or wrong.";
+
/** The longest label an override may set, in characters (trimmed). */
export const VERDICT_LABEL_MAX = 24;
diff --git a/common/lib/report/verdicts.ts b/common/lib/report/verdicts.ts
@@ -6,6 +6,8 @@ import {
VERDICT_COLOR_RE as VERDICT_COLOR_RE_JS,
VERDICT_DEFAULTS as VERDICT_DEFAULTS_JS,
VERDICT_LABEL_MAX as VERDICT_LABEL_MAX_JS,
+ VERDICT_MEANINGS as VERDICT_MEANINGS_JS,
+ VERDICT_TIE_RULE as VERDICT_TIE_RULE_JS,
VERDICTS as VERDICTS_JS,
resolveVerdicts as resolveVerdictsJs,
verdictOverrideProblems as verdictOverrideProblemsJs,
@@ -23,6 +25,12 @@ export const VERDICT_DEFAULTS = VERDICT_DEFAULTS_JS as Readonly<Record<Verdict,
export const VERDICT_LABEL_MAX: number = VERDICT_LABEL_MAX_JS;
+// What each verdict means (the operator's standard) and the CORROBORATED/PARTLY
+// tie rule: the one copy the bench's prompt, REPORT.md and umtool read.
+export const VERDICT_MEANINGS = VERDICT_MEANINGS_JS as Readonly<Record<Verdict, string>>;
+
+export const VERDICT_TIE_RULE: string = VERDICT_TIE_RULE_JS;
+
export const VERDICT_COLOR_RE: RegExp = VERDICT_COLOR_RE_JS;
export function isVerdict(v: unknown): v is Verdict {
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,9 @@
# Changelog
## [Unreleased]
+- **The verdict bench asks to the operator's standard, and says which prompt it asked with.** What each verdict means is written once (`common/lib/report/verdicts.mjs`) and read by the bench's prompt, REPORT.md and umtool's bench page: CORROBORATED when the substance of the claim is shown by the cited words (framing, emphasis or a detail the transcript does not show does not demote it), PARTLY only when a part is shown overstated or wrong, and when in doubt between the two, CORROBORATED. The model now writes its reason before its verdict, and sees the report's title, the claim's section, and each cited line's speaker and recording date. Each run records its prompt version and a hash of its items; a run made before this is version 1, and a run is never resumed under another version. Needs a restart of the editor and umtool.
+- **`archilyzer reports bench-verdicts` takes `--items-from <run>`, `--window-mode seconds|turn` and a stratified `--limit`.** `--items-from vb-r28` asks the same items again (for example a local model on a new prompt, at no cost). `--window-mode turn` shows the cited speaker's turn instead of a fixed number of seconds either side, bounded by `--window`. `--limit` keeps every verdict the operator ruled, in proportion. A re-run of a run asks only the models it names, so a local-only re-run never asks a paid model again. A citation that gives no transcript is listed with its reason instead of being left out silently. `pnpm ops bench-verdicts` takes the same keys (`itemsFrom`, `windowMode`, `limit`).
+- **umtool's verdict bench compares runs and takes your marks.** `/tools/bench` shows each run's prompt version and items hash, and **compare with** lists the runs over the same items: each model's agreement in both and every claim whose answer changed. Each disagreement has **Right** and **Wrong** (was the model right?), kept beside the run, and the not-CORROBORATED precision and recall beside the bar are shown as ruled and with your marks, so the bar can be set from what you marked. "What the verdicts mean" lists the definitions.
- **The research board keeps a key pressed just after a save, too.** A key that arrived after a save's answer, or after its redraw but before the moved line took the focus back, could still lose `e`'s field (the claim then went nowhere). The board now waits until the redraw is fully done before acting on any key. Needs a restart of umtool.
- **A recurring report's tick no longer calls a capped scan "nothing new".** Triage used to take the scope from one `enumerate_matches(".")`, which stops at 2,000 recordings — the co-host pilot's five channels hold 23,284, the newest read last, so its first tick found "0 new" and ended quiet. Tier 0 now lists the scope from the build's own per-channel manifests (every recording, uncapped, dated by the build's index) and reads the terms only over the new recordings (and, on a first run, from the start date). A scan that still hits a cap or misses a channel is **partial**: the tick says "partial — not reached: …" as a **Your call** card in umtool (never quiet, no quiet edition recorded), the triage run says so on its page, and its set of seen recordings is not kept, so the next run counts new from the last complete run (or from its start date). The same rule holds for a Refresh's search again (a capped search with nothing new ends **partial**, not "no change"), a series' window check, and the Inbox's daily refresh check (a partial check still raises its card, naming what it did not reach; `umtool refresh --check` prints PARTIAL). Needs a restart of the editor and umtool.
- **`enumerate_matches` takes `ids`.** Only the pages that hold those recordings are read, so the scan is bounded by them rather than by the scope; the footer says how many the scope holds. A sweep restricted to given recordings (a refresh's update, a triage's escalation) now scans only theirs.
diff --git a/editor/app/api/ops/_benchVerdicts.test.ts b/editor/app/api/ops/_benchVerdicts.test.ts
@@ -73,6 +73,12 @@ test("the body: models required, the run id and reports checked, numbers as numb
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 });
+ // Release 29 V1: the window mode and items-from.
+ assert.deepEqual(parseBenchVerdictsBody({ models: ["q"], windowMode: "turn" }), { models: ["q"], windowMode: "turn" });
+ assert.throws(() => parseBenchVerdictsBody({ models: ["q"], windowMode: "line" }), /"windowMode" is "seconds" or "turn"/);
+ assert.deepEqual(parseBenchVerdictsBody({ models: ["q"], itemsFrom: "vb-r28" }), { models: ["q"], itemsFrom: "vb-r28" });
+ assert.throws(() => parseBenchVerdictsBody({ models: ["q"], itemsFrom: "../x" }), /"itemsFrom" is a run id/);
+ assert.throws(() => parseBenchVerdictsBody({ models: ["q"], itemsFrom: "vb-r28", window: 30 }), /drop the window/);
});
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 () => {
diff --git a/editor/app/api/ops/bench-verdicts/route.ts b/editor/app/api/ops/bench-verdicts/route.ts
@@ -5,7 +5,7 @@ import { jobResponse, ops } from "../_lib";
export const dynamic = "force-dynamic";
-// POST { models, run?, reports?, window?, maxUsd?, limit? }
+// POST { models, run?, reports?, window?, windowMode?, maxUsd?, limit?, itemsFrom? }
// -> { ok: true, jobId, run }
//
// The verdict bench (release 28 M7), as a `bench-verdicts` job: every ruled
@@ -16,7 +16,9 @@ export const dynamic = "force-dynamic";
// 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}`.
+// them). Release 29 V1: `windowMode` ("turn": the cited speaker's turn),
+// a stratified `limit`, `itemsFrom` (an earlier run's exact items).
+// `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) {
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -9460,3 +9460,38 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
plan and confirm guard it, there is no red button and no Signal outline since P6b); a toggle that is on is
`pressed` (the panel ground); a state that is not a judgement wears `badgeVariants` `state` (a dashed ink edge);
Meter is measurement. `e2e/visual-audit.spec.ts` measures every page's actions by computed colour.
+
+## Release 29 V1: the verdict bench, v2 (verified 2026-10-15, branch `r29/verdicts`)
+
+- **What a verdict means is written once:** `VERDICT_MEANINGS` and `VERDICT_TIE_RULE` in
+ `common/lib/report/verdicts.mjs` (typed through `verdicts.ts`). The bench's system prompt, REPORT.md's verdicts table
+ (`lib/report/docs.ts`), `CLAIM_FIELD_DOCS.verdict` (a pointer to it) and umtool's `/tools/bench` read them; nothing
+ else spells them out. Changing a sentence changes the prompt: bump `PROMPT_VERSION`.
+- **The prompt version contract.** `PROMPT_VERSION` (`draft/bench/prompt.ts`) is a string bumped BY HAND with any change
+ to the system prompt, the meanings, the answer schema or the user prompt's shape. A run records `summary.promptVersion`;
+ a run without one is release 28's, `M7_PROMPT_VERSION` `"1"`. A run is never resumed under another version (refused,
+ naming `--items-from`). The answer schema is `{reason, verdict}`, reason first.
+- **An items hash** (`benchItemsHash`): sha256 (16 hex) of each item's key, ruling and windows (recording, from, to,
+ cue count) — not its context lines. `summary.itemsHash`; a run before V1 has it computed from its `items.jsonl`.
+ Two runs "on the same items" means equal hashes; umtool compares only those.
+- **`--items-from <run>`** (`itemsFrom`): a new run takes that run's `items.jsonl` exactly (and its skipped, dropped,
+ window and limit), filling the context lines (title, section, a quote's date) an older item lacks from the registry
+ as it is now — the hash does not change. Refused with `--report`, `--window`, `--window-mode` or `--limit`.
+- **Resume asks only the invocation's models** (`runVerdictBench` iterates `validateBenchOptions(o).models`);
+ `summary.models` is the union, in first-asked order. A qwen-only re-run of a run never re-asks an API pair.
+- **Window modes** (`items.ts`): `seconds` (±windowS, M7's) and `turn` — the cited speaker's run of attribution
+ segments (`diskTurnsOf`, `attribution.json`), else the cues until a ≥ `TURN_GAP_S` (2 s) pause or a `>>` cue,
+ clipped to ±windowS; each window's `bound` is `seconds | speaker | pause | limit`. A citation of a kept claim that
+ gives no window is `dropped` with its reason (`summary.dropped`); a `--limit` is `stratifiedLimit` (every ruled verdict
+ kept, the rarest first, the rest in proportion) and the rest are skipped "left out by the limit".
+- **A run's dir gains** `trace.jsonl` (appended: a `start` line per invocation with the system prompt and schema, a
+ `call` line per call with the user prompt, the raw answer, the verdict, ms, usd) and `marks.json`
+ (`archilyzer-bench-marks` v1, `{marks: {<model>: {<report>/<claim>: {verdict: right|wrong, answer, at}}}}`, written
+ by umtool alone — `umtool/lib/bench-marks.mjs`, R6's discipline; read by common's `readBenchMarks`). A mark says
+ whether the MODEL was right on a disagreement; it applies only while the model's answer is still `answer`.
+- **Scores** (`score.ts`): `notCorroborated {tp, fp, fn, precision, recall}` per model (a failed answer is never a
+ positive); `compareBenchRuns(a, b)` (shared item keys, models asked in both: agreement each, `changed`, `fixed`,
+ `broke`); `markedScore` (a disagreement marked Right counts as agreeing) tallied by `markTally`
+ (`draft/triage/types.ts`, which `precisionOf` now uses too).
+- **The injected model** is `BenchDeps.ask(system, user, schema, model)` — no Meter, so an injected ask costs nothing
+ in the run's spend.
diff --git a/plans/release-29.md b/plans/release-29.md
@@ -179,6 +179,83 @@ The three release 28 smoke drafts deleted through `archilyzer reports delete <id
`r28-smoke-research` and `r28-smoke-research2` (articles in the making — 265 KiB and 262 KiB). The usage ledger's rows
and the shared prepared-media cache are kept, as the command keeps them.
+### V1, as shipped (2026-10-15, lane B, `r29/verdicts`)
+
+Bench v2: the verdict bench asks to the operator's standard, says which prompt and which items a run used, and can be
+compared and marked, so the bar can be set from marked precision. No real calls were made (the fakes and the injected
+`ask` only); V2's runs are the orchestrator's.
+
+- **The meanings are written once** — `VERDICT_MEANINGS` and `VERDICT_TIE_RULE` in `common/lib/report/verdicts.mjs`
+ (typed in `verdicts.ts`): CORROBORATED = the substance of the claim is shown by the cited words (framing, emphasis or
+ a detail the transcript does not show does not demote it); PARTLY = a part is shown overstated or wrong (a part only
+ not shown is not PARTLY); CONTRADICTED and NOT_FOUND sharpened to the claim's substance; UNTESTABLE as before; the tie
+ rule "In doubt between CORROBORATED and PARTLY: CORROBORATED, unless a part of the claim is shown overstated or
+ wrong." The bench's system prompt, REPORT.md's verdicts table (a "Means" column and the tie rule, `docs.ts`),
+ `CLAIM_FIELD_DOCS.verdict` (a pointer) and umtool's `/tools/bench` read them.
+- **The prompt** (`bench/prompt.ts`): rules only (Q0), the meanings and the tie rule, "write the reason first"; the
+ answer schema `{reason, verdict}` (reason first); the user prompt carries `Report:` (the title), `Section:` (the
+ claim's heading), each cited line's speaker (the citation's, else the channel) and recording date (the citation's,
+ else the record's `upload_date` — `bench/disk.ts` `diskDateOf`), each window headed with its channel and date.
+ `PROMPT_VERSION = "2"`; a run without one is `"1"` (`M7_PROMPT_VERSION`). The local prompt stays under 7,800
+ estimated tokens (the window trimmed, as before).
+- **Items** (`bench/items.ts`): `--window-mode seconds|turn` — `turn` is the cited speaker's run of attribution
+ segments (`diskTurnsOf`), else the cues until a ≥ 2 s pause or a `>>` cue, clipped to ±`--window`; a window's
+ `bound` says which. A citation of a kept claim that gives no window is DROPPED with its reason (not in the report's
+ citations, not a video or audio citation, the recording has no cues, no cues around the cited seconds) and listed in
+ `summary.dropped`, the dry run and the page. `--limit` is stratified (`stratifiedLimit`: every ruled verdict kept,
+ the rarest first, the rest in proportion, the largest remainder); the rest are skipped "left out by the limit".
+ `unruledItemsOfReport` is M8's reading of the unruled claims.
+- **Runs** (`bench/run.ts`, `store.ts`): `--items-from <run>` takes that run's exact items (context lines filled from
+ the registry; refused with `--report`, `--window`, `--window-mode`, `--limit`); a resume asks ONLY this invocation's
+ models (a qwen-only re-run never re-asks an API pair; `summary.models` the union); the summary records
+ `promptVersion`, `itemsHash` (`benchItemsHash`: keys, rulings and windows), `windowMode`, `itemsFrom`, `dropped`; a
+ resume under another prompt version, or with `itemsFrom` naming other items, is refused. Every call is traced
+ (`trace.jsonl` in the run dir: a `start` line per invocation with the system prompt and schema, a `call` line with the
+ user prompt, the raw answer, the verdict, ms, usd). The model is injectable (`BenchDeps.ask(system, user, schema,
+ model)`, R6's shape).
+- **Scores** (`bench/score.ts`): `notCorroborated {tp, fp, fn, precision, recall}` per model and the baseline;
+ `compareBenchRuns` (each model asked in both: agreement in each over the shared items, the claims whose answers
+ changed, fixed and broke); `markedScore` (a disagreement marked Right counts as the model agreeing) tallied by
+ `markTally`, which triage's `precisionOf` now uses too (its output and tests unchanged).
+- **umtool `/tools/bench`** (inside the page, on the redesign's primitives): the status line names the window mode, the
+ prompt version (`data-prompt-version`) and the items hash (`data-items-hash`, and `from <run>`); **compare with**
+ (`nav "compare with"`, chips `<run> · prompt v<n>` over the runs with the same items hash) and its table (region
+ `compare`, `data-compare`, `data-metric` `agreement-a|agreement-b|changed`, list `changed answers`); **Right** /
+ **Wrong** (pressed when set, again to unmark; `data-mark`) on every answered disagreement, kept in the run's
+ `marks.json` (`lib/bench-marks.mjs`, R6's discipline, umtool the one writer; `POST /api/bench/marks {run, model,
+ key, verdict}`, refused on an agreement); region `precision` beside the bar (`data-metric`
+ `precision|marked-precision|marks`); "what the verdicts mean" (`data-meaning`); the dropped citations.
+- **CLI/ops:** `archilyzer reports bench-verdicts` gains `--window-mode`, `--items-from` and the stratified `--limit`;
+ the body keys `windowMode`, `itemsFrom` (controller, the editor route, `pnpm ops` help); COMMANDS.md and REPORT.md
+ regenerated.
+
+| Commit | What |
+| --- | --- |
+| `243cf1ec` | common, editor: the meanings, the prompt v2, window modes, drops, the stratified limit, items-from, the resume, the items hash, the new scores, the injected ask and the trace; CLI/ops/route flags; `bench.test.ts` (+5), `reports-bench-verdicts.test.ts`, `_benchVerdicts.test.ts`; COMMANDS.md, REPORT.md |
+| `452446a9` | umtool: `/tools/bench` — version, hash, compare, marks, precision, meanings, drops; `lib/bench-marks.mjs` (+ test), `/api/bench/marks`, `MarkButtons`; `verdict-bench.spec` (+2) and its fixture's second run |
+| (this commit) | this record, FACTS, CHANGELOG |
+
+Gates (at `452446a9`; branch start `3217bdfb` in brackets):
+
+| Gate | Result |
+| --- | --- |
+| repo-wide `tsc --noEmit` | clean at each commit |
+| common `pnpm --filter yt-dlp-transcript-common test` | **4198/4198** [4193] (+5 in `bench.test.ts`: the meanings, tie rule, schema order and context; the turn mode and the drops; the stratified limit; the injected ask, the trace, items-from, the resume over its own models, a cross-version resume refused; not-CORROBORATED, the compare, the marks) |
+| editor unit `pnpm --filter editor test` | 304/304 [304] (`_benchVerdicts.test.ts` gains the two body keys) |
+| mcp `pnpm --filter yt-dlp-transcript-mcp test` | 370/370 [370] |
+| `pnpm run test:scripts` | 1014 tests, 1011 pass, 3 skipped, 0 fail [1013: 1009 pass, 3 skipped, 1 fail — `queue-lock.test.mjs` "two builds never overlap", the timing flake D1 owns; green this time] (+1 `bench-marks.test.mjs`) |
+| `pnpm --filter umtool test` | 33/33 [33] |
+| `archilyzer docs cli|files|env --check`, `settings example --check` | clean |
+| umtool e2e `verdict-bench.spec.ts` (foreground, queued; its prebuild 69 s) | **4 passed**, 0 failed, 24.6 s |
+
+Found and left:
+- **No dry run over the real registry was made** from the worktree (it has no corpus and no `vb-r28`); the first
+ `--dry --items-from vb-r28` is V2's, through the primary.
+- **The turn mode without attribution** reads the cues' pauses: on a stream whose cues run back to back (as the
+ synthetic ones do) a turn is the whole ±window, `bound: "limit"`. With an `attribution.json` it is the speaker's run
+ of segments.
+- **An injected `ask` has no Meter**: its calls cost nothing in the run's spend (the cap still applies to the estimate).
+
## Not in this release
Auto-posting to X/Bluesky/YouTube (text only); any umtool restructuring; the "en track → 0 cues" bug (closed in r20).
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -424,7 +424,8 @@ const ACTIONS = [
// 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?}),
+ // model, one per call ({models, run?, reports?, window?, windowMode?,
+ // maxUsd?, limit?, itemsFrom?}),
// as a bench-verdicts job on draft:local (any local model) or draft:api.
"bench-verdicts",
// RECURRING REPORTS (umtool R5): a living report or a dated series on a
@@ -1313,15 +1314,20 @@ export function usage() {
"",
'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",
+ ' "windowMode"? ("seconds" | "turn": the cited speaker\'s turn, bounded by',
+ ' the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the',
+ ' operator\'s verdict), "itemsFrom"? (an earlier run\'s exact items; no',
+ ' reports, window, windowMode or limit with it)} -> {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",
+ " report's title, the claim's section, the claim, its quotes, the transcript",
+ " in 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 with this",
+ " call's models only (answered pairs are skipped; refused under another",
+ " prompt version). Results stay local, in .generation/bench/verdicts/<run>/",
+ " (umtool's /tools/bench). The log ends with",
" @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}.",
"",
'report-schedule keeps a recurring report on a cadence the editor ticks:',
diff --git a/umtool/app/api/bench/marks/route.ts b/umtool/app/api/bench/marks/route.ts
@@ -0,0 +1,26 @@
+import { markBenchItem } from "@/lib/bench";
+
+export const dynamic = "force-dynamic";
+
+// MARK A DISAGREEMENT (release 29 V1): the operator's Right / Wrong on one
+// model's answer that is not the ruling — was the MODEL right? — kept beside
+// the run (umtool's own file, lib/bench-marks.mjs); marked precision is read
+// from them on /tools/bench.
+// POST {run, model, key, verdict: "right" | "wrong" | null} -> {mark}
+// 400 a bad body or not a disagreement; 404 no such run, item or answer;
+// 409 a marks file that does not read
+export async function POST(request: Request) {
+ const headers = { "cache-control": "no-store" };
+ try {
+ const b = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!b || typeof b.run !== "string" || typeof b.model !== "string" || typeof b.key !== "string") {
+ return Response.json({ error: 'send {"run", "model", "key", "verdict": "right" | "wrong" | null}' }, { status: 400, headers });
+ }
+ const verdict = b.verdict === "right" || b.verdict === "wrong" ? b.verdict : b.verdict === null ? null : undefined;
+ if (verdict === undefined) return Response.json({ error: '"verdict" is "right", "wrong" or null' }, { status: 400, headers });
+ return Response.json(await markBenchItem(b.run, b.model, b.key, verdict), { headers });
+ } catch (e) {
+ const status = (e as { status?: number })?.status ?? 500;
+ return Response.json({ error: (e as Error)?.message ?? String(e) }, { status, headers });
+ }
+}
diff --git a/umtool/app/tools/bench/page.tsx b/umtool/app/tools/bench/page.tsx
@@ -1,17 +1,20 @@
import Link from "next/link";
import AppShell from "@/components/shell/AppShell";
import BarForm from "@/components/bench/BarForm";
+import MarkButtons from "@/components/bench/MarkButtons";
import { badgeVariants } from "@/components/ui/badge";
import {
BASELINE_MODEL,
VERDICTS,
+ VERDICT_MEANINGS,
+ VERDICT_TIE_RULE,
filterBenchRows,
passesBar,
readBenchRuns,
readBenchView,
readVerdictsPolicy,
} from "@/lib/bench";
-import type { ModelScore } from "yt-dlp-transcript-common/lib/report/draft/bench/index";
+import type { MarkedScore, ModelScore } from "yt-dlp-transcript-common/lib/report/draft/bench/index";
import type { GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings";
export const dynamic = "force-dynamic";
@@ -24,9 +27,15 @@ export const dynamic = "force-dynamic";
// first. The bar (settings.generation.verdicts) is set here, and each model's
// pass or fail read against it — the handoff for the verdict proposals. The
// runs are local-only (`archilyzer reports bench-verdicts`); zero client JS
-// but the bar's form.
+// but the bar's form and the marks.
+//
+// Release 29 V1: the run's prompt version and items hash; "compare with" over
+// the runs with the same items (each model's agreement in both, the claims
+// whose answers changed); a Right / Wrong mark on each disagreement; the
+// not-CORROBORATED precision and recall beside the bar, marked and not; what
+// the verdicts mean (the one copy, verdicts.mjs).
-type Search = { run?: string; model?: string; verdict?: string };
+type Search = { run?: string; model?: string; verdict?: string; compare?: string };
const pct = (v: number | null) => (v === null ? "—" : `${Math.round(v * 1000) / 10}%`);
@@ -34,7 +43,8 @@ export default async function BenchPage({ searchParams }: { searchParams: Promis
const sp = await searchParams;
const runs = await readBenchRuns();
const id = sp.run && runs.some((r) => r.id === sp.run) ? sp.run : runs[0]?.id;
- const view = id ? await readBenchView(id) : null;
+ const view = id ? await readBenchView(id, sp.compare) : null;
+ const sameItems = view ? runs.filter((r) => r.id !== id && r.itemsHash === view.itemsHash) : [];
let policy: GenerationVerdicts | null = null;
let policyError: string | null = null;
try {
@@ -81,7 +91,7 @@ export default async function BenchPage({ searchParams }: { searchParams: Promis
run {id} cannot be read
</p>
) : (
- <RunView view={view} policy={policy} policyError={policyError} sp={sp} qs={qs} />
+ <RunView view={view} policy={policy} policyError={policyError} sp={sp} qs={qs} sameItems={sameItems} />
)}
</>
)}
@@ -96,12 +106,14 @@ function RunView({
policyError,
sp,
qs,
+ sameItems,
}: {
view: NonNullable<Awaited<ReturnType<typeof readBenchView>>>;
policy: GenerationVerdicts | null;
policyError: string | null;
sp: Search;
qs: (n: Partial<Search>) => string;
+ sameItems: Awaited<ReturnType<typeof readBenchRuns>>;
}) {
const { summary: s, score } = view;
const bar = policy?.bar ?? null;
@@ -110,7 +122,14 @@ function RunView({
return (
<div data-bench-run={s.id} data-status={s.status} className="flex flex-col gap-4">
<p role="status" className="text-[var(--color-dim)]">
- {s.status} · {s.items} items · {s.skipped.length} skipped · a {s.windowS} s window · ${s.spentUsd.toFixed(4)} of ${s.maxUsd} ·{" "}
+ {s.status} · {s.items} items · {s.skipped.length} skipped
+ {s.dropped?.length ? ` · ${s.dropped.length} citations dropped` : ""} ·{" "}
+ {s.windowMode === "turn" ? `the speaker's turn within ${s.windowS} s` : `a ${s.windowS} s window`} ·{" "}
+ <span data-prompt-version={view.promptVersion}>prompt v{view.promptVersion}</span> ·{" "}
+ <span data-items-hash={view.itemsHash} className="font-mono">
+ items {view.itemsHash}
+ </span>
+ {s.itemsFrom ? ` (from ${s.itemsFrom})` : ""} · ${s.spentUsd.toFixed(4)} of ${s.maxUsd} ·{" "}
{new Date(s.createdAt).toISOString().slice(0, 16).replace("T", " ")} UTC
{s.stopped?.length ? ` · stopped: ${s.stopped.join("; ")}` : ""}
</p>
@@ -119,15 +138,19 @@ function RunView({
<ModelTile key={m.model} m={m} baseline={m.model === BASELINE_MODEL ? null : score.baseline} pass={bar && m.model !== BASELINE_MODEL ? passesBar(m, bar) : null} />
))}
</section>
- <section aria-label="the bar" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3">
- {policy ? (
- <BarForm initial={policy} models={score.models} />
- ) : (
- <p role="alert" className="text-[var(--color-bad)]">
- the bar cannot be read: {policyError}
- </p>
- )}
- </section>
+ <div className="flex flex-wrap items-start gap-3">
+ <section aria-label="the bar" className="min-w-[24rem] flex-1 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3">
+ {policy ? (
+ <BarForm initial={policy} models={score.models} />
+ ) : (
+ <p role="alert" className="text-[var(--color-bad)]">
+ the bar cannot be read: {policyError}
+ </p>
+ )}
+ </section>
+ <Precision scores={score.models} marked={view.marked} />
+ </div>
+ <Compare view={view} sameItems={sameItems} qs={qs} current={sp.compare} />
<section aria-label="confusion" className="flex flex-wrap gap-4">
{score.models.map((m) => (
<Matrix key={m.model} m={m} />
@@ -176,6 +199,7 @@ function RunView({
<>
<span className={`font-mono ${a.verdict === r.verdict ? "text-[var(--color-good)]" : "text-[var(--color-bad)]"}`}>{a.verdict}</span>
{a.reason && <div className="text-[var(--color-dim)]">{a.reason}</div>}
+ {a.verdict !== r.verdict && <MarkButtons run={s.id} model={m} item={r.key} initial={a.mark} />}
</>
) : (
<span className="text-[var(--color-bad)]">
@@ -190,6 +214,30 @@ function RunView({
</tbody>
</table>
</section>
+ <details>
+ <summary className="micro cursor-pointer">what the verdicts mean</summary>
+ <dl aria-label="the verdicts" className="mt-1 grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5">
+ {VERDICTS.map((v) => (
+ <div key={v} className="contents">
+ <dt className="font-mono">{v}</dt>
+ <dd data-meaning={v}>{VERDICT_MEANINGS[v]}</dd>
+ </div>
+ ))}
+ </dl>
+ <p className="mt-1 text-[var(--color-dim)]">{VERDICT_TIE_RULE}</p>
+ </details>
+ {s.dropped && s.dropped.length > 0 && (
+ <details>
+ <summary className="micro cursor-pointer">dropped {s.dropped.length}</summary>
+ <ul aria-label="dropped" className="mt-1 flex flex-col gap-0.5">
+ {s.dropped.map((d) => (
+ <li key={`${d.key} ${d.citation}`} className="font-mono text-[var(--color-dim)]">
+ {d.key} {d.citation} — {d.reason}
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
{s.skipped.length > 0 && (
<details>
<summary className="micro cursor-pointer">skipped {s.skipped.length}</summary>
@@ -206,6 +254,111 @@ function RunView({
);
}
+// "Not CORROBORATED" as the positive class — the claims a proposal would put
+// in front of the operator — plain and with the operator's marks applied.
+function Precision({ scores, marked }: { scores: ModelScore[]; marked: MarkedScore[] }) {
+ return (
+ <section aria-label="precision" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3">
+ <span className="micro">not CORROBORATED · precision / recall</span>
+ <table className="mt-1 border-collapse">
+ <thead>
+ <tr className="micro text-left">
+ <th className="pr-3">model</th>
+ <th className="pr-3">as ruled</th>
+ <th className="pr-3">marked</th>
+ <th>marks</th>
+ </tr>
+ </thead>
+ <tbody>
+ {scores.map((m) => {
+ const k = marked.find((x) => x.model === m.model);
+ return (
+ <tr key={m.model} data-model={m.model}>
+ <td className="pr-3 font-mono">{m.model}</td>
+ <td className="pr-3" data-metric="precision">
+ {pct(m.notCorroborated.precision)} / {pct(m.notCorroborated.recall)}
+ </td>
+ <td className="pr-3" data-metric="marked-precision">
+ {k ? `${pct(k.notCorroborated.precision)} / ${pct(k.notCorroborated.recall)}` : "—"}
+ </td>
+ <td data-metric="marks">{k && k.marks.marked ? `${k.marks.right} right · ${k.marks.wrong} wrong` : "none yet"}</td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </section>
+ );
+}
+
+// Another run over the SAME items (the same hash): each model asked in both,
+// its agreement there and here, and every claim whose answer changed.
+function Compare({
+ view,
+ sameItems,
+ qs,
+ current,
+}: {
+ view: NonNullable<Awaited<ReturnType<typeof readBenchView>>>;
+ sameItems: Awaited<ReturnType<typeof readBenchRuns>>;
+ qs: (n: Partial<Search>) => string;
+ current?: string;
+}) {
+ if (!sameItems.length) return null;
+ const c = view.compare;
+ return (
+ <section aria-label="compare" className="flex flex-col gap-2">
+ <nav aria-label="compare with" className="flex flex-wrap items-center gap-1.5">
+ <span className="micro">compare with</span>
+ {sameItems.map((r) => (
+ <Chip key={r.id} href={qs({ compare: r.id === current ? "" : r.id })} on={r.id === current} label={`${r.id} · prompt v${r.promptVersion}`} />
+ ))}
+ </nav>
+ {c && (
+ <div data-compare={c.with}>
+ <table className="border-collapse">
+ <thead>
+ <tr className="micro text-left">
+ <th className="pr-3">model</th>
+ <th className="pr-3">{c.with} (v{c.promptVersion})</th>
+ <th className="pr-3">this run (v{view.promptVersion})</th>
+ <th>changed</th>
+ </tr>
+ </thead>
+ <tbody>
+ {c.result.models.map((m) => (
+ <tr key={m.model} data-model={m.model}>
+ <td className="pr-3 font-mono">{m.model}</td>
+ <td className="pr-3" data-metric="agreement-a">
+ {pct(m.a.agreement)}
+ </td>
+ <td className="pr-3" data-metric="agreement-b">
+ {pct(m.b.agreement)}
+ </td>
+ <td data-metric="changed">
+ {m.changed.length} · {m.fixed} now agree · {m.broke} no longer
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {c.result.models.some((m) => m.changed.length) && (
+ <ul aria-label="changed answers" className="mt-1 flex flex-col gap-0.5">
+ {c.result.models.flatMap((m) =>
+ m.changed.map((x) => (
+ <li key={`${m.model} ${x.key}`} data-changed={x.key} data-model={m.model} className="font-mono">
+ {m.model} {x.key}: {x.a ?? "none"} → {x.b ?? "none"} (ruled {x.ruled})
+ </li>
+ )),
+ )}
+ </ul>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
+
function ModelTile({ m, baseline, pass }: { m: ModelScore; baseline: ModelScore | null; pass: { pass: boolean; misses: string[] } | null }) {
const vs = (v: number | null, b: number | null | undefined) => (baseline ? `${pct(v)} (baseline ${pct(b ?? null)})` : pct(v));
return (
diff --git a/umtool/components/bench/MarkButtons.tsx b/umtool/components/bench/MarkButtons.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { useState } from "react";
+import { useRouter } from "next/navigation";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+// THE OPERATOR'S MARK ON A DISAGREEMENT (release 29 V1): was the MODEL right,
+// where its answer is not the ruling? Right / Wrong (pressed when set; again
+// to unmark), POSTed to /api/bench/marks, then the page re-reads so the
+// marked precision beside the bar moves. R6's triage marks, on the bench.
+
+export default function MarkButtons({ run, model, item, initial }: { run: string; model: string; item: string; initial?: "right" | "wrong" }) {
+ const router = useRouter();
+ const [mark, setMark] = useState<"right" | "wrong" | undefined>(initial);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ async function send(next: "right" | "wrong") {
+ const verdict = mark === next ? null : next;
+ setBusy(true);
+ setError(null);
+ try {
+ const r = await fetch("/api/bench/marks", { method: "POST", body: JSON.stringify({ run, model, key: item, verdict }) });
+ const body = await r.json();
+ if (!r.ok) throw new Error(body.error ?? `HTTP ${r.status}`);
+ setMark(body.mark ?? undefined);
+ router.refresh();
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ const cls = (on: boolean) => cn(buttonVariants({ variant: on ? "pressed" : "outline", size: "sm" }));
+ return (
+ <span className="mt-1 flex flex-wrap items-center gap-1" data-mark={mark ?? "none"}>
+ <button type="button" disabled={busy} aria-pressed={mark === "right"} className={cls(mark === "right")} onClick={() => void send("right")}>
+ Right
+ </button>
+ <button type="button" disabled={busy} aria-pressed={mark === "wrong"} className={cls(mark === "wrong")} onClick={() => void send("wrong")}>
+ Wrong
+ </button>
+ {error && (
+ <span role="alert" className="text-[var(--color-bad)]">
+ {error}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/umtool/e2e/fixtures/bench-fixture.mjs b/umtool/e2e/fixtures/bench-fixture.mjs
@@ -23,8 +23,10 @@ const said = {
[QWEN]: ["CORROBORATED", "CORROBORATED", "CORROBORATED", null],
};
-export function makeBenchRun(root) {
- const dir = path.join(root, BENCH_RUN);
+export function makeBenchRun(root, o = {}) {
+ const run = o.run ?? BENCH_RUN;
+ const answers = o.said ?? said;
+ const dir = path.join(root, run);
rmSync(dir, { recursive: true, force: true });
mkdirSync(dir, { recursive: true });
const items = claims.map(([id, text, verdict], i) => ({
@@ -37,7 +39,7 @@ export function makeBenchRun(root) {
windows: [{ channel: "synth-kitchen", id: "bread-day-01", from: 0, to: 80, cited: [{ start: 10 + i * 15, end: 14 + i * 15 }], cues: [{ start: 10 + i * 15, end: 14 + i * 15, text: "a line" }] }],
}));
const results = [];
- for (const [model, verdicts] of Object.entries(said)) {
+ for (const [model, verdicts] of Object.entries(answers)) {
items.forEach((it, i) => {
const v = verdicts[i];
results.push({
@@ -61,15 +63,16 @@ export function makeBenchRun(root) {
JSON.stringify({
format: "archilyzer-verdict-bench",
version: 1,
- id: BENCH_RUN,
- createdAt: "2026-10-13T12:00:00.000Z",
+ id: run,
+ createdAt: o.createdAt ?? "2026-10-13T12:00:00.000Z",
updatedAt: "2026-10-13T12:05:00.000Z",
status: "done",
- models: [SONNET, QWEN],
+ models: Object.keys(answers),
+ ...(o.promptVersion ? { promptVersion: o.promptVersion } : {}),
windowS: 60,
maxUsd: 5,
reports: [],
- spentUsd: 0.016,
+ spentUsd: Object.keys(answers).includes(SONNET) ? 0.016 : 0,
items: items.length,
skipped: [{ key: "synth-bench/c5", report: "synth-bench", claim: "c5", reason: "no citation" }],
score: {},
@@ -77,3 +80,16 @@ export function makeBenchRun(root) {
);
return dir;
}
+
+// Release 29 V1: a second run over the SAME items (prompt version 2, made
+// earlier so the page still opens the first by default), Sonnet alone: it now
+// calls c2 PARTLY (as ruled) and c3 PARTLY (ruled CONTRADICTED).
+export const BENCH_RUN_V2 = "vb-e2e-v2";
+export function makeBenchRunV2(root) {
+ return makeBenchRun(root, {
+ run: BENCH_RUN_V2,
+ said: { [SONNET]: ["CORROBORATED", "PARTLY", "PARTLY", "NOT_FOUND"] },
+ promptVersion: "2",
+ createdAt: "2026-10-13T11:00:00.000Z",
+ });
+}
diff --git a/umtool/e2e/verdict-bench.spec.ts b/umtool/e2e/verdict-bench.spec.ts
@@ -3,7 +3,7 @@ import { readFileSync, rmSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { WARM_TIMEOUT, warm } from "./warm";
-import { BENCH_RUN, QWEN, SONNET, makeBenchRun } from "./fixtures/bench-fixture.mjs";
+import { BENCH_RUN, BENCH_RUN_V2, QWEN, SONNET, makeBenchRun, makeBenchRunV2 } from "./fixtures/bench-fixture.mjs";
// ---------------------------------------------------------------------------
// The verdict bench's page (release 28 M7) over a synthetic run in the
@@ -25,11 +25,13 @@ const stubAsked = (route: string) =>
test.beforeAll(async ({ playwright }) => {
test.setTimeout(WARM_TIMEOUT);
makeBenchRun(ROOT);
+ makeBenchRunV2(ROOT);
await warm(playwright, ["/bench", "/api/bench/bar"]);
});
test.afterAll(async ({ request }) => {
await request.post("/api/bench/bar", { data: { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] } });
rmSync(path.join(ROOT, BENCH_RUN), { recursive: true, force: true });
+ rmSync(path.join(ROOT, BENCH_RUN_V2), { recursive: true, force: true });
});
test("the run: each model's tile against the baseline, the matrix, the items with disagreements first, the filters", async ({ page }) => {
@@ -95,3 +97,56 @@ test("the bar: saved through the editor's settings action; a passing model ticke
await expect(page.getByRole("form", { name: "bar" }).getByRole("checkbox", { name: `use ${SONNET}` })).toBeChecked();
await expect(page.getByRole("form", { name: "bar" }).getByRole("spinbutton", { name: "minimum agreement" })).toHaveValue("50");
});
+
+test("V1: the run's prompt version and items hash; compare with a run over the same items", async ({ page }) => {
+ await page.goto(`/tools/bench?run=${BENCH_RUN_V2}`);
+ const status = page.locator(`[data-bench-run="${BENCH_RUN_V2}"]`).getByRole("status");
+ await expect(status.locator("[data-prompt-version]")).toHaveText("prompt v2");
+ const hash = await status.locator("[data-items-hash]").getAttribute("data-items-hash");
+ expect(hash).toMatch(/^[0-9a-f]{16}$/);
+ // The first run (made before V1: version 1) has the same items.
+ await page.goto(`/tools/bench?run=${BENCH_RUN}`);
+ await expect(page.locator(`[data-bench-run="${BENCH_RUN}"]`).getByRole("status").locator("[data-prompt-version]")).toHaveText("prompt v1");
+ await expect(page.locator(`[data-bench-run="${BENCH_RUN}"]`).getByRole("status").locator("[data-items-hash]")).toHaveAttribute("data-items-hash", hash!);
+ await page.goto(`/tools/bench?run=${BENCH_RUN_V2}`);
+ const compare = page.getByRole("region", { name: "compare" });
+ await compare.getByRole("navigation", { name: "compare with" }).getByRole("link", { name: `${BENCH_RUN} · prompt v1` }).click();
+ await expect(page).toHaveURL(new RegExp(`compare=${BENCH_RUN}`));
+ const row = compare.locator(`[data-compare="${BENCH_RUN}"] tr[data-model="${SONNET}"]`);
+ await expect(row.locator('[data-metric="agreement-a"]')).toHaveText("75%");
+ await expect(row.locator('[data-metric="agreement-b"]')).toHaveText("75%");
+ await expect(row.locator('[data-metric="changed"]')).toHaveText("2 · 1 now agree · 1 no longer");
+ // Only Sonnet was asked in both.
+ await expect(compare.locator(`tr[data-model="${QWEN}"]`)).toHaveCount(0);
+ const changed = compare.getByRole("list", { name: "changed answers" }).locator("li");
+ await expect(changed).toHaveCount(2);
+ await expect(changed.nth(0)).toHaveText(`${SONNET} synth-bench/c2: CORROBORATED → PARTLY (ruled PARTLY)`);
+ await expect(changed.nth(1)).toHaveText(`${SONNET} synth-bench/c3: CONTRADICTED → PARTLY (ruled CONTRADICTED)`);
+ // What the verdicts mean: the one copy.
+ await page.getByText("what the verdicts mean").click();
+ await expect(page.locator('[data-meaning="CORROBORATED"]')).toContainText("the substance of the claim is shown by the cited words");
+});
+
+test("V1: a Right mark on a disagreement moves the marked precision; again unmarks", async ({ page }) => {
+ await page.goto(`/tools/bench?run=${BENCH_RUN}`);
+ const precision = page.getByRole("region", { name: "precision" }).locator(`tr[data-model="${SONNET}"]`);
+ await expect(precision.locator('[data-metric="precision"]')).toHaveText("100% / 66.7%");
+ await expect(precision.locator('[data-metric="marked-precision"]')).toHaveText("100% / 66.7%");
+ await expect(precision.locator('[data-metric="marks"]')).toHaveText("none yet");
+ // Sonnet called the PARTLY claim c2 CORROBORATED: the operator says the model was right.
+ const cell = page.getByRole("region", { name: "items" }).locator('tr[data-item="synth-bench/c2"]').locator(`[data-model="${SONNET}"]`);
+ // An agreeing answer has no mark buttons.
+ await expect(page.getByRole("region", { name: "items" }).locator('tr[data-item="synth-bench/c1"]').locator(`[data-model="${SONNET}"]`).getByRole("button")).toHaveCount(0);
+ await cell.getByRole("button", { name: "Right" }).click();
+ await expect(cell.getByRole("button", { name: "Right" })).toHaveAttribute("aria-pressed", "true");
+ await expect(precision.locator('[data-metric="marked-precision"]')).toHaveText("100% / 100%");
+ await expect(precision.locator('[data-metric="marks"]')).toHaveText("1 right · 0 wrong");
+ // The plain score is the ruling's, unmoved.
+ await expect(precision.locator('[data-metric="precision"]')).toHaveText("100% / 66.7%");
+ // Kept across a reload; again unmarks.
+ await page.reload();
+ await expect(cell.locator("[data-mark]")).toHaveAttribute("data-mark", "right");
+ await cell.getByRole("button", { name: "Right" }).click();
+ await expect(precision.locator('[data-metric="marks"]')).toHaveText("none yet");
+ await expect(cell.getByRole("button", { name: "Right" })).toHaveAttribute("aria-pressed", "false");
+});
diff --git a/umtool/lib/bench-marks.mjs b/umtool/lib/bench-marks.mjs
@@ -0,0 +1,123 @@
+// THE VERDICT BENCH'S MARKS (release 29 V1): the operator's Right / Wrong on
+// a disagreement — was the MODEL right, where its answer is not the ruling? —
+// kept beside the run, so the bar can be set from marked precision
+// (common's `markedScore`, tallied by triage's `markTally`).
+//
+// <bench root>/<run>/marks.json
+// { format: "archilyzer-bench-marks", version: 1, run,
+// marks: { "<model>": { "<report>/<claim>": { verdict: "right" | "wrong",
+// answer, at } } },
+// updatedAt }
+//
+// `answer` is the model's verdict the mark was made on: a resumed run that
+// asked again and got another answer leaves the mark stale (not applied).
+//
+// R6's discipline (lib/research/triage-marks.mjs): ONE writer (umtool),
+// serialised in-process; the whole file to a temp name and a rename; a file
+// that does not parse is never overwritten (a write refuses with 409). The
+// run's other files are the editor's job's; this one is never touched by it.
+//
+// Plain ESM: the unit test reads it the way the app does.
+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+export const BENCH_MARKS_FORMAT = "archilyzer-bench-marks";
+export const BENCH_MARKS_VERSION = 1;
+const RUN_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;
+const KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}\/[A-Za-z0-9._:-]{1,64}$/;
+const VERDICTS = ["CORROBORATED", "PARTLY", "CONTRADICTED", "NOT_FOUND", "UNTESTABLE"];
+
+export class BenchMarksError extends Error {
+ constructor(message, status = 400) {
+ super(message);
+ this.status = status;
+ }
+}
+
+export const benchMarksFile = (root, run) => {
+ if (!RUN_RE.test(run)) throw new BenchMarksError(`not a run id: ${JSON.stringify(run)}`);
+ return path.join(root, run, "marks.json");
+};
+
+function clean(raw, run) {
+ const marks = {};
+ const given = raw?.marks && typeof raw.marks === "object" ? raw.marks : {};
+ for (const [model, byKey] of Object.entries(given)) {
+ if (!MODEL_RE.test(model) || !byKey || typeof byKey !== "object") continue;
+ for (const [key, m] of Object.entries(byKey)) {
+ if (!KEY_RE.test(key) || !m || (m.verdict !== "right" && m.verdict !== "wrong")) continue;
+ (marks[model] ??= {})[key] = {
+ verdict: m.verdict,
+ answer: VERDICTS.includes(m.answer) ? m.answer : null,
+ at: typeof m.at === "string" ? m.at.slice(0, 40) : "",
+ };
+ }
+ }
+ return { format: BENCH_MARKS_FORMAT, version: BENCH_MARKS_VERSION, run, marks, updatedAt: typeof raw?.updatedAt === "string" ? raw.updatedAt : "" };
+}
+
+/** A run's marks (none: an empty set). A file that does not read is a 409. */
+export async function readBenchMarksDoc(root, run) {
+ let text;
+ try {
+ text = await readFile(/* turbopackIgnore: true */ benchMarksFile(root, run), "utf8");
+ } catch (err) {
+ if (err?.code === "ENOENT") return clean(null, run);
+ if (err instanceof BenchMarksError) throw err;
+ throw new BenchMarksError(`the marks of ${run} cannot be read: ${err?.message ?? err}`, 409);
+ }
+ let raw;
+ try {
+ raw = JSON.parse(text);
+ } catch (err) {
+ throw new BenchMarksError(`${run}/marks.json is not JSON: ${err.message}`, 409);
+ }
+ if (raw?.format !== BENCH_MARKS_FORMAT) throw new BenchMarksError(`${run}/marks.json is not a ${BENCH_MARKS_FORMAT} file`, 409);
+ return clean(raw, run);
+}
+
+let chain = Promise.resolve();
+function serialised(fn) {
+ const run = chain.then(fn);
+ chain = run.catch(() => {});
+ return run;
+}
+
+/**
+ * Mark one disagreement right or wrong (`verdict` null: unmark), on the
+ * model's `answer`. Answers the marks as written.
+ *
+ * @param {string} root the bench runs' directory
+ * @param {string} run
+ * @param {{ model: string, key: string, verdict: "right" | "wrong" | null, answer: string | null, now?: Date }} m
+ */
+export function setBenchMark(root, run, m) {
+ return serialised(async () => {
+ if (!MODEL_RE.test(m.model ?? "")) throw new BenchMarksError(`not a model: ${JSON.stringify(m.model)}`);
+ if (!KEY_RE.test(m.key ?? "")) throw new BenchMarksError(`not an item: ${JSON.stringify(m.key)}`);
+ if (m.verdict !== null && m.verdict !== "right" && m.verdict !== "wrong") throw new BenchMarksError('"verdict" is "right", "wrong" or null');
+ const doc = await readBenchMarksDoc(root, run);
+ const at = (m.now ?? new Date()).toISOString();
+ if (m.verdict === null) {
+ if (doc.marks[m.model]) {
+ delete doc.marks[m.model][m.key];
+ if (!Object.keys(doc.marks[m.model]).length) delete doc.marks[m.model];
+ }
+ } else {
+ (doc.marks[m.model] ??= {})[m.key] = { verdict: m.verdict, answer: VERDICTS.includes(m.answer) ? m.answer : null, at };
+ }
+ doc.updatedAt = at;
+ const file = benchMarksFile(root, run);
+ await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
+ try {
+ await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`);
+ await rename(/* turbopackIgnore: true */ tmp, file);
+ } catch (err) {
+ await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {});
+ throw err;
+ }
+ return doc;
+ });
+}
diff --git a/umtool/lib/bench-marks.test.mjs b/umtool/lib/bench-marks.test.mjs
@@ -0,0 +1,35 @@
+// The verdict bench's marks (release 29 V1): set, unmark, per model and item,
+// the file shape common's reader takes; a broken file is never overwritten.
+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 { BenchMarksError, benchMarksFile, readBenchMarksDoc, setBenchMark } from "./bench-marks.mjs";
+
+test("bench marks: right and wrong per model and item, on the answer marked; unmark; a broken file refuses", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "bench-marks-"));
+ try {
+ assert.deepEqual((await readBenchMarksDoc(root, "vb-x")).marks, {});
+ const now = new Date("2026-10-15T10:00:00Z");
+ await setBenchMark(root, "vb-x", { model: "qwen3:8b", key: "synth-ruled/r01", verdict: "right", answer: "PARTLY", now });
+ await setBenchMark(root, "vb-x", { model: "qwen3:8b", key: "synth-ruled/r02", verdict: "wrong", answer: "NOT_FOUND", now });
+ const doc = await setBenchMark(root, "vb-x", { model: "claude-sonnet-5-5", key: "synth-ruled/r01", verdict: "wrong", answer: "CONTRADICTED", now });
+ assert.deepEqual(doc.marks["qwen3:8b"]["synth-ruled/r01"], { verdict: "right", answer: "PARTLY", at: now.toISOString() });
+ assert.deepEqual(Object.keys(doc.marks).sort(), ["claude-sonnet-5-5", "qwen3:8b"]);
+ const after = await setBenchMark(root, "vb-x", { model: "claude-sonnet-5-5", key: "synth-ruled/r01", verdict: null, answer: null });
+ assert.deepEqual(Object.keys(after.marks), ["qwen3:8b"]);
+ const onDisk = JSON.parse(await readFile(benchMarksFile(root, "vb-x"), "utf8"));
+ assert.equal(onDisk.format, "archilyzer-bench-marks");
+ assert.equal(onDisk.run, "vb-x");
+ await assert.rejects(setBenchMark(root, "vb-x", { model: "q", key: "no-slash", verdict: "right", answer: null }), BenchMarksError);
+ await assert.rejects(setBenchMark(root, "Bad Run", { model: "q", key: "a/b", verdict: "right", answer: null }), /not a run id/);
+
+ await mkdir(path.join(root, "vb-broken"), { recursive: true });
+ await writeFile(benchMarksFile(root, "vb-broken"), "{ nope");
+ await assert.rejects(setBenchMark(root, "vb-broken", { model: "q", key: "a/b", verdict: "right", answer: null }), (e) => e.status === 409);
+ assert.equal(await readFile(benchMarksFile(root, "vb-broken"), "utf8"), "{ nope");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/bench.ts b/umtool/lib/bench.ts
@@ -1,31 +1,49 @@
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import {
+ benchItemsHash,
benchRootOf,
+ compareBenchRuns,
listBenchRuns,
+ markedScore,
passesBar,
+ readBenchMarks,
readBenchRun,
scoreBench,
BASELINE_MODEL,
+ M7_PROMPT_VERSION,
type BenchItem,
+ type BenchMarks,
type BenchResult,
type BenchScore,
type BenchSummary,
+ type MarkedScore,
+ type RunCompare,
type VerdictBar,
} from "yt-dlp-transcript-common/lib/report/draft/bench/index";
-import { VERDICTS, type Verdict } from "yt-dlp-transcript-common/lib/report/verdicts";
+import { VERDICT_MEANINGS, VERDICT_TIE_RULE, VERDICTS, isVerdict, type Verdict } from "yt-dlp-transcript-common/lib/report/verdicts";
import { sanitizeGeneration, type GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings";
+import { BenchMarksError, setBenchMark } from "./bench-marks.mjs";
import { askEditor, EditorError } from "@/lib/articles/generation";
// THE VERDICT BENCH, AS UMTOOL SEES IT (release 28 M7): the runs `archilyzer
// reports bench-verdicts` wrote under the checkout's `.generation/bench/
-// verdicts/` (local-only; read here, never written), scored again from their
-// items and results so the page and the files cannot disagree, and the
-// operator's bar — settings.generation.verdicts — read from and written
-// through the editor's settings action, as the generation policy is.
+// verdicts/` (local-only; read here, never written — but for the operator's
+// marks, V1), scored again from their items and results so the page and the
+// files cannot disagree, and the operator's bar — settings.generation.verdicts
+// — read from and written through the editor's settings action, as the
+// generation policy is.
+//
+// Release 29 V1: each run's prompt version and items hash (a run before V1:
+// version "1", its hash computed from its items), a comparison with another
+// run over the same items, the operator's Right/Wrong marks on disagreements
+// (marks.json beside the run, ./bench-marks.mjs) and the marked scores.
//
// SERVER-ONLY.
-export type BenchRunRow = Pick<BenchSummary, "id" | "createdAt" | "status" | "models" | "items" | "spentUsd" | "maxUsd">;
+export type BenchRunRow = Pick<BenchSummary, "id" | "createdAt" | "status" | "models" | "items" | "spentUsd" | "maxUsd"> & {
+ promptVersion: string;
+ itemsHash: string;
+};
export type BenchItemRow = {
key: string;
@@ -33,34 +51,53 @@ export type BenchItemRow = {
claim: string;
text: string;
verdict: Verdict;
- answers: Record<string, { verdict: Verdict | null; reason?: string; failure?: string; error?: string }>;
+ answers: Record<string, { verdict: Verdict | null; reason?: string; failure?: string; error?: string; mark?: "right" | "wrong" }>;
// A model whose answer is not the operator's (failures included).
disagree: string[];
};
export type BenchView = {
summary: BenchSummary;
+ promptVersion: string;
+ itemsHash: string;
score: BenchScore;
+ // Each model's score with the operator's marks applied.
+ marked: MarkedScore[];
items: BenchItemRow[];
+ // The other run, over the same items, this one is compared with.
+ compare?: { with: string; promptVersion: string; result: RunCompare };
};
export function benchRoot(): string {
return benchRootOf(getPaths());
}
+// A run's items hash: its summary's, else (a run before V1) computed from its items.
+async function hashOf(s: BenchSummary): Promise<string> {
+ if (s.itemsHash) return s.itemsHash;
+ const run = await readBenchRun(benchRoot(), s.id).catch(() => null);
+ return run ? benchItemsHash(run.items) : "";
+}
+
export async function readBenchRuns(): Promise<BenchRunRow[]> {
- return (await listBenchRuns(benchRoot())).map((s) => ({
- id: s.id,
- createdAt: s.createdAt,
- status: s.status,
- models: s.models,
- items: s.items,
- spentUsd: s.spentUsd,
- maxUsd: s.maxUsd,
- }));
+ const out: BenchRunRow[] = [];
+ for (const s of await listBenchRuns(benchRoot())) {
+ out.push({
+ id: s.id,
+ createdAt: s.createdAt,
+ status: s.status,
+ models: s.models,
+ items: s.items,
+ spentUsd: s.spentUsd,
+ maxUsd: s.maxUsd,
+ promptVersion: s.promptVersion ?? M7_PROMPT_VERSION,
+ itemsHash: await hashOf(s),
+ });
+ }
+ return out;
}
-function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], models: readonly string[]): BenchItemRow[] {
+function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], models: readonly string[], marks: BenchMarks = {}): BenchItemRow[] {
const by = new Map<string, BenchResult>();
for (const r of results) by.set(`${r.model}\u0000${r.key}`, r);
return items.map((it) => {
@@ -69,20 +106,78 @@ function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], mo
for (const m of models) {
const r = by.get(`${m}\u0000${it.key}`);
if (!r) continue;
- answers[m] = { verdict: r.verdict, ...(r.reason ? { reason: r.reason } : {}), ...(r.failure ? { failure: r.failure } : {}), ...(r.error ? { error: r.error } : {}) };
+ const mk = marks[m]?.[it.key];
+ const mark = mk && r.verdict !== it.verdict && mk.answer === r.verdict ? mk.verdict : undefined;
+ answers[m] = {
+ verdict: r.verdict,
+ ...(r.reason ? { reason: r.reason } : {}),
+ ...(r.failure ? { failure: r.failure } : {}),
+ ...(r.error ? { error: r.error } : {}),
+ ...(mark ? { mark } : {}),
+ };
if (r.verdict !== it.verdict) disagree.push(m);
}
return { key: it.key, report: it.report, claim: it.claim, text: it.text, verdict: it.verdict, answers, disagree };
});
}
-export async function readBenchView(id: string): Promise<BenchView | null> {
- const run = await readBenchRun(benchRoot(), id).catch(() => null);
+export async function readBenchView(id: string, compareWith?: string): Promise<BenchView | null> {
+ const root = benchRoot();
+ const run = await readBenchRun(root, id).catch(() => null);
if (!run) return null;
- const score = scoreBench(run.items, run.results, run.summary.models);
- return { summary: run.summary, score, items: rowsOf(run.items, run.results, run.summary.models) };
+ const models = run.summary.models;
+ const score = scoreBench(run.items, run.results, models);
+ const marks = await readBenchMarks(root, id);
+ const itemsHash = run.summary.itemsHash ?? benchItemsHash(run.items);
+ let compare: BenchView["compare"];
+ if (compareWith && compareWith !== id) {
+ const other = await readBenchRun(root, compareWith).catch(() => null);
+ // Only a run over the same items is compared.
+ if (other && (other.summary.itemsHash ?? benchItemsHash(other.items)) === itemsHash) {
+ compare = {
+ with: compareWith,
+ promptVersion: other.summary.promptVersion ?? M7_PROMPT_VERSION,
+ result: compareBenchRuns(
+ { items: other.items, results: other.results, models: other.summary.models },
+ { items: run.items, results: run.results, models },
+ ),
+ };
+ }
+ }
+ return {
+ summary: run.summary,
+ promptVersion: run.summary.promptVersion ?? M7_PROMPT_VERSION,
+ itemsHash,
+ score,
+ marked: models.map((m) => markedScore(run.items, run.results, m, marks)),
+ items: rowsOf(run.items, run.results, models, marks),
+ ...(compare ? { compare } : {}),
+ };
}
+/**
+ * Mark one disagreement: was the model right where its answer is not the
+ * operator's ruling? Only a disagreement with an answer is marked; the mark
+ * records the answer it was made on. Answers the item's row as it now is.
+ */
+export async function markBenchItem(run: string, model: string, key: string, verdict: "right" | "wrong" | null): Promise<{ mark: "right" | "wrong" | null }> {
+ const root = benchRoot();
+ const r = await readBenchRun(root, run).catch(() => null);
+ if (!r) throw new BenchMarksError(`no run ${run}`, 404);
+ const item = r.items.find((i) => i.key === key);
+ if (!item) throw new BenchMarksError(`no item ${key} in run ${run}`, 404);
+ let answer: BenchResult | undefined;
+ for (const x of r.results) if (x.model === model && x.key === key) answer = x;
+ if (!answer) throw new BenchMarksError(`${model} was not asked about ${key}`, 404);
+ if (verdict !== null && (!isVerdict(answer.verdict) || answer.verdict === item.verdict)) {
+ throw new BenchMarksError(`${model}'s answer on ${key} is not a disagreement to mark`, 400);
+ }
+ await setBenchMark(root, run, { model, key, verdict, answer: answer.verdict });
+ return { mark: verdict };
+}
+
+export { VERDICT_MEANINGS, VERDICT_TIE_RULE };
+
// The rows a filter keeps, disagreements first (then in item order).
export function filterBenchRows(rows: readonly BenchItemRow[], f: { model?: string; verdict?: string }): BenchItemRow[] {
const kept = rows.filter(