import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { benchItemsHash, benchRootOf, compareBenchRuns, listBenchRuns, markedScore, passesBar, readBenchMarks, readBenchRun, scoreBench, BASELINE_MODEL, M7_PROMPT_VERSION, type BenchItem, type BenchMarks, type BenchResult, type BenchScore, type BenchSummary, type MarkedScore, type RunCompare, type VerdictBar, } from "yt-dlp-transcript-common/lib/report/draft/bench/index"; import { VERDICT_MEANINGS, VERDICT_PARTS_RULE, VERDICTS, isVerdict, type Verdict } from "yt-dlp-transcript-common/lib/report/verdicts"; import { sanitizeGeneration, type GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings"; import { BenchMarksError, setBenchMark } from "./bench-marks.mjs"; import { askEditor, EditorError } from "@/lib/articles/generation"; // THE VERDICT BENCH, AS UMTOOL SEES IT (release 28 M7): the runs `archilyzer // reports bench-verdicts` wrote under the checkout's `.generation/bench/ // verdicts/` (local-only; read here, never written — but for the operator's // marks, V1), scored again from their items and results so the page and the // files cannot disagree, and the operator's bar — settings.generation.verdicts // — read from and written through the editor's settings action, as the // generation policy is. // // Bench v3 (release 30): each item row carries what the model saw (the // windows and the cited posts and pages) and each answer the model's parts. // // Release 29 V1: each run's prompt version and items hash (a run before V1: // version "1", its hash computed from its items), a comparison with another // run over the same items, the operator's Right/Wrong marks on disagreements // (marks.json beside the run, ./bench-marks.mjs) and the marked scores. // // SERVER-ONLY. export type BenchRunRow = Pick & { promptVersion: string; itemsHash: string; }; export type BenchItemRow = { key: string; report: string; claim: string; text: string; verdict: Verdict; // What the model saw beside the claim (bench v3): each window's span and // cues, and the cited posts and pages. windows: Pick[]; evidence: NonNullable; answers: Record< string, { verdict: Verdict | null; reason?: string; failure?: string; error?: string; mark?: "right" | "wrong"; parts?: BenchResult["parts"]; checkable?: false } >; // A model whose answer is not the operator's (failures included). disagree: string[]; }; export type BenchView = { summary: BenchSummary; promptVersion: string; itemsHash: string; score: BenchScore; // Each model's score with the operator's marks applied. marked: MarkedScore[]; items: BenchItemRow[]; // The other run, over the same items, this one is compared with. compare?: { with: string; promptVersion: string; result: RunCompare }; }; export function benchRoot(): string { return benchRootOf(getPaths()); } // A run's items hash: its summary's, else (a run before V1) computed from its items. async function hashOf(s: BenchSummary): Promise { if (s.itemsHash) return s.itemsHash; const run = await readBenchRun(benchRoot(), s.id).catch(() => null); return run ? benchItemsHash(run.items) : ""; } export async function readBenchRuns(): Promise { const out: BenchRunRow[] = []; for (const s of await listBenchRuns(benchRoot())) { out.push({ id: s.id, createdAt: s.createdAt, status: s.status, models: s.models, items: s.items, spentUsd: s.spentUsd, maxUsd: s.maxUsd, promptVersion: s.promptVersion ?? M7_PROMPT_VERSION, itemsHash: await hashOf(s), }); } return out; } function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], models: readonly string[], marks: BenchMarks = {}): BenchItemRow[] { const by = new Map(); for (const r of results) by.set(`${r.model}\u0000${r.key}`, r); return items.map((it) => { const answers: BenchItemRow["answers"] = {}; const disagree: string[] = []; for (const m of models) { const r = by.get(`${m}\u0000${it.key}`); if (!r) continue; const mk = marks[m]?.[it.key]; const mark = mk && r.verdict !== it.verdict && mk.answer === r.verdict ? mk.verdict : undefined; answers[m] = { verdict: r.verdict, ...(r.reason ? { reason: r.reason } : {}), ...(r.failure ? { failure: r.failure } : {}), ...(r.error ? { error: r.error } : {}), ...(mark ? { mark } : {}), ...(r.parts?.length ? { parts: r.parts } : {}), ...(r.checkable === false ? { checkable: false as const } : {}), }; if (r.verdict !== it.verdict) disagree.push(m); } return { key: it.key, report: it.report, claim: it.claim, text: it.text, verdict: it.verdict, windows: it.windows.map((w) => ({ channel: w.channel, id: w.id, ...(w.label ? { label: w.label } : {}), from: w.from, to: w.to, ...(w.bound ? { bound: w.bound } : {}), cues: w.cues })), evidence: it.evidence ?? [], answers, disagree, }; }); } export async function readBenchView(id: string, compareWith?: string): Promise { const root = benchRoot(); const run = await readBenchRun(root, id).catch(() => null); if (!run) return null; const models = run.summary.models; const score = scoreBench(run.items, run.results, models); const marks = await readBenchMarks(root, id); const itemsHash = run.summary.itemsHash ?? benchItemsHash(run.items); let compare: BenchView["compare"]; if (compareWith && compareWith !== id) { const other = await readBenchRun(root, compareWith).catch(() => null); // Only a run over the same items is compared. if (other && (other.summary.itemsHash ?? benchItemsHash(other.items)) === itemsHash) { compare = { with: compareWith, promptVersion: other.summary.promptVersion ?? M7_PROMPT_VERSION, result: compareBenchRuns( { items: other.items, results: other.results, models: other.summary.models }, { items: run.items, results: run.results, models }, ), }; } } return { summary: run.summary, promptVersion: run.summary.promptVersion ?? M7_PROMPT_VERSION, itemsHash, score, marked: models.map((m) => markedScore(run.items, run.results, m, marks)), items: rowsOf(run.items, run.results, models, marks), ...(compare ? { compare } : {}), }; } /** * Mark one disagreement: was the model right where its answer is not the * operator's ruling? Only a disagreement with an answer is marked; the mark * records the answer it was made on. Answers the item's row as it now is. */ export async function markBenchItem(run: string, model: string, key: string, verdict: "right" | "wrong" | null): Promise<{ mark: "right" | "wrong" | null }> { const root = benchRoot(); const r = await readBenchRun(root, run).catch(() => null); if (!r) throw new BenchMarksError(`no run ${run}`, 404); const item = r.items.find((i) => i.key === key); if (!item) throw new BenchMarksError(`no item ${key} in run ${run}`, 404); let answer: BenchResult | undefined; for (const x of r.results) if (x.model === model && x.key === key) answer = x; if (!answer) throw new BenchMarksError(`${model} was not asked about ${key}`, 404); if (verdict !== null && (!isVerdict(answer.verdict) || answer.verdict === item.verdict)) { throw new BenchMarksError(`${model}'s answer on ${key} is not a disagreement to mark`, 400); } await setBenchMark(root, run, { model, key, verdict, answer: answer.verdict }); return { mark: verdict }; } export { VERDICT_MEANINGS, VERDICT_PARTS_RULE }; // The rows a filter keeps, disagreements first (then in item order). export function filterBenchRows(rows: readonly BenchItemRow[], f: { model?: string; verdict?: string }): BenchItemRow[] { const kept = rows.filter( (r) => (!f.verdict || r.verdict === f.verdict) && (!f.model || f.model in r.answers), ); const disagrees = (r: BenchItemRow) => (f.model ? r.disagree.includes(f.model) : r.disagree.length > 0); return [...kept.filter(disagrees), ...kept.filter((r) => !disagrees(r))]; } export { passesBar, BASELINE_MODEL, VERDICTS }; export type { VerdictBar }; // ─── The bar (settings.generation.verdicts) ─── export async function readVerdictsPolicy(): Promise { const answer = await askEditor<{ value?: unknown }>("/api/ops/settings?key=generation"); return sanitizeGeneration(answer.value ?? {}).verdicts; } /** Write the bar and the ticked models whole (a nested block replaces). Answers it as read back. */ export async function writeVerdictsPolicy(v: unknown): Promise { if (!v || typeof v !== "object" || Array.isArray(v)) throw new EditorError("send {bar, models}", 400); const o = v as Record; const b = (o.bar ?? {}) as Record; for (const k of ["agreement", "contradictedRecall", "notFoundRecall"]) { const x = b[k]; if (typeof x !== "number" || !Number.isFinite(x) || x < 0 || x > 1) throw new EditorError(`bar.${k} is a fraction from 0 to 1`, 400); } if (!Array.isArray(o.models) || !o.models.every((m) => typeof m === "string")) throw new EditorError("models is a list of model names", 400); // The window proposals read (release 29): the run's the bar is set on, when // the form sends it; else the one in settings is kept (the block is written whole). let window = o.window as Record | undefined; if (window !== undefined) { if (!window || typeof window !== "object" || (window.mode !== "seconds" && window.mode !== "turn") || typeof window.seconds !== "number" || window.seconds < 0 || window.seconds > 600) { throw new EditorError('window is {mode: "seconds" | "turn", seconds: 0–600}', 400); } } else window = (await readVerdictsPolicy()).window; const verdicts = sanitizeGeneration({ verdicts: { bar: b, models: o.models, window } }).verdicts; await askEditor("/api/ops/settings", { method: "POST", body: { patch: { generation: { verdicts } } } }); return readVerdictsPolicy(); }