// THE VERDICT BENCH'S ITEMS (release 28 M7; release 29 V1; bench v3): one per // ruled fact-check claim. // // An item is a claim of a `kind: "factcheck"` article that carries the // operator's `verdict` and at least one span citation (video or audio) whose // recording has cues around the cited seconds: the claim's text, its context // (the report's title, the claim's section heading; each quote's speaker and // date), the cited quotes, the transcript WINDOW around each cited span — // overlapping windows of one recording merged — and (v3) the claim's cited // POSTS and PAGES as EVIDENCE: their quoted words, label, speaker and date // (never a page's `note`, which is the checker's own comment). Every other // claim is SKIPPED, and every citation of a kept claim that gives no window // and is not evidence is DROPPED, each with its reason, and counted: nothing // is left out silently. // // v3 also, from the diagnosis of bench v2's disagreements: // - a section heading that NAMES A VERDICT ("Only partially so", "Corroborated, // with clips") is withheld from the item: it is the answer, not context // (`sectionNamesVerdict`); // - a claim that repeats an earlier item — the same text over the same cited // spans, as a report re-cut from another carries — is SKIPPED as the same // claim (`benchItemsOf`'s `dedupe`) — counted once, asked once. OFF by // default (operator ruling 2026-10-17): a fresh bench asks every claim, and // dedupe is an explicit option (`--dedupe`, the body's `dedupe: true`). // // THE WINDOW MODES (V1): // seconds the cues within ±`windowS` of the cited span (M7's, the default) // turn the cited speaker's TURN: the recording's speaker segments // (`turnsOf`, the attribution sidecar) around the span, else the // cues run on until a pause of TURN_GAP_S or a `>>` speaker change — // bounded by ±`windowS` either way (a window's `bound` says which) // // The operator's `verdict` is the answer key: it is kept on the item for the // scorer, and the prompt (./prompt.ts) never reads it. The claim's `findings`, // `gist`, `flag` and `title` are never copied onto an item at all — they say // what the check found. // // The UNRULED mode (M8's proposals) is the same reading over the claims with // NO verdict: a ruled claim is skipped ("ruled by the operator"). // // The reports are read through the article registry (`listArticleDirs`, // `articleFile`, `parseReport`), never by globbing the corpus; the cues through // a `CuesOf` (the local corpus's `diskCuesOf`, or the synthetic corpus in tests). import { createHash } from "node:crypto"; import { readJsonFile } from "../../../jsonFile-server"; import type { Paths } from "../../../paths"; import { isSpanCitation, type Citation } from "../../../citations/schema"; import type { CuesOf } from "../../convertShared"; import { articleFile, listArticleDirs } from "../../registry"; import type { Claim, Report } from "../../schema"; import { parseReport } from "../../validate"; import { isVerdict, VERDICT_DEFAULTS, VERDICTS, type Verdict } from "../../verdicts"; export const DEFAULT_WINDOW_S = 60; export const WINDOW_MODES = ["seconds", "turn"] as const; export type WindowMode = (typeof WINDOW_MODES)[number]; export const isWindowMode = (v: unknown): v is WindowMode => typeof v === "string" && (WINDOW_MODES as readonly string[]).includes(v); // The turn mode with no speaker segments: a pause this long between two cues // ends the turn. export const TURN_GAP_S = 2; export type BenchCue = { start: number; end: number; text: string }; export type BenchQuote = { citation: string; channel: string; id: string; start: number; end: number; quote: string; label?: string; speaker?: string; date?: string; }; // What ended a window: the seconds either side (`seconds`), the speaker's own // segments (`speaker`), a pause or a speaker change in the cues (`pause`), or // the ±windowS bound a turn ran into (`limit`). export type WindowBound = "seconds" | "speaker" | "pause" | "limit"; // One recording's cues around the cited spans in it. export type BenchWindow = { channel: string; id: string; label?: string; from: number; to: number; // The cited spans in this window (for the trim: the cues nearest them stay). cited: { start: number; end: number }[]; cues: BenchCue[]; bound?: WindowBound; }; // A cited post or page (v3): what the operator read beside the transcript. export type BenchEvidence = { citation: string; kind: "post" | "page"; quote: string; // A post's channel, a page's title. channel?: string; title?: string; label?: string; speaker?: string; date?: string; }; // The most evidence an item carries, and the longest quote of one (code, not // the prompt, holds both). export const EVIDENCE_MAX = 8; export const EVIDENCE_QUOTE_MAX = 600; export type BenchItem = { // `/`: unique across a run. key: string; report: string; claim: string; text: string; // THE ANSWER: the operator's ruling. Never shown to a model. verdict: Verdict; quotes: BenchQuote[]; windows: BenchWindow[]; // v3: the claim's cited posts and pages (absent: none, or an item made before v3). evidence?: BenchEvidence[]; // Context for the model (V1): the report's title and the claim's section heading. title?: string; section?: string; }; // An unruled claim, read the same way (M8's proposals): no answer key. export type ClaimItem = Omit; export type BenchSkipped = { key: string; report: string; claim: string; reason: string }; // A citation of a KEPT claim that gave no window, and why. export type BenchDropped = { key: string; citation: string; reason: string }; export type BenchReport = { id: string; report: Report }; export type BenchItems = { items: BenchItem[]; skipped: BenchSkipped[]; dropped: BenchDropped[] }; // A recording's speaker segments (the attribution sidecar's), or null. export type SpeakerTurn = { start: number; end: number; speaker: number | string }; export type TurnsOf = (channel: string, id: string) => Promise; // A recording's own date (`YYYY-MM-DD`), for a quote whose citation names none. export type DateOf = (channel: string, id: string) => Promise; export type ItemOptions = { cuesOf: CuesOf; windowS?: number; windowMode?: WindowMode; turnsOf?: TurnsOf; dateOf?: DateOf; }; export class BenchInputError extends Error {} // The fact-checks the bench reads: every article of kind `factcheck` (or the // named ones, each of which must be one), in id order. export async function benchReportsOf( paths: Pick, ids?: readonly string[], ): Promise { const all = await listArticleDirs(paths); const wanted = ids && ids.length ? [...new Set(ids)] : null; if (wanted) { const missing = wanted.filter((id) => !all.includes(id)); if (missing.length) throw new BenchInputError(`no article ${missing.map((m) => `"${m}"`).join(", ")} in the registry`); } const out: BenchReport[] = []; for (const id of wanted ?? all) { const read = await readJsonFile(articleFile(paths, id)); if (!read.ok) { if (wanted) throw new BenchInputError(`article "${id}": report.json is ${read.reason}`); continue; } const parsed = parseReport(read.value, { id }); if (!parsed.ok) { if (wanted) throw new BenchInputError(`article "${id}": report.json does not parse as a report`); continue; } if (parsed.value.kind !== "factcheck") { if (wanted) throw new BenchInputError(`article "${id}" is a ${parsed.value.kind}, not a factcheck`); continue; } out.push({ id, report: parsed.value }); } return out; } const BOUND_RANK: Record = { seconds: 0, speaker: 1, pause: 2, limit: 3 }; function mergeWindows(windows: BenchWindow[]): BenchWindow[] { const byRecord = new Map(); for (const w of windows) { const k = `${w.channel}/${w.id}`; byRecord.set(k, [...(byRecord.get(k) ?? []), w]); } const out: BenchWindow[] = []; for (const list of byRecord.values()) { list.sort((a, b) => a.from - b.from); let cur: BenchWindow | null = null; for (const w of list) { if (cur && w.from <= cur.to) { cur.to = Math.max(cur.to, w.to); cur.cited.push(...w.cited); const seen = new Set(cur.cues.map((c) => `${c.start}`)); for (const c of w.cues) if (!seen.has(`${c.start}`)) cur.cues.push(c); cur.cues.sort((a, b) => a.start - b.start); if (w.bound && (!cur.bound || BOUND_RANK[w.bound] > BOUND_RANK[cur.bound])) cur.bound = w.bound; } else { if (cur) out.push(cur); cur = { ...w, cited: [...w.cited], cues: [...w.cues] }; } } if (cur) out.push(cur); } return out; } const VERDICT_WORDS_RE = new RegExp( [ ...VERDICTS.map((v) => v.replace(/_/g, "[ _]")), ...VERDICTS.map((v) => VERDICT_DEFAULTS[v].label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")), "corroborat", "contradict", "partially", "partly", "untestable", ].join("|"), "i", ); /** * Whether a section heading names a verdict (its code, its default label, or * a word of one: "Corroborated, with clips", "Only partially so") — the * operator's grouping of claims BY their ruling, which an item must not carry. * Pure. */ export function sectionNamesVerdict(title: string | undefined): boolean { return !!title && VERDICT_WORDS_RE.test(title); } const overlaps = (a: { start: number; end: number }, from: number, to: number) => a.end >= from && a.start <= to; const changesSpeaker = (text: string) => /^\s*>>/.test(text); /** * The cited speaker's turn around `span`, bounded by [lo, hi]: the speaker's * run of segments when `turns` has one over the span, else the cues run on * until a pause of TURN_GAP_S or a `>>` speaker change. The cited span is * always inside; a turn cut by the bound says `limit`. Pure. */ export function turnOf( cues: readonly BenchCue[], turns: readonly SpeakerTurn[] | null, span: { start: number; end: number }, lo: number, hi: number, ): { from: number; to: number; bound: WindowBound } { const clip = (from: number, to: number, bound: WindowBound) => ({ from: Math.max(lo, Math.min(from, span.start)), to: Math.min(hi, Math.max(to, span.end)), bound: from < lo || to > hi ? ("limit" as const) : bound, }); const segs = (turns ?? []).filter((s) => Number.isFinite(s.start) && Number.isFinite(s.end) && s.end > s.start).slice().sort((a, b) => a.start - b.start); let best = -1; let most = 0; segs.forEach((s, i) => { const o = Math.min(s.end, span.end) - Math.max(s.start, span.start); if (o > most) { most = o; best = i; } }); if (best >= 0) { const who = segs[best]!.speaker; let a = best; let b = best; while (a > 0 && segs[a - 1]!.speaker === who) a--; while (b < segs.length - 1 && segs[b + 1]!.speaker === who) b++; return clip(segs[a]!.start, segs[b]!.end, "speaker"); } const sorted = cues.slice().sort((x, y) => x.start - y.start); const hit = sorted.flatMap((c, i) => (overlaps(c, span.start, span.end) ? [i] : [])); if (!hit.length) return clip(span.start, span.end, "pause"); let a = hit[0]!; let b = hit[hit.length - 1]!; // Back: the cue before joins while there is no pause and the turn did not start here. while (a > 0 && !changesSpeaker(sorted[a]!.text) && sorted[a]!.start - sorted[a - 1]!.end < TURN_GAP_S) a--; // On: the next cue joins while there is no pause and it does not change the speaker. while (b < sorted.length - 1 && !changesSpeaker(sorted[b + 1]!.text) && sorted[b + 1]!.start - sorted[b]!.end < TURN_GAP_S) b++; return clip(sorted[a]!.start, sorted[b]!.end, "pause"); } function evidenceOf(id: string, c: Extract): BenchEvidence { const quote = c.quote.length > EVIDENCE_QUOTE_MAX ? `${c.quote.slice(0, EVIDENCE_QUOTE_MAX - 1)}…` : c.quote; return { citation: id, kind: c.kind, quote, ...(c.kind === "post" ? { channel: c.channel } : c.title ? { title: c.title } : {}), ...(c.label ? { label: c.label } : {}), ...(c.speaker ? { speaker: c.speaker } : {}), ...(c.date ? { date: c.date } : {}), }; } type ReadClaim = { ok: true; item: ClaimItem; dropped: BenchDropped[] } | { ok: false; reason: string }; // One claim's quotes and windows (its verdict is the caller's business). async function readClaim(r: BenchReport, sectionTitle: string, claim: Claim, o: ItemOptions): Promise { const windowS = o.windowS ?? DEFAULT_WINDOW_S; const mode = o.windowMode ?? "seconds"; const key = `${r.id}/${claim.id}`; const citations = (r.report.citations ?? {}) as Record; const dropped: BenchDropped[] = []; const ids = claim.citations ?? []; if (!ids.length) return { ok: false, reason: "no citation" }; const spans: (readonly [string, Citation])[] = []; const evidence: BenchEvidence[] = []; for (const id of ids) { const c = citations[id]; if (!c) dropped.push({ key, citation: id, reason: "not in the report's citations" }); else if (c.kind === "post" || c.kind === "page") { if (evidence.length >= EVIDENCE_MAX) dropped.push({ key, citation: id, reason: `past the ${EVIDENCE_MAX} posts and pages an item carries` }); else evidence.push(evidenceOf(id, c)); } else if (!isSpanCitation(c)) dropped.push({ key, citation: id, reason: "not a video, audio, post or page citation" }); else spans.push([id, c]); } if (!spans.length) return { ok: false, reason: "no video or audio citation" }; const quotes: BenchQuote[] = []; const windows: BenchWindow[] = []; for (const [cid, c] of spans) { if (!isSpanCitation(c)) continue; const cues = await o.cuesOf(c.channel, c.id).catch(() => null); if (!cues || !cues.length) { dropped.push({ key, citation: cid, reason: "the recording has no cues" }); continue; } const lo = Math.max(0, c.start - windowS); const hi = c.end + windowS; let from = lo; let to = hi; let bound: WindowBound = "seconds"; if (mode === "turn") { const turns = o.turnsOf ? await o.turnsOf(c.channel, c.id).catch(() => null) : null; ({ from, to, bound } = turnOf(cues, turns, { start: c.start, end: c.end }, lo, hi)); } const inWindow = cues.filter((q) => overlaps(q, from, to)).map((q) => ({ start: q.start, end: q.end, text: q.text })); if (!inWindow.length) { dropped.push({ key, citation: cid, reason: "no cues around the cited seconds" }); continue; } const date = c.date ?? (o.dateOf ? await o.dateOf(c.channel, c.id).catch(() => null) : null); quotes.push({ citation: cid, channel: c.channel, id: c.id, start: c.start, end: c.end, quote: c.quote, ...(c.label ? { label: c.label } : {}), ...(c.speaker ? { speaker: c.speaker } : {}), ...(date ? { date } : {}), }); windows.push({ channel: c.channel, id: c.id, ...(c.label ? { label: c.label } : {}), from, to, cited: [{ start: c.start, end: c.end }], cues: inWindow, bound }); } if (!quotes.length) return { ok: false, reason: "no cited recording has cues around the cited seconds" }; return { ok: true, item: { key, report: r.id, claim: claim.id, text: claim.text, quotes, windows: mergeWindows(windows), ...(evidence.length ? { evidence } : {}), ...(r.report.title ? { title: r.report.title } : {}), ...(sectionTitle && !sectionNamesVerdict(sectionTitle) ? { section: sectionTitle } : {}), }, dropped, }; } // The items of one report: its ruled claims with a span citation that has cues. export async function benchItemsOfReport(r: BenchReport, o: ItemOptions): Promise { const items: BenchItem[] = []; const skipped: BenchSkipped[] = []; const dropped: BenchDropped[] = []; for (const section of r.report.sections) { for (const claim of section.claims ?? []) { const key = `${r.id}/${claim.id}`; if (!isVerdict(claim.verdict)) { skipped.push({ key, report: r.id, claim: claim.id, reason: "no operator verdict" }); continue; } const got = await readClaim(r, section.title, claim, o); if (!got.ok) { skipped.push({ key, report: r.id, claim: claim.id, reason: got.reason }); continue; } dropped.push(...got.dropped); items.push({ ...got.item, verdict: claim.verdict }); } } return { items, skipped, dropped }; } // The UNRULED claims of one report (M8's proposals): every claim with no // verdict, read as a bench item is; a ruled claim is skipped. `claims` keeps // only those ids. export async function unruledItemsOfReport( r: BenchReport, o: ItemOptions & { claims?: readonly string[] }, ): Promise<{ items: ClaimItem[]; skipped: BenchSkipped[]; dropped: BenchDropped[] }> { const items: ClaimItem[] = []; const skipped: BenchSkipped[] = []; const dropped: BenchDropped[] = []; const only = o.claims?.length ? new Set(o.claims) : null; for (const section of r.report.sections) { for (const claim of section.claims ?? []) { if (only && !only.has(claim.id)) continue; const key = `${r.id}/${claim.id}`; if (isVerdict(claim.verdict)) { skipped.push({ key, report: r.id, claim: claim.id, reason: "ruled by the operator" }); continue; } const got = await readClaim(r, section.title, claim, o); if (!got.ok) { skipped.push({ key, report: r.id, claim: claim.id, reason: got.reason }); continue; } dropped.push(...got.dropped); items.push(got.item); } } return { items, skipped, dropped }; } export const LIMIT_REASON = "left out by the limit"; /** * A stratified `limit`: the items kept by the operator's verdict in proportion * to how many were ruled each way, at least one of each verdict there is (the * rarest first, when the limit is smaller than the verdicts), the rest by the * largest remainder. Within a verdict the first items are kept; the kept ones * stay in their order. Pure. */ export function stratifiedLimit(items: readonly T[], limit: number): { kept: T[]; left: T[] } { if (limit >= items.length) return { kept: [...items], left: [] }; const by = new Map(); for (const it of items) by.set(it.verdict, [...(by.get(it.verdict) ?? []), it]); const size = (v: Verdict) => by.get(v)!.length; const classes = [...by.keys()].sort((a, b) => size(a) - size(b) || VERDICTS.indexOf(a) - VERDICTS.indexOf(b)); const take = new Map(classes.map((v) => [v, 0])); let left = limit; for (const v of classes) { if (left <= 0) break; take.set(v, 1); left--; } if (left > 0) { const share = classes.map((v) => { const want = (limit * size(v)) / items.length; return { v, want, rem: want - Math.floor(want) }; }); for (const s of share) { const e = Math.min(left, Math.max(0, Math.min(size(s.v), Math.floor(s.want)) - take.get(s.v)!)); take.set(s.v, take.get(s.v)! + e); left -= e; } const order = share.slice().sort((a, b) => b.rem - a.rem || size(b.v) - size(a.v)); while (left > 0) { let moved = false; for (const s of order) { if (left <= 0) break; if (take.get(s.v)! < size(s.v)) { take.set(s.v, take.get(s.v)! + 1); left--; moved = true; } } if (!moved) break; } } const keep = new Set(); for (const v of classes) for (const it of by.get(v)!.slice(0, take.get(v)!)) keep.add(it); return { kept: items.filter((it) => keep.has(it)), left: items.filter((it) => !keep.has(it)) }; } export const SAME_CLAIM_REASON = "the same claim as"; // What makes two items the same claim: the text and the cited spans. const sameness = (i: Pick) => JSON.stringify([i.text.trim(), i.quotes.map((q) => [q.channel, q.id, q.start, q.end]).sort()]); // Every item of every report, in report then claim order; `dedupe: true` // (default off) skips a claim that repeats an earlier item (SAME_CLAIM_REASON // and its key); `limit` keeps a stratified sample (the rest are skipped, LIMIT_REASON). export async function benchItemsOf(reports: readonly BenchReport[], o: ItemOptions & { limit?: number; dedupe?: boolean }): Promise { const items: BenchItem[] = []; const skipped: BenchSkipped[] = []; const dropped: BenchDropped[] = []; const seen = new Map(); for (const r of reports) { const got = await benchItemsOfReport(r, o); skipped.push(...got.skipped); for (const it of got.items) { const same = o.dedupe === true ? seen.get(sameness(it)) : undefined; if (same) { skipped.push({ key: it.key, report: it.report, claim: it.claim, reason: `${SAME_CLAIM_REASON} ${same}` }); continue; } seen.set(sameness(it), it.key); items.push(it); dropped.push(...got.dropped.filter((d) => d.key === it.key)); } } if (o.limit === undefined || o.limit < 0 || o.limit >= items.length) return { items, skipped, dropped }; const { kept, left } = stratifiedLimit(items, o.limit); const keptKeys = new Set(kept.map((i) => i.key)); return { items: kept, skipped: [...skipped, ...left.map((i) => ({ key: i.key, report: i.report, claim: i.claim, reason: LIMIT_REASON }))], dropped: dropped.filter((d) => keptKeys.has(d.key)), }; } /** * The identity of a run's items, so two runs can be said to be over the SAME * items: each item's key, the claim's text, the operator's verdict, its quotes' * spans, its windows (recording, from, to, how many cues) and (v3) its posts' * and pages' quotes — not the context * lines, which a run made from an earlier run's items may add. 16 hex * characters of a sha256. */ export function benchItemsHash(items: readonly Pick[]): string { const canon = items .map((i) => ({ k: i.key, t: i.text, v: i.verdict, q: i.quotes.map((q) => [q.citation, q.channel, q.id, q.start, q.end, q.quote]), w: i.windows.map((w) => [w.channel, w.id, w.from, w.to, w.cues.length]), // v3's evidence, only when an item has some: an item before v3 hashes as it did. ...(i.evidence?.length ? { e: i.evidence.map((e) => [e.citation, e.kind, e.quote]) } : {}), })) .sort((a, b) => (a.k < b.k ? -1 : a.k > b.k ? 1 : 0)); return createHash("sha256").update(JSON.stringify(canon)).digest("hex").slice(0, 16); }