// 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, 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 // three errors in a row is stopped (the rest of its items stay unasked) and // the run goes on with the next. // // RESUME: a run id whose directory exists continues it — its items are the // stored ones, and each (item, model) pair already ANSWERED is skipped; a // failed one is asked again. 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"; import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, type LlmConfig } from "../../../llm"; import { ApiKeyError } from "../../../llm/anthropic"; import { CHARS_PER_TOKEN } from "../../../llm/ollama"; import type { CuesOf } from "../../convertShared"; import { 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, readVerdictAnswer, 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, writeBenchResults, writeBenchSummary, type BenchStatus, type BenchSummary, } from "./store"; export const DEFAULT_BENCH_MAX_USD = 5; // Above this a run is refused outright (the release's real run is ≤ $5). export const BENCH_MAX_USD_LIMIT = 50; // A model stopped after this many errors in a row. export const BENCH_ERROR_STREAK = 3; // The estimate's allowances per call: the tool definition and instruction // around the prompt, and the answer (with a strict model's possible re-ask). const CALL_OVERHEAD_TOKENS = 350; const ANSWER_TOKENS = 300; const MAX_ANSWER_TOKENS = 1024; export type BenchOptions = { // A run to continue, or the new run's id (default `vb-`). runId?: string; // The fact-checks to read (default: every one in the registry). 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; // Ask a claim that repeats an earlier one (same text, same cited spans) once // (items.ts SAME_CLAIM_REASON). Off by default: every claim is asked. dedupe?: boolean; }; // The model, injected (R6's shape; tests): a structured answer to the prompt. export type BenchAsk = (system: string, user: string, schema: object, model: string) => Promise; export type BenchDeps = { paths: Pick; // 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; // A local prompt's cap in tokens (default LOCAL_PROMPT_CAP, under the 8k). localCapTokens?: number; }; export type BenchModelEstimate = { model: string; provider: "api" | "local"; calls: number; inputTokens: number; outputTokens: number; usd: number }; export type BenchPlan = { items: BenchItem[]; skipped: BenchSkipped[]; dropped: BenchDropped[]; reports: string[]; windowS: number; windowMode: WindowMode; promptVersion: string; itemsHash: string; itemsFrom?: string; estimate: BenchModelEstimate[]; estimateUsd: number; }; export type ValidBenchOptions = { models: string[]; windowS: number; windowMode: WindowMode; maxUsd: number; limit?: number; itemsFrom?: string; dedupe?: true }; 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) { if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(m)) throw new BenchInputError(`"${m}" is not a model name`); } const windowS = o.windowS ?? DEFAULT_WINDOW_S; if (!Number.isFinite(windowS) || windowS < 0 || windowS > 600) throw new BenchInputError("the window is 0 to 600 seconds"); 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"); if (o.dedupe !== undefined && typeof o.dedupe !== "boolean") throw new BenchInputError("dedupe is true or false"); 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" : "", o.dedupe ? "dedupe" : ""].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 } : {}), ...(o.dedupe === true ? { dedupe: true as const } : {}), }; } // What one call to `model` about `item` would cost, by the prompt's size. export function estimateCall(item: BenchItem, model: string, localCapTokens = LOCAL_PROMPT_CAP): { inputTokens: number; outputTokens: number; usd: number } { const local = providerOf(model) === "local"; const p = benchPrompt(item, local ? { capTokens: localCapTokens } : {}); const inputTokens = Math.ceil((p.system.length + p.user.length + JSON.stringify(VERDICT_ANSWER_SCHEMA).length) / CHARS_PER_TOKEN) + CALL_OVERHEAD_TOKENS; const outputTokens = ANSWER_TOKENS; const price = priceOf(model); return { inputTokens, outputTokens, usd: (inputTokens * price.input + outputTokens * price.output) / 1e6 }; } function estimateOf(items: readonly BenchItem[], models: readonly string[], localCapTokens?: number): BenchModelEstimate[] { return models.map((model) => { let inputTokens = 0; let outputTokens = 0; let usd = 0; for (const it of items) { const e = estimateCall(it, model, localCapTokens); inputTokens += e.inputTokens; outputTokens += e.outputTokens; usd += e.usd; } return { model, provider: providerOf(model), calls: items.length, inputTokens, outputTokens, usd: Math.round(usd * 10_000) / 10_000 }; }); } type ItemSet = { items: BenchItem[]; skipped: BenchSkipped[]; dropped: BenchDropped[]; reports: string[]; windowS: number; windowMode: WindowMode; limit?: number; itemsFrom?: string; dedupe?: true; }; // 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): Promise { const reports = new Map>[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): Promise { 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 } : {}), ...(src.summary.dedupe ? { dedupe: true as const } : {}), itemsFrom: v.itemsFrom, }; } const reports = await benchReportsOf(deps.paths, o.reports); 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 } : {}), ...(v.dedupe ? { dedupe: true } : {}), }); return { ...got, reports: o.reports?.length ? [...new Set(o.reports)] : [], windowS: v.windowS, windowMode: v.windowMode, ...(v.limit !== undefined ? { limit: v.limit } : {}), ...(v.dedupe ? { dedupe: true as const } : {}), // (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): Promise { 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, }; } // `spent`: this invocation's spend per model (a resumed run's earlier spend is // in `summary.spentUsd`, not here) — what a job's usage ledger rows record. export type BenchOutcome = { id: string; dir: string; summary: BenchSummary; spent: ReturnType }; const round6 = (v: number) => Math.round(v * 1e6) / 1e6; export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise { const v = validateBenchOptions(o); const now = () => (deps.now ? deps.now() : new Date()); const log = deps.log ?? (() => {}); const root = deps.root ?? benchRootOf(deps.paths); const id = o.runId ?? newBenchRunId(now()); const dir = benchRunDir(root, id); const localCap = deps.localCapTokens ?? LOCAL_PROMPT_CAP; 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 set: ItemSet; let results: BenchResult[]; let models: 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.limit !== undefined && o.limit !== s.limit) { throw new BenchInputError(`run ${id} was made ${s.limit === undefined ? "with no limit" : `with a limit of ${s.limit}`}: drop the limit, or start a new run`); } if (o.dedupe !== undefined && o.dedupe !== (s.dedupe === true)) { throw new BenchInputError(`run ${id} was made ${s.dedupe ? "with" : "without"} dedupe: drop it, 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`); } 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 } : {}), ...(s.dedupe ? { dedupe: true as const } : {}), }; results = prior.results; models = [...s.models, ...v.models.filter((m) => !s.models.includes(m))]; createdAt = s.createdAt; log(`continuing run ${id}: ${set.items.length} items, ${results.filter((r) => r.verdict !== null).length} answers on disk; asking ${v.models.join(", ")}`); } else { set = await itemSetOf(v, o, { ...deps, root }); itemsHash = benchItemsHash(set.items); results = []; models = v.models; createdAt = now().toISOString(); await mkdir(dir, { recursive: true }); 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(); let status: BenchStatus = "running"; const stopped: string[] = []; const summaryOf = (): BenchSummary => ({ format: BENCH_FORMAT, version: BENCH_VERSION, id, createdAt, updatedAt: now().toISOString(), status, ...(stopped.length ? { stopped: [...stopped] } : {}), models, windowS: set.windowS, windowMode: set.windowMode, promptVersion: PROMPT_VERSION, itemsHash, ...(set.itemsFrom ? { itemsFrom: set.itemsFrom } : {}), maxUsd: v.maxUsd, reports: set.reports, ...(set.limit !== undefined ? { limit: set.limit } : {}), ...(set.dedupe ? { dedupe: true as const } : {}), spentUsd: round6(priorSpend + meter.usd), items: items.length, skipped: set.skipped, dropped: set.dropped, score: scoreBench(items, results, models), }); const save = async () => { await writeBenchResults(dir, results); await writeBenchSummary(dir, summaryOf()); }; const record = (r: BenchResult) => { const at = results.findIndex((x) => x.key === r.key && x.model === r.model); if (at >= 0) results[at] = r; else results.push(r); }; let traceBroken = false; const trace = async (line: Record) => { 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 ?? ((system: string, user: string, schema: object, model: string) => structuredAnswer({ 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 { // 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) { if (answered.has(`${model}\u0000${item.key}`)) continue; if (deps.signal?.aborted) { status = "cancelled"; stopped.push("cancelled"); break models; } if (!local) { const next = estimateCall(item, model, localCap).usd; const spent = priorSpend + meter.usd; if (spent + next > v.maxUsd) { status = "capped"; stopped.push(`the cap: $${spent.toFixed(4)} spent, the next call (~$${next.toFixed(4)}) would pass $${v.maxUsd}`); log(`stopped at the cap ($${spent.toFixed(4)} of $${v.maxUsd})`); break models; } } const prompt = benchPrompt(item, local ? { capTokens: localCap } : {}); const before = meter.summary().byModel[model]; const usdBefore = meter.usd; const t0 = Date.now(); let r: BenchResult; let raw: unknown = undefined; try { const ans = await ask(prompt.system, prompt.user, VERDICT_ANSWER_SCHEMA, model); raw = ans; // v3: the parts and their findings; the verdict follows in code. const read = readVerdictAnswer(ans); r = { key: item.key, model, verdict: read.ok ? read.verdict : null, ...(read.reason ? { reason: read.reason } : {}), ...(read.ok ? { parts: read.parts, ...(read.checkable ? {} : { checkable: false }) } : { failure: "parse" as const, error: read.error }), ms: Date.now() - t0, usd: 0, inputTokens: 0, outputTokens: 0, at: now().toISOString(), }; streak = 0; } catch (err) { if (deps.signal?.aborted) { status = "cancelled"; stopped.push("cancelled"); break models; } const parse = err instanceof StructuredAnswerError; r = { key: item.key, model, verdict: null, failure: parse ? "parse" : "error", error: (err as Error).message.slice(0, 300), ms: Date.now() - t0, usd: 0, inputTokens: 0, outputTokens: 0, at: now().toISOString(), }; if (parse) streak = 0; else streak++; if (err instanceof ApiKeyError) streak = BENCH_ERROR_STREAK; } const after = meter.summary().byModel[model]; r.usd = round6(meter.usd - usdBefore); r.inputTokens = (after?.input ?? 0) + (after?.cacheRead ?? 0) + (after?.cacheWrite ?? 0) - ((before?.input ?? 0) + (before?.cacheRead ?? 0) + (before?.cacheWrite ?? 0)); r.outputTokens = (after?.output ?? 0) - (before?.output ?? 0); if (prompt.cuesTrimmed) r.cuesTrimmed = prompt.cuesTrimmed; record(r); await save(); 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})`); log(`${model}: stopped after ${BENCH_ERROR_STREAK} errors in a row`); continue models; } } } if (status === "running") status = "done"; } catch (err) { status = "failed"; stopped.push((err as Error).message); await save(); throw err; } await save(); return { id, dir, summary: summaryOf(), spent: meter.summary() }; }