Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit d1d4c16033675f246aa9438f8b6a7039f7bb64ad
parent 1dc5c6e12878eea8d706c3ec084e647cf4aae05e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 21:25:39 -0400

umtool: /bench — the verdict bench's results, and the operator's bar

A run at a time: per model a tile (agreement, CONTRADICTED and NOT_FOUND
recall against the always-CORROBORATED baseline, PARTLY strict and adjacent,
cost, latency, failures), the confusion matrix, every item with each model's
verdict and reason, disagreements first, filtered by model or by the
operator's verdict. The bar form writes settings.generation.verdicts whole
through the editor's settings action (/api/bench/bar); each model's pass or
fail is read against it, and a failing model cannot be ticked. Linked from
/articles. e2e verdict-bench.spec.ts over a synthetic run.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/bench/bar/route.ts | 27+++++++++++++++++++++++++++
Mumtool/app/articles/page.tsx | 3+++
Aumtool/app/bench/page.tsx | 305++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/bench/BarForm.tsx | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/bench-fixture.mjs | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/verdict-bench.spec.ts | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/bench.ts | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 732 insertions(+), 0 deletions(-)

diff --git a/umtool/app/api/bench/bar/route.ts b/umtool/app/api/bench/bar/route.ts @@ -0,0 +1,27 @@ +import { errorResponse } from "@/lib/articles/generation"; +import { readVerdictsPolicy, writeVerdictsPolicy } from "@/lib/bench"; + +export const dynamic = "force-dynamic"; + +// THE VERDICT BENCH'S BAR (release 28 M7): settings.generation.verdicts — the +// operator's bar and the passing models they ticked — read from and written +// through the editor's settings action (POST /api/ops/settings), whole. +// +// GET -> { verdicts } +// POST { bar: {agreement, contradictedRecall, notFoundRecall}, models } -> { ok, verdicts } +export async function GET() { + try { + return Response.json({ verdicts: await readVerdictsPolicy() }, { headers: { "cache-control": "no-store" } }); + } catch (err) { + return errorResponse(err); + } +} + +export async function POST(request: Request) { + try { + const body = await request.json().catch(() => null); + return Response.json({ ok: true, verdicts: await writeVerdictsPolicy(body) }, { headers: { "cache-control": "no-store" } }); + } catch (err) { + return errorResponse(err); + } +} diff --git a/umtool/app/articles/page.tsx b/umtool/app/articles/page.tsx @@ -63,6 +63,9 @@ export default async function ArticlesPage({ searchParams }: { searchParams: Pro <Link href="/sites" className="ml-2 text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"> site pages </Link> + <Link href="/bench" className="ml-2 text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"> + verdict bench + </Link> </div> {pending.length > 0 && ( <section aria-label="in the making" className="mb-4"> diff --git a/umtool/app/bench/page.tsx b/umtool/app/bench/page.tsx @@ -0,0 +1,305 @@ +import Link from "next/link"; +import BrowseHeader from "@/components/BrowseHeader"; +import BarForm from "@/components/bench/BarForm"; +import { badgeVariants } from "@/components/ui/badge"; +import { + BASELINE_MODEL, + VERDICTS, + filterBenchRows, + passesBar, + readBenchRuns, + readBenchView, + readVerdictsPolicy, +} from "@/lib/bench"; +import type { ModelScore } from "yt-dlp-transcript-common/lib/report/draft/bench/index"; +import type { GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings"; + +export const dynamic = "force-dynamic"; + +// THE VERDICT BENCH (release 28 M7): could a model propose a fact-check +// verdict well enough to be worth a review? One run at a time: per model its +// agreement with the operator's rulings and its CONTRADICTED and NOT_FOUND +// recall beside the always-CORROBORATED baseline, its cost; the confusion +// matrix; every item with each model's verdict and reason, disagreements +// first. The bar (settings.generation.verdicts) is set here, and each model's +// pass or fail read against it — the handoff for the verdict proposals. The +// runs are local-only (`archilyzer reports bench-verdicts`); zero client JS +// but the bar's form. + +type Search = { run?: string; model?: string; verdict?: string }; + +const pct = (v: number | null) => (v === null ? "—" : `${Math.round(v * 1000) / 10}%`); + +export default async function BenchPage({ searchParams }: { searchParams: Promise<Search> }) { + const sp = await searchParams; + const runs = await readBenchRuns(); + const id = sp.run && runs.some((r) => r.id === sp.run) ? sp.run : runs[0]?.id; + const view = id ? await readBenchView(id) : null; + let policy: GenerationVerdicts | null = null; + let policyError: string | null = null; + try { + policy = await readVerdictsPolicy(); + } catch (e) { + policyError = (e as Error).message; + } + const qs = (next: Partial<Search>) => { + const p = new URLSearchParams(); + for (const [k, v] of Object.entries({ ...sp, run: id, ...next })) if (v) p.set(k, String(v)); + return `/bench?${p.toString()}`; + }; + + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + active="articles" + crumbs={[{ label: "articles", href: "/articles" }, { label: "verdict bench" }]} + note={`${runs.length} run${runs.length === 1 ? "" : "s"}`} + /> + <main className="deck-main flex-1 p-4 text-[12px]"> + {runs.length === 0 ? ( + <p className="text-[var(--color-dim)]"> + no bench runs — <code className="font-mono">archilyzer reports bench-verdicts --models …</code> + </p> + ) : ( + <> + <nav aria-label="runs" className="mb-3 flex flex-wrap items-center gap-1.5"> + <span className="micro">run</span> + {runs.map((r) => ( + <Link + key={r.id} + href={`/bench?run=${r.id}`} + data-run={r.id} + aria-current={r.id === id ? "true" : undefined} + className={badgeVariants({ variant: r.id === id ? "on" : "neutral" })} + > + {r.id} · {r.status} · {r.items} + </Link> + ))} + </nav> + {!view ? ( + <p role="alert" className="text-[var(--color-bad)]"> + run {id} cannot be read + </p> + ) : ( + <RunView view={view} policy={policy} policyError={policyError} sp={sp} qs={qs} /> + )} + </> + )} + </main> + </div> + ); +} + +function RunView({ + view, + policy, + policyError, + sp, + qs, +}: { + view: NonNullable<Awaited<ReturnType<typeof readBenchView>>>; + policy: GenerationVerdicts | null; + policyError: string | null; + sp: Search; + qs: (n: Partial<Search>) => string; +}) { + const { summary: s, score } = view; + const bar = policy?.bar ?? null; + const rows = filterBenchRows(view.items, { model: sp.model, verdict: sp.verdict }); + const models = sp.model ? s.models.filter((m) => m === sp.model) : s.models; + return ( + <div data-bench-run={s.id} data-status={s.status} className="flex flex-col gap-4"> + <p role="status" className="text-[var(--color-dim)]"> + {s.status} · {s.items} items · {s.skipped.length} skipped · a {s.windowS} s window · ${s.spentUsd.toFixed(4)} of ${s.maxUsd} ·{" "} + {new Date(s.createdAt).toISOString().slice(0, 16).replace("T", " ")} UTC + {s.stopped?.length ? ` · stopped: ${s.stopped.join("; ")}` : ""} + </p> + <section aria-label="models" className="flex flex-wrap gap-2"> + {[...score.models, score.baseline].map((m) => ( + <ModelTile key={m.model} m={m} baseline={m.model === BASELINE_MODEL ? null : score.baseline} pass={bar && m.model !== BASELINE_MODEL ? passesBar(m, bar) : null} /> + ))} + </section> + <section aria-label="the bar" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3"> + {policy ? ( + <BarForm initial={policy} models={score.models} /> + ) : ( + <p role="alert" className="text-[var(--color-bad)]"> + the bar cannot be read: {policyError} + </p> + )} + </section> + <section aria-label="confusion" className="flex flex-wrap gap-4"> + {score.models.map((m) => ( + <Matrix key={m.model} m={m} /> + ))} + </section> + <section aria-label="items"> + <div className="mb-2 flex flex-wrap items-center gap-1.5"> + <span className="micro">model</span> + <Chip href={qs({ model: "" })} on={!sp.model} label="all" /> + {s.models.map((m) => ( + <Chip key={m} href={qs({ model: m })} on={sp.model === m} label={m} /> + ))} + <span className="micro ml-3">operator</span> + <Chip href={qs({ verdict: "" })} on={!sp.verdict} label="all" /> + {VERDICTS.filter((v) => score.ruled[v] > 0).map((v) => ( + <Chip key={v} href={qs({ verdict: v })} on={sp.verdict === v} label={`${v} ${score.ruled[v]}`} /> + ))} + </div> + <table className="w-full border-collapse"> + <thead> + <tr className="micro text-left"> + <th className="py-1 pr-2">claim</th> + <th className="py-1 pr-2">operator</th> + {models.map((m) => ( + <th key={m} className="py-1 pr-2 font-mono"> + {m} + </th> + ))} + </tr> + </thead> + <tbody> + {rows.map((r) => ( + <tr key={r.key} data-item={r.key} data-disagree={r.disagree.length ? r.disagree.join(" ") : undefined} className="border-t border-[var(--color-line)] align-top"> + <td className="max-w-[28rem] py-1.5 pr-2"> + <div className="font-mono text-[10px] text-[var(--color-dim)]">{r.key}</div> + {r.text} + </td> + <td className="py-1.5 pr-2 font-mono">{r.verdict}</td> + {models.map((m) => { + const a = r.answers[m]; + return ( + <td key={m} data-model={m} data-verdict={a?.verdict ?? "none"} className="max-w-[20rem] py-1.5 pr-2"> + {!a ? ( + <span className="text-[var(--color-dim)]">not asked</span> + ) : a.verdict ? ( + <> + <span className={`font-mono ${a.verdict === r.verdict ? "text-[var(--color-good)]" : "text-[var(--color-bad)]"}`}>{a.verdict}</span> + {a.reason && <div className="text-[var(--color-dim)]">{a.reason}</div>} + </> + ) : ( + <span className="text-[var(--color-bad)]"> + {a.failure}: {a.error} + </span> + )} + </td> + ); + })} + </tr> + ))} + </tbody> + </table> + </section> + {s.skipped.length > 0 && ( + <details> + <summary className="micro cursor-pointer">skipped {s.skipped.length}</summary> + <ul aria-label="skipped" className="mt-1 flex flex-col gap-0.5"> + {s.skipped.map((k) => ( + <li key={k.key} className="font-mono text-[var(--color-dim)]"> + {k.key} — {k.reason} + </li> + ))} + </ul> + </details> + )} + </div> + ); +} + +function ModelTile({ m, baseline, pass }: { m: ModelScore; baseline: ModelScore | null; pass: { pass: boolean; misses: string[] } | null }) { + const vs = (v: number | null, b: number | null | undefined) => (baseline ? `${pct(v)} (baseline ${pct(b ?? null)})` : pct(v)); + return ( + <div + data-model={m.model} + data-pass={pass ? String(pass.pass) : undefined} + className="min-w-[15rem] rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2" + > + <div className="mb-1 flex items-center gap-2"> + <span className="font-mono text-[var(--color-text)]">{m.model}</span> + {pass && ( + <span className={badgeVariants({ variant: pass.pass ? "on" : "blocking", size: "sm" })} title={pass.misses.join("; ") || undefined}> + {pass.pass ? "passes" : "fails"} the bar + </span> + )} + </div> + <dl className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5"> + <dt className="text-[var(--color-dim)]">agreement</dt> + <dd data-metric="agreement">{vs(m.agreement, baseline?.agreement)}</dd> + <dt className="text-[var(--color-dim)]">with PARTLY ~ CORROBORATED</dt> + <dd>{vs(m.agreementAdjacent, baseline?.agreementAdjacent)}</dd> + <dt className="text-[var(--color-dim)]">CONTRADICTED recall</dt> + <dd data-metric="contradicted"> + {vs(m.recall.CONTRADICTED.recall, baseline?.recall.CONTRADICTED.recall)} of {m.recall.CONTRADICTED.ruled} + </dd> + <dt className="text-[var(--color-dim)]">NOT_FOUND recall</dt> + <dd data-metric="not-found"> + {vs(m.recall.NOT_FOUND.recall, baseline?.recall.NOT_FOUND.recall)} of {m.recall.NOT_FOUND.ruled} + </dd> + <dt className="text-[var(--color-dim)]">PARTLY recall</dt> + <dd> + {pct(m.recall.PARTLY.recall)} · adjacent {pct(m.recall.PARTLY_ADJACENT.recall)} + </dd> + {baseline && ( + <> + <dt className="text-[var(--color-dim)]">cost</dt> + <dd data-metric="cost">${m.usd.toFixed(4)}</dd> + <dt className="text-[var(--color-dim)]">latency</dt> + <dd>{m.latency.medianMs === null ? "—" : `${(m.latency.medianMs / 1000).toFixed(1)} s median, ${((m.latency.p90Ms ?? 0) / 1000).toFixed(1)} s p90`}</dd> + <dt className="text-[var(--color-dim)]">answered</dt> + <dd> + {m.answered} of {m.asked} + {m.parseFailures ? ` · ${m.parseFailures} parse failures` : ""} + {m.errors ? ` · ${m.errors} errors` : ""} + </dd> + </> + )} + </dl> + </div> + ); +} + +function Matrix({ m }: { m: ModelScore }) { + return ( + <table aria-label={`confusion ${m.model}`} className="border-collapse font-mono text-[11px]"> + <caption className="micro mb-1 text-left"> + {m.model} — rows: operator, columns: model + </caption> + <thead> + <tr> + <th /> + {VERDICTS.map((v) => ( + <th key={v} className="px-1.5 py-0.5 text-[var(--color-dim)]" title={v}> + {v.slice(0, 4)} + </th> + ))} + <th className="px-1.5 py-0.5 text-[var(--color-dim)]">none</th> + </tr> + </thead> + <tbody> + {VERDICTS.map((op, i) => ( + <tr key={op}> + <th className="pr-1.5 text-left text-[var(--color-dim)]">{op}</th> + {VERDICTS.map((v, j) => ( + <td + key={v} + data-cell={`${op}:${v}`} + className={`border border-[var(--color-line)] px-1.5 py-0.5 text-right ${i === j && m.matrix[i]![j]! > 0 ? "text-[var(--color-good)]" : m.matrix[i]![j]! > 0 ? "text-[var(--color-text)]" : "text-[var(--color-dim)]"}`} + > + {m.matrix[i]![j]} + </td> + ))} + <td className="border border-[var(--color-line)] px-1.5 py-0.5 text-right text-[var(--color-dim)]">{m.unanswered[i]}</td> + </tr> + ))} + </tbody> + </table> + ); +} + +function Chip({ href, on, label }: { href: string; on: boolean; label: string }) { + return ( + <Link href={href} aria-current={on ? "true" : undefined} className={badgeVariants({ variant: on ? "on" : "neutral" })}> + {label} + </Link> + ); +} diff --git a/umtool/components/bench/BarForm.tsx b/umtool/components/bench/BarForm.tsx @@ -0,0 +1,103 @@ +"use client"; + +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { passesBar, type ModelScore, type VerdictBar } from "yt-dlp-transcript-common/lib/report/draft/bench/score"; +import type { GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings"; + +// THE BAR (release 28 M7): the least agreement, CONTRADICTED recall and +// NOT_FOUND recall a model must reach on this run, and the passing models the +// operator ticks for the verdict proposals — settings.generation.verdicts, +// written whole through /api/bench/bar (the editor's settings action). A +// model is never ticked automatically, and one that fails the bar as typed +// cannot be ticked. + +const KEYS: { key: keyof VerdictBar; label: string }[] = [ + { key: "agreement", label: "minimum agreement" }, + { key: "contradictedRecall", label: "minimum CONTRADICTED recall" }, + { key: "notFoundRecall", label: "minimum NOT_FOUND recall" }, +]; +const field = "w-16 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; +const toPct = (v: number) => String(Math.round(v * 1000) / 10); + +export default function BarForm({ initial, models }: { initial: GenerationVerdicts; models: ModelScore[] }) { + const [typed, setTyped] = useState(() => Object.fromEntries(KEYS.map((k) => [k.key, toPct(initial.bar[k.key])])) as Record<keyof VerdictBar, string>); + const [ticked, setTicked] = useState<string[]>(initial.models); + const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null); + const [busy, setBusy] = useState(false); + const bar = Object.fromEntries(KEYS.map((k) => [k.key, Math.min(100, Math.max(0, Number(typed[k.key]) || 0)) / 100])) as VerdictBar; + // A model ticked in settings but not in this run is kept as it is. + const here = new Set(models.map((m) => m.model)); + + async function save(e: React.FormEvent) { + e.preventDefault(); + setBusy(true); + setStatus(null); + const keep = ticked.filter((m) => !here.has(m) || passesBar(models.find((x) => x.model === m)!, bar).pass); + try { + const r = await fetch("/api/bench/bar", { method: "POST", body: JSON.stringify({ bar, models: keep }) }); + const body = await r.json(); + if (!r.ok) throw new Error(body.error ?? `HTTP ${r.status}`); + const v = body.verdicts as GenerationVerdicts; + setTyped(Object.fromEntries(KEYS.map((k) => [k.key, toPct(v.bar[k.key])])) as Record<keyof VerdictBar, string>); + setTicked(v.models); + setStatus({ ok: true, text: "Saved." }); + } catch (err) { + setStatus({ ok: false, text: (err as Error).message }); + } finally { + setBusy(false); + } + } + + return ( + <form aria-label="bar" onSubmit={save} className="flex flex-col gap-2 text-[12px]"> + <div className="flex flex-wrap items-center gap-3"> + <span className="micro">the bar</span> + {KEYS.map((k) => ( + <label key={k.key} className="flex items-center gap-1"> + <span className="text-[var(--color-dim)]">{k.label}</span> + <input + aria-label={k.label} + className={field} + type="number" + min={0} + max={100} + step={0.1} + value={typed[k.key]} + onChange={(e) => setTyped({ ...typed, [k.key]: e.target.value })} + /> + <span className="text-[var(--color-dim)]">%</span> + </label> + ))} + </div> + <div className="flex flex-wrap items-center gap-3"> + <span className="micro">verdict proposals on</span> + {models.map((m) => { + const check = passesBar(m, bar); + const on = ticked.includes(m.model) && check.pass; + return ( + <label key={m.model} data-model={m.model} data-pass={String(check.pass)} className="flex items-center gap-1" title={check.misses.join("; ") || undefined}> + <input + type="checkbox" + aria-label={`use ${m.model}`} + checked={on} + disabled={!check.pass} + onChange={(e) => setTicked(e.target.checked ? [...new Set([...ticked, m.model])] : ticked.filter((x) => x !== m.model))} + /> + <span className="font-mono">{m.model}</span> + <span className={check.pass ? "text-[var(--color-good)]" : "text-[var(--color-bad)]"}>{check.pass ? "passes" : "fails"}</span> + </label> + ); + })} + <Button type="submit" size="sm" disabled={busy}> + Save the bar + </Button> + {status && ( + <span role="status" className={status.ok ? "text-[var(--color-dim)]" : "text-[var(--color-bad)]"}> + {status.text} + </span> + )} + </div> + </form> + ); +} diff --git a/umtool/e2e/fixtures/bench-fixture.mjs b/umtool/e2e/fixtures/bench-fixture.mjs @@ -0,0 +1,79 @@ +// A verdict bench run, synthetic (release 28 M7), for verdict-bench.spec.ts: +// four invented claims ruled CORROBORATED, PARTLY, CONTRADICTED and +// NOT_FOUND, asked of two models — one right on three (it calls the PARTLY +// one CORROBORATED), one that always says CORROBORATED and fails to parse +// once. Written as `archilyzer reports bench-verdicts` writes a run +// (common/lib/report/draft/bench/store.ts); the page scores it again. + +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +export const BENCH_RUN = "vb-e2e"; +export const SONNET = "claude-sonnet-5-5"; +export const QWEN = "qwen3:8b"; + +const claims = [ + ["c1", "The article says she opened the shop in spring.", "CORROBORATED"], + ["c2", "The article says the oven was broken for a month.", "PARTLY"], + ["c3", "The article says she sold the van.", "CONTRADICTED"], + ["c4", "The article says she named the supplier.", "NOT_FOUND"], +]; +const said = { + [SONNET]: ["CORROBORATED", "CORROBORATED", "CONTRADICTED", "NOT_FOUND"], + [QWEN]: ["CORROBORATED", "CORROBORATED", "CORROBORATED", null], +}; + +export function makeBenchRun(root) { + const dir = path.join(root, BENCH_RUN); + rmSync(dir, { recursive: true, force: true }); + mkdirSync(dir, { recursive: true }); + const items = claims.map(([id, text, verdict], i) => ({ + key: `synth-bench/${id}`, + report: "synth-bench", + claim: id, + text, + verdict, + quotes: [{ citation: `q${i}`, channel: "synth-kitchen", id: "bread-day-01", start: 10 + i * 15, end: 14 + i * 15, quote: "a line" }], + windows: [{ channel: "synth-kitchen", id: "bread-day-01", from: 0, to: 80, cited: [{ start: 10 + i * 15, end: 14 + i * 15 }], cues: [{ start: 10 + i * 15, end: 14 + i * 15, text: "a line" }] }], + })); + const results = []; + for (const [model, verdicts] of Object.entries(said)) { + items.forEach((it, i) => { + const v = verdicts[i]; + results.push({ + key: it.key, + model, + verdict: v, + ...(v ? { reason: `${model} read the window for ${it.claim}` } : { failure: "parse", error: "the answer is not JSON" }), + ms: 1200 + i * 100, + usd: model === SONNET ? 0.004 : 0, + inputTokens: 900, + outputTokens: 60, + at: "2026-10-13T12:00:00.000Z", + }); + }); + } + const jsonl = (rows) => rows.map((r) => `${JSON.stringify(r)}\n`).join(""); + writeFileSync(path.join(dir, "items.jsonl"), jsonl(items)); + writeFileSync(path.join(dir, "results.jsonl"), jsonl(results)); + writeFileSync( + path.join(dir, "summary.json"), + JSON.stringify({ + format: "archilyzer-verdict-bench", + version: 1, + id: BENCH_RUN, + createdAt: "2026-10-13T12:00:00.000Z", + updatedAt: "2026-10-13T12:05:00.000Z", + status: "done", + models: [SONNET, QWEN], + windowS: 60, + maxUsd: 5, + reports: [], + spentUsd: 0.016, + items: items.length, + skipped: [{ key: "synth-bench/c5", report: "synth-bench", claim: "c5", reason: "no citation" }], + score: {}, + }), + ); + return dir; +} diff --git a/umtool/e2e/verdict-bench.spec.ts b/umtool/e2e/verdict-bench.spec.ts @@ -0,0 +1,97 @@ +import { test, expect } from "@playwright/test"; +import { readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { WARM_TIMEOUT, warm } from "./warm"; +import { BENCH_RUN, QWEN, SONNET, makeBenchRun } from "./fixtures/bench-fixture.mjs"; + +// --------------------------------------------------------------------------- +// The verdict bench's page (release 28 M7) over a synthetic run in the +// fixture's `.generation`-style root (GENERATION_USAGE_FILE is the fixture's, +// so the runs root is <fixture>/bench/verdicts): the tiles against the +// baseline, the confusion matrix, the items with disagreements first and the +// filters, and the bar — written through the (stubbed) editor's settings +// action, each model's pass or fail read against it, and a failing model +// never tickable. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const ROOT = path.join(FIXTURE, "bench", "verdicts"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const stubAsked = (route: string) => + (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; [k: string]: unknown }[]).filter((r) => r.route === route); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + makeBenchRun(ROOT); + await warm(playwright, ["/bench", "/api/bench/bar"]); +}); +test.afterAll(async ({ request }) => { + await request.post("/api/bench/bar", { data: { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] } }); + rmSync(path.join(ROOT, BENCH_RUN), { recursive: true, force: true }); +}); + +test("the run: each model's tile against the baseline, the matrix, the items with disagreements first, the filters", async ({ page }) => { + await page.goto("/articles"); + await page.getByRole("link", { name: "verdict bench" }).click(); + await expect(page).toHaveURL(/\/bench$/); + await expect(page.locator(`[data-bench-run="${BENCH_RUN}"]`)).toHaveAttribute("data-status", "done"); + const models = page.getByRole("region", { name: "models" }); + const sonnet = models.locator(`[data-model="${SONNET}"]`); + await expect(sonnet.locator('[data-metric="agreement"]')).toHaveText("75% (baseline 25%)"); + await expect(sonnet.locator('[data-metric="contradicted"]')).toHaveText("100% (baseline 0%) of 1"); + await expect(sonnet.locator('[data-metric="not-found"]')).toHaveText("100% (baseline 0%) of 1"); + await expect(sonnet.locator('[data-metric="cost"]')).toHaveText("$0.0160"); + const qwen = models.locator(`[data-model="${QWEN}"]`); + await expect(qwen.locator('[data-metric="agreement"]')).toHaveText("25% (baseline 25%)"); + await expect(qwen).toContainText("3 of 4 · 1 parse failures"); + await expect(models.locator('[data-model="always-CORROBORATED"]')).toBeVisible(); + // The matrix: rows the operator, columns the model. + const m = page.getByRole("table", { name: `confusion ${SONNET}` }); + await expect(m.locator('[data-cell="PARTLY:CORROBORATED"]')).toHaveText("1"); + await expect(m.locator('[data-cell="CONTRADICTED:CONTRADICTED"]')).toHaveText("1"); + // The items: every disagreement first. + const rows = page.getByRole("region", { name: "items" }).locator("tbody tr"); + await expect(rows).toHaveCount(4); + await expect(rows.nth(0)).toHaveAttribute("data-item", "synth-bench/c2"); + await expect(rows.nth(3)).toHaveAttribute("data-item", "synth-bench/c1"); + await expect(rows.nth(0).locator(`[data-model="${SONNET}"]`)).toContainText("read the window for c2"); + await expect(rows.nth(2).locator(`[data-model="${QWEN}"]`)).toContainText("parse: the answer is not JSON"); + // By model: that model's disagreements first, its column alone. + await page.getByRole("region", { name: "items" }).getByRole("link", { name: SONNET, exact: true }).click(); + await expect(rows.nth(0)).toHaveAttribute("data-item", "synth-bench/c2"); + await expect(rows.nth(1)).toHaveAttribute("data-item", "synth-bench/c1"); + await expect(page.getByRole("region", { name: "items" }).locator(`thead th`)).toHaveCount(3); + // By the operator's verdict. + await page.getByRole("region", { name: "items" }).getByRole("link", { name: "CONTRADICTED 1" }).click(); + await expect(rows).toHaveCount(1); + await expect(rows.nth(0)).toHaveAttribute("data-item", "synth-bench/c3"); + await expect(page.getByText("skipped 1")).toBeVisible(); +}); + +test("the bar: saved through the editor's settings action; a passing model ticked, a failing one never", async ({ page }) => { + await page.goto(`/bench?run=${BENCH_RUN}`); + const form = page.getByRole("form", { name: "bar" }); + await form.getByRole("spinbutton", { name: "minimum agreement" }).fill("50"); + await form.getByRole("spinbutton", { name: "minimum CONTRADICTED recall" }).fill("50"); + await form.getByRole("spinbutton", { name: "minimum NOT_FOUND recall" }).fill("50"); + await expect(form.getByRole("checkbox", { name: `use ${QWEN}` })).toBeDisabled(); + await expect(form.locator(`[data-model="${QWEN}"]`)).toHaveAttribute("data-pass", "false"); + const use = form.getByRole("checkbox", { name: `use ${SONNET}` }); + await expect(use).toBeEnabled(); + await use.check(); + await form.getByRole("button", { name: "Save the bar" }).click(); + await expect(form.getByRole("status")).toHaveText("Saved."); + expect(stubAsked("settings").at(-1)).toMatchObject({ + patch: { generation: { verdicts: { bar: { agreement: 0.5, contradictedRecall: 0.5, notFoundRecall: 0.5 }, models: [SONNET] } } }, + authorization: "Bearer umtool-e2e-token", + }); + // Read back: the tiles say who passes the saved bar. + await page.reload(); + const models = page.getByRole("region", { name: "models" }); + await expect(models.locator(`[data-model="${SONNET}"]`)).toHaveAttribute("data-pass", "true"); + await expect(models.locator(`[data-model="${QWEN}"]`)).toHaveAttribute("data-pass", "false"); + await expect(page.getByRole("form", { name: "bar" }).getByRole("checkbox", { name: `use ${SONNET}` })).toBeChecked(); + await expect(page.getByRole("form", { name: "bar" }).getByRole("spinbutton", { name: "minimum agreement" })).toHaveValue("50"); +}); diff --git a/umtool/lib/bench.ts b/umtool/lib/bench.ts @@ -0,0 +1,118 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { + benchRootOf, + listBenchRuns, + passesBar, + readBenchRun, + scoreBench, + BASELINE_MODEL, + type BenchItem, + type BenchResult, + type BenchScore, + type BenchSummary, + type VerdictBar, +} from "yt-dlp-transcript-common/lib/report/draft/bench/index"; +import { VERDICTS, type Verdict } from "yt-dlp-transcript-common/lib/report/verdicts"; +import { sanitizeGeneration, type GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings"; +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), 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. +// +// SERVER-ONLY. + +export type BenchRunRow = Pick<BenchSummary, "id" | "createdAt" | "status" | "models" | "items" | "spentUsd" | "maxUsd">; + +export type BenchItemRow = { + key: string; + report: string; + claim: string; + text: string; + verdict: Verdict; + answers: Record<string, { verdict: Verdict | null; reason?: string; failure?: string; error?: string }>; + // A model whose answer is not the operator's (failures included). + disagree: string[]; +}; + +export type BenchView = { + summary: BenchSummary; + score: BenchScore; + items: BenchItemRow[]; +}; + +export function benchRoot(): string { + return benchRootOf(getPaths()); +} + +export async function readBenchRuns(): Promise<BenchRunRow[]> { + return (await listBenchRuns(benchRoot())).map((s) => ({ + id: s.id, + createdAt: s.createdAt, + status: s.status, + models: s.models, + items: s.items, + spentUsd: s.spentUsd, + maxUsd: s.maxUsd, + })); +} + +function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], models: readonly string[]): BenchItemRow[] { + const by = new Map<string, BenchResult>(); + 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; + answers[m] = { verdict: r.verdict, ...(r.reason ? { reason: r.reason } : {}), ...(r.failure ? { failure: r.failure } : {}), ...(r.error ? { error: r.error } : {}) }; + if (r.verdict !== it.verdict) disagree.push(m); + } + return { key: it.key, report: it.report, claim: it.claim, text: it.text, verdict: it.verdict, answers, disagree }; + }); +} + +export async function readBenchView(id: string): Promise<BenchView | null> { + const run = await readBenchRun(benchRoot(), id).catch(() => null); + if (!run) return null; + const score = scoreBench(run.items, run.results, run.summary.models); + return { summary: run.summary, score, items: rowsOf(run.items, run.results, run.summary.models) }; +} + +// 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<GenerationVerdicts> { + 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<GenerationVerdicts> { + if (!v || typeof v !== "object" || Array.isArray(v)) throw new EditorError("send {bar, models}", 400); + const o = v as Record<string, unknown>; + const b = (o.bar ?? {}) as Record<string, unknown>; + 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); + const verdicts = sanitizeGeneration({ verdicts: { bar: b, models: o.models } }).verdicts; + await askEditor("/api/ops/settings", { method: "POST", body: { patch: { generation: { verdicts } } } }); + return readVerdictsPolicy(); +}