commit 291f5ff77eb853b7085e5eedb184ef5d0b699ed8
parent 458fbbf518bdae09c1ec17e6e52c33ff58d4934e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 15 Oct 2026 07:15:09 -0400
common, editor: verdict bench v2 — the verdicts' meanings in one place (verdicts.mjs VERDICT_MEANINGS + the CORROBORATED/PARTLY tie rule; the prompt, REPORT.md and the claim docs read them), the prompt to the operator's standard with reason before verdict, the report/section/speaker/date context and PROMPT_VERSION; window modes (seconds, the speaker's turn), dropped citations listed by reason, a stratified limit; --items-from, a resume that asks only its own models and refuses another prompt version, the items hash; not-CORROBORATED precision/recall, compareBenchRuns, markedScore over triage's markTally; the injected ask and a per-call trace; CLI/ops/route flags, COMMANDS.md, REPORT.md
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
21 files changed, 1253 insertions(+), 174 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/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/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:',