#!/usr/bin/env python3
"""Render the rubric library + experiment metrics as one self-contained page.
python3 make_browser.py --out browser.html
Everything inlined -- no server, no fetches: open the file. Regenerate after
any pipeline run; the page states which corpus and truth source produced each
number so a stale copy cannot masquerade as current.
"""
from __future__ import annotations
import argparse
import html
import json
import re
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
CSS = """
body{font-family:-apple-system,Segoe UI,Helvetica,Arial,sans-serif;margin:0;background:#0f1115;color:#e6e6e6}
header{padding:24px 32px;background:#161a22;border-bottom:1px solid #2a2f3a}
h1{margin:0 0 6px;font-size:22px} .sub{color:#9aa4b2;font-size:13px}
main{max-width:1100px;margin:0 auto;padding:24px 32px}
h2{font-size:17px;border-bottom:1px solid #2a2f3a;padding-bottom:6px;margin-top:36px}
table{border-collapse:collapse;width:100%;font-size:13px;margin:12px 0}
th,td{border:1px solid #2a2f3a;padding:6px 10px;text-align:left}
th{background:#161a22} .good{color:#7ee08a} .bad{color:#ff7d7d} .warn{color:#ffd479}
.note{color:#9aa4b2;font-size:12px;margin:4px 0 16px}
details{border:1px solid #2a2f3a;border-radius:6px;margin:8px 0;background:#141822}
summary{cursor:pointer;padding:10px 14px;font-size:14px}
summary .cls{display:inline-block;min-width:170px;color:#8ab4ff}
summary .prov{float:right;color:#9aa4b2;font-size:12px}
.body{padding:0 18px 14px;font-size:13px;line-height:1.5}
.body pre{background:#0b0d12;border:1px solid #232838;border-radius:4px;padding:10px;overflow-x:auto;font-size:12px}
.body code{color:#ffd479}
.filter{margin:12px 0}
.filter button{background:#161a22;color:#e6e6e6;border:1px solid #2a2f3a;border-radius:4px;padding:4px 10px;margin-right:6px;cursor:pointer;font-size:12px}
.filter button.on{background:#2a3550;border-color:#8ab4ff}
"""
JS = """
function filt(cls,btn){
document.querySelectorAll('.filter button').forEach(b=>b.classList.remove('on'));
btn.classList.add('on');
document.querySelectorAll('details.rubric').forEach(d=>{
d.style.display=(cls==='all'||d.dataset.cls===cls)?'':'none';});
}
"""
def md_to_html(text: str) -> str:
"""Just enough markdown for these rubric files."""
out, in_code = [], False
for line in text.splitlines():
if line.strip().startswith("```"):
out.append("" if in_code else "
")
in_code = not in_code
continue
if in_code:
out.append(html.escape(line))
continue
esc = html.escape(line)
esc = re.sub(r"\*\*(.+?)\*\*", r"\1", esc)
esc = re.sub(r"`([^`]+)`", r"\1", esc)
if esc.startswith("### "):
esc = f"
truth source: {html.escape(pr.get('truth_source','?'))} "
f"· {pr.get('decisions','?')} blind decisions across "
f"{len(pr.get('eval_competitions',[]))} held-out competitions
")
rows = ["
family
precision
95% CI
"
"
recall
95% CI
tp/fp/fn
"]
for fam in ("conceptual", "control_generic", "control_shuffled",
"control_conceptual"):
m = (pr.get("by_family") or {}).get(fam)
if not m:
continue
cls = "good" if fam == "conceptual" else "warn"
rows.append(
f"
{fam}
"
f"
{fmt(m.get('precision'))}
{m.get('precision_ci95') or '—'}
"
f"
{fmt(m.get('recall'))}
{m.get('recall_ci95') or '—'}
"
f"
{m.get('tp')}/{m.get('fp')}/{m.get('fn')}
")
rows.append("
")
parts.append("".join(rows))
parts.append("
Controls are the floor: vague criticism and "
"domain-swapped rubrics score zero precision; whatever the real "
"rubrics score above that is earned signal.
")
if truth_rep:
parts.append(f"
ground-truth annotator agreement: "
f"{fmt(truth_rep.get('annotator_agreement_per_group'), pct=True)} per group of "
f"{truth_rep.get('annotation_batch','?')} (reference protocol reports 97%)
")
if assist:
p = assist.get("paired") or {}
parts.append("
Utility: does giving the rubrics to a coding agent help?
")
parts.append(
f"
paired states
guided better
revise better
"
f"
ties
mean advantage
median advantage
"
f"
{p.get('paired_states','—')}
"
f"
{p.get('guided_better','—')}
"
f"
{p.get('revise_better','—')}
"
f"
{p.get('ties','—')}
"
f"
{fmt(p.get('mean_paired_advantage'), pct=True)}
"
f"
{fmt(p.get('median_paired_advantage'), pct=True)}
")
parts.append("
guided = revision with retrieved rubrics; revise = "
"same revision without them (the control). The rubrics' contribution "
"is the difference, paired on the same starting program.
")
if cf:
parts.append("
Causal: does removing the flagged pattern improve the score?
")
parts.append(
f"
fires measured
improved
causal precision
"
f"
mean improvement
outcomes
"
f"
{cf.get('measured')}
{cf.get('helped')}
"
f"
{fmt(cf.get('causal_precision'))}
"
f"
{cf.get('mean_improvement')}
"
f"
{html.escape(json.dumps(cf.get('outcomes', {})))}
")
parts.append("
Patch out exactly what the rubric flagged, re-run, "
"re-grade against the official answers. Failed edits are excluded "
"from the denominator; they are facts about the editor.
")
return "\n".join(parts)
def rubric_section() -> str:
files = sorted((HERE / "out" / "conceptual").glob("*.md"))
classes = sorted({f.name.split("__")[0].upper() for f in files})
buttons = ["
"]
for cls in classes:
n = sum(1 for f in files if f.name.split("__")[0].upper() == cls)
buttons.append(f"")
buttons.append("
")
cards = []
lib = {}
for row in (load_json(HERE / "data" / "conceptual_applicable.jsonl") or []):
pass # jsonl, not json -- handled below
try:
for line in (HERE / "data" / "conceptual_applicable.jsonl").read_text().splitlines():
if line.strip():
r = json.loads(line)
lib[r["id"]] = r
except OSError:
pass
for f in files:
cls = f.name.split("__")[0].upper()
text = f.read_text()
title = re.search(r"### P1 — (.+)", text)
cand = lib.get(f.stem.rsplit("__", 1)[-1], {})
prov = cand.get("provenance", "")
eff = cand.get("measured_effect")
prov_txt = prov + (f" · effect {eff:+.4f}" if eff is not None else "")
cards.append(
f""
f"{cls} · {html.escape(f.name.split('__')[1])} "
f"{html.escape(title.group(1) if title else f.name)}"
f"{prov_txt}"
f"