import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { errorTurn, startFakeAnthropic, toolTurn } from "../../../../testing/llm/fakeAnthropic.mjs"; import { jsonReply, reply, startFakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; import { cuesOf } from "../../../../testing/draft/corpus.mjs"; import { VERDICTS, type Verdict } from "../../verdicts"; import { BASELINE_MODEL, benchItemsOf, benchPrompt, benchReportsOf, benchRootOf, LOCAL_PROMPT_CAP, passesBar, planVerdictBench, validateBenchOptions, readBenchRun, runVerdictBench, scoreBench, VERDICT_BENCH_SYSTEM, VERDICT_ANSWER_SCHEMA, PROMPT_VERSION, benchItemsHash, compareBenchRuns, markedScore, stratifiedLimit, turnOf, readVerdictAnswer, verdictOfParts, sectionNamesVerdict, EVIDENCE_MAX, EVIDENCE_QUOTE_MAX, PARTS_MAX, PART_MAX, REASON_MAX, type BenchAsk, type BenchItem, type BenchResult, } from "./index"; import { VERDICT_MEANINGS, VERDICT_PARTS_RULE } from "../../verdicts"; import { CLAIM_FIELD_DOCS } from "../../schema"; import { renderReportMarkdown } from "../../docs"; import { promptEstimate } from "../../../llm/ollama"; const RULED = path.join(import.meta.dirname, "../../../../testing/draft/reports/ruled.report.json"); // The operator's rulings in the synthetic fact-check, by claim. const TRUTH: Record = { r01: "CORROBORATED", r02: "PARTLY", r03: "PARTLY", r04: "CONTRADICTED", r05: "CONTRADICTED", r06: "CORROBORATED", r07: "NOT_FOUND", }; async function store(mutate?: (r: any) => void) { const dir = await mkdtemp(path.join(os.tmpdir(), "bench-")); const report = JSON.parse(await readFile(RULED, "utf8")); mutate?.(report); await mkdir(path.join(dir, "reports", report.id), { recursive: true }); await writeFile(path.join(dir, "reports", report.id, "report.json"), JSON.stringify(report)); // A sweep beside it: never an item. await mkdir(path.join(dir, "reports", "a-sweep"), { recursive: true }); await writeFile( path.join(dir, "reports", "a-sweep", "report.json"), JSON.stringify({ format: "archilyzer-report", version: 1, id: "a-sweep", kind: "sweep", title: "A sweep", sections: [] }), ); const paths = { articlesDir: path.join(dir, "reports"), exportIndexDir: path.join(dir, "export-index"), generationUsageFile: path.join(dir, ".generation", "usage.jsonl"), }; return { dir, paths, done: () => rm(dir, { recursive: true, force: true }) }; } // A v3 answer (the parts and their findings) that makes verdict `v`. function answerOf(v: Verdict, reason: string) { const parts: Record = { CORROBORATED: [{ part: "what she said", finding: "shown" }], PARTLY: [{ part: "what she said", finding: "shown" }, { part: "the rest", finding: "not shown" }], CONTRADICTED: [{ part: "what she said", finding: "shown wrong" }], NOT_FOUND: [{ part: "what she said", finding: "not shown" }], UNTESTABLE: [], }; return { parts: parts[v], checkable: v !== "UNTESTABLE", reason }; } const claimOf = (user: string) => /^Claim: (.*)$/m.exec(user)?.[1] ?? ""; // The synthetic claims' texts, to answer by. async function claimTexts(): Promise> { const report = JSON.parse(await readFile(RULED, "utf8")); const out: Record = {}; for (const s of report.sections) for (const c of s.claims) out[c.text] = c.id; return out; } function userOf(body: any): string { const m = body.messages?.[0]?.content; return typeof m === "string" ? m : ""; } test("items: the ruled claims with cues; a claim with no citation skipped, with its reason; the answer kept off the prompt", async () => { const s = await store(); try { const reports = await benchReportsOf(s.paths); assert.deepEqual(reports.map((r) => r.id), ["synth-ruled"]); const { items, skipped } = await benchItemsOf(reports, { cuesOf, windowS: 60 }); assert.deepEqual(items.map((i) => i.claim), ["r01", "r02", "r03", "r04", "r05", "r06", "r07"]); assert.deepEqual(skipped, [{ key: "synth-ruled/r08", report: "synth-ruled", claim: "r08", reason: "no citation" }]); for (const it of items) assert.equal(it.verdict, TRUTH[it.claim]); const r04 = items.find((i) => i.claim === "r04")!; assert.equal(r04.windows.length, 1); const w = r04.windows[0]!; assert.equal(w.from, 150); assert.equal(w.to, 274.8); assert.ok(w.cues.length > 0 && w.cues.every((c) => c.end >= 150 && c.start <= 274.8)); // Nothing the check found is on an item, and the prompt never shows the verdict. for (const it of items) { assert.equal("findings" in it, false); const p = benchPrompt(it); assert.ok(p.user.includes(it.text)); assert.ok(p.user.includes(it.quotes[0]!.quote)); assert.ok(!p.user.includes(it.verdict), `${it.claim}'s prompt names its verdict`); } const findings = JSON.parse(await readFile(RULED, "utf8")).sections.flatMap((x: any) => x.claims).map((c: any) => c.findings); for (const it of items) for (const f of findings) assert.ok(!benchPrompt(it).user.includes(f)); } finally { await s.done(); } }); test("items: a citation whose recording has no cues, and a post-only claim, are skipped; a named report must be a fact-check", async () => { const s = await store((r) => { r.citations.q07.id = "no-such-recording"; r.citations.p1 = { kind: "post", channel: "synth-kitchen-posts", id: "p-1", quote: "a post" }; r.sections[1].claims[1].citations = ["q07"]; r.sections[1].claims.push({ id: "r09", text: "The article says she posted about it.", verdict: "CORROBORATED", citations: ["p1"] }); }); try { const { items, skipped } = await benchItemsOf(await benchReportsOf(s.paths, ["synth-ruled"]), { cuesOf }); assert.equal(items.length, 6); assert.deepEqual( skipped.map((x) => [x.claim, x.reason]), [ ["r07", "no cited recording has cues around the cited seconds"], ["r08", "no citation"], ["r09", "no video or audio citation"], ], ); await assert.rejects(benchReportsOf(s.paths, ["a-sweep"]), /a sweep, not a factcheck/); await assert.rejects(benchReportsOf(s.paths, ["nope"]), /no article "nope"/); } finally { await s.done(); } }); test("prompt: rules only (every verdict defined, no example); a local prompt's window trimmed to the cap, never the claim", async () => { for (const v of VERDICTS) assert.ok(VERDICT_BENCH_SYSTEM.includes(`- ${v}:`), v); assert.ok(!/example/i.test(VERDICT_BENCH_SYSTEM)); // A claim with a very long window: thousands of cues. const cues = Array.from({ length: 4000 }, (_, i) => ({ start: i * 5, end: i * 5 + 4.9, text: `line ${i} of a long stream about the bakery and the oven` })); const item: BenchItem = { key: "x/c1", report: "x", claim: "c1", text: "The article says the oven was broken.", verdict: "PARTLY", quotes: [{ citation: "q", channel: "c", id: "v", start: 10000, end: 10004.9, quote: "the oven was fine" }], windows: [{ channel: "c", id: "v", from: 0, to: 20000, cited: [{ start: 10000, end: 10004.9 }], cues }], }; const whole = benchPrompt(item); assert.equal(whole.cuesTrimmed, 0); assert.ok(whole.estimate > 8000); const local = benchPrompt(item, { capTokens: LOCAL_PROMPT_CAP }); assert.ok(local.cuesTrimmed > 0); assert.ok(local.estimate <= LOCAL_PROMPT_CAP && LOCAL_PROMPT_CAP < 8000); assert.equal(local.estimate, promptEstimate({ messages: [{ role: "system", content: local.system }, { role: "user", content: local.user }], format: (await import("./prompt")).VERDICT_ANSWER_SCHEMA })); assert.ok(local.user.includes("Claim: The article says the oven was broken.")); assert.ok(local.user.includes('"the oven was fine"')); // The cues nearest the cited span stay; the farthest go. assert.ok(local.user.includes("line 2000 of")); assert.ok(!local.user.includes("line 0 of")); assert.ok(!local.user.includes("line 3999 of")); }); test("score: agreement, the matrix, the recalls (PARTLY strict and adjacent), failures, and the always-CORROBORATED baseline", () => { const items = Object.entries(TRUTH).map(([claim, verdict]) => ({ key: `r/${claim}`, verdict })); const said: Record = { r01: "CORROBORATED", r02: "CORROBORATED", // adjacent r03: "PARTLY", r04: "CONTRADICTED", r05: "PARTLY", r06: "parse", r07: "NOT_FOUND", }; const results: BenchResult[] = Object.entries(said).map(([claim, v]) => ({ key: `r/${claim}`, model: "m", verdict: v === "parse" || v === "error" ? null : v, ...(v === "parse" ? { failure: "parse" as const } : {}), ms: 100, usd: 0.01, inputTokens: 10, outputTokens: 5, at: "", })); const s = scoreBench(items, results, ["m"]); const m = s.models[0]!; assert.equal(s.items, 7); assert.deepEqual(s.ruled, { CORROBORATED: 2, PARTLY: 2, CONTRADICTED: 2, NOT_FOUND: 1, UNTESTABLE: 0 }); assert.equal(m.asked, 7); assert.equal(m.answered, 6); assert.equal(m.parseFailures, 1); assert.equal(m.agreed, 4); // r01 r03 r04 r07 assert.equal(m.agreement, 0.5714); assert.equal(m.agreedAdjacent, 5); // + r02 const C = VERDICTS.indexOf("CORROBORATED"); const P = VERDICTS.indexOf("PARTLY"); const X = VERDICTS.indexOf("CONTRADICTED"); assert.equal(m.matrix[P]![C], 1); assert.equal(m.matrix[X]![P], 1); assert.equal(m.unanswered[C], 1); assert.deepEqual(m.recall.CONTRADICTED, { ruled: 2, matched: 1, recall: 0.5 }); assert.deepEqual(m.recall.NOT_FOUND, { ruled: 1, matched: 1, recall: 1 }); assert.deepEqual(m.recall.PARTLY, { ruled: 2, matched: 1, recall: 0.5 }); assert.deepEqual(m.recall.PARTLY_ADJACENT, { ruled: 2, matched: 2, recall: 1 }); assert.equal(m.usd, 0.07); assert.equal(m.latency.medianMs, 100); // The baseline: right on every CORROBORATED, finds no CONTRADICTED or NOT_FOUND. assert.equal(s.baseline.model, BASELINE_MODEL); assert.equal(s.baseline.agreement, 0.2857); assert.equal(s.baseline.agreementAdjacent, 0.5714); assert.equal(s.baseline.recall.CONTRADICTED.recall, 0); assert.equal(s.baseline.recall.NOT_FOUND.recall, 0); // The bar. assert.deepEqual(passesBar(m, { agreement: 0.5, contradictedRecall: 0.5, notFoundRecall: 0.5 }), { pass: true, misses: [] }); const fail = passesBar(m, { agreement: 0.6, contradictedRecall: 0.75, notFoundRecall: 0 }); assert.equal(fail.pass, false); assert.equal(fail.misses.length, 2); assert.equal(passesBar(s.baseline, { agreement: 0, contradictedRecall: 0.1, notFoundRecall: 0 }).pass, false); }); test("run: Sonnet over the fake API, qwen over the fake ollama — answers written as they land, scored, costed; a parse failure counted", async () => { const s = await store(); const texts = await claimTexts(); const api = await startFakeAnthropic(); const ol = await startFakeOllama(); // Sonnet: right on everything but r05 (PARTLY). for (let i = 0; i < 7; i++) { api.push((body: any) => { const id = texts[claimOf(userOf(body))]!; return toolTurn("answer", answerOf(id === "r05" ? "PARTLY" : TRUTH[id]!, `ruled on ${id} ${"x".repeat(400)}`)); }); } // qwen: always CORROBORATED, and r03's answer is not JSON (twice: the retry too). for (let i = 0; i < 8; i++) { ol.push((body: any) => { const id = texts[claimOf(body.messages[1].content)]!; return id === "r03" ? reply("I think it is partly true") : jsonReply(answerOf("CORROBORATED", "she says so")); }); } try { const lines: string[] = []; const out = await runVerdictBench( { runId: "vb-test", models: ["claude-sonnet-5-5", "qwen3:8b"] }, { paths: s.paths, cuesOf, llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }, ollama: { baseUrl: ol.url } }, log: (l) => lines.push(l), }, ); assert.equal(out.summary.status, "done"); assert.equal(out.dir, path.join(benchRootOf(s.paths), "vb-test")); assert.equal(api.requests.length, 7); // The strict model's way: the answer tool, tool_choice auto, no temperature. assert.equal(api.requests[0].tool_choice.type, "auto"); assert.equal(api.requests[0].tools[0].name, "answer"); // The findings never reach a model. for (const r of [...api.requests.map((b: any) => JSON.stringify(b)), ...ol.requests.map((b: any) => JSON.stringify(b))]) { assert.ok(!r.includes("She calls it a small place")); } const sonnet = out.summary.score.models[0]!; assert.equal(sonnet.model, "claude-sonnet-5-5"); assert.equal(sonnet.agreed, 6); assert.ok(sonnet.usd > 0); assert.ok(Math.abs(out.summary.spentUsd - sonnet.usd) < 1e-5); const qwen = out.summary.score.models[1]!; assert.equal(qwen.parseFailures, 1); assert.equal(qwen.agreed, 2); assert.equal(qwen.usd, 0); // On disk: the items (answer key included), every result, the summary. const run = (await readBenchRun(benchRootOf(s.paths), "vb-test"))!; assert.equal(run.items.length, 7); assert.equal(run.results.length, 14); assert.ok(run.results.every((r) => (r.reason ?? "").length <= 300)); assert.equal(run.summary.skipped.length, 1); assert.equal(run.summary.score.baseline.agreed, 2); assert.ok(lines.some((l) => l.startsWith("run vb-test: 7 items"))); } finally { await api.close(); await ol.close(); await s.done(); } }); test("run: the cap is checked before each API call — past it the run stops capped, with what it did", async () => { const s = await store(); const api = await startFakeAnthropic(); for (let i = 0; i < 7; i++) api.push(toolTurn("answer", answerOf("CORROBORATED", "ok"))); try { // One call costs about a cent at Opus 5.5's price; a two-cent cap stops early. const out = await runVerdictBench( { runId: "vb-cap", models: ["claude-opus-5-5"], maxUsd: 0.02 }, { paths: s.paths, cuesOf, llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } } }, ); assert.equal(out.summary.status, "capped"); assert.ok(api.requests.length >= 1 && api.requests.length < 7, `${api.requests.length} calls`); assert.ok(out.summary.spentUsd <= 0.02); assert.match(out.summary.stopped![0]!, /the cap/); assert.equal(out.summary.score.models[0]!.asked, api.requests.length); // A cap smaller than one call: nothing is sent at all. const none = await runVerdictBench( { runId: "vb-cap-0", models: ["claude-opus-5-5"], maxUsd: 0.0001 }, { paths: s.paths, cuesOf, llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } } }, ); assert.equal(none.summary.status, "capped"); assert.equal(none.summary.score.models[0]!.asked, 0); } finally { await api.close(); await s.done(); } }); test("run: a re-run with the same id resumes — answered pairs skipped, failed ones asked again; three errors in a row stop a model", async () => { const s = await store(); const texts = await claimTexts(); const api = await startFakeAnthropic(); const llm = { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }; // First run: r01–r03 answered, then three 400s in a row (not retried) stop the model. for (let i = 0; i < 3; i++) api.push((body: any) => toolTurn("answer", answerOf(TRUTH[texts[claimOf(userOf(body))]!]!, "ok"))); for (let i = 0; i < 3; i++) api.push(errorTurn(400, "invalid_request_error", "a bad request")); try { const first = await runVerdictBench({ runId: "vb-resume", models: ["claude-sonnet-5-5"] }, { paths: s.paths, cuesOf, llm }); assert.equal(first.summary.status, "done"); assert.equal(api.requests.length, 6); assert.match(first.summary.stopped![0]!, /stopped after 3 errors in a row/); assert.equal(first.summary.score.models[0]!.errors, 3); assert.equal(first.summary.score.models[0]!.asked, 6); // The re-run asks only the four not answered (three failed, one never asked). for (let i = 0; i < 4; i++) api.push((body: any) => toolTurn("answer", answerOf(TRUTH[texts[claimOf(userOf(body))]!]!, "ok"))); const again = await runVerdictBench({ runId: "vb-resume", models: ["claude-sonnet-5-5"] }, { paths: s.paths, cuesOf, llm }); assert.equal(api.requests.length, 10); const asked = api.requests.slice(6).map((b: any) => texts[claimOf(userOf(b))]); assert.deepEqual(asked, ["r04", "r05", "r06", "r07"]); assert.equal(again.summary.status, "done"); assert.equal(again.summary.score.models[0]!.agreed, 7); assert.equal(again.summary.score.models[0]!.errors, 0); assert.equal((await readBenchRun(benchRootOf(s.paths), "vb-resume"))!.results.length, 7); // The window is the run's: another one is refused. await assert.rejects(runVerdictBench({ runId: "vb-resume", models: ["claude-sonnet-5-5"], windowS: 30 }, { paths: s.paths, cuesOf, llm }), /60 s window/); } finally { await api.close(); await s.done(); } }); test("plan (the dry run): the items, the skipped, an estimate per model; nothing asked, nothing written", async () => { const s = await store(); try { const plan = await planVerdictBench({ models: ["claude-sonnet-5-5", "claude-opus-5-5", "qwen3:8b"], limit: 5 }, { paths: s.paths, cuesOf }); assert.equal(plan.items.length, 5); // The limit is stratified: every verdict ruled is kept; the rest are skipped, said so. assert.deepEqual([...new Set(plan.items.map((i) => i.verdict))].sort(), ["CONTRADICTED", "CORROBORATED", "NOT_FOUND", "PARTLY"]); assert.equal(plan.skipped.length, 3); assert.equal(plan.skipped.filter((x) => x.reason === "left out by the limit").length, 2); assert.equal(plan.promptVersion, PROMPT_VERSION); assert.match(plan.itemsHash, /^[0-9a-f]{16}$/); assert.deepEqual(plan.reports, ["synth-ruled"]); const [sonnet, opus, qwen] = plan.estimate; assert.ok(sonnet!.usd > 0 && opus!.usd > sonnet!.usd); assert.equal(qwen!.usd, 0); assert.equal(qwen!.provider, "local"); assert.equal(plan.estimateUsd, Math.round((sonnet!.usd + opus!.usd) * 10_000) / 10_000); await assert.rejects(readFile(path.join(benchRootOf(s.paths), "x")), /ENOENT/); await assert.rejects(planVerdictBench({ models: [] }, { paths: s.paths, cuesOf }), /at least one model/); await assert.rejects(planVerdictBench({ models: ["m"], maxUsd: 500 }, { paths: s.paths, cuesOf }), /over the bench's limit/); } finally { await s.done(); } }); // ─── release 29 V1: bench v2 ─── // A stubbed model (R6's injected ask): answers each claim from a table, and // records what it was asked. function stubAsk(answers: (model: string, id: string) => unknown, texts: Record) { const asked: { model: string; id: string; system: string; user: string; schema: any }[] = []; const ask: BenchAsk = async (system: string, user: string, schema: object, model: string) => { const id = texts[claimOf(user)]!; asked.push({ model, id, system, user, schema }); const a = answers(model, id); if (a instanceof Error) throw a; return a as T; }; return { ask, asked }; } test("V1/v3 prompt: the meanings are the shared module's, the parts rule is in, parts before the reason, the context shown, a version", async () => { for (const v of VERDICTS) assert.ok(VERDICT_BENCH_SYSTEM.includes(`- ${v}: ${VERDICT_MEANINGS[v]}`), v); assert.ok(VERDICT_BENCH_SYSTEM.includes(VERDICT_PARTS_RULE)); assert.match(VERDICT_MEANINGS.CORROBORATED, /substance/); assert.match(VERDICT_MEANINGS.PARTLY, /some parts .* at least one is not/); assert.ok(!/example|e\.g\./i.test(VERDICT_BENCH_SYSTEM)); assert.deepEqual(Object.keys(VERDICT_ANSWER_SCHEMA.properties), ["parts", "checkable", "reason"]); assert.deepEqual(VERDICT_ANSWER_SCHEMA.required, ["parts", "checkable", "reason"]); // The model names no verdict: the schema has none. assert.ok(!("verdict" in VERDICT_ANSWER_SCHEMA.properties)); assert.equal(typeof PROMPT_VERSION, "string"); // The same sentences in REPORT.md and the claim's docs: nowhere else spells them out. const md = renderReportMarkdown(); for (const v of VERDICTS) assert.ok(md.includes(VERDICT_MEANINGS[v]), `REPORT.md lacks ${v}'s meaning`); assert.ok(md.includes(VERDICT_PARTS_RULE)); assert.match(CLAIM_FIELD_DOCS.verdict, /what each means/); // The context: the report's title, the section, each quote's speaker (the channel) and date. const s = await store(); try { const { items } = await benchItemsOf(await benchReportsOf(s.paths), { cuesOf, dateOf: async (_c, id) => (id === "bread-day-01" ? "2026-01-05" : null), }); const r02 = items.find((i) => i.claim === "r02")!; assert.equal(r02.title, "Synth Kitchen — what an article says about the baker, checked"); assert.equal(r02.section, "The bakery"); const u = benchPrompt(r02).user; assert.match(u, /^Report: Synth Kitchen/m); assert.match(u, /^Section: The bakery$/m); assert.match(u, /"the oven was fine it just ran hot" \(speaker: synth-kitchen; recorded: 2026-01-05\)/); assert.match(u, /^## Bread day, 0:00 to 1:34 \(channel: synth-kitchen; recorded: 2026-01-05\)$/m); assert.ok(!u.includes(r02.verdict)); // A local prompt stays under the 8k cap with the longer system prompt. for (const it of items) assert.ok(benchPrompt(it, { capTokens: LOCAL_PROMPT_CAP }).estimate <= LOCAL_PROMPT_CAP); } finally { await s.done(); } }); test("V1 items: the turn mode — the speaker's segments, else a pause or a >> change — bounded by the window; drops listed by reason", async () => { const cues = [ { start: 0, end: 4, text: "hello" }, { start: 4.5, end: 8, text: "the oven" }, { start: 9, end: 12, text: "ran hot" }, { start: 16, end: 19, text: ">> no it did not" }, { start: 19.5, end: 22, text: "it was fine" }, ]; // No segments: back to the pause at 0 (none: the first cue), on until the >> change. assert.deepEqual(turnOf(cues, null, { start: 5, end: 7 }, 0, 100), { from: 0, to: 12, bound: "pause" }); // A >> cue starts its own turn: it runs on, never back. assert.deepEqual(turnOf(cues, null, { start: 17, end: 18 }, 0, 100), { from: 16, to: 22, bound: "pause" }); // The bound cuts a turn: `limit`. assert.deepEqual(turnOf(cues, null, { start: 5, end: 7 }, 3, 10), { from: 3, to: 10, bound: "limit" }); // Speaker segments win: speaker 1's run around the span. const segs = [ { start: 0, end: 4, speaker: 0 }, { start: 4, end: 9, speaker: 1 }, { start: 9, end: 13, speaker: 1 }, { start: 13, end: 22, speaker: 0 }, ]; assert.deepEqual(turnOf(cues, segs, { start: 5, end: 7 }, 0, 100), { from: 4, to: 13, bound: "speaker" }); const s = await store((r) => { // r01 cites a missing citation (dropped) and a post beside its span (v3: its evidence), the claim kept. r.citations.p1 = { kind: "post", channel: "synth-kitchen-posts", id: "p-1", quote: "a post" }; r.sections[0].claims[0].citations = ["q01", "p1", "gone"]; // r02's second citation is a recording with no cues: dropped. r.citations.q99 = { ...r.citations.q02, id: "no-such-recording" }; r.sections[0].claims[1].citations = ["q02", "q99"]; }); try { const reports = await benchReportsOf(s.paths); const secs = await benchItemsOf(reports, { cuesOf, windowS: 60 }); assert.deepEqual( secs.dropped.map((d) => [d.key, d.citation, d.reason]), [ ["synth-ruled/r01", "gone", "not in the report's citations"], ["synth-ruled/r02", "q99", "the recording has no cues"], ], ); assert.deepEqual(secs.items.find((i) => i.claim === "r01")!.evidence!.map((e) => e.citation), ["p1"]); assert.ok(secs.items.every((i) => i.windows.every((w) => w.bound === "seconds"))); // Turn mode over the synthetic cues (0.2 s apart: one long turn) is bounded by the window. const turn = await benchItemsOf(reports, { cuesOf, windowS: 10, windowMode: "turn" }); const r02 = turn.items.find((i) => i.claim === "r02")!; assert.equal(r02.windows[0]!.bound, "limit"); assert.equal(r02.windows[0]!.from, 20); assert.equal(r02.windows[0]!.to, 44.8); // With the speaker's segments: exactly the turn. const turns = await benchItemsOf(reports, { cuesOf, windowS: 60, windowMode: "turn", turnsOf: async (_c, id) => (id === "bread-day-01" ? [{ start: 0, end: 25, speaker: 0 }, { start: 25, end: 40, speaker: 1 }, { start: 40, end: 70, speaker: 0 }] : null), }); const w = turns.items.find((i) => i.claim === "r02")!.windows[0]!; assert.deepEqual([w.from, w.to, w.bound], [25, 40, "speaker"]); assert.deepEqual(w.cues.map((c) => c.start), [25, 30, 35, 40]); } finally { await s.done(); } }); test("V1 stratified limit: every verdict kept, in proportion, the rest by the largest remainder; order kept", () => { const mk = (n: number, v: Verdict) => Array.from({ length: n }, (_, i) => ({ key: `${v}-${i}`, verdict: v })); const items = [...mk(78, "CORROBORATED"), ...mk(58, "PARTLY"), ...mk(6, "NOT_FOUND"), ...mk(4, "CONTRADICTED"), ...mk(1, "UNTESTABLE")]; const { kept, left } = stratifiedLimit(items, 20); assert.equal(kept.length, 20); assert.equal(left.length, 127); const count = (v: Verdict) => kept.filter((k) => k.verdict === v).length; assert.deepEqual(VERDICTS.map(count), [10, 7, 1, 1, 1]); assert.deepEqual(kept.slice(0, 2).map((k) => k.key), ["CORROBORATED-0", "CORROBORATED-1"]); // Smaller than the verdicts: the rarest first. assert.deepEqual(stratifiedLimit(items, 2).kept.map((k) => k.verdict), ["CONTRADICTED", "UNTESTABLE"]); assert.equal(stratifiedLimit(items, 500).kept.length, 147); }); test("V1 run: the injected ask, reason before verdict, a per-call trace; --items-from takes the exact items; a resume asks only its own models; another prompt version is refused", async () => { const s = await store(); const texts = await claimTexts(); // Sonnet right everywhere; qwen says PARTLY on r01, right elsewhere. const { ask, asked } = stubAsk((model, id) => answerOf(model === "qwen3:8b" && id === "r01" ? "PARTLY" : TRUTH[id]!, `on ${id}`), texts); const root = benchRootOf(s.paths); try { const first = await runVerdictBench({ runId: "vb-one", models: ["claude-sonnet-5-5", "qwen3:8b"] }, { paths: s.paths, cuesOf, llm: {}, ask }); assert.equal(first.summary.status, "done"); assert.equal(asked.length, 14); assert.equal(first.summary.promptVersion, PROMPT_VERSION); assert.equal(first.summary.windowMode, "seconds"); assert.match(first.summary.itemsHash!, /^[0-9a-f]{16}$/); assert.deepEqual(Object.keys(asked[0]!.schema.properties), ["parts", "checkable", "reason"]); // The trace: a start line and one line per call with the prompt the model saw and its answer. const trace = (await readFile(path.join(root, "vb-one", "trace.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); assert.equal(trace[0].t, "start"); assert.equal(trace[0].promptVersion, PROMPT_VERSION); const calls = trace.filter((l) => l.t === "call"); assert.equal(calls.length, 14); assert.ok(calls[0].user.startsWith("Report: ")); assert.deepEqual(calls[0].answer, answerOf("CORROBORATED", "on r01")); // A run from vb-one's items: the same items, the same hash; only qwen asked. asked.length = 0; const two = await runVerdictBench({ runId: "vb-two", models: ["qwen3:8b"], itemsFrom: "vb-one" }, { paths: s.paths, cuesOf, llm: {}, ask }); assert.equal(two.summary.itemsFrom, "vb-one"); assert.equal(two.summary.itemsHash, first.summary.itemsHash); assert.equal(asked.length, 7); assert.ok(asked.every((a) => a.model === "qwen3:8b")); // Resume with Sonnet too: only Sonnet is asked; qwen's pairs are not re-asked. asked.length = 0; const again = await runVerdictBench({ runId: "vb-two", models: ["claude-sonnet-5-5"] }, { paths: s.paths, cuesOf, llm: {}, ask }); assert.equal(asked.length, 7); assert.ok(asked.every((a) => a.model === "claude-sonnet-5-5")); assert.deepEqual(again.summary.models, ["qwen3:8b", "claude-sonnet-5-5"]); // A resume with qwen alone asks nothing. asked.length = 0; await runVerdictBench({ runId: "vb-two", models: ["qwen3:8b"] }, { paths: s.paths, cuesOf, llm: {}, ask }); assert.equal(asked.length, 0); // A resume with another limit is refused (review fix 5). await assert.rejects(runVerdictBench({ runId: "vb-two", models: ["qwen3:8b"], limit: 3 }, { paths: s.paths, cuesOf, llm: {}, ask }), /with no limit: drop the limit/); // items-from refuses what would change the items, and a run that does not exist. await assert.rejects(runVerdictBench({ runId: "vb-x", models: ["m"], itemsFrom: "vb-one", limit: 3 }, { paths: s.paths, cuesOf, llm: {}, ask }), /drop the limit/); await assert.rejects(runVerdictBench({ runId: "vb-x", models: ["m"], itemsFrom: "vb-nope" }, { paths: s.paths, cuesOf, llm: {}, ask }), /no run "vb-nope"/); // An M7 run (no prompt version) is not resumed under this one. const sum = JSON.parse(await readFile(path.join(root, "vb-one", "summary.json"), "utf8")); delete sum.promptVersion; await writeFile(path.join(root, "vb-one", "summary.json"), JSON.stringify(sum)); await assert.rejects(runVerdictBench({ runId: "vb-one", models: ["qwen3:8b"] }, { paths: s.paths, cuesOf, llm: {}, ask }), /prompt version 1, and this is version/); // ... but its items are taken as they are, and fill the context M7's items lacked. const m7 = (await readBenchRun(root, "vb-one"))!; const bare = m7.items.map(({ title: _t, section: _s, ...rest }) => rest); await writeFile(path.join(root, "vb-one", "items.jsonl"), bare.map((i) => `${JSON.stringify(i)}\n`).join("")); asked.length = 0; const three = await runVerdictBench({ runId: "vb-three", models: ["qwen3:8b"], itemsFrom: "vb-one" }, { paths: s.paths, cuesOf, llm: {}, ask }); assert.equal(three.summary.itemsHash, first.summary.itemsHash); assert.match(asked[0]!.user, /^Section: /m); } finally { await s.done(); } }); test("V1 score: not-CORROBORATED precision and recall; two runs compared; the operator's marks on disagreements", () => { const items = Object.entries(TRUTH).map(([claim, verdict]) => ({ key: `r/${claim}`, verdict })); const res = (model: string, said: Record): BenchResult[] => Object.entries(said).map(([claim, v]) => ({ key: `r/${claim}`, model, verdict: v, ...(v ? {} : { failure: "parse" as const }), ms: 1, usd: 0, inputTokens: 0, outputTokens: 0, at: "" })); // Run A: PARTLY on both CORROBORATED (2 false flags), finds r02 r04 r07, misses r03 (CORROBORATED), r05 (failed). const a = res("m", { r01: "PARTLY", r02: "PARTLY", r03: "CORROBORATED", r04: "CONTRADICTED", r05: null, r06: "PARTLY", r07: "NOT_FOUND" }); const sa = scoreBench(items, a, ["m"]).models[0]!; // positives: r01 r02 r04 r06 r07 → tp r02 r04 r07 (3), fp r01 r06 (2); fn r03 r05 (2). assert.deepEqual(sa.notCorroborated, { tp: 3, fp: 2, fn: 2, precision: 0.6, recall: 0.6 }); assert.equal(scoreBench(items, a, ["m"]).baseline.notCorroborated.recall, 0); // Run B on the same items: r01 fixed, r04 broken. const b = res("m", { r01: "CORROBORATED", r02: "PARTLY", r03: "CORROBORATED", r04: "PARTLY", r05: null, r06: "PARTLY", r07: "NOT_FOUND" }); const cmp = compareBenchRuns({ items, results: a, models: ["m"] }, { items, results: b, models: ["m", "n"] }); assert.equal(cmp.items, 7); assert.equal(cmp.models.length, 1); const m = cmp.models[0]!; assert.deepEqual([m.a.agreed, m.b.agreed], [3, 3]); assert.deepEqual(m.changed, [ { key: "r/r01", ruled: "CORROBORATED", a: "PARTLY", b: "CORROBORATED" }, { key: "r/r04", ruled: "CONTRADICTED", a: "CONTRADICTED", b: "PARTLY" }, ]); assert.deepEqual([m.fixed, m.broke], [1, 1]); // Marks: r06's PARTLY marked Right (the model saw what the ruling missed), // r01's marked Wrong, and a stale mark (on an answer since changed) ignored. const marks = { m: { "r/r06": { verdict: "right" as const, answer: "PARTLY" as const, at: "" }, "r/r01": { verdict: "wrong" as const, answer: "PARTLY" as const, at: "" }, "r/r02": { verdict: "right" as const, answer: "CORROBORATED" as const, at: "" }, }, }; const ms = markedScore(items, a, "m", marks); assert.deepEqual(ms.marks, { marked: 2, right: 1, wrong: 1, precision: 0.5 }); assert.equal(ms.agreed, 4); assert.deepEqual(ms.notCorroborated, { tp: 4, fp: 1, fn: 2, precision: 0.8, recall: 0.6667 }); // The hash is the items' identity: context lines do not change it. const one = { key: "a", text: "The article says so.", verdict: "PARTLY" as const, quotes: [{ citation: "q", channel: "c", id: "v", start: 1, end: 2, quote: "so" }], windows: [] }; assert.equal(benchItemsHash([one]), benchItemsHash([{ ...one, title: "t", section: "s" } as typeof one])); // The claim's text and its quotes' spans are the items' identity too (review fix 6). assert.notEqual(benchItemsHash([one]), benchItemsHash([{ ...one, text: "The article says otherwise." }])); assert.notEqual(benchItemsHash([one]), benchItemsHash([{ ...one, quotes: [{ ...one.quotes[0]!, end: 3 }] }])); }); test("v3 answer: the verdict follows from the parts in code; the counts and lengths are held in code", () => { const P = (...f: string[]) => f.map((finding, i) => ({ part: `p${i}`, finding: finding as "shown" })); assert.equal(verdictOfParts(P("shown", "shown"), true), "CORROBORATED"); assert.equal(verdictOfParts(P("shown", "not shown"), true), "PARTLY"); assert.equal(verdictOfParts(P("shown", "shown wrong"), true), "PARTLY"); assert.equal(verdictOfParts(P("shown wrong", "not shown"), true), "CONTRADICTED"); assert.equal(verdictOfParts(P("shown wrong"), true), "CONTRADICTED"); assert.equal(verdictOfParts(P("not shown", "not shown"), true), "NOT_FOUND"); assert.equal(verdictOfParts(P("shown"), false), "UNTESTABLE"); assert.equal(verdictOfParts([], false), "UNTESTABLE"); assert.equal(verdictOfParts([], true), null); // Too many parts, a part too long, a reason too long: cut. A part with an // unknown finding is not a part. const many = Array.from({ length: PARTS_MAX + 3 }, (_, i) => ({ part: `${"w".repeat(PART_MAX + 50)}${i}`, finding: "shown" })); const a = readVerdictAnswer({ parts: [{ part: "x", finding: "maybe" }, ...many], checkable: true, reason: "r".repeat(REASON_MAX + 99) }); assert.ok(a.ok); if (a.ok) { assert.equal(a.parts.length, PARTS_MAX); assert.ok(a.parts.every((p) => p.part.length === PART_MAX)); assert.equal(a.reason.length, REASON_MAX); assert.equal(a.verdict, "CORROBORATED"); } // The parts past the limit never count: a "not shown" seventh part leaves it CORROBORATED. const seventh = readVerdictAnswer({ parts: [...many.slice(0, PARTS_MAX), { part: "late", finding: "not shown" }], checkable: true, reason: "ok" }); assert.ok(seventh.ok && seventh.verdict === "CORROBORATED"); // Untestable with no parts; failures named. const u = readVerdictAnswer({ parts: [], checkable: false, reason: "an opinion" }); assert.ok(u.ok && u.verdict === "UNTESTABLE"); assert.deepEqual(readVerdictAnswer({ parts: [], checkable: true, reason: "x" }), { ok: false, error: "no part with a finding", reason: "x" }); assert.equal(readVerdictAnswer({ parts: [{ part: "a", finding: "shown" }], checkable: true, reason: " " }).ok, false); assert.equal(readVerdictAnswer({ verdict: "CORROBORATED", reason: "a v2 answer" }).ok, false); assert.equal(readVerdictAnswer(null).ok, false); }); test("v3 items: a claim's posts and pages are its evidence (quoted, never a note); a heading naming a verdict withheld; a repeated claim asked once", async () => { assert.equal(sectionNamesVerdict("Corroborated, with clips"), true); assert.equal(sectionNamesVerdict("Only partially so"), true); assert.equal(sectionNamesVerdict("Not found anywhere"), true); assert.equal(sectionNamesVerdict("NOT_FOUND"), true); assert.equal(sectionNamesVerdict("Found on the stream"), false); assert.equal(sectionNamesVerdict("The bakery"), false); assert.equal(sectionNamesVerdict(undefined), false); const long = "y".repeat(EVIDENCE_QUOTE_MAX + 40); const s = await store((r) => { r.citations.p1 = { kind: "post", channel: "synth-kitchen-posts", id: "p-1", quote: "the oven ran hot all week", label: "post, 2026-01-06", speaker: "synth-kitchen", date: "2026-01-06" }; r.citations.g1 = { kind: "page", url: "https://example.invalid/a", title: "A page", quote: long, note: "the checker's own comment" }; r.citations.s1 = { kind: "source", source: "the-article", quote: "the claim's own sentence" }; for (let i = 0; i < EVIDENCE_MAX; i++) r.citations[`px${i}`] = { kind: "post", channel: "synth-kitchen-posts", id: `px-${i}`, quote: `post ${i}` }; r.sections[0].claims[1].citations = ["q02", "p1", "g1", "s1"]; r.sections[0].claims[2].citations = ["q03", ...Array.from({ length: EVIDENCE_MAX }, (_, i) => `px${i}`), "p1"]; r.sections[1].title = "Only partially so"; }); try { const reports = await benchReportsOf(s.paths); const { items, dropped } = await benchItemsOf(reports, { cuesOf }); const r02 = items.find((i) => i.claim === "r02")!; assert.deepEqual(r02.evidence!.map((e) => [e.citation, e.kind]), [["p1", "post"], ["g1", "page"]]); assert.equal(r02.evidence![1]!.quote.length, EVIDENCE_QUOTE_MAX); assert.equal(r02.evidence![1]!.title, "A page"); assert.ok(!JSON.stringify(r02).includes("the checker's own comment")); assert.deepEqual(dropped.filter((d) => d.key.endsWith("/r02")).map((d) => [d.citation, d.reason]), [["s1", "not a video, audio, post or page citation"]]); assert.equal(items.find((i) => i.claim === "r03")!.evidence!.length, EVIDENCE_MAX); assert.deepEqual(dropped.filter((d) => d.key.endsWith("/r03")).map((d) => d.citation), ["p1"]); // The prompt quotes the evidence, with who and when. const u = benchPrompt(r02).user; assert.match(u, /^Cited posts and pages:$/m); assert.match(u, /^- \[post, post, 2026-01-06\] "the oven ran hot all week" \(by: synth-kitchen; dated: 2026-01-06\)$/m); assert.match(u, /^- \[page, A page\] "y+…"$/m); // A heading that names a verdict is the answer: withheld. The other stays. assert.equal(items.find((i) => i.claim === "r06")!.section, undefined); assert.ok(!benchPrompt(items.find((i) => i.claim === "r06")!).user.includes("Section:")); assert.equal(r02.section, "The bakery"); // The hash covers the evidence; an item without any hashes as before v3. const bare = items.map(({ evidence: _e, ...rest }) => rest); assert.notEqual(benchItemsHash(items), benchItemsHash(bare)); assert.equal(benchItemsHash(bare), benchItemsHash(bare.map((i) => ({ ...i, evidence: [] })))); } finally { await s.done(); } // A report re-cut from another: its claims repeat the first's — asked once // with dedupe, every claim asked without it (the default; ruling 2026-10-17). const t = await store(); try { const report = JSON.parse(await readFile(RULED, "utf8")); report.id = "synth-ruled-recut"; report.sections[0].claims[0].text = "A claim this re-cut words differently."; await mkdir(path.join(t.paths.articlesDir, report.id), { recursive: true }); await writeFile(path.join(t.paths.articlesDir, report.id, "report.json"), JSON.stringify(report)); const reports = await benchReportsOf(t.paths); const all = await benchItemsOf(reports, { cuesOf }); assert.equal(all.items.length, 14); assert.equal(all.skipped.filter((x) => x.reason.startsWith("the same claim as")).length, 0); const { items, skipped } = await benchItemsOf(reports, { cuesOf, dedupe: true }); assert.equal(items.length, 8); assert.deepEqual(items.filter((i) => i.report === "synth-ruled-recut").map((i) => i.claim), ["r01"]); const same = skipped.filter((x) => x.reason.startsWith("the same claim as")); assert.equal(same.length, 6); assert.deepEqual(same[0], { key: "synth-ruled-recut/r02", report: "synth-ruled-recut", claim: "r02", reason: "the same claim as synth-ruled/r02" }); assert.equal((await benchItemsOf(reports, { cuesOf, dedupe: false })).items.length, 14); // The bench's option: a plan with dedupe asks 8, without it 14; dedupe // never goes with items-from (that run's items are taken as they are). assert.equal((await planVerdictBench({ models: ["qwen3:8b"] }, { paths: t.paths, cuesOf })).items.length, 14); assert.equal((await planVerdictBench({ models: ["qwen3:8b"], dedupe: true }, { paths: t.paths, cuesOf })).items.length, 8); assert.throws(() => validateBenchOptions({ models: ["qwen3:8b"], itemsFrom: "vb-x", dedupe: true }), /drop the dedupe/); } finally { await t.done(); } });