Archilyzer · Source

archilyzer

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

commit 771a555e384482c60771c8a176efaa0fc30a8c03
parent 291f5ff77eb853b7085e5eedb184ef5d0b699ed8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 15 Oct 2026 07:21:36 -0400

umtool: the verdict bench v2 on /tools/bench — each run's prompt version and items hash, "compare with" over the runs with the same items (each model's agreement in both, the claims whose answers changed), a Right/Wrong mark on each disagreement (marks.json beside the run, lib/bench-marks.mjs, R6's discipline; /api/bench/marks), not-CORROBORATED precision and recall beside the bar, as ruled and marked, what the verdicts mean, the dropped citations; verdict-bench.spec gains the version, the compare and the marks; bench-marks.test.mjs

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

Diffstat:
Aumtool/app/api/bench/marks/route.ts | 26++++++++++++++++++++++++++
Mumtool/app/tools/bench/page.tsx | 183++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Aumtool/components/bench/MarkButtons.tsx | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/bench-fixture.mjs | 30+++++++++++++++++++++++-------
Mumtool/e2e/verdict-bench.spec.ts | 57++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/lib/bench-marks.mjs | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/bench-marks.test.mjs | 35+++++++++++++++++++++++++++++++++++
Mumtool/lib/bench.ts | 139++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
8 files changed, 600 insertions(+), 45 deletions(-)

diff --git a/umtool/app/api/bench/marks/route.ts b/umtool/app/api/bench/marks/route.ts @@ -0,0 +1,26 @@ +import { markBenchItem } from "@/lib/bench"; + +export const dynamic = "force-dynamic"; + +// MARK A DISAGREEMENT (release 29 V1): the operator's Right / Wrong on one +// model's answer that is not the ruling — was the MODEL right? — kept beside +// the run (umtool's own file, lib/bench-marks.mjs); marked precision is read +// from them on /tools/bench. +// POST {run, model, key, verdict: "right" | "wrong" | null} -> {mark} +// 400 a bad body or not a disagreement; 404 no such run, item or answer; +// 409 a marks file that does not read +export async function POST(request: Request) { + const headers = { "cache-control": "no-store" }; + try { + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!b || typeof b.run !== "string" || typeof b.model !== "string" || typeof b.key !== "string") { + return Response.json({ error: 'send {"run", "model", "key", "verdict": "right" | "wrong" | null}' }, { status: 400, headers }); + } + const verdict = b.verdict === "right" || b.verdict === "wrong" ? b.verdict : b.verdict === null ? null : undefined; + if (verdict === undefined) return Response.json({ error: '"verdict" is "right", "wrong" or null' }, { status: 400, headers }); + return Response.json(await markBenchItem(b.run, b.model, b.key, verdict), { headers }); + } catch (e) { + const status = (e as { status?: number })?.status ?? 500; + return Response.json({ error: (e as Error)?.message ?? String(e) }, { status, headers }); + } +} diff --git a/umtool/app/tools/bench/page.tsx b/umtool/app/tools/bench/page.tsx @@ -1,17 +1,20 @@ import Link from "next/link"; import AppShell from "@/components/shell/AppShell"; import BarForm from "@/components/bench/BarForm"; +import MarkButtons from "@/components/bench/MarkButtons"; import { badgeVariants } from "@/components/ui/badge"; import { BASELINE_MODEL, VERDICTS, + VERDICT_MEANINGS, + VERDICT_TIE_RULE, filterBenchRows, passesBar, readBenchRuns, readBenchView, readVerdictsPolicy, } from "@/lib/bench"; -import type { ModelScore } from "yt-dlp-transcript-common/lib/report/draft/bench/index"; +import type { MarkedScore, 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"; @@ -24,9 +27,15 @@ export const dynamic = "force-dynamic"; // 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. +// but the bar's form and the marks. +// +// Release 29 V1: the run's prompt version and items hash; "compare with" over +// the runs with the same items (each model's agreement in both, the claims +// whose answers changed); a Right / Wrong mark on each disagreement; the +// not-CORROBORATED precision and recall beside the bar, marked and not; what +// the verdicts mean (the one copy, verdicts.mjs). -type Search = { run?: string; model?: string; verdict?: string }; +type Search = { run?: string; model?: string; verdict?: string; compare?: string }; const pct = (v: number | null) => (v === null ? "—" : `${Math.round(v * 1000) / 10}%`); @@ -34,7 +43,8 @@ export default async function BenchPage({ searchParams }: { searchParams: Promis 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; + const view = id ? await readBenchView(id, sp.compare) : null; + const sameItems = view ? runs.filter((r) => r.id !== id && r.itemsHash === view.itemsHash) : []; let policy: GenerationVerdicts | null = null; let policyError: string | null = null; try { @@ -81,7 +91,7 @@ export default async function BenchPage({ searchParams }: { searchParams: Promis run {id} cannot be read </p> ) : ( - <RunView view={view} policy={policy} policyError={policyError} sp={sp} qs={qs} /> + <RunView view={view} policy={policy} policyError={policyError} sp={sp} qs={qs} sameItems={sameItems} /> )} </> )} @@ -96,12 +106,14 @@ function RunView({ policyError, sp, qs, + sameItems, }: { view: NonNullable<Awaited<ReturnType<typeof readBenchView>>>; policy: GenerationVerdicts | null; policyError: string | null; sp: Search; qs: (n: Partial<Search>) => string; + sameItems: Awaited<ReturnType<typeof readBenchRuns>>; }) { const { summary: s, score } = view; const bar = policy?.bar ?? null; @@ -110,7 +122,14 @@ function RunView({ 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} ·{" "} + {s.status} · {s.items} items · {s.skipped.length} skipped + {s.dropped?.length ? ` · ${s.dropped.length} citations dropped` : ""} ·{" "} + {s.windowMode === "turn" ? `the speaker's turn within ${s.windowS} s` : `a ${s.windowS} s window`} ·{" "} + <span data-prompt-version={view.promptVersion}>prompt v{view.promptVersion}</span> ·{" "} + <span data-items-hash={view.itemsHash} className="font-mono"> + items {view.itemsHash} + </span> + {s.itemsFrom ? ` (from ${s.itemsFrom})` : ""} · ${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> @@ -119,15 +138,19 @@ function RunView({ <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> + <div className="flex flex-wrap items-start gap-3"> + <section aria-label="the bar" className="min-w-[24rem] flex-1 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> + <Precision scores={score.models} marked={view.marked} /> + </div> + <Compare view={view} sameItems={sameItems} qs={qs} current={sp.compare} /> <section aria-label="confusion" className="flex flex-wrap gap-4"> {score.models.map((m) => ( <Matrix key={m.model} m={m} /> @@ -176,6 +199,7 @@ function RunView({ <> <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>} + {a.verdict !== r.verdict && <MarkButtons run={s.id} model={m} item={r.key} initial={a.mark} />} </> ) : ( <span className="text-[var(--color-bad)]"> @@ -190,6 +214,30 @@ function RunView({ </tbody> </table> </section> + <details> + <summary className="micro cursor-pointer">what the verdicts mean</summary> + <dl aria-label="the verdicts" className="mt-1 grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5"> + {VERDICTS.map((v) => ( + <div key={v} className="contents"> + <dt className="font-mono">{v}</dt> + <dd data-meaning={v}>{VERDICT_MEANINGS[v]}</dd> + </div> + ))} + </dl> + <p className="mt-1 text-[var(--color-dim)]">{VERDICT_TIE_RULE}</p> + </details> + {s.dropped && s.dropped.length > 0 && ( + <details> + <summary className="micro cursor-pointer">dropped {s.dropped.length}</summary> + <ul aria-label="dropped" className="mt-1 flex flex-col gap-0.5"> + {s.dropped.map((d) => ( + <li key={`${d.key} ${d.citation}`} className="font-mono text-[var(--color-dim)]"> + {d.key} {d.citation} — {d.reason} + </li> + ))} + </ul> + </details> + )} {s.skipped.length > 0 && ( <details> <summary className="micro cursor-pointer">skipped {s.skipped.length}</summary> @@ -206,6 +254,111 @@ function RunView({ ); } +// "Not CORROBORATED" as the positive class — the claims a proposal would put +// in front of the operator — plain and with the operator's marks applied. +function Precision({ scores, marked }: { scores: ModelScore[]; marked: MarkedScore[] }) { + return ( + <section aria-label="precision" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3"> + <span className="micro">not CORROBORATED · precision / recall</span> + <table className="mt-1 border-collapse"> + <thead> + <tr className="micro text-left"> + <th className="pr-3">model</th> + <th className="pr-3">as ruled</th> + <th className="pr-3">marked</th> + <th>marks</th> + </tr> + </thead> + <tbody> + {scores.map((m) => { + const k = marked.find((x) => x.model === m.model); + return ( + <tr key={m.model} data-model={m.model}> + <td className="pr-3 font-mono">{m.model}</td> + <td className="pr-3" data-metric="precision"> + {pct(m.notCorroborated.precision)} / {pct(m.notCorroborated.recall)} + </td> + <td className="pr-3" data-metric="marked-precision"> + {k ? `${pct(k.notCorroborated.precision)} / ${pct(k.notCorroborated.recall)}` : "—"} + </td> + <td data-metric="marks">{k && k.marks.marked ? `${k.marks.right} right · ${k.marks.wrong} wrong` : "none yet"}</td> + </tr> + ); + })} + </tbody> + </table> + </section> + ); +} + +// Another run over the SAME items (the same hash): each model asked in both, +// its agreement there and here, and every claim whose answer changed. +function Compare({ + view, + sameItems, + qs, + current, +}: { + view: NonNullable<Awaited<ReturnType<typeof readBenchView>>>; + sameItems: Awaited<ReturnType<typeof readBenchRuns>>; + qs: (n: Partial<Search>) => string; + current?: string; +}) { + if (!sameItems.length) return null; + const c = view.compare; + return ( + <section aria-label="compare" className="flex flex-col gap-2"> + <nav aria-label="compare with" className="flex flex-wrap items-center gap-1.5"> + <span className="micro">compare with</span> + {sameItems.map((r) => ( + <Chip key={r.id} href={qs({ compare: r.id === current ? "" : r.id })} on={r.id === current} label={`${r.id} · prompt v${r.promptVersion}`} /> + ))} + </nav> + {c && ( + <div data-compare={c.with}> + <table className="border-collapse"> + <thead> + <tr className="micro text-left"> + <th className="pr-3">model</th> + <th className="pr-3">{c.with} (v{c.promptVersion})</th> + <th className="pr-3">this run (v{view.promptVersion})</th> + <th>changed</th> + </tr> + </thead> + <tbody> + {c.result.models.map((m) => ( + <tr key={m.model} data-model={m.model}> + <td className="pr-3 font-mono">{m.model}</td> + <td className="pr-3" data-metric="agreement-a"> + {pct(m.a.agreement)} + </td> + <td className="pr-3" data-metric="agreement-b"> + {pct(m.b.agreement)} + </td> + <td data-metric="changed"> + {m.changed.length} · {m.fixed} now agree · {m.broke} no longer + </td> + </tr> + ))} + </tbody> + </table> + {c.result.models.some((m) => m.changed.length) && ( + <ul aria-label="changed answers" className="mt-1 flex flex-col gap-0.5"> + {c.result.models.flatMap((m) => + m.changed.map((x) => ( + <li key={`${m.model} ${x.key}`} data-changed={x.key} data-model={m.model} className="font-mono"> + {m.model} {x.key}: {x.a ?? "none"} → {x.b ?? "none"} (ruled {x.ruled}) + </li> + )), + )} + </ul> + )} + </div> + )} + </section> + ); +} + 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 ( diff --git a/umtool/components/bench/MarkButtons.tsx b/umtool/components/bench/MarkButtons.tsx @@ -0,0 +1,52 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +// THE OPERATOR'S MARK ON A DISAGREEMENT (release 29 V1): was the MODEL right, +// where its answer is not the ruling? Right / Wrong (pressed when set; again +// to unmark), POSTed to /api/bench/marks, then the page re-reads so the +// marked precision beside the bar moves. R6's triage marks, on the bench. + +export default function MarkButtons({ run, model, item, initial }: { run: string; model: string; item: string; initial?: "right" | "wrong" }) { + const router = useRouter(); + const [mark, setMark] = useState<"right" | "wrong" | undefined>(initial); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + + async function send(next: "right" | "wrong") { + const verdict = mark === next ? null : next; + setBusy(true); + setError(null); + try { + const r = await fetch("/api/bench/marks", { method: "POST", body: JSON.stringify({ run, model, key: item, verdict }) }); + const body = await r.json(); + if (!r.ok) throw new Error(body.error ?? `HTTP ${r.status}`); + setMark(body.mark ?? undefined); + router.refresh(); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(false); + } + } + + const cls = (on: boolean) => cn(buttonVariants({ variant: on ? "pressed" : "outline", size: "sm" })); + return ( + <span className="mt-1 flex flex-wrap items-center gap-1" data-mark={mark ?? "none"}> + <button type="button" disabled={busy} aria-pressed={mark === "right"} className={cls(mark === "right")} onClick={() => void send("right")}> + Right + </button> + <button type="button" disabled={busy} aria-pressed={mark === "wrong"} className={cls(mark === "wrong")} onClick={() => void send("wrong")}> + Wrong + </button> + {error && ( + <span role="alert" className="text-[var(--color-bad)]"> + {error} + </span> + )} + </span> + ); +} diff --git a/umtool/e2e/fixtures/bench-fixture.mjs b/umtool/e2e/fixtures/bench-fixture.mjs @@ -23,8 +23,10 @@ const said = { [QWEN]: ["CORROBORATED", "CORROBORATED", "CORROBORATED", null], }; -export function makeBenchRun(root) { - const dir = path.join(root, BENCH_RUN); +export function makeBenchRun(root, o = {}) { + const run = o.run ?? BENCH_RUN; + const answers = o.said ?? said; + const dir = path.join(root, run); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true }); const items = claims.map(([id, text, verdict], i) => ({ @@ -37,7 +39,7 @@ export function makeBenchRun(root) { 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)) { + for (const [model, verdicts] of Object.entries(answers)) { items.forEach((it, i) => { const v = verdicts[i]; results.push({ @@ -61,15 +63,16 @@ export function makeBenchRun(root) { JSON.stringify({ format: "archilyzer-verdict-bench", version: 1, - id: BENCH_RUN, - createdAt: "2026-10-13T12:00:00.000Z", + id: run, + createdAt: o.createdAt ?? "2026-10-13T12:00:00.000Z", updatedAt: "2026-10-13T12:05:00.000Z", status: "done", - models: [SONNET, QWEN], + models: Object.keys(answers), + ...(o.promptVersion ? { promptVersion: o.promptVersion } : {}), windowS: 60, maxUsd: 5, reports: [], - spentUsd: 0.016, + spentUsd: Object.keys(answers).includes(SONNET) ? 0.016 : 0, items: items.length, skipped: [{ key: "synth-bench/c5", report: "synth-bench", claim: "c5", reason: "no citation" }], score: {}, @@ -77,3 +80,16 @@ export function makeBenchRun(root) { ); return dir; } + +// Release 29 V1: a second run over the SAME items (prompt version 2, made +// earlier so the page still opens the first by default), Sonnet alone: it now +// calls c2 PARTLY (as ruled) and c3 PARTLY (ruled CONTRADICTED). +export const BENCH_RUN_V2 = "vb-e2e-v2"; +export function makeBenchRunV2(root) { + return makeBenchRun(root, { + run: BENCH_RUN_V2, + said: { [SONNET]: ["CORROBORATED", "PARTLY", "PARTLY", "NOT_FOUND"] }, + promptVersion: "2", + createdAt: "2026-10-13T11:00:00.000Z", + }); +} diff --git a/umtool/e2e/verdict-bench.spec.ts b/umtool/e2e/verdict-bench.spec.ts @@ -3,7 +3,7 @@ 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"; +import { BENCH_RUN, BENCH_RUN_V2, QWEN, SONNET, makeBenchRun, makeBenchRunV2 } from "./fixtures/bench-fixture.mjs"; // --------------------------------------------------------------------------- // The verdict bench's page (release 28 M7) over a synthetic run in the @@ -25,11 +25,13 @@ const stubAsked = (route: string) => test.beforeAll(async ({ playwright }) => { test.setTimeout(WARM_TIMEOUT); makeBenchRun(ROOT); + makeBenchRunV2(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 }); + rmSync(path.join(ROOT, BENCH_RUN_V2), { 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 }) => { @@ -95,3 +97,56 @@ test("the bar: saved through the editor's settings action; a passing model ticke 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"); }); + +test("V1: the run's prompt version and items hash; compare with a run over the same items", async ({ page }) => { + await page.goto(`/tools/bench?run=${BENCH_RUN_V2}`); + const status = page.locator(`[data-bench-run="${BENCH_RUN_V2}"]`).getByRole("status"); + await expect(status.locator("[data-prompt-version]")).toHaveText("prompt v2"); + const hash = await status.locator("[data-items-hash]").getAttribute("data-items-hash"); + expect(hash).toMatch(/^[0-9a-f]{16}$/); + // The first run (made before V1: version 1) has the same items. + await page.goto(`/tools/bench?run=${BENCH_RUN}`); + await expect(page.locator(`[data-bench-run="${BENCH_RUN}"]`).getByRole("status").locator("[data-prompt-version]")).toHaveText("prompt v1"); + await expect(page.locator(`[data-bench-run="${BENCH_RUN}"]`).getByRole("status").locator("[data-items-hash]")).toHaveAttribute("data-items-hash", hash!); + await page.goto(`/tools/bench?run=${BENCH_RUN_V2}`); + const compare = page.getByRole("region", { name: "compare" }); + await compare.getByRole("navigation", { name: "compare with" }).getByRole("link", { name: `${BENCH_RUN} · prompt v1` }).click(); + await expect(page).toHaveURL(new RegExp(`compare=${BENCH_RUN}`)); + const row = compare.locator(`[data-compare="${BENCH_RUN}"] tr[data-model="${SONNET}"]`); + await expect(row.locator('[data-metric="agreement-a"]')).toHaveText("75%"); + await expect(row.locator('[data-metric="agreement-b"]')).toHaveText("75%"); + await expect(row.locator('[data-metric="changed"]')).toHaveText("2 · 1 now agree · 1 no longer"); + // Only Sonnet was asked in both. + await expect(compare.locator(`tr[data-model="${QWEN}"]`)).toHaveCount(0); + const changed = compare.getByRole("list", { name: "changed answers" }).locator("li"); + await expect(changed).toHaveCount(2); + await expect(changed.nth(0)).toHaveText(`${SONNET} synth-bench/c2: CORROBORATED → PARTLY (ruled PARTLY)`); + await expect(changed.nth(1)).toHaveText(`${SONNET} synth-bench/c3: CONTRADICTED → PARTLY (ruled CONTRADICTED)`); + // What the verdicts mean: the one copy. + await page.getByText("what the verdicts mean").click(); + await expect(page.locator('[data-meaning="CORROBORATED"]')).toContainText("the substance of the claim is shown by the cited words"); +}); + +test("V1: a Right mark on a disagreement moves the marked precision; again unmarks", async ({ page }) => { + await page.goto(`/tools/bench?run=${BENCH_RUN}`); + const precision = page.getByRole("region", { name: "precision" }).locator(`tr[data-model="${SONNET}"]`); + await expect(precision.locator('[data-metric="precision"]')).toHaveText("100% / 66.7%"); + await expect(precision.locator('[data-metric="marked-precision"]')).toHaveText("100% / 66.7%"); + await expect(precision.locator('[data-metric="marks"]')).toHaveText("none yet"); + // Sonnet called the PARTLY claim c2 CORROBORATED: the operator says the model was right. + const cell = page.getByRole("region", { name: "items" }).locator('tr[data-item="synth-bench/c2"]').locator(`[data-model="${SONNET}"]`); + // An agreeing answer has no mark buttons. + await expect(page.getByRole("region", { name: "items" }).locator('tr[data-item="synth-bench/c1"]').locator(`[data-model="${SONNET}"]`).getByRole("button")).toHaveCount(0); + await cell.getByRole("button", { name: "Right" }).click(); + await expect(cell.getByRole("button", { name: "Right" })).toHaveAttribute("aria-pressed", "true"); + await expect(precision.locator('[data-metric="marked-precision"]')).toHaveText("100% / 100%"); + await expect(precision.locator('[data-metric="marks"]')).toHaveText("1 right · 0 wrong"); + // The plain score is the ruling's, unmoved. + await expect(precision.locator('[data-metric="precision"]')).toHaveText("100% / 66.7%"); + // Kept across a reload; again unmarks. + await page.reload(); + await expect(cell.locator("[data-mark]")).toHaveAttribute("data-mark", "right"); + await cell.getByRole("button", { name: "Right" }).click(); + await expect(precision.locator('[data-metric="marks"]')).toHaveText("none yet"); + await expect(cell.getByRole("button", { name: "Right" })).toHaveAttribute("aria-pressed", "false"); +}); diff --git a/umtool/lib/bench-marks.mjs b/umtool/lib/bench-marks.mjs @@ -0,0 +1,123 @@ +// THE VERDICT BENCH'S MARKS (release 29 V1): the operator's Right / Wrong on +// a disagreement — was the MODEL right, where its answer is not the ruling? — +// kept beside the run, so the bar can be set from marked precision +// (common's `markedScore`, tallied by triage's `markTally`). +// +// <bench root>/<run>/marks.json +// { format: "archilyzer-bench-marks", version: 1, run, +// marks: { "<model>": { "<report>/<claim>": { verdict: "right" | "wrong", +// answer, at } } }, +// updatedAt } +// +// `answer` is the model's verdict the mark was made on: a resumed run that +// asked again and got another answer leaves the mark stale (not applied). +// +// R6's discipline (lib/research/triage-marks.mjs): ONE writer (umtool), +// serialised in-process; the whole file to a temp name and a rename; a file +// that does not parse is never overwritten (a write refuses with 409). The +// run's other files are the editor's job's; this one is never touched by it. +// +// Plain ESM: the unit test reads it the way the app does. +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const BENCH_MARKS_FORMAT = "archilyzer-bench-marks"; +export const BENCH_MARKS_VERSION = 1; +const RUN_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; +const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/; +const KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}\/[A-Za-z0-9._:-]{1,64}$/; +const VERDICTS = ["CORROBORATED", "PARTLY", "CONTRADICTED", "NOT_FOUND", "UNTESTABLE"]; + +export class BenchMarksError extends Error { + constructor(message, status = 400) { + super(message); + this.status = status; + } +} + +export const benchMarksFile = (root, run) => { + if (!RUN_RE.test(run)) throw new BenchMarksError(`not a run id: ${JSON.stringify(run)}`); + return path.join(root, run, "marks.json"); +}; + +function clean(raw, run) { + const marks = {}; + const given = raw?.marks && typeof raw.marks === "object" ? raw.marks : {}; + for (const [model, byKey] of Object.entries(given)) { + if (!MODEL_RE.test(model) || !byKey || typeof byKey !== "object") continue; + for (const [key, m] of Object.entries(byKey)) { + if (!KEY_RE.test(key) || !m || (m.verdict !== "right" && m.verdict !== "wrong")) continue; + (marks[model] ??= {})[key] = { + verdict: m.verdict, + answer: VERDICTS.includes(m.answer) ? m.answer : null, + at: typeof m.at === "string" ? m.at.slice(0, 40) : "", + }; + } + } + return { format: BENCH_MARKS_FORMAT, version: BENCH_MARKS_VERSION, run, marks, updatedAt: typeof raw?.updatedAt === "string" ? raw.updatedAt : "" }; +} + +/** A run's marks (none: an empty set). A file that does not read is a 409. */ +export async function readBenchMarksDoc(root, run) { + let text; + try { + text = await readFile(/* turbopackIgnore: true */ benchMarksFile(root, run), "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return clean(null, run); + if (err instanceof BenchMarksError) throw err; + throw new BenchMarksError(`the marks of ${run} cannot be read: ${err?.message ?? err}`, 409); + } + let raw; + try { + raw = JSON.parse(text); + } catch (err) { + throw new BenchMarksError(`${run}/marks.json is not JSON: ${err.message}`, 409); + } + if (raw?.format !== BENCH_MARKS_FORMAT) throw new BenchMarksError(`${run}/marks.json is not a ${BENCH_MARKS_FORMAT} file`, 409); + return clean(raw, run); +} + +let chain = Promise.resolve(); +function serialised(fn) { + const run = chain.then(fn); + chain = run.catch(() => {}); + return run; +} + +/** + * Mark one disagreement right or wrong (`verdict` null: unmark), on the + * model's `answer`. Answers the marks as written. + * + * @param {string} root the bench runs' directory + * @param {string} run + * @param {{ model: string, key: string, verdict: "right" | "wrong" | null, answer: string | null, now?: Date }} m + */ +export function setBenchMark(root, run, m) { + return serialised(async () => { + if (!MODEL_RE.test(m.model ?? "")) throw new BenchMarksError(`not a model: ${JSON.stringify(m.model)}`); + if (!KEY_RE.test(m.key ?? "")) throw new BenchMarksError(`not an item: ${JSON.stringify(m.key)}`); + if (m.verdict !== null && m.verdict !== "right" && m.verdict !== "wrong") throw new BenchMarksError('"verdict" is "right", "wrong" or null'); + const doc = await readBenchMarksDoc(root, run); + const at = (m.now ?? new Date()).toISOString(); + if (m.verdict === null) { + if (doc.marks[m.model]) { + delete doc.marks[m.model][m.key]; + if (!Object.keys(doc.marks[m.model]).length) delete doc.marks[m.model]; + } + } else { + (doc.marks[m.model] ??= {})[m.key] = { verdict: m.verdict, answer: VERDICTS.includes(m.answer) ? m.answer : null, at }; + } + doc.updatedAt = at; + const file = benchMarksFile(root, run); + await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + try { + await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); + await rename(/* turbopackIgnore: true */ tmp, file); + } catch (err) { + await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); + throw err; + } + return doc; + }); +} diff --git a/umtool/lib/bench-marks.test.mjs b/umtool/lib/bench-marks.test.mjs @@ -0,0 +1,35 @@ +// The verdict bench's marks (release 29 V1): set, unmark, per model and item, +// the file shape common's reader takes; a broken file is never overwritten. +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 { BenchMarksError, benchMarksFile, readBenchMarksDoc, setBenchMark } from "./bench-marks.mjs"; + +test("bench marks: right and wrong per model and item, on the answer marked; unmark; a broken file refuses", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "bench-marks-")); + try { + assert.deepEqual((await readBenchMarksDoc(root, "vb-x")).marks, {}); + const now = new Date("2026-10-15T10:00:00Z"); + await setBenchMark(root, "vb-x", { model: "qwen3:8b", key: "synth-ruled/r01", verdict: "right", answer: "PARTLY", now }); + await setBenchMark(root, "vb-x", { model: "qwen3:8b", key: "synth-ruled/r02", verdict: "wrong", answer: "NOT_FOUND", now }); + const doc = await setBenchMark(root, "vb-x", { model: "claude-sonnet-5-5", key: "synth-ruled/r01", verdict: "wrong", answer: "CONTRADICTED", now }); + assert.deepEqual(doc.marks["qwen3:8b"]["synth-ruled/r01"], { verdict: "right", answer: "PARTLY", at: now.toISOString() }); + assert.deepEqual(Object.keys(doc.marks).sort(), ["claude-sonnet-5-5", "qwen3:8b"]); + const after = await setBenchMark(root, "vb-x", { model: "claude-sonnet-5-5", key: "synth-ruled/r01", verdict: null, answer: null }); + assert.deepEqual(Object.keys(after.marks), ["qwen3:8b"]); + const onDisk = JSON.parse(await readFile(benchMarksFile(root, "vb-x"), "utf8")); + assert.equal(onDisk.format, "archilyzer-bench-marks"); + assert.equal(onDisk.run, "vb-x"); + await assert.rejects(setBenchMark(root, "vb-x", { model: "q", key: "no-slash", verdict: "right", answer: null }), BenchMarksError); + await assert.rejects(setBenchMark(root, "Bad Run", { model: "q", key: "a/b", verdict: "right", answer: null }), /not a run id/); + + await mkdir(path.join(root, "vb-broken"), { recursive: true }); + await writeFile(benchMarksFile(root, "vb-broken"), "{ nope"); + await assert.rejects(setBenchMark(root, "vb-broken", { model: "q", key: "a/b", verdict: "right", answer: null }), (e) => e.status === 409); + assert.equal(await readFile(benchMarksFile(root, "vb-broken"), "utf8"), "{ nope"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/bench.ts b/umtool/lib/bench.ts @@ -1,31 +1,49 @@ 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 { VERDICTS, type Verdict } from "yt-dlp-transcript-common/lib/report/verdicts"; +import { VERDICT_MEANINGS, VERDICT_TIE_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), 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. +// 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. +// +// 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<BenchSummary, "id" | "createdAt" | "status" | "models" | "items" | "spentUsd" | "maxUsd">; +export type BenchRunRow = Pick<BenchSummary, "id" | "createdAt" | "status" | "models" | "items" | "spentUsd" | "maxUsd"> & { + promptVersion: string; + itemsHash: string; +}; export type BenchItemRow = { key: string; @@ -33,34 +51,53 @@ export type BenchItemRow = { claim: string; text: string; verdict: Verdict; - answers: Record<string, { verdict: Verdict | null; reason?: string; failure?: string; error?: string }>; + answers: Record<string, { verdict: Verdict | null; reason?: string; failure?: string; error?: string; mark?: "right" | "wrong" }>; // 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<string> { + 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<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, - })); + 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[]): BenchItemRow[] { +function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], models: readonly string[], marks: BenchMarks = {}): BenchItemRow[] { const by = new Map<string, BenchResult>(); for (const r of results) by.set(`${r.model}\u0000${r.key}`, r); return items.map((it) => { @@ -69,20 +106,78 @@ function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], mo 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 } : {}) }; + 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 } : {}), + }; 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); +export async function readBenchView(id: string, compareWith?: string): Promise<BenchView | null> { + const root = benchRoot(); + const run = await readBenchRun(root, 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) }; + 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_TIE_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(