commit 896da18aa3c74e663f90549c7a1cc8289e11af4f
parent 0639c8dc2572ae5b64f521eaf27a611fb348586d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 15 Oct 2026 07:40:10 -0400
common, editor: verdict proposals (M8, code) — the sidecar reports/<id>/verdicts.proposed.json written only by lib/report/verdictProposals.ts under the article store's lock (record, review: approve sets the claim's verdict through patchArticle, reject marks it), the `verdicts` task (tasks/verdicts.ts: unruledItemsOfReport + benchPrompt, PROMPT_VERSION on each proposal; refuses a model not in settings.generation.verdicts.models; never writes a verdict; skips ruled and reviewed claims; capped), GENERATION_TASKS + every preset's route (verdictsModelOf), report-draft's dispatch and `claims` key (controller/reportVerdicts.ts: draft:local through the GPU arbiter or draft:api, the ledger, iteration 0), `pnpm ops verdict-review` (POST /api/ops/verdict-review); tests; COMMANDS.md, SETTINGS.md, REPORT.md, settings.json.example
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
17 files changed, 941 insertions(+), 12 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -145,8 +145,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` |
| `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` |
| `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` |
-| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "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` |
+| `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}}. "verdicts" proposes a verdict for each UNRULED claim of a fact-check ("article"; "claims"? only those; "model"?, "maxUsd"?): the verdict bench's prompt, one claim per call, on a model in settings.generation.verdicts.models only (refused otherwise; none named: the first of them on the verdicts route). No iteration (iteration 0): the proposals go to the article's verdicts.proposed.json, never report.json; a claim the operator ruled, or whose proposal was reviewed, is not asked. Its log ends with @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}. | `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`<br>`pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --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}'` |
+| `verdict-review` | verdict-review settles one verdict proposal: {"article", "claim", "decision": "approve" \| "reject", "note"?} -> {proposal}. approve sets the claim's verdict to the proposal's (through the registry; refused when the claim was ruled meanwhile); reject leaves the claim unruled. Synchronous. | `pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve"}'` |
| `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"}'` |
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` (what each means: "The verdicts", below). 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. Only the operator sets it: a model's proposal is kept in the article's `verdicts.proposed.json`, never here. |
| `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). |
@@ -135,6 +135,7 @@ An article made or revised by a model keeps each generation as an **iteration**,
- **Use this iteration** (umtool's Iterations tab) writes the article's `report.json` from a done iteration through the registry's writer: locked, validated, the article's `audience` and attached `video` kept. Nothing a generation runs writes the article's `report.json`; the next export records the change as the next Revision.
- Iterations are never published: compose, the homepage and the site history read only the article's own files.
- A directory with iterations and no `report.json` is an article **in the making**: the registry lists it neither as published nor as a draft until an iteration is made current.
+- **Verdict proposals** (release 29) are a sidecar, `verdicts.proposed.json` beside the article's `report.json` (`common/lib/report/verdictProposals.ts`): a model's proposed verdict, reason, model and prompt version per unruled claim, each `proposed`, `approved` or `rejected`. They are never in `report.json` (a claim's `verdict` is the operator's) and never published; approving one sets the claim's `verdict` through the registry.
- An iteration's video project is off the corpus disk, in `<settings.generation.projectsRoot>/<id>/i<n>/` (blank: `~/reports/articles`).
- `archilyzer reports iterations <id>` lists an article's iterations; `pnpm ops get iterations <id>` reads them from the editor.
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -1004,6 +1004,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `flips` | `"local"` | A media draft: THEN/NOW pairs over the cut's clips. |
| `threads` | `"local"` | A media draft: the cut's threads and each clip's thread. |
| `youtube` | `"local"` | A media draft: the YouTube title and description. |
+| `verdicts` | `"local"` | Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named. |
#### `generation.models`
@@ -1088,7 +1089,8 @@ Default:
"teaser": "local",
"flips": "local",
"threads": "local",
- "youtube": "local"
+ "youtube": "local",
+ "verdicts": "local"
},
"models": {
"api": "claude-sonnet-5-5",
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -131,6 +131,8 @@ export const REPORT_DRAFT_BODY_KEYS = [
"since",
"maxCandidates",
"triage",
+ // release 29 M8: a `verdicts` job's claims (default: every unruled one).
+ "claims",
] as const;
// A seed's size: a board of a few hundred quotes, with room.
@@ -178,6 +180,8 @@ export type ReportDraftBody = {
maxCandidates?: number;
// A sweep's: the triage it escalates ("<owner>/<k>").
triage?: { owner: string; k: number };
+ // A verdicts job's (release 29 M8): the claims to propose for.
+ claims?: string[];
};
// A Claude model the price table knows: one of its ids, or a dated id of one
@@ -324,6 +328,17 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
if (!m) fail('"triage" names a triage run: "<owner>/<k>"');
out.triage = { owner: m![1]!, k: Number(m![2]) };
}
+ // Verdict proposals (release 29 M8): the article's current report, no iteration.
+ const claims = list("claims");
+ if (claims !== undefined) {
+ if (out.task !== "verdicts") fail('"claims" is a verdicts job\'s (the claims to propose for)');
+ if (!claims.every((c) => /^[A-Za-z0-9._:-]{1,64}$/.test(c))) fail('"claims" is a list of claim ids');
+ out.claims = [...new Set(claims)];
+ }
+ if (out.task === "verdicts") {
+ const extra = (["iteration", "copyOf", "feedback", "question", "channels", "from", "to", "seed", "cards", "entries", "force", "autonomy", "ids", "source", "build"] as const).filter((k) => out[k] !== undefined);
+ if (extra.length) fail(`a verdicts job reads the article's current report: it takes no ${extra.join(", ")}`);
+ }
if (out.task === REFRESH_TASK) {
const extra = (["question", "channels", "from", "to", "feedback", "copyOf", "seed", "cards", "entries", "force", "autonomy"] as const).filter((k) => out[k] !== undefined);
if (extra.length) fail(`a refresh takes its question and scope from the iteration it refreshes — not ${extra.join(", ")}`);
@@ -362,7 +377,7 @@ function kindOf(task: GenerationTask): Iteration["kind"] {
}
const capOf = (task: GenerationTask): "sweep" | "revision" | "narration" =>
- isStepTask(task) ? "narration" : task === "revise-report" || task === "revise-video" ? "revision" : "sweep";
+ isStepTask(task) ? "narration" : task === "revise-report" || task === "revise-video" || task === "verdicts" ? "revision" : "sweep";
export function expandHome(p: string): string {
return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
@@ -474,6 +489,14 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
return refuse((e as Error).message);
}
}
+ if (body.task === "verdicts") {
+ try {
+ const { enqueueVerdictProposals } = await import("./reportVerdicts");
+ return await enqueueVerdictProposals(body, deps);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ }
if (body.task === REFRESH_TASK) {
if (body.dryRun) return refuse('a refresh\'s plan is planRefresh\'s ("dryRun": true at the ops route)');
try {
@@ -676,7 +699,8 @@ async function runReportDraft(
switch (body.task) {
case "refresh":
case "triage":
- // A refresh and a triage are their own jobs (./reportRefresh.ts, ./reportTriage.ts), never this one.
+ case "verdicts":
+ // A refresh, a triage and verdict proposals are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts), never this one.
throw new Error(`a ${body.task} runs as its own job`);
case "sweep":
input =
diff --git a/common/controller/reportVerdicts.ts b/common/controller/reportVerdicts.ts
@@ -0,0 +1,159 @@
+// `report-draft {"task": "verdicts", "article", "model"?, "claims"?, "maxUsd"?}`
+// — verdict proposals (release 29 M8) as an editor job, and the operator's
+// review of one (`verdict-review`).
+//
+// enqueueVerdictProposals refused unless the model is in
+// settings.generation.verdicts.models (verdictsModelOf),
+// the article is a fact-check, and (an API model) the
+// caps allow; then ONE `report-draft` job on the model's
+// lane: `draft:local` (every ollama call through the GPU
+// arbiter; ollama unloaded when the job ends) or
+// `draft:api` (metered, held to the revision cap and the
+// daily cap, its usage in the ledger as task `verdicts`).
+// The cues are the local corpus's (`diskCuesOf`), as the
+// bench reads them. No iteration is made: the answer's
+// `iteration` is 0. The log ends `@@report-draft {article,
+// iteration: 0, task: "verdicts", status, summary, usd,
+// verdicts: {proposed, failed, skipped}}`.
+// reviewProposal `pnpm ops verdict-review {article, claim, decision:
+// "approve" | "reject", note?}` (the editor's route and
+// umtool's article tab): approve sets the claim's verdict
+// through patchArticle, reject marks the proposal only
+// (lib/report/verdictProposals.ts).
+
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys";
+import { getSettings } from "../lib/settings";
+import { capFor } from "../lib/generationSettings";
+import { providerOf, unloadOllama } from "../lib/llm";
+import { diskCuesOf } from "../lib/report/convert-server";
+import { diskDateOf, diskTurnsOf } from "../lib/report/draft/bench/disk";
+import { benchReportsOf } from "../lib/report/draft/bench/index";
+import { usageOf } from "../lib/report/draft/tasks/run";
+import { proposeVerdicts, verdictsModelOf, VERDICTS_TASK, type VerdictsOutcome } from "../lib/report/draft/tasks/verdicts";
+import { reviewVerdictProposal, VerdictProposalsError, type ProposalReview } from "../lib/report/verdictProposals";
+import { isReportId } from "../lib/report/schema";
+import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
+import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft";
+
+export { VERDICTS_TASK };
+
+export async function enqueueVerdictProposals(body: ReportDraftBody, deps: ReportDraftDeps): Promise<ReportDraftEnqueued | { result: StreamActionResult & { ok: false } }> {
+ const refuse = (error: string) => ({ result: { ok: false as const, error } });
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ let model: string;
+ try {
+ model = verdictsModelOf(gen, body.model);
+ // A fact-check with report.json (benchReportsOf refuses anything else).
+ await benchReportsOf(paths, [body.article]);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const provider = providerOf(model);
+ let maxUsd: number | undefined;
+ if (provider === "api") {
+ try {
+ maxUsd = capFor(gen.caps, "revision", body.maxUsd);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily);
+ if (refusal) return refuse(refusal);
+ }
+ const result = await runManagedFunction({
+ kind: REPORT_DRAFT_JOB_KIND,
+ queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE,
+ paths,
+ fn: async (onLog, signal, setProgress, ctx) => {
+ const g = (deps.settings ?? getSettings)().generation;
+ if (provider === "api") {
+ // Again at the job's turn: jobs ahead in the queue may have spent the day.
+ const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily);
+ if (late) throw new Error(late);
+ }
+ onLog(`verdicts ${body.article} on ${model} (${provider === "api" ? `the Claude API, cap $${maxUsd}` : "the local model, through the GPU arbiter"})`);
+ let out: VerdictsOutcome | null = null;
+ try {
+ out = await proposeVerdicts(
+ { article: body.article, model, ...(body.claims?.length ? { claims: body.claims } : {}), ...(maxUsd !== undefined ? { maxUsd } : {}) },
+ {
+ paths,
+ cuesOf: diskCuesOf(paths.channelsDir),
+ turnsOf: diskTurnsOf(paths.channelsDir),
+ dateOf: diskDateOf(paths.channelsDir),
+ llm: llmConfigOf(g, paths, provider === "local" ? { onLog, signal } : undefined),
+ // Read again at the job's turn: a model unticked meanwhile is refused.
+ allowed: g.verdicts.models,
+ log: onLog,
+ progress: (done, total) => setProgress?.({ metric: "entries", initial: 0, target: Math.max(total, done), current: done }),
+ signal,
+ ...(deps.now ? { now: deps.now } : {}),
+ },
+ );
+ } finally {
+ if (provider === "local") {
+ await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, model).then(
+ () => onLog(`unloaded ${model} from ollama`),
+ (e) => onLog(`ollama unload failed: ${(e as Error).message}`),
+ );
+ }
+ }
+ if (provider === "api") {
+ const at = deps.now?.() ?? new Date();
+ const rows: GenerationUsageRow[] = Object.entries(out.byModel)
+ .filter(([, t]) => t.calls > 0)
+ .map(([m, t]) => {
+ const u = usageOf(t);
+ return {
+ at: at.toISOString(),
+ day: utcDay(at),
+ jobId: ctx.jobId,
+ article: body.article,
+ iteration: 0,
+ task: VERDICTS_TASK,
+ model: m,
+ inputTokens: u.inputTokens,
+ outputTokens: u.outputTokens,
+ cacheReadTokens: u.cacheReadTokens ?? 0,
+ cacheWriteTokens: u.cacheWriteTokens ?? 0,
+ usd: Math.round(u.usd * 10_000) / 10_000,
+ };
+ });
+ await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`));
+ }
+ onLog(
+ `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({
+ article: body.article,
+ iteration: 0,
+ task: VERDICTS_TASK,
+ status: out.status,
+ summary: out.summary,
+ usd: out.usd,
+ verdicts: { proposed: out.proposed.length, failed: out.failed.length, skipped: out.skipped.length, promptVersion: out.promptVersion },
+ })}`,
+ );
+ if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled");
+ },
+ });
+ if (!result.ok) return { result };
+ return { result, iteration: 0 };
+}
+
+// ─── verdict-review ───
+
+export const VERDICT_REVIEW_BODY_KEYS = ["article", "claim", "decision", "note"] as const;
+
+/** The body, judged without touching the disk. */
+export function parseVerdictReviewBody(b: Record<string, unknown>): ProposalReview {
+ if (!isReportId(b.article)) throw new VerdictProposalsError('"article" is an article id');
+ if (typeof b.claim !== "string" || !/^[A-Za-z0-9._:-]{1,64}$/.test(b.claim)) throw new VerdictProposalsError('"claim" is a claim id');
+ if (b.decision !== "approve" && b.decision !== "reject") throw new VerdictProposalsError('"decision" is "approve" or "reject"');
+ if (b.note !== undefined && b.note !== null && typeof b.note !== "string") throw new VerdictProposalsError('"note" is text');
+ return { article: b.article as string, claim: b.claim, decision: b.decision, ...(typeof b.note === "string" && b.note.trim() ? { note: b.note } : {}) };
+}
+
+export async function reviewProposal(raw: Record<string, unknown>, deps: Pick<ReportDraftDeps, "paths" | "now">) {
+ const r = parseVerdictReviewBody(raw);
+ return reviewVerdictProposal(r, deps.paths, deps.now?.() ?? new Date());
+}
diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts
@@ -18,7 +18,10 @@ export const MEDIA_STEP_TASKS = ["narrate", "cut", "onscreen", "teaser", "flips"
export type MediaStepTask = (typeof MEDIA_STEP_TASKS)[number];
export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "string" && (MEDIA_STEP_TASKS as readonly string[]).includes(t);
-export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube"] as const;
+// `verdicts` (release 29 M8): verdict proposals for a fact-check's unruled
+// claims — no iteration, no step: a sidecar beside the article, and only on a
+// model in `verdicts.models` (the bench's bar).
+export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "verdicts"] as const;
export type GenerationTask = (typeof GENERATION_TASKS)[number];
// The tasks every settings file since release 27 S6 routes.
const FIRST_TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate"];
@@ -30,10 +33,10 @@ export type GenerationRoute = (typeof GENERATION_ROUTES)[number];
const mediaRoutes = <R extends GenerationRoute>(r: R) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r }) as const;
export const GENERATION_PRESETS = {
- code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code") },
- balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local") },
- api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api") },
- local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local") },
+ code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code" },
+ balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local" },
+ api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api" },
+ local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local" },
} as const satisfies Record<string, Record<GenerationTask, GenerationRoute>>;
export type GenerationPreset = keyof typeof GENERATION_PRESETS;
export const GENERATION_PRESET_NAMES = Object.keys(GENERATION_PRESETS) as GenerationPreset[];
@@ -178,6 +181,8 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = {
flips: "A media draft: THEN/NOW pairs over the cut's clips.",
threads: "A media draft: the cut's threads and each clip's thread.",
youtube: "A media draft: the YouTube title and description.",
+ verdicts:
+ "Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named.",
};
export const GENERATION_MODELS_FIELD_DOCS: FieldDocs<GenerationModels> = {
diff --git a/common/lib/report/docs.ts b/common/lib/report/docs.ts
@@ -191,6 +191,13 @@ export function renderReportMarkdown(): string {
"registry lists it neither as published nor as a draft until an iteration is made current.",
);
out.push(
+ "- **Verdict proposals** (release 29) are a sidecar, `verdicts.proposed.json` beside the " +
+ "article's `report.json` (`common/lib/report/verdictProposals.ts`): a model's proposed " +
+ "verdict, reason, model and prompt version per unruled claim, each `proposed`, `approved` or " +
+ "`rejected`. They are never in `report.json` (a claim's `verdict` is the operator's) and never " +
+ "published; approving one sets the claim's `verdict` through the registry.",
+ );
+ out.push(
"- An iteration's video project is off the corpus disk, in " +
"`<settings.generation.projectsRoot>/<id>/i<n>/` (blank: `~/reports/articles`).",
);
diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts
@@ -61,6 +61,8 @@ export { pickCorpusBuild, listCorpusBuilds, siteOriginOf, NoCorpusBuildError, ty
export { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
export { checkQuotes, convertSweepText, dropFailedFindings, type QuoteProblem } from "./quotes";
export { projectDirOf } from "./project";
+// Release 29 M8: verdict proposals (a job of their own, no iteration: controller/reportVerdicts.ts).
+export { proposeVerdicts, verdictsModelOf, VerdictsRefusal, VERDICTS_TASK, type VerdictsDeps, type VerdictsInput, type VerdictsOutcome } from "./verdicts";
// umtool R4: the sweep's `ids` restriction (a general sweep option).
export { restrictEnumerateText, restrictTools } from "./restrict";
// umtool R3: a sweep's trace (trace.jsonl).
diff --git a/common/lib/report/draft/tasks/verdicts.test.ts b/common/lib/report/draft/tasks/verdicts.test.ts
@@ -0,0 +1,155 @@
+// Verdict proposals (release 29 M8): the task never writes a claim's verdict,
+// refuses a model that has not cleared the bar, skips what the operator has
+// ruled or reviewed; the sidecar survives makeCurrent; the operator's approve
+// sets the verdict through patchArticle. Temp stores and the synthetic corpus.
+//
+// Run with: node_modules/.bin/tsx --test lib/report/draft/tasks/verdicts.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { cuesOf } from "../../../../testing/draft/corpus.mjs";
+import { startFakeAnthropic, toolTurn } from "../../../../testing/llm/fakeAnthropic.mjs";
+import { articleFile, writeArticle } from "../../registry";
+import { createIteration, makeCurrent, updateIteration, writeIterationFile } from "../../iterations";
+import { readVerdictProposals, recordVerdictProposals, reviewVerdictProposal, verdictProposalsFile, waitingProposals } from "../../verdictProposals";
+import { sanitizeGeneration } from "../../../generationSettings";
+import { PROMPT_VERSION, type BenchAsk } from "../bench/index";
+import { proposeVerdicts, verdictsModelOf, VerdictsRefusal } from "./verdicts";
+
+const RULED = path.join(import.meta.dirname, "../../../../testing/draft/reports/ruled.report.json");
+const ROOTS: string[] = [];
+after(() => {
+ for (const r of ROOTS) rmSync(r, { recursive: true, force: true });
+});
+
+const NOW = new Date("2026-10-15T12:00:00.000Z");
+const QWEN = "qwen3:8b";
+
+// The synthetic fact-check with r02, r04 and r07 unruled (r08 unruled, no citation).
+async function store() {
+ const root = mkdtempSync(path.join(tmpdir(), "verdict-proposals-"));
+ ROOTS.push(root);
+ const paths = { articlesDir: path.join(root, "reports"), exportIndexDir: path.join(root, ".export-index") };
+ const report = JSON.parse(readFileSync(RULED, "utf8"));
+ for (const s of report.sections) for (const c of s.claims) if (["r02", "r04", "r07", "r08"].includes(c.id)) delete c.verdict;
+ await writeArticle(report, { paths });
+ return { paths, id: report.id as string, file: articleFile(paths, report.id) };
+}
+
+const claimOf = (user: string) => /^Claim: (.*)$/m.exec(user)?.[1] ?? "";
+
+function stub(answer: (claimText: string) => unknown) {
+ const asked: { model: string; user: string; system: string }[] = [];
+ const ask: BenchAsk = async <T,>(system: string, user: string, _schema: object, model: string) => {
+ asked.push({ model, user, system });
+ return answer(claimOf(user)) as T;
+ };
+ return { ask, asked };
+}
+
+test("the model: only one in verdicts.models — the asked one, else the first on the route; none, or code, refused", () => {
+ const gen = (models: string[], route: "api" | "local" | "code") => {
+ const g = sanitizeGeneration({ verdicts: { bar: { agreement: 0.6, contradictedRecall: 0.5, notFoundRecall: 0.5 }, models } });
+ g.routes.verdicts = route;
+ return g;
+ };
+ assert.equal(sanitizeGeneration({}).verdicts.models.length, 0);
+ assert.throws(() => verdictsModelOf(gen([], "local")), /models is empty/);
+ assert.equal(verdictsModelOf(gen([QWEN, "claude-opus-5-5"], "local")), QWEN);
+ assert.equal(verdictsModelOf(gen([QWEN, "claude-opus-5-5"], "api")), "claude-opus-5-5");
+ assert.throws(() => verdictsModelOf(gen([QWEN], "api")), /runs on the api route/);
+ assert.throws(() => verdictsModelOf(gen([QWEN], "code")), /routed to Claude Code/);
+ assert.equal(verdictsModelOf(gen([QWEN], "code"), QWEN), QWEN);
+ assert.throws(() => verdictsModelOf(gen([QWEN], "local"), "claude-sonnet-5-5"), VerdictsRefusal);
+ // Every preset routes verdicts.
+ assert.equal(sanitizeGeneration({}).routes.verdicts, "local");
+});
+
+test("proposals: the unruled claims only, the bench's prompt, written to the sidecar — never a verdict on a claim; an unlisted model refused", async () => {
+ const s = await store();
+ const before = readFileSync(s.file, "utf8");
+ const { ask, asked } = stub((text) => ({ reason: `the window shows it: ${text.slice(0, 20)}`, verdict: text.includes("oven") ? "PARTLY" : "NOT_FOUND" }));
+ await assert.rejects(proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: [], ask }), /models is empty/);
+ await assert.rejects(proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: ["claude-opus-5-5"], ask }), /has not cleared the verdict bench's bar/);
+ assert.equal(asked.length, 0);
+
+ const out = await proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: [QWEN], ask, now: () => NOW });
+ assert.equal(out.status, "done");
+ assert.deepEqual(out.proposed, ["r02", "r04", "r07"]);
+ // The ruled claims are not asked; r08 has no citation.
+ assert.equal(asked.length, 3);
+ assert.ok(out.skipped.some((x) => x.claim === "r01" && x.reason === "ruled by the operator"));
+ assert.ok(out.skipped.some((x) => x.claim === "r08" && x.reason === "no citation"));
+ assert.ok(asked[0]!.user.startsWith("Report: "));
+ // report.json is untouched: not a byte.
+ assert.equal(readFileSync(s.file, "utf8"), before);
+ const f = (await readVerdictProposals(s.id, s.paths))!;
+ assert.deepEqual(f.proposals.r02, { verdict: "PARTLY", reason: f.proposals.r02!.reason, model: QWEN, promptVersion: PROMPT_VERSION, at: NOW.toISOString(), status: "proposed" });
+ assert.equal(waitingProposals(f).length, 3);
+ assert.equal(path.basename(verdictProposalsFile(s.paths, s.id)), "verdicts.proposed.json");
+});
+
+test("the sidecar survives makeCurrent; approve sets the verdict through patchArticle, reject leaves the claim; a reviewed proposal is never asked again", async () => {
+ const s = await store();
+ const { ask, asked } = stub(() => ({ reason: "shown", verdict: "CONTRADICTED" }));
+ await proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: [QWEN], ask, now: () => NOW });
+ // A new iteration made current replaces report.json whole: the proposals stay.
+ const report = JSON.parse(readFileSync(s.file, "utf8"));
+ await createIteration(s.id, { kind: "sweep", model: QWEN, question: "What does the article get right?" }, s.paths, NOW);
+ await writeIterationFile(s.id, 1, "report.json", { ...report, title: "Retitled" }, s.paths);
+ await updateIteration(s.id, 1, { status: "done" }, s.paths, NOW);
+ await makeCurrent(s.id, 1, s.paths, NOW);
+ assert.equal(JSON.parse(readFileSync(s.file, "utf8")).title, "Retitled");
+ assert.equal(waitingProposals(await readVerdictProposals(s.id, s.paths)).length, 3);
+
+ // Approve r04: the claim's verdict is set, the proposal approved.
+ const ok = await reviewVerdictProposal({ article: s.id, claim: "r04", decision: "approve" }, s.paths, NOW);
+ assert.equal(ok.status, "approved");
+ const claimVerdict = (id: string) => JSON.parse(readFileSync(s.file, "utf8")).sections.flatMap((x: any) => x.claims).find((c: any) => c.id === id).verdict;
+ assert.equal(claimVerdict("r04"), "CONTRADICTED");
+ // Reject r07, with a note: the claim stays unruled.
+ const no = await reviewVerdictProposal({ article: s.id, claim: "r07", decision: "reject", note: "the window is too short" }, s.paths, NOW);
+ assert.deepEqual([no.status, no.note], ["rejected", "the window is too short"]);
+ assert.equal(claimVerdict("r07"), undefined);
+ // Twice: refused. No proposal: 404.
+ await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r04", decision: "approve" }, s.paths, NOW), /approved already/);
+ await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r01", decision: "approve" }, s.paths, NOW), (e: any) => e.status === 404);
+
+ // A rerun: r04 is ruled now and r07's proposal was rejected — only r02 is asked.
+ asked.length = 0;
+ const again = await proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: [QWEN], ask, now: () => NOW });
+ assert.deepEqual(again.proposed, ["r02"]);
+ assert.equal(asked.length, 1);
+ assert.ok(again.skipped.some((x) => x.claim === "r07" && /rejected by the operator/.test(x.reason)));
+ // A reviewed proposal is never replaced by a record either.
+ const rec = await recordVerdictProposals(s.id, { r07: { verdict: "PARTLY", reason: "x", model: QWEN, promptVersion: PROMPT_VERSION, at: NOW.toISOString() } }, s.paths, NOW);
+ assert.deepEqual(rec, { written: [], kept: ["r07"] });
+
+ // A claim ruled by hand after its proposal: approving is refused, the verdict kept.
+ const r = JSON.parse(readFileSync(s.file, "utf8"));
+ for (const sec of r.sections) for (const c of sec.claims) if (c.id === "r02") c.verdict = "CORROBORATED";
+ await writeArticle(r, { paths: s.paths });
+ await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r02", decision: "approve" }, s.paths, NOW), /ruled already/);
+ assert.equal(claimVerdict("r02"), "CORROBORATED");
+});
+
+test("an API model: held to maxUsd before each call; the spend is the Meter's", async () => {
+ const s = await store();
+ const api = await startFakeAnthropic();
+ try {
+ for (let i = 0; i < 3; i++) api.push(toolTurn("answer", { reason: "shown", verdict: "PARTLY" }));
+ const out = await proposeVerdicts(
+ { article: s.id, model: "claude-opus-5-5", maxUsd: 0.015 },
+ { paths: s.paths, cuesOf, llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, allowed: ["claude-opus-5-5"] },
+ );
+ assert.equal(out.status, "capped");
+ assert.ok(out.proposed.length >= 1 && out.proposed.length < 3, `${out.proposed.length}`);
+ assert.ok(out.usd > 0 && out.usd <= 0.015);
+ assert.equal(api.requests.length, out.proposed.length);
+ } finally {
+ await api.close();
+ }
+});
diff --git a/common/lib/report/draft/tasks/verdicts.ts b/common/lib/report/draft/tasks/verdicts.ts
@@ -0,0 +1,196 @@
+// THE `verdicts` TASK (release 29 M8): proposed verdicts for a fact-check's
+// UNRULED claims, asked of a model that cleared the verdict bench's bar.
+//
+// It reads the article as the bench does — `unruledItemsOfReport` (the claims
+// with no verdict; each one's quotes and transcript window) — and asks each
+// claim with the bench's own prompt (`benchPrompt`, PROMPT_VERSION recorded on
+// every proposal), so a proposal is made exactly the way the model was
+// measured. One claim per call, sequential.
+//
+// What it writes: proposals, through the sidecar store
+// (../../verdictProposals.ts recordVerdictProposals — each as it lands).
+// What it NEVER writes: a claim's `verdict` (only the operator's review does,
+// through patchArticle). It REFUSES a model not in
+// `settings.generation.verdicts.models` (`allowed`: empty by default, so
+// nothing runs until the operator sets the bar and ticks a model). A claim the
+// operator has ruled is never asked; neither is one whose proposal the
+// operator has already approved or rejected.
+//
+// An API model is held to `maxUsd` (checked before each call against the
+// spend so far plus that call's estimate: past it the run ends `capped`).
+
+import { Meter, providerOf, StructuredAnswerError, structuredAnswer, type LlmConfig } from "../../../llm";
+import type { GenerationSettings } from "../../../generationSettings";
+import type { Paths } from "../../../paths";
+import type { CuesOf } from "../../convertShared";
+import { isVerdict } from "../../verdicts";
+import { readVerdictProposals, recordVerdictProposals, type NewProposal } from "../../verdictProposals";
+import {
+ benchPrompt,
+ benchReportsOf,
+ estimateCall,
+ LOCAL_PROMPT_CAP,
+ PROMPT_VERSION,
+ REASON_MAX,
+ unruledItemsOfReport,
+ VERDICT_ANSWER_SCHEMA,
+ type BenchAsk,
+ type BenchDropped,
+ type BenchSkipped,
+ type DateOf,
+ type TurnsOf,
+ type WindowMode,
+} from "../bench/index";
+
+export const VERDICTS_TASK = "verdicts" as const;
+const MAX_ANSWER_TOKENS = 1024;
+
+export class VerdictsRefusal extends Error {}
+
+/**
+ * The model proposals run on: the asked one, which must be in
+ * `verdicts.models`; else the first of them on the task's route (`api` or
+ * `local`). Refused when none is — nothing runs on a model the operator has
+ * not ticked.
+ */
+export function verdictsModelOf(gen: Pick<GenerationSettings, "verdicts" | "routes">, asked?: string): string {
+ const allowed = gen.verdicts.models;
+ if (!allowed.length) throw new VerdictsRefusal("no model has cleared the verdict bench's bar: settings.generation.verdicts.models is empty (tick a passing model on umtool's /tools/bench)");
+ if (asked) {
+ if (!allowed.includes(asked)) throw new VerdictsRefusal(`${asked} has not cleared the verdict bench's bar: settings.generation.verdicts.models is ${allowed.join(", ")}`);
+ return asked;
+ }
+ const route = gen.routes.verdicts;
+ if (route === "code") throw new VerdictsRefusal(`verdicts is routed to Claude Code (settings.generation.routes): name a model (${allowed.join(", ")})`);
+ const pick = allowed.find((m) => providerOf(m) === route);
+ if (!pick) throw new VerdictsRefusal(`no model in settings.generation.verdicts.models (${allowed.join(", ")}) runs on the ${route} route: name one, or route verdicts to ${route === "api" ? "local" : "api"}`);
+ return pick;
+}
+
+export type VerdictsInput = {
+ article: string;
+ model: string;
+ // Only these claims (default: every unruled one).
+ claims?: string[];
+ maxUsd?: number;
+ windowS?: number;
+ windowMode?: WindowMode;
+};
+
+export type VerdictsDeps = {
+ paths: Pick<Paths, "articlesDir" | "exportIndexDir">;
+ cuesOf: CuesOf;
+ turnsOf?: TurnsOf;
+ dateOf?: DateOf;
+ llm: LlmConfig;
+ // settings.generation.verdicts.models: the only models a proposal may run on.
+ allowed: readonly string[];
+ // The model, stubbed (tests; the bench's shape).
+ ask?: BenchAsk;
+ log?: (line: string) => void;
+ progress?: (done: number, total: number) => void;
+ signal?: AbortSignal;
+ now?: () => Date;
+ localCapTokens?: number;
+};
+
+export type VerdictsOutcome = {
+ status: "done" | "capped" | "cancelled";
+ article: string;
+ model: string;
+ promptVersion: string;
+ // The claims proposed for, in order.
+ proposed: string[];
+ failed: { claim: string; error: string }[];
+ skipped: BenchSkipped[];
+ dropped: BenchDropped[];
+ usd: number;
+ byModel: ReturnType<Meter["summary"]>["byModel"];
+ summary: string;
+};
+
+export async function proposeVerdicts(input: VerdictsInput, deps: VerdictsDeps): Promise<VerdictsOutcome> {
+ const { article, model } = input;
+ if (!deps.allowed.includes(model)) {
+ throw new VerdictsRefusal(
+ deps.allowed.length
+ ? `${model} has not cleared the verdict bench's bar: settings.generation.verdicts.models is ${deps.allowed.join(", ")}`
+ : "no model has cleared the verdict bench's bar: settings.generation.verdicts.models is empty",
+ );
+ }
+ const log = deps.log ?? (() => {});
+ const now = () => deps.now?.() ?? new Date();
+ const local = providerOf(model) === "local";
+ const localCap = deps.localCapTokens ?? LOCAL_PROMPT_CAP;
+ const [report] = await benchReportsOf(deps.paths, [article]);
+ const { items, skipped, dropped } = await unruledItemsOfReport(report!, {
+ cuesOf: deps.cuesOf,
+ ...(input.windowS !== undefined ? { windowS: input.windowS } : {}),
+ ...(input.windowMode ? { windowMode: input.windowMode } : {}),
+ ...(deps.turnsOf ? { turnsOf: deps.turnsOf } : {}),
+ ...(deps.dateOf ? { dateOf: deps.dateOf } : {}),
+ ...(input.claims?.length ? { claims: input.claims } : {}),
+ });
+ // A proposal the operator has reviewed is not asked again.
+ const prior = await readVerdictProposals(article, deps.paths);
+ const todo = items.filter((it) => {
+ const p = prior?.proposals[it.claim];
+ if (p && p.status !== "proposed") {
+ skipped.push({ key: it.key, report: article, claim: it.claim, reason: `its proposal was ${p.status} by the operator` });
+ return false;
+ }
+ return true;
+ });
+ log(`verdicts ${article} on ${model} (prompt version ${PROMPT_VERSION}): ${todo.length} unruled claim${todo.length === 1 ? "" : "s"} to propose for, ${skipped.length} skipped, ${dropped.length} citations dropped`);
+
+ const meter = new Meter();
+ const ask: BenchAsk =
+ deps.ask ??
+ (<T,>(system: string, user: string, schema: object, m: string) =>
+ structuredAnswer<T>({ llm: deps.llm, model: m, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens: MAX_ANSWER_TOKENS }));
+ const proposed: string[] = [];
+ const failed: VerdictsOutcome["failed"] = [];
+ let status: VerdictsOutcome["status"] = "done";
+ let done = 0;
+ deps.progress?.(0, todo.length);
+ for (const item of todo) {
+ if (deps.signal?.aborted) {
+ status = "cancelled";
+ break;
+ }
+ if (!local && input.maxUsd !== undefined) {
+ const next = estimateCall({ ...item, verdict: "CORROBORATED" }, model, localCap).usd;
+ if (meter.usd + next > input.maxUsd) {
+ status = "capped";
+ log(`stopped at the cap: $${meter.usd.toFixed(4)} spent, the next call (~$${next.toFixed(4)}) would pass $${input.maxUsd}`);
+ break;
+ }
+ }
+ const prompt = benchPrompt(item, local ? { capTokens: localCap } : {});
+ try {
+ const ans = await ask<{ verdict?: unknown; reason?: unknown }>(prompt.system, prompt.user, VERDICT_ANSWER_SCHEMA, model);
+ const reason = typeof ans?.reason === "string" ? ans.reason.trim().slice(0, REASON_MAX) : "";
+ if (!isVerdict(ans?.verdict) || !reason) throw new StructuredAnswerError(`not a verdict and a reason: ${JSON.stringify(ans ?? null).slice(0, 120)}`);
+ const p: NewProposal = { verdict: ans.verdict, reason, model, promptVersion: PROMPT_VERSION, at: now().toISOString() };
+ const { written } = await recordVerdictProposals(article, { [item.claim]: p }, deps.paths, now());
+ if (written.length) proposed.push(item.claim);
+ log(`${item.claim}: ${ans.verdict} — ${reason}`);
+ } catch (err) {
+ if (deps.signal?.aborted) {
+ status = "cancelled";
+ break;
+ }
+ const error = (err as Error).message.slice(0, 300);
+ failed.push({ claim: item.claim, error });
+ log(`${item.claim}: no proposal (${error})`);
+ }
+ deps.progress?.(++done, todo.length);
+ }
+ const usd = Math.round(meter.usd * 1e6) / 1e6;
+ const summary =
+ `${proposed.length} verdict${proposed.length === 1 ? "" : "s"} proposed on ${model}` +
+ (failed.length ? `, ${failed.length} failed` : "") +
+ (status === "capped" ? ", stopped at the cap" : status === "cancelled" ? ", cancelled" : "") +
+ (usd ? ` · $${usd.toFixed(4)}` : "");
+ return { status, article, model, promptVersion: PROMPT_VERSION, proposed, failed, skipped, dropped, usd, byModel: meter.summary().byModel, summary };
+}
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(", ")} (what each means: "The verdicts", below). 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. Only the operator sets it: a model's proposal is kept in the article's \`verdicts.proposed.json\`, never here.`,
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/verdictProposals.ts b/common/lib/report/verdictProposals.ts
@@ -0,0 +1,218 @@
+// VERDICT PROPOSALS (release 29 M8) — a model's proposed verdicts for a
+// fact-check's unruled claims, kept in a SIDECAR beside the article:
+//
+// transcripts/reports/<id>/verdicts.proposed.json
+// { format: "archilyzer-verdict-proposals", version: 1, article,
+// proposals: { "<claim id>": { verdict, reason, model, promptVersion, at,
+// status: "proposed" | "approved" | "rejected",
+// note?, reviewedAt? } },
+// updatedAt }
+//
+// NEVER in report.json: the claim schema is strict, and `makeCurrent`
+// (./iterations.ts) replaces the article's report.json whole, so a proposal
+// kept there would vanish with the next iteration. The sidecar is written
+// only here, under the article store's lock (./registry.ts
+// withArticleStoreLock), whole and atomic, as the store's other per-article
+// files are; reads are lock-free.
+//
+// A proposal never sets a verdict. The operator's review does: approve →
+// `patchArticle` sets the claim's `verdict` to the proposal's (refused when
+// the claim was ruled meanwhile), then the proposal is marked approved;
+// reject → the proposal is marked rejected (the claim stays unruled). A
+// reviewed proposal is never replaced by a later run, and a ruled claim is
+// never proposed (draft/tasks/verdicts.ts reads the unruled claims only).
+//
+// SERVER-ONLY (node:fs).
+
+import path from "node:path";
+import { getPaths, type Paths } from "../paths";
+import { readJsonFile, writeJsonAtomic } from "../jsonFile-server";
+import { ArticleRegistryError, articleDir, patchArticle, withArticleStoreLock } from "./registry";
+import type { Section } from "./schema";
+import { isVerdict, type Verdict } from "./verdicts";
+
+export const VERDICT_PROPOSALS_FILE = "verdicts.proposed.json";
+export const VERDICT_PROPOSALS_FORMAT = "archilyzer-verdict-proposals";
+export const VERDICT_PROPOSALS_VERSION = 1;
+export const PROPOSAL_STATUSES = ["proposed", "approved", "rejected"] as const;
+export type ProposalStatus = (typeof PROPOSAL_STATUSES)[number];
+export const PROPOSAL_NOTE_MAX = 500;
+export const PROPOSAL_REASON_MAX = 300;
+
+export type VerdictProposal = {
+ verdict: Verdict;
+ reason: string;
+ model: string;
+ promptVersion: string;
+ at: string;
+ status: ProposalStatus;
+ note?: string;
+ reviewedAt?: string;
+};
+
+export type VerdictProposalsFile = {
+ format: typeof VERDICT_PROPOSALS_FORMAT;
+ version: typeof VERDICT_PROPOSALS_VERSION;
+ article: string;
+ proposals: Record<string, VerdictProposal>;
+ updatedAt: string;
+};
+
+// A proposal as a run makes it: everything but its status.
+export type NewProposal = Omit<VerdictProposal, "status" | "note" | "reviewedAt">;
+
+type StorePaths = Pick<Paths, "articlesDir" | "exportIndexDir">;
+
+export class VerdictProposalsError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ this.name = "VerdictProposalsError";
+ }
+}
+
+const CLAIM_ID_RE = /^[A-Za-z0-9._:-]{1,64}$/;
+
+export function verdictProposalsFile(paths: StorePaths, article: string): string {
+ return path.join(articleDir(paths, article), VERDICT_PROPOSALS_FILE);
+}
+
+function clean(raw: unknown, article: string): VerdictProposalsFile {
+ const r = (raw ?? {}) as Record<string, unknown>;
+ const proposals: Record<string, VerdictProposal> = {};
+ const given = r.proposals && typeof r.proposals === "object" && !Array.isArray(r.proposals) ? (r.proposals as Record<string, unknown>) : {};
+ for (const [claim, v] of Object.entries(given)) {
+ const p = v as Record<string, unknown> | null;
+ if (!CLAIM_ID_RE.test(claim) || !p || !isVerdict(p.verdict) || !(PROPOSAL_STATUSES as readonly unknown[]).includes(p.status)) continue;
+ proposals[claim] = {
+ verdict: p.verdict,
+ reason: typeof p.reason === "string" ? p.reason.slice(0, PROPOSAL_REASON_MAX) : "",
+ model: typeof p.model === "string" ? p.model : "",
+ promptVersion: typeof p.promptVersion === "string" ? p.promptVersion : "",
+ at: typeof p.at === "string" ? p.at : "",
+ status: p.status as ProposalStatus,
+ ...(typeof p.note === "string" && p.note ? { note: p.note.slice(0, PROPOSAL_NOTE_MAX) } : {}),
+ ...(typeof p.reviewedAt === "string" ? { reviewedAt: p.reviewedAt } : {}),
+ };
+ }
+ return {
+ format: VERDICT_PROPOSALS_FORMAT,
+ version: VERDICT_PROPOSALS_VERSION,
+ article,
+ proposals,
+ updatedAt: typeof r.updatedAt === "string" ? r.updatedAt : "",
+ };
+}
+
+/**
+ * An article's proposals: null when it has none; a file that does not read as
+ * one is an error (409) — never taken for empty, so no write replaces it.
+ */
+export async function readVerdictProposals(article: string, paths: StorePaths = getPaths()): Promise<VerdictProposalsFile | null> {
+ const read = await readJsonFile(verdictProposalsFile(paths, article));
+ if (!read.ok) {
+ if (read.reason === "absent") return null;
+ throw new VerdictProposalsError(`reports/${article}/${VERDICT_PROPOSALS_FILE} is ${read.reason}`, 409);
+ }
+ const v = read.value as { format?: unknown };
+ if (!v || v.format !== VERDICT_PROPOSALS_FORMAT) throw new VerdictProposalsError(`reports/${article}/${VERDICT_PROPOSALS_FILE} is not an ${VERDICT_PROPOSALS_FORMAT} file`, 409);
+ return clean(read.value, article);
+}
+
+/** The proposals still waiting on the operator (status `proposed`). */
+export function waitingProposals(f: VerdictProposalsFile | null): [string, VerdictProposal][] {
+ return Object.entries(f?.proposals ?? {}).filter(([, p]) => p.status === "proposed");
+}
+
+/**
+ * Record a run's proposals, under the store's lock. A proposal the operator
+ * has reviewed (approved or rejected) is kept as it is; a waiting one is
+ * replaced by the newer. Answers which claims were written and which kept.
+ */
+export async function recordVerdictProposals(
+ article: string,
+ made: Record<string, NewProposal>,
+ paths: StorePaths = getPaths(),
+ now: Date = new Date(),
+): Promise<{ written: string[]; kept: string[] }> {
+ return withArticleStoreLock(async () => {
+ const cur = (await readVerdictProposals(article, paths)) ?? clean(null, article);
+ const written: string[] = [];
+ const kept: string[] = [];
+ for (const [claim, p] of Object.entries(made)) {
+ if (!CLAIM_ID_RE.test(claim)) throw new VerdictProposalsError(`"${claim}" is not a claim id`);
+ if (!isVerdict(p.verdict)) throw new VerdictProposalsError(`${claim}: "${String(p.verdict)}" is not a verdict`);
+ const was = cur.proposals[claim];
+ if (was && was.status !== "proposed") {
+ kept.push(claim);
+ continue;
+ }
+ cur.proposals[claim] = { verdict: p.verdict, reason: p.reason.slice(0, PROPOSAL_REASON_MAX), model: p.model, promptVersion: p.promptVersion, at: p.at, status: "proposed" };
+ written.push(claim);
+ }
+ if (written.length) {
+ cur.updatedAt = now.toISOString();
+ await writeJsonAtomic(verdictProposalsFile(paths, article), cur, { mkdir: true });
+ }
+ return { written, kept };
+ }, paths);
+}
+
+export type ProposalReview = { article: string; claim: string; decision: "approve" | "reject"; note?: string };
+
+/**
+ * The operator's review of one waiting proposal. Approve: the claim's
+ * `verdict` set to the proposal's through `patchArticle` (refused when the
+ * claim has been ruled since, or is gone), then the proposal marked approved.
+ * Reject: the proposal marked rejected; the claim is untouched. Answers the
+ * proposal as it now is.
+ */
+export async function reviewVerdictProposal(r: ProposalReview, paths: StorePaths = getPaths(), now: Date = new Date()): Promise<VerdictProposal & { claim: string }> {
+ if (r.decision !== "approve" && r.decision !== "reject") throw new VerdictProposalsError('"decision" is "approve" or "reject"');
+ const note = typeof r.note === "string" ? r.note.trim().slice(0, PROPOSAL_NOTE_MAX) : "";
+ const f = await readVerdictProposals(r.article, paths);
+ const p = f?.proposals[r.claim];
+ if (!p) throw new VerdictProposalsError(`${r.article} has no proposal for claim ${r.claim}`, 404);
+ if (p.status !== "proposed") throw new VerdictProposalsError(`${r.article}/${r.claim}'s proposal was ${p.status} already`, 409);
+ if (r.decision === "approve") {
+ const patched = await patchArticle(
+ r.article,
+ (report) => {
+ let found = false;
+ const sections = report.sections.map((s: Section) => ({
+ ...s,
+ ...(s.claims
+ ? {
+ claims: s.claims.map((c) => {
+ if (c.id !== r.claim) return c;
+ found = true;
+ if (isVerdict(c.verdict)) throw new ArticleRegistryError(`${r.article}/${r.claim} is ruled already (${c.verdict})`);
+ return { ...c, verdict: p.verdict };
+ }),
+ }
+ : {}),
+ }));
+ if (!found) throw new ArticleRegistryError(`${r.article} has no claim ${r.claim}`);
+ return { sections };
+ },
+ paths,
+ );
+ if (!patched) throw new VerdictProposalsError(`${r.article} has no report.json`, 404);
+ }
+ return withArticleStoreLock(async () => {
+ const cur = (await readVerdictProposals(r.article, paths)) ?? clean(null, r.article);
+ const was = cur.proposals[r.claim] ?? p;
+ const next: VerdictProposal = {
+ ...was,
+ status: r.decision === "approve" ? "approved" : "rejected",
+ reviewedAt: now.toISOString(),
+ ...(note ? { note } : {}),
+ };
+ cur.proposals[r.claim] = next;
+ cur.updatedAt = now.toISOString();
+ await writeJsonAtomic(verdictProposalsFile(paths, r.article), cur, { mkdir: true });
+ return { ...next, claim: r.claim };
+ }, paths);
+}
diff --git a/editor/app/api/ops/_verdicts.test.ts b/editor/app/api/ops/_verdicts.test.ts
@@ -0,0 +1,103 @@
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { CHANNELS } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+import { jsonReply, startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs";
+import { enqueueReportDraft, parseReportDraftBody, type ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft";
+import { parseVerdictReviewBody, reviewProposal } from "yt-dlp-transcript-common/controller/reportVerdicts";
+import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { readVerdictProposals } from "yt-dlp-transcript-common/lib/report/verdictProposals";
+import { articleFile } from "yt-dlp-transcript-common/lib/report/registry";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_verdicts.test.ts"
+//
+// Verdict proposals (release 29 M8) end to end in this process: report-draft
+// {task: "verdicts"} — the controller the route adapts — over the synthetic
+// fact-check (r02, r04, r07 unruled) in a temp article store, the synthetic
+// recordings' cues on disk and the fake ollama; then verdict-review's
+// controller (the editor's /api/ops/verdict-review adapts it).
+
+const RULED = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../common/testing/draft/reports/ruled.report.json");
+let tmp: string;
+let ol: FakeOllama;
+let paths: Paths;
+let gen: GenerationSettings;
+let id: string;
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "verdict-proposals-"));
+ ol = await startFakeOllama();
+ const report = JSON.parse(await readFile(RULED, "utf8"));
+ for (const s of report.sections) for (const c of s.claims) if (["r02", "r04", "r07"].includes(c.id)) delete c.verdict;
+ id = report.id;
+ await mkdir(path.join(tmp, "reports", id), { recursive: true });
+ await writeFile(path.join(tmp, "reports", id, "report.json"), JSON.stringify(report));
+ for (const ch of CHANNELS) {
+ for (const r of ch.records) {
+ const rec = path.join(tmp, "channels", ch.slug, "data", r.id);
+ await mkdir(rec, { recursive: true });
+ await writeFile(path.join(rec, "transcript.cues.json"), JSON.stringify({ cues: r.cues }));
+ }
+ }
+ paths = {
+ jobsDir: path.join(tmp, ".jobs"),
+ articlesDir: path.join(tmp, "reports"),
+ exportIndexDir: path.join(tmp, ".export-index"),
+ channelsDir: path.join(tmp, "channels"),
+ generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"),
+ ollamaUrl: ol.url,
+ } as Paths;
+ gen = sanitizeGeneration({});
+});
+
+after(async () => {
+ await ol.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+const deps = (g: Partial<GenerationSettings> = {}): ReportDraftDeps =>
+ ({ paths, settings: () => ({ generation: { ...gen, ...g } }), corpusTools: async () => { throw new Error("no corpus tools for verdicts"); } }) as unknown as ReportDraftDeps;
+
+test("the body: a verdicts job takes claims, never an iteration; claims are a verdicts job's", () => {
+ assert.deepEqual(parseReportDraftBody({ task: "verdicts", article: "a", claims: ["c1", "c2"] }), { task: "verdicts", article: "a", claims: ["c1", "c2"] });
+ assert.throws(() => parseReportDraftBody({ task: "verdicts", article: "a", iteration: 2 }), /takes no iteration/);
+ assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["c"], claims: ["c1"] }), /"claims" is a verdicts job's/);
+ assert.throws(() => parseVerdictReviewBody({ article: "a", claim: "c1", decision: "maybe" }), /"approve" or "reject"/);
+});
+
+test("refused until a model clears the bar; then a report-draft job on draft:local writes proposals, never a verdict; approve sets it", async () => {
+ const none = await enqueueReportDraft({ task: "verdicts", article: id }, deps());
+ assert.equal(none.result.ok, false);
+ assert.match((none.result as { error: string }).error, /models is empty/);
+ const unlisted = await enqueueReportDraft({ task: "verdicts", article: id, model: "qwen3:8b" }, deps({ verdicts: { bar: gen.verdicts.bar, models: ["claude-opus-5-5"] } }));
+ assert.match((unlisted.result as { error: string }).error, /has not cleared the verdict bench's bar/);
+
+ const before = await readFile(articleFile(paths, id), "utf8");
+ for (let i = 0; i < 3; i++) ol.push(jsonReply({ reason: "the window shows the opposite", verdict: "CONTRADICTED" }));
+ const out = await enqueueReportDraft({ task: "verdicts", article: id }, deps({ verdicts: { bar: gen.verdicts.bar, models: ["qwen3:8b"] } }));
+ assert.ok(out.result.ok, (out.result as { error?: string }).error);
+ assert.equal("iteration" in out ? out.iteration : null, 0);
+ const job = getRegistry().get(out.result.jobId)!;
+ assert.equal(job.kind, "report-draft");
+ assert.equal(job.queueKey, "draft:local");
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ const log = await readFile(job.logPath, "utf8");
+ assert.equal(done.status, "done", log);
+ assert.match(log, /@@report-draft \{"article":"synth-ruled","iteration":0,"task":"verdicts","status":"done"/);
+ assert.match(log, /unloaded qwen3:8b from ollama/);
+ assert.deepEqual(ol.unloads.at(-1), "qwen3:8b");
+ assert.equal(await readFile(articleFile(paths, id), "utf8"), before, "report.json untouched");
+ const f = (await readVerdictProposals(id, paths))!;
+ assert.deepEqual(Object.keys(f.proposals).sort(), ["r02", "r04", "r07"]);
+
+ const p = await reviewProposal({ article: id, claim: "r04", decision: "approve" }, { paths });
+ assert.equal(p.status, "approved");
+ const after = JSON.parse(await readFile(articleFile(paths, id), "utf8"));
+ assert.equal(after.sections.flatMap((s: any) => s.claims).find((c: any) => c.id === "r04").verdict, "CONTRADICTED");
+});
diff --git a/editor/app/api/ops/verdict-review/route.ts b/editor/app/api/ops/verdict-review/route.ts
@@ -0,0 +1,34 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { VERDICT_REVIEW_BODY_KEYS, reviewProposal } from "yt-dlp-transcript-common/controller/reportVerdicts";
+import { VerdictProposalsError } from "yt-dlp-transcript-common/lib/report/verdictProposals";
+import { ArticleRegistryError } from "yt-dlp-transcript-common/lib/report/registry";
+import { opsFail, ops } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { article, claim, decision: "approve" | "reject", note? }
+// -> { ok: true, proposal: {claim, verdict, reason, model, promptVersion, at, status, note?, reviewedAt} }
+//
+// The operator's review of one verdict PROPOSAL (release 29 M8): a model's
+// proposed verdict for an unruled fact-check claim, kept in
+// `reports/<article>/verdicts.proposed.json` (never report.json). Approve
+// sets the claim's `verdict` to the proposal's through the registry's
+// patchArticle, then marks the proposal approved; reject marks it rejected
+// and leaves the claim unruled. Synchronous. 404 no such proposal; 409 one
+// reviewed already, a claim ruled meanwhile, or a sidecar that does not read.
+//
+// AN ADAPTER: the rules are the controller's (controller/reportVerdicts.ts,
+// lib/report/verdictProposals.ts).
+export async function POST(request: Request) {
+ return ops(request, VERDICT_REVIEW_BODY_KEYS, async (body) => {
+ try {
+ const proposal = await reviewProposal(body, { paths: getPaths() });
+ return NextResponse.json({ ok: true, proposal });
+ } catch (e) {
+ if (e instanceof VerdictProposalsError) return opsFail(e.message, e.status);
+ if (e instanceof ArticleRegistryError) return opsFail(e.message, 409);
+ throw e;
+ }
+ });
+}
diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts
@@ -141,6 +141,8 @@ test("generation_policy sets a preset as its routes, and one route alone", async
flips: "api",
threads: "api",
youtube: "api",
+ // Verdict proposals (release 29 M8): on a model in verdicts.models only.
+ verdicts: "api",
},
},
},
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -113,6 +113,8 @@
// pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'
// pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait
// pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait
+// pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait
+// pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve"}'
// pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'
// 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}'
// pnpm ops report-schedule --json '{"action":"list"}'
@@ -423,6 +425,10 @@ const ACTIONS = [
// job — refreshed from their jobs, then approved (run through the editor) or
// rejected ({article, iteration, ids?, approve?, note?}). Synchronous.
"research-approve",
+ // VERDICT PROPOSALS (release 29 M8): the operator's review of one model's
+ // proposed verdict ({article, claim, decision: approve | reject, note?}):
+ // approve sets the claim's verdict through the registry. Synchronous.
+ "verdict-review",
// THE VERDICT BENCH (release 28 M7): ruled fact-check claims asked of each
// model, one per call ({models, run?, reports?, window?, windowMode?,
// maxUsd?, limit?, itemsFrom?}),
@@ -1297,6 +1303,19 @@ export function usage() {
' "dryRun": true answers {plan} and writes nothing. Its log ends with',
" @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted,",
" summary}}.",
+ ' "verdicts" proposes a verdict for each UNRULED claim of a fact-check',
+ ' ("article"; "claims"? only those; "model"?, "maxUsd"?): the verdict bench\'s',
+ " prompt, one claim per call, on a model in settings.generation.verdicts.models",
+ " only (refused otherwise; none named: the first of them on the verdicts",
+ " route). No iteration (iteration 0): the proposals go to the article's",
+ " verdicts.proposed.json, never report.json; a claim the operator ruled, or",
+ " whose proposal was reviewed, is not asked. Its log ends with",
+ " @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}.",
+ "",
+ 'verdict-review settles one verdict proposal: {"article", "claim",',
+ ' "decision": "approve" | "reject", "note"?} -> {proposal}. approve sets the',
+ " claim's verdict to the proposal's (through the registry; refused when the",
+ " claim was ruled meanwhile); reject leaves the claim unruled. Synchronous.",
"",
'research-approve settles a research run\'s acquisitions: {"article",',
' "iteration", "ids"?: ["p01", …], "approve"?: true | false, "note"?} ->',
diff --git a/settings.json.example b/settings.json.example
@@ -253,7 +253,8 @@
"teaser": "local",
"flips": "local",
"threads": "local",
- "youtube": "local"
+ "youtube": "local",
+ "verdicts": "local"
},
"models": {
"api": "claude-sonnet-5-5",