/* NEEDLEPOINT Studio front end. Vanilla ES module, no dependencies, no external requests. */ // ============================================================== utilities const $ = (sel, root = document) => root.querySelector(sel); const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel)); const SVGNS = "http://www.w3.org/2000/svg"; const motionQuery = window.matchMedia("(prefers-reduced-motion: reduce)"); const forceReduce = /[?&]motion=reduce\b/.test(location.search); // handy for testing: /?motion=reduce const reduced = () => forceReduce || motionQuery.matches; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const wait = (ms) => (reduced() ? Promise.resolve() : sleep(ms)); const clamp = (v, a, b) => Math.max(a, Math.min(b, v)); /** Create an HTML element. attrs: plain attributes, plus on* handlers, `class`, `style` (string), `html`. */ function h(tag, attrs = {}, ...kids) { const el = document.createElement(tag); setAttrs(el, attrs); append(el, kids); return el; } /** Create an SVG element. */ function s(tag, attrs = {}, ...kids) { const el = document.createElementNS(SVGNS, tag); setAttrs(el, attrs); append(el, kids); return el; } function setAttrs(el, attrs) { for (const [k, v] of Object.entries(attrs || {})) { if (v === null || v === undefined || v === false) continue; if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2), v); else if (k === "html") el.innerHTML = v; else if (k === "text") el.textContent = v; else el.setAttribute(k, v === true ? "" : String(v)); } } function append(el, kids) { for (const k of kids.flat(Infinity)) { if (k === null || k === undefined || k === false) continue; el.append(k instanceof Node ? k : document.createTextNode(String(k))); } } const esc = (t) => String(t).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); async function api(path, opts = {}) { const init = { headers: {} }; if (opts.body !== undefined) { init.method = "POST"; init.headers["content-type"] = "application/json"; init.body = JSON.stringify(opts.body); } let res; try { res = await fetch(path, init); } catch (e) { throw new Error("Cannot reach the local NEEDLEPOINT server. Is `needlepoint serve` running?"); } if (!res.ok) { let msg = `${res.status} ${res.statusText}`; try { const j = await res.json(); if (j.detail) msg += `: ${typeof j.detail === "string" ? j.detail : JSON.stringify(j.detail)}`; } catch (_) { /* not JSON */ } throw new Error(msg); } return res.json(); } const fmtInt = (n) => Number(n).toLocaleString("en-US"); const pct = (p, d = 0) => (p === null || p === undefined ? "n/a" : `${(p * 100).toFixed(d)}%`); function usd(v) { if (v === 0) return "$0"; if (Math.abs(v) < 0.1) return `$${v.toFixed(5)}`; return `$${v.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; } function fmtNum(v, tol) { if (typeof v !== "number") return String(v); const d = tol === undefined || tol === null ? 2 : tol >= 1 ? 1 : Math.max(1, Math.ceil(-Math.log10(tol))); return Number(v.toFixed(Math.min(d, 4))).toString(); } const shortHash = (x) => (x ? (x.startsWith("sha256:") ? x.slice(7) : x) : ""); const trunc = (x, a = 10, b = 6) => (x.length > a + b + 1 ? `${x.slice(0, a)}…${x.slice(-b)}` : x); // ------------------------------------------------------------- icons (icon + word, never colour alone) const ICON = { check: '', cross: '', pending: '', copy: '', download: '', seal: '', twin: '', }; const passFail = (ok) => (ok ? `${ICON.check}Pass` : `${ICON.cross}Fail`); // ------------------------------------------------------------- vocabulary const MODEL_NAMES = { "gpt-6.2-astra": "GPT-6.2 Astra", "claude-opus-5-5": "Claude Opus 5.5", "gpt-6-luna": "GPT-6 Luna", "claude-haiku-5-5": "Claude Haiku 5.5", "gemini-3.1-flash-lite": "Gemini 3.1 Flash-Lite", "claude-sonnet-5-5": "Claude Sonnet 5.5", "gemini-3.1-pro-preview": "Gemini 3.1 Pro (preview)", "gemini-3.8-flash": "Gemini 3.8 Flash", }; const MODEL_SHORT = { "gpt-6.2-astra": "Astra", "claude-opus-5-5": "Opus", "gpt-6-luna": "Luna", "claude-haiku-5-5": "Haiku", "gemini-3.1-flash-lite": "Flash-Lite" }; const mName = (m) => MODEL_NAMES[m] || m; const mShort = (m) => MODEL_SHORT[m] || mName(m); const mColor = (m) => `var(--m-${m.replace(/[^a-z0-9]+/gi, "-")}, var(--muted))`; const swatch = (m, cls = "swatch") => h("span", { class: cls, style: `background:${mColor(m)}`, "aria-hidden": "true" }); const GATE_FALLBACK = { W3_legibility: "Label legibility", W4_leak: "No answer leak", G7_twin: "Answer-flip twin" }; const gateLabel = (id) => (state.meta?.gates || []).find((g) => g.id === id)?.label || GATE_FALLBACK[id] || id.replace(/^[A-Z]\d+_/, "").replace(/_/g, " "); const gateShort = (id) => id.split("_")[0]; const OP_INFO = { READ: "Read one instrument", THRESH: "Is it in its alarm range?", COMPARE: "Which reading is highest?", DIFF: "Difference of two readings", COUNT_ALARM: "Count instruments in alarm", SCALE: "Apply the scale multiplier", BIND: "Bind a tag to its instrument", ABSTAIN: "Indicator hidden: must abstain", TRACE: "Trace a wire through crossings", }; const FAULTS = { occluded: { name: "Occluded needle", desc: "A cover plate hides the needle. Nobody can read it from the image, so the task must not ship.", icon: '' }, illegible: { name: "Illegible labels", desc: "Scale numbers shrunk and faded until they cannot be read reliably.", icon: '' }, near_threshold: { name: "Near-threshold reading", desc: "The value sits a hair from the alarm line, so an honest reader could go either way.", icon: '' }, wrong_key: { name: "Wrong answer key", desc: "The image says one thing and the answer key says another.", icon: '' }, leak: { name: "Answer leaked in question", desc: "The question text gives the answer away, so the image is never needed.", icon: '' }, missing_glyph: { name: "Missing glyph", desc: "A character the font cannot draw renders as an empty box (tofu).", icon: '' }, }; // ------------------------------------------------------------- global state const state = { meta: null, runs: [], results: null, models: null, current: null, // {run_id, tasks, metrics?, seed?, family?, rejections?} lastGenerated: null, // run_id proofOn: false, insp: null, // {run, list, idx, task, proof, opener, pushed} }; const loaded = {}; // ------------------------------------------------------------- toast, copy, tooltip let toastTimer; function toast(msg) { const t = $("#toast"); t.textContent = msg; t.classList.add("show"); clearTimeout(toastTimer); toastTimer = setTimeout(() => t.classList.remove("show"), 1800); } async function copyText(text, what = "Copied") { try { await navigator.clipboard.writeText(text); } catch (_) { const ta = h("textarea", { style: "position:fixed;opacity:0" }); ta.value = text; document.body.append(ta); ta.select(); try { document.execCommand("copy"); } catch (e) { /* ignore */ } ta.remove(); } toast(`${what} copied`); } const copyBtn = (text, label) => h("button", { type: "button", class: "icon-btn copy-btn", "aria-label": `Copy ${label}`, title: `Copy ${label}`, html: ICON.copy, onclick: () => copyText(text, label) }); const tip = h("div", { class: "tooltip", role: "tooltip", id: "np-tooltip" }); document.body.append(tip); function showTip(html, target) { tip.innerHTML = html; tip.classList.add("show"); const r = target.getBoundingClientRect(); const tw = tip.offsetWidth, th = tip.offsetHeight; let x = r.left + r.width / 2 - tw / 2; let y = r.top - th - 10; if (y < 70) y = r.bottom + 10; x = clamp(x, 8, window.innerWidth - tw - 8); tip.style.left = `${x}px`; tip.style.top = `${y}px`; } const hideTip = () => { tip.classList.remove("show"); tip.style.left = "0px"; tip.style.top = "0px"; }; function bindTip(el, html) { const show = () => showTip(typeof html === "function" ? html() : html, el); el.addEventListener("mouseenter", show); el.addEventListener("mouseleave", hideTip); el.addEventListener("focus", show); el.addEventListener("blur", hideTip); } window.addEventListener("scroll", hideTip, { passive: true }); /** Roving tabindex over a 2-D grid of focusable elements (arrow keys move, one tab stop). */ function roving(grid) { const flat = grid.flat().filter(Boolean); flat.forEach((el, i) => el.setAttribute("tabindex", i === 0 ? "0" : "-1")); grid.forEach((row, r) => row.forEach((el, c) => { if (!el) return; el.addEventListener("keydown", (e) => { let nr = r, nc = c; if (e.key === "ArrowRight") nc++; else if (e.key === "ArrowLeft") nc--; else if (e.key === "ArrowDown") nr++; else if (e.key === "ArrowUp") nr--; else if (e.key === "Home") nc = 0; else if (e.key === "End") nc = row.length - 1; else return; e.preventDefault(); nr = clamp(nr, 0, grid.length - 1); nc = clamp(nc, 0, grid[nr].length - 1); const nxt = grid[nr][nc]; if (nxt) { flat.forEach((x) => x.setAttribute("tabindex", "-1")); nxt.setAttribute("tabindex", "0"); nxt.focus(); } }); })); } /** Count-up for a number in an element (instant when reduced motion). */ function countUp(el, to, { dur = 1200, fmt = (v) => fmtInt(Math.round(v)) } = {}) { if (reduced()) { el.textContent = fmt(to); return; } const t0 = performance.now(); const step = (t) => { const p = clamp((t - t0) / dur, 0, 1); const e = 1 - Math.pow(1 - p, 4); el.textContent = fmt(to * e); if (p < 1) requestAnimationFrame(step); }; requestAnimationFrame(step); } // ============================================================== theme function currentTheme() { return document.documentElement.dataset.theme === "light" ? "light" : "dark"; } function applyThemeLabel() { const light = currentTheme() === "light"; const btn = $("#theme-toggle"); btn.querySelector(".theme-toggle-label").textContent = light ? "Dark theme" : "Light theme"; btn.setAttribute("aria-label", light ? "Switch to dark theme" : "Switch to light theme"); btn.removeAttribute("aria-pressed"); } $("#theme-toggle").addEventListener("click", () => { const next = currentTheme() === "light" ? "dark" : "light"; document.documentElement.dataset.theme = next; try { localStorage.setItem("np-theme", next); } catch (_) { /* storage blocked */ } applyThemeLabel(); if (state.results && !$("#view-map").hidden) renderMap(false); }); applyThemeLabel(); // ============================================================== nav & router const VIEWS = ["home", "factory", "lab", "map", "ship", "how"]; const TITLES = { home: "NEEDLEPOINT Studio", factory: "Factory", lab: "Verifier Lab", map: "Capability Map", ship: "Ship it", how: "How it works" }; let currentView = null; let firstRoute = true; const navToggle = $("#nav-toggle"); const nav = $("#primary-nav"); navToggle.addEventListener("click", () => { const open = navToggle.getAttribute("aria-expanded") !== "true"; navToggle.setAttribute("aria-expanded", String(open)); nav.classList.toggle("open", open); if (open) nav.querySelector("a")?.focus(); }); function closeNav() { navToggle.setAttribute("aria-expanded", "false"); nav.classList.remove("open"); } nav.addEventListener("click", (e) => { if (e.target.closest("a")) closeNav(); }); document.addEventListener("keydown", (e) => { if (e.key === "Escape" && nav.classList.contains("open")) { closeNav(); navToggle.focus(); } }); document.addEventListener("click", (e) => { if (nav.classList.contains("open") && !e.target.closest("#topbar")) closeNav(); }); $("#skip-link").addEventListener("click", (e) => { e.preventDefault(); const v = currentView && $(`#view-${currentView} h1`); (v || $("#main")).focus(); }); function parseHash() { const raw = location.hash.replace(/^#\/?/, ""); const parts = raw.split("/").filter(Boolean).map(decodeURIComponent); if (parts[0] === "task" && parts[1] && parts[2]) return { view: "factory", task: { run: parts[1], task: parts[2] } }; return { view: VIEWS.includes(parts[0]) ? parts[0] : "home" }; } function route() { if (location.hash && !location.hash.startsWith("#/")) return; // in-page anchors const r = parseHash(); showView(r.view); if (r.task) openInspector(r.task.run, r.task.task); else if (state.insp) closeInspector({ fromRoute: true }); } window.addEventListener("hashchange", route); function showView(view) { if (view === currentView) return; for (const v of VIEWS) $(`#view-${v}`).hidden = v !== view; $$(".primary-nav a").forEach((a) => { if (a.dataset.route === view) a.setAttribute("aria-current", "page"); else a.removeAttribute("aria-current"); }); document.title = view === "home" ? TITLES.home : `${TITLES[view]} · NEEDLEPOINT Studio`; currentView = view; if (!firstRoute) { window.scrollTo({ top: 0, behavior: "instant" }); $(`#view-${view} h1`)?.focus({ preventScroll: true }); } firstRoute = false; ({ home: initHome, factory: initFactory, lab: initLab, map: initMap, ship: initShip, how: initHow })[view](); } // ============================================================== shared data let metaP = null; function getMeta() { if (!metaP) metaP = api("/api/meta").then((m) => { state.meta = m; $("#footer-version").textContent = `v${m.version}`; return m; }) .catch((e) => { metaP = null; throw e; }); return metaP; } async function refreshRuns() { try { state.runs = (await api("/api/runs")).runs || []; } catch (_) { state.runs = []; } return state.runs; } function errorBox(el, err, retry) { el.hidden = false; el.replaceChildren(h("strong", {}, "Something went wrong."), h("span", {}, err.message || String(err)), retry ? h("button", { type: "button", class: "btn btn-sm btn-ghost", onclick: () => { el.hidden = true; retry(); } }, "Try again") : null); } // ============================================================== HOME function heroGauge() { const C = { x: 64, y: 64 }, R = 40; const a0 = 230.5, a1 = -50.5; // scale spans the logo's dial arc const pt = (deg, r) => [C.x + r * Math.cos((deg * Math.PI) / 180), C.y - r * Math.sin((deg * Math.PI) / 180)]; const ticks = []; for (let i = 0; i <= 50; i++) { const deg = a0 + ((a1 - a0) * i) / 50; const major = i % 10 === 0; const mid = i % 5 === 0; const [x1, y1] = pt(deg, 45.5); const [x2, y2] = pt(deg, major ? 50.5 : mid ? 49 : 47.5); ticks.push(s("line", { x1, y1, x2, y2, class: `hg-tick${major ? " major" : ""}`, "stroke-width": major ? 1.1 : 0.6 })); if (major) { const [tx, ty] = pt(deg, 55.5); ticks.push(s("text", { x: tx, y: ty, class: "hg-num" }, String(i * 2))); } } const svg = s("svg", { viewBox: "-4 -4 136 136", role: "img", "aria-label": "Animated gauge: the needle sweeps across the dial and settles into a check mark, the NEEDLEPOINT logo." }, s("defs", {}, s("radialGradient", { id: "hg-face", cx: "50%", cy: "42%", r: "60%" }, s("stop", { offset: "0", "stop-color": "#1A2A4C" }), s("stop", { offset: "1", "stop-color": "#0B1220" })), s("radialGradient", { id: "hg-face-light", cx: "50%", cy: "42%", r: "60%" }, s("stop", { offset: "0", "stop-color": "#22345C" }), s("stop", { offset: "1", "stop-color": "#0F1A30" })), s("linearGradient", { id: "hg-dial", x1: "0", y1: "1", x2: "1", y2: "0" }, s("stop", { offset: "0", "stop-color": "#22D3EE" }), s("stop", { offset: "1", "stop-color": "#7C5CFF" })), s("filter", { id: "hg-glow", x: "-50%", y: "-50%", width: "200%", height: "200%" }, s("feGaussianBlur", { stdDeviation: "1.6", result: "b" }), s("feMerge", {}, s("feMergeNode", { in: "b" }), s("feMergeNode", { in: "SourceGraphic" })))), s("circle", { cx: 64, cy: 64, r: 61, class: "hg-face" }), s("circle", { cx: 64, cy: 64, r: 61, class: "hg-ring", id: "hg-ring" }), s("g", { style: "color:#F8FAFC" }, ticks), s("path", { d: "M35.72,98.28 A40,40 0 1 1 103.39,76.95", fill: "none", stroke: "url(#hg-dial)", "stroke-width": 7, "stroke-linecap": "round", id: "hg-arc" }), s("path", { d: "M102.04,82.36 A40,40 0 0 1 92.28,98.28", fill: "none", stroke: "#FF4D5E", "stroke-width": 7, "stroke-linecap": "round" }), s("path", { d: "M46,60 L60,74", fill: "none", stroke: "#F8FAFC", "stroke-width": 8, "stroke-linecap": "round", id: "hg-short", "stroke-dasharray": "20", "stroke-dashoffset": "20" }), s("g", { id: "hg-needle", style: "transform-box:view-box;transform-origin:60px 74px" }, s("path", { d: "M60,74 L83.4,44.1", fill: "none", stroke: "#F8FAFC", "stroke-width": 8, "stroke-linecap": "round" }), s("circle", { cx: 83.4, cy: 44.1, r: 5, fill: "#22D3EE", filter: "url(#hg-glow)" })), s("text", { x: 64, y: 107, class: "hg-readout", id: "hg-readout", style: "fill:#B6C2D4", opacity: 0 }, "CERTIFIED"), ); return svg; } function playHero() { const wrap = $("#hero-visual"); if (!wrap.querySelector("svg")) wrap.replaceChildren(heroGauge()); const needle = $("#hg-needle"), short = $("#hg-short"), ring = $("#hg-ring"), readout = $("#hg-readout"); needle.getAnimations?.().forEach((a) => a.cancel()); if (reduced()) { short.setAttribute("stroke-dashoffset", "0"); readout.setAttribute("opacity", "1"); return; } short.setAttribute("stroke-dashoffset", "20"); readout.setAttribute("opacity", "0"); needle.animate([ { transform: "rotate(-178deg)", easing: "cubic-bezier(.3,0,.25,1)" }, { transform: "rotate(24deg)", offset: 0.55, easing: "ease-in-out" }, { transform: "rotate(-11deg)", offset: 0.72, easing: "ease-in-out" }, { transform: "rotate(5deg)", offset: 0.85, easing: "ease-in-out" }, { transform: "rotate(-1.5deg)", offset: 0.94 }, { transform: "rotate(0deg)" }, ], { duration: 1900, delay: 250, fill: "backwards" }); short.animate([{ strokeDashoffset: 20 }, { strokeDashoffset: 0 }], { duration: 320, delay: 2050, easing: "cubic-bezier(.16,1,.3,1)", fill: "forwards" }) .finished.then(() => short.setAttribute("stroke-dashoffset", "0")).catch(() => {}); ring.animate([{ opacity: 0.9, strokeWidth: 0.6, transform: "scale(.92)" }, { opacity: 0, strokeWidth: 0.2, transform: "scale(1.06)" }], { duration: 900, delay: 2250, easing: "ease-out", fill: "none" }); ring.style.transformBox = "view-box"; ring.style.transformOrigin = "64px 64px"; readout.animate([{ opacity: 0, transform: "translateY(3px)" }, { opacity: 1, transform: "none" }], { duration: 500, delay: 2350, fill: "forwards", easing: "ease-out" }) .finished.then(() => readout.setAttribute("opacity", "1")).catch(() => {}); } async function initHome() { playHero(); if (loaded.home) return; loaded.home = true; const ul = $("#home-stats"); try { const m = await getMeta(); const ev = m.evidence || {}; const recalls = Object.values(ev.fault_recall || {}); const recall = recalls.length ? recalls.reduce((a, b) => a + b, 0) / recalls.length : null; const [hOk, hN] = String(ev.harbor_checks || "0/0").split("/").map(Number); const stats = [ { to: ev.final_tasks || 0, fmt: (v) => fmtInt(Math.round(v)), label: "certified tasks in the final evaluation" }, { to: recall === null ? 0 : recall * 100, fmt: (v) => `${Math.round(v)}%`, label: `planted-defect recall across ${recalls.length} defect classes` }, { to: hOk, fmt: (v) => `${Math.round(v)}/${hN}`, label: "Harbor validation checks passed" }, { to: 0, fmt: () => "$0", label: "API cost to generate a task" }, ]; ul.replaceChildren(...stats.map((st) => { const num = h("span", { class: "stat-num", "aria-hidden": "true" }, st.fmt(0)); const li = h("li", { class: "stat" }, num, h("span", { class: "sr-only" }, `${st.fmt(st.to)} `), h("span", { class: "stat-label" }, st.label)); countUp(num, st.to, { fmt: st.fmt, dur: 1400 }); return li; })); } catch (e) { loaded.home = false; ul.replaceChildren(h("li", { class: "stat" }, h("span", { class: "stat-label" }, `Could not load evidence: ${e.message}`))); } } // ============================================================== FACTORY const PIPE_STAGES = [ { name: "Spec", icon: '' }, { name: "Render", icon: '' }, { name: "Question program", icon: '' }, { name: "Gates", icon: '' }, { name: "Certified", icon: '' }, ]; const fx = { family: "instruments", diffs: { instruments: new Set([1, 2, 3]), wiring: new Set([1, 2, 3]) } }; async function initFactory() { if (loaded.factory) return; loaded.factory = true; renderGridSkeleton(); try { await getMeta(); } catch (e) { loaded.factory = false; errorBox($("#factory-error"), e, initFactory); $("#task-grid").replaceChildren(); return; } renderDiffChips(); bindFactoryForm(); await populateRunSelect(); const r = parseHash(); const want = r.task ? r.task.run : state.lastGenerated || "final-instruments"; if (!state.current || state.current.run_id !== want) await loadRun(want); } function renderGridSkeleton(n = 8) { $("#task-grid").replaceChildren(...Array.from({ length: n }, (_, i) => h("li", { class: "task-card", style: `--i:${i}`, "aria-hidden": "true" }, h("div", { class: "task-btn" }, h("div", { class: "task-thumb" }, h("span", { class: "skeleton" })), h("div", { class: "task-info" }, h("span", { class: "skeleton sk-line", style: "width:40%" }), h("span", { class: "skeleton sk-line" }), h("span", { class: "skeleton sk-line", style: "width:70%" })))))); } function renderDiffChips() { const fam = state.meta.families[fx.family]; const box = $("#diff-chips"); box.replaceChildren(...fam.difficulties.map((d) => { const on = fx.diffs[fx.family].has(d); return h("button", { type: "button", class: "chip-toggle", "aria-pressed": String(on), title: `Difficulty ${d}`, onclick: (e) => { const set = fx.diffs[fx.family]; if (set.has(d) && set.size === 1) { toast("Keep at least one difficulty"); return; } set.has(d) ? set.delete(d) : set.add(d); e.currentTarget.setAttribute("aria-pressed", String(set.has(d))); }, }, h("svg", { class: "tick", viewBox: "0 0 12 12", "aria-hidden": "true", html: '' }), h("span", { class: "sr-only" }, "Difficulty "), `D${d}`); })); $("#profile-ctl").hidden = fx.family !== "instruments"; $("#count-label").textContent = fx.family === "wiring" ? "Tasks per level" : "Tasks"; } function bindFactoryForm() { const form = $("#gen-form"); form.addEventListener("change", (e) => { if (e.target.name === "family") { fx.family = e.target.value; $("#count").value = fx.family === "wiring" ? 2 : 8; renderDiffChips(); } }); $("#dice-btn").addEventListener("click", (e) => { $("#seed").value = Math.floor(Math.random() * 1e6); const b = e.currentTarget; b.classList.remove("rolling"); void b.offsetWidth; b.classList.add("rolling"); toast(`Seed set to ${$("#seed").value}`); }); $("#seed-copy").addEventListener("click", () => { const v = $("#seed").value || state.current?.seed; if (v === undefined || v === null || v === "") { toast("No seed yet: roll one or generate"); return; } copyText(String(v), `Seed ${v}`); }); form.addEventListener("submit", (e) => { e.preventDefault(); generate(); }); $("#run-select").addEventListener("change", (e) => loadRun(e.target.value)); } async function populateRunSelect() { await refreshRuns(); const sel = $("#run-select"); const opts = [h("option", { value: "final-instruments" }, "Frozen evidence set · final-instruments")]; for (const r of state.runs) opts.push(h("option", { value: r.run_id }, `${r.run_id} · ${r.n_tasks} task${r.n_tasks === 1 ? "" : "s"}`)); sel.replaceChildren(...opts); if (state.current) sel.value = state.current.run_id; populateExportSelect(); } async function loadRun(runId) { $("#factory-error").hidden = true; $("#funnel").hidden = true; $("#pipeline").hidden = true; renderGridSkeleton(6); try { const r = await api(`/api/runs/${encodeURIComponent(runId)}`); const seedMatch = /^[a-z]+-(\d+)-/.exec(runId); state.current = { run_id: runId, tasks: r.tasks, seed: seedMatch ? Number(seedMatch[1]) : null }; $("#run-select").value = runId; renderRunMeta(); renderGrid(); } catch (e) { errorBox($("#factory-error"), e, () => loadRun(runId)); $("#task-grid").replaceChildren(); } } const visibleTasks = () => (state.current?.tasks || []).filter((t) => t.has_image); function renderRunMeta() { const c = state.current; const box = $("#run-meta"); const shown = visibleTasks().length, total = c.tasks.length; const pills = [h("span", { class: "pill" }, "Run ", h("span", { class: "mono" }, c.run_id), copyBtn(c.run_id, "run id"))]; if (c.seed !== null && c.seed !== undefined) pills.push(h("span", { class: "pill" }, "Seed ", h("span", { class: "mono" }, String(c.seed)), copyBtn(String(c.seed), `Seed ${c.seed}`))); pills.push(h("span", { class: "pill" }, h("span", { class: "mono" }, String(shown)), shown === total ? " certified tasks" : ` of ${total} tasks have stored images`)); if (c.run_id === "final-instruments") pills.push(h("span", { class: "hint" }, "The rest regenerate byte-identically from their seeds.")); else if (c.seed !== null) pills.push(h("span", { class: "hint" }, "Same seed and settings reproduce byte-identical images.")); box.replaceChildren(...pills); } function renderGrid() { const grid = $("#task-grid"); const tasks = visibleTasks(); if (!tasks.length) { grid.replaceChildren(h("li", { class: "empty" }, "No tasks with images in this run. Generate a batch above.")); return; } grid.replaceChildren(...tasks.map((t, i) => { const thumb = h("div", { class: "task-thumb" }, h("span", { class: "skeleton" })); const img = h("img", { src: t.image_url, alt: t.alt, loading: "lazy", decoding: "async", width: 1024, height: 768 }); img.addEventListener("load", () => { img.classList.add("loaded"); thumb.querySelector(".skeleton")?.remove(); }); img.addEventListener("error", () => thumb.querySelector(".skeleton")?.classList.remove("skeleton")); thumb.prepend(img); const btn = h("button", { type: "button", class: "task-btn", "data-task": t.task_id, onclick: () => { location.hash = `#/task/${encodeURIComponent(t.run_id)}/${encodeURIComponent(t.task_id)}`; }, }, thumb, h("div", { class: "task-info" }, h("div", { class: "task-tags" }, h("span", { class: "op-badge" }, t.op), h("span", { class: "sr-only" }, " task. "), diffPips(t.difficulty, t.family), t.twin_id ? h("span", { class: "twin-badge", html: `${ICON.twin} twin` }) : null), h("p", { class: "task-q" }, t.question), h("span", { class: "cert-mark", html: `${ICON.check.replace('class="vi"', 'class="vi" style="width:14px;height:14px"')} Certified` }))); return h("li", { class: "task-card", style: `--i:${Math.min(i, 24)}` }, btn); })); } function diffPips(d, family) { const max = family === "wiring" ? 6 : 5; return h("span", { class: "diff", title: `Difficulty ${d} of ${max}` }, h("span", { class: "sr-only" }, `Difficulty ${d} of ${max}`), h("span", { "aria-hidden": "true", style: "display:inline-flex;gap:2px" }, Array.from({ length: max }, (_, i) => h("i", { class: i < d ? "on" : "" }))), h("span", { "aria-hidden": "true" }, ` D${d}`)); } // --- pipeline animation function pipelineRunner(family) { const pipe = $("#pipeline"); const stages = $("#pipe-stages"), lamps = $("#gate-lamps"); const gates = (state.meta.gates || []).filter((g) => (family === "wiring" ? g.id.startsWith("W") : g.id.startsWith("G"))); stages.replaceChildren(...PIPE_STAGES.map((st) => h("li", { class: "pipe-stage" }, h("span", { class: "pipe-node", html: st.icon }), st.name))); lamps.replaceChildren(...gates.map((g) => h("li", { class: "gate-lamp" }, h("span", { class: "lamp", "aria-hidden": "true" }), h("span", { class: "gid" }, gateShort(g.id)), g.label))); pipe.hidden = false; const stEls = $$(".pipe-stage", stages), lampEls = $$(".gate-lamp", lamps); let stopped = false; const setStage = (i) => stEls.forEach((el, k) => { el.classList.toggle("done", k < i); el.classList.toggle("active", k === i); }); const loop = (async () => { if (reduced()) { setStage(3); return; } for (let i = 0; i < 3 && !stopped; i++) { setStage(i); await sleep(380); } setStage(3); while (!stopped) { for (let k = 0; k < lampEls.length && !stopped; k++) { lampEls[k].classList.add("checking"); await sleep(150); lampEls[k].classList.remove("checking"); lampEls[k].classList.add("lit"); } if (stopped) break; await sleep(260); if (!stopped) lampEls.forEach((l) => l.classList.remove("lit")); } })(); return { async finish(ok) { stopped = true; await loop; lampEls.forEach((l) => { l.classList.remove("checking"); if (ok) l.classList.add("lit"); }); if (ok) { setStage(4); await wait(380); stEls.forEach((el) => { el.classList.remove("active"); el.classList.add("done"); }); } else { pipe.hidden = true; } }, }; } let generating = false; async function generate() { if (generating) return; const fam = fx.family; const famMeta = state.meta.families[fam]; let n = parseInt($("#count").value, 10); if (!Number.isFinite(n)) n = fam === "wiring" ? 2 : 8; n = clamp(n, 1, 48); $("#count").value = n; const seedRaw = $("#seed").value.trim(); const seed = seedRaw === "" ? null : clamp(parseInt(seedRaw, 10) || 0, 0, 999999999); const difficulty = [...fx.diffs[fam]].filter((d) => famMeta.difficulties.includes(d)).sort((a, b) => a - b); // the API takes n as total for instruments, per level for wiring (it divides n by #levels) const body = { family: fam, n: fam === "wiring" ? clamp(n * difficulty.length, 1, 48) : n, seed, difficulty, profile: $("#profile").value }; const btn = $("#gen-btn"); const status = $("#gen-status"); generating = true; btn.disabled = true; btn.setAttribute("aria-busy", "true"); $("#factory-error").hidden = true; $("#funnel").hidden = true; status.textContent = `Generating ${fam} tasks${seed !== null ? ` with seed ${seed}` : ""}. Running every candidate through the gates.`; const runner = pipelineRunner(fam); renderGridSkeleton(Math.min(8, n)); const t0 = performance.now(); try { const [res] = await Promise.all([api("/api/generate", { body }), wait(1700)]); await runner.finish(true); state.lastGenerated = res.run_id; state.current = { run_id: res.run_id, tasks: res.tasks, metrics: res.metrics, seed: res.seed, family: res.family, rejections: res.rejections }; $("#seed").value = res.seed; await populateRunSelect(); $("#run-select").value = res.run_id; renderRunMeta(); renderFunnel(); renderGrid(); const m = res.metrics; status.textContent = `Done. ${m.accepted} certified task${m.accepted === 1 ? "" : "s"} in ${m.seconds} seconds. Seed ${res.seed}.`; } catch (e) { await runner.finish(false); errorBox($("#factory-error"), e, generate); status.textContent = `Generation failed: ${e.message}`; if (state.current) renderGrid(); else $("#task-grid").replaceChildren(); } finally { generating = false; btn.disabled = false; btn.removeAttribute("aria-busy"); void t0; } } function renderFunnel() { const c = state.current, m = c.metrics; const f = $("#funnel"); if (!m) { f.hidden = true; return; } const rej = Object.entries(m.rejections_by_gate || {}).sort((a, b) => b[1] - a[1]); const maxRej = Math.max(1, ...rej.map((r) => r[1])); // The instruments factory counts answer-flip twins as accepted tasks but not as candidates; add them back. const ids = new Set(c.tasks.map((t) => t.task_id)); const twins = c.family === "wiring" ? 0 : Math.floor(c.tasks.filter((t) => t.twin_id && ids.has(t.twin_id)).length / 2); const cand = Math.max(m.accepted, m.candidates + twins); const rejected = cand - m.accepted; const left = h("div", {}, h("h2", {}, "Certification funnel"), h("p", { class: "funnel-big" }, String(m.accepted), h("small", {}, ` / ${cand} candidates certified`)), h("div", { class: "funnel-bar", role: "img", "aria-label": `${m.accepted} of ${cand} candidates certified` }, h("span", { style: `width:${(100 * m.accepted) / Math.max(1, cand)}%` })), h("p", { class: "hint" }, `${rejected} rejected${twins ? ` · ${twins} answer-flip twin${twins === 1 ? "" : "s"} included` : ""} · ${m.seconds} s · seed ${c.seed}`)); const right = h("div", {}, h("h2", {}, "Rejections by gate")); if (!rej.length) right.append(h("p", { class: "muted" }, "No candidate was rejected in this batch.")); else { right.append(h("ul", { class: "rej-list" }, rej.map(([g, n], i) => h("li", { class: "rej-row" }, h("span", { class: "rej-label", title: gateLabel(g) }, h("span", { class: "mono" }, gateShort(g)), ` ${gateLabel(g)}`), h("span", { class: "rej-track", "aria-hidden": "true" }, h("span", { style: `width:${(100 * n) / maxRej}%;animation-delay:${i * 80}ms` })), h("span", { class: "mono" }, String(n)))))); } if (c.rejections?.length) { right.append(h("details", { class: "rej-log" }, h("summary", {}, `Rejection log (${c.rejections.length})`), h("ul", {}, c.rejections.slice(0, 12).map((r) => h("li", {}, h("span", { class: "mono" }, `seed ${r.seed} · ${r.op}`), " failed ", r.failed.map((g) => `${gateShort(g)} (${gateLabel(g)})`).join(", "), ": ", Object.values(r.detail || {}).join("; ")))))); } f.replaceChildren(left, right); f.hidden = false; } // ============================================================== INSPECTOR const drawer = $("#inspector"), backdrop = $("#drawer-backdrop"); let inspToken = 0; async function openInspector(runId, taskId) { const wasOpen = !!state.insp; if (!wasOpen) { state.insp = { opener: document.activeElement, run: runId }; drawer.hidden = false; backdrop.hidden = false; drawer.classList.remove("closing"); document.body.style.overflow = "hidden"; $("#main").setAttribute("inert", ""); $("#topbar").setAttribute("inert", ""); } const ins = state.insp; ins.run = runId; // make sure we have the run's task list for prev/next if (!state.current || state.current.run_id !== runId) { try { const r = await api(`/api/runs/${encodeURIComponent(runId)}`); state.current = { run_id: runId, tasks: r.tasks, seed: (/^[a-z]+-(\d+)-/.exec(runId) || [])[1] ?? null }; if (loaded.factory) { $("#run-select").value = runId; $("#funnel").hidden = true; $("#pipeline").hidden = true; renderRunMeta(); renderGrid(); } } catch (e) { $("#insp-body").replaceChildren(h("div", { class: "error-box", role: "alert" }, h("strong", {}, "Could not open this run. "), e.message)); return; } } ins.list = visibleTasks(); ins.idx = ins.list.findIndex((t) => t.task_id === taskId); if (!wasOpen) $("#insp-title").focus(); await renderInspector(taskId); } function closeInspector({ fromRoute = false } = {}) { if (!state.insp) return; const opener = state.insp.opener; const taskId = state.insp.task?.task_id; state.insp = null; hideTip(); const done = () => { drawer.hidden = true; backdrop.hidden = true; drawer.classList.remove("closing"); }; if (reduced()) done(); else { drawer.classList.add("closing"); setTimeout(done, 190); } document.body.style.overflow = ""; $("#main").removeAttribute("inert"); $("#topbar").removeAttribute("inert"); if (!fromRoute) { history.pushState(null, "", "#/factory"); route(); } const card = taskId && document.querySelector(`.task-btn[data-task="${CSS.escape(taskId)}"]`); (card || (opener && document.contains(opener) ? opener : null) || $("#factory-title")).focus({ preventScroll: false }); } function stepInspector(delta) { const ins = state.insp; if (!ins || !ins.list.length) return; const idx = ins.idx < 0 ? 0 : (ins.idx + delta + ins.list.length) % ins.list.length; const t = ins.list[idx]; history.replaceState(null, "", `#/task/${encodeURIComponent(t.run_id)}/${encodeURIComponent(t.task_id)}`); ins.idx = idx; renderInspector(t.task_id); } $("#insp-close").addEventListener("click", () => closeInspector()); $("#insp-prev").addEventListener("click", () => stepInspector(-1)); $("#insp-next").addEventListener("click", () => stepInspector(1)); backdrop.addEventListener("click", () => closeInspector()); drawer.addEventListener("keydown", (e) => { const tag = (e.target.tagName || "").toLowerCase(); const typing = tag === "input" || tag === "select" || tag === "textarea"; if (e.key === "Escape") { e.preventDefault(); closeInspector(); return; } if (e.key === "Tab") { trapFocus(e); return; } if (typing || e.metaKey || e.ctrlKey || e.altKey) return; if (e.key === "ArrowLeft") { e.preventDefault(); stepInspector(-1); } else if (e.key === "ArrowRight") { e.preventDefault(); stepInspector(1); } else if (e.key === "p" || e.key === "P") { e.preventDefault(); toggleProof(); } }); function trapFocus(e) { const f = $$('a[href], button:not([disabled]), input, select, [tabindex]:not([tabindex="-1"])', drawer).filter((el) => el.offsetParent !== null); if (!f.length) return; const first = f[0], last = f[f.length - 1]; if (e.shiftKey && (document.activeElement === first || !drawer.contains(document.activeElement))) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } } async function renderInspector(taskId) { const token = ++inspToken; const ins = state.insp; const run = ins.run; const summary = ins.list.find((t) => t.task_id === taskId); $("#insp-title").textContent = taskId; $("#insp-eyebrow").textContent = summary ? `${run} · ${summary.op} · difficulty ${summary.difficulty}` : run; $("#insp-pos").textContent = ins.idx >= 0 ? `${ins.idx + 1} / ${ins.list.length}` : ""; $("#insp-prev").disabled = $("#insp-next").disabled = ins.list.length < 2; const body = $("#insp-body"); body.replaceChildren(h("div", { class: "insp-grid" }, h("div", { class: "insp-main" }, h("div", { class: "card figure-card" }, h("span", { class: "skeleton sk-img" }))), h("div", { class: "insp-side" }, h("div", { class: "card" }, h("span", { class: "skeleton sk-title" }), h("span", { class: "skeleton sk-line" }), h("span", { class: "skeleton sk-line", style: "margin-top:8px;width:60%" }))))); body.scrollTop = 0; const base = `/api/tasks/${encodeURIComponent(run)}/${encodeURIComponent(taskId)}`; let task, proof; try { [task, proof] = await Promise.all([api(base), api(`${base}/proof`).catch((e) => ({ error: e.message }))]); } catch (e) { if (token !== inspToken) return; body.replaceChildren(h("div", { class: "error-box", role: "alert" }, h("strong", {}, "Could not load this task. "), e.message, h("button", { type: "button", class: "btn btn-sm btn-ghost", onclick: () => renderInspector(taskId) }, "Try again"))); return; } if (token !== inspToken || !state.insp) return; ins.task = task; ins.proof = proof; $("#insp-eyebrow").textContent = `${run} · ${task.op} · difficulty ${task.difficulty}`; // --- figure with proof overlay const img = h("img", { src: task.image_url, alt: task.alt, width: 1024, height: 768 }); const stage = h("div", { class: "proof-stage" }, img); const proofBtn = h("button", { type: "button", class: "switch", id: "proof-toggle", "aria-pressed": String(state.proofOn), onclick: toggleProof }, h("span", { class: "switch-track", "aria-hidden": "true" }, h("span", { class: "switch-thumb" })), "Show proof ", h("kbd", { "aria-hidden": "true" }, "P")); const verdicts = h("div", { class: "verdicts", id: "verdicts", "aria-live": "polite" }); const fig = h("div", { class: "card figure-card" }, h("div", { class: "figure-toolbar" }, proofBtn, h("p", { class: "hint" }, task.family === "wiring" ? "Proof: the image-only tracer's path" : "Proof: what the image-only decoder read")), stage, verdicts); // --- question + reveal const ansSlot = h("div", { class: "answer-box" }); const revealBtn = h("button", { type: "button", class: "btn btn-ghost", onclick: async () => { revealBtn.disabled = true; revealBtn.textContent = "Revealing…"; try { const r = await api(`${base}?reveal=true`); revealBtn.remove(); ansSlot.append(h("span", { class: "answer-val" }, formatAnswer(r.answer)), h("span", { class: "hint" }, `answer type: ${r.answer.answer_type}`)); ansSlot.setAttribute("aria-live", "polite"); } catch (e) { revealBtn.disabled = false; revealBtn.textContent = "Reveal answer"; toast(`Could not reveal: ${e.message}`); } } }, "Reveal answer"); ansSlot.append(revealBtn); const qCard = h("div", { class: "card q-card" }, h("h3", {}, `Question · ${task.op}`), h("p", { class: "q-text" }, task.question), h("p", { class: "hint", style: "margin:-6px 0 12px" }, OP_INFO[task.op] || ""), ansSlot); // --- certificate const cert = task.certificate || {}; const gateEntries = Object.entries(cert.gates || {}); const allPass = gateEntries.every(([, g]) => g.pass); const sig = cert.variation_signature || {}; const certCard = h("div", { class: "card cert-card" }, h("h3", { html: `${ICON.seal} Certificate ${allPass ? "· all gates passed" : "· gate failures"}` }), h("p", { class: "sub-h" }, "Gate checklist"), h("ul", { class: "gate-list" }, gateEntries.map(([id, g]) => gateRow(id, g))), h("p", { class: "sub-h" }, "Provenance"), h("dl", { class: "kv" }, h("dt", {}, "Generator"), h("dd", {}, h("span", {}, `v${cert.generator?.version ?? "?"} · seed ${cert.generator?.seed ?? "?"}`), copyBtn(String(cert.generator?.seed ?? ""), "generator seed")), h("dt", {}, "Image SHA-256"), h("dd", {}, h("span", { title: cert.image_sha256 }, trunc(cert.image_sha256 || "")), copyBtn(cert.image_sha256 || "", "image SHA-256")), h("dt", {}, "Spec hash"), h("dd", {}, h("span", { title: cert.spec_hash }, trunc(shortHash(cert.spec_hash))), copyBtn(shortHash(cert.spec_hash), "spec hash")), cert.tracer_full_agreement !== null && cert.tracer_full_agreement !== undefined ? [h("dt", {}, "Tracer, all wires"), h("dd", { html: cert.tracer_full_agreement ? `${ICON.check}agrees on every wire` : `${ICON.cross}partial` })] : null), h("details", { class: "rej-log trace-details" }, h("summary", {}, "Reasoning trace (shows the answer)"), h("ol", { class: "trace-list" }, (cert.trace || []).map((t) => h("li", {}, t)))), h("p", { class: "sub-h" }, "Variation signature"), h("div", { class: "sig-chips" }, Object.entries(sig).map(([k, v]) => h("span", { class: "sig-chip" }, `${k}: `, h("b", {}, Array.isArray(v) ? v.join(", ") : String(v)))))); const side = h("div", { class: "insp-side" }, qCard, certCard); const main = h("div", { class: "insp-main" }, fig); // --- twin compare if (task.twin_id) main.append(twinCard(task, run)); body.replaceChildren(h("div", { class: "insp-grid" }, main, side)); renderProof(); // pre-load neighbours for snappy navigation [-1, 1].forEach((d) => { const n = ins.list[(ins.idx + d + ins.list.length) % ins.list.length]; if (n) { const p = new Image(); p.src = n.image_url; } }); } function gateRow(id, g) { return h("li", { class: `gate-row ${g.pass ? "pass" : "fail"}`, html: `${g.pass ? ICON.check : ICON.cross}${esc(gateShort(id))}${esc(gateLabel(id))}${g.pass ? "Pass" : "Fail"}${esc(g.detail || "")}` }); } function formatAnswer(a) { if (!a) return ""; if (a.answer_type === "number") return `${fmtNum(a.answer, a.tolerance)}${a.unit ? ` ${a.unit}` : ""}${a.tolerance ? ` ± ${fmtNum(a.tolerance)}` : ""}`; if (a.answer_type === "int" && a.tolerance) return `${a.answer} ± ${a.tolerance}`; return String(a.answer); } function twinCard(task, run) { const twinSummary = state.current?.tasks.find((t) => t.task_id === task.twin_id); const card = h("div", { class: "card twin-card" }, h("h3", {}, "Answer-flip twin")); if (twinSummary && !twinSummary.has_image) { card.append(h("p", { class: "twin-cap" }, `Twin ${task.twin_id} exists, but its image is not stored in this evidence set (it regenerates from its seed).`)); return card; } const twinUrl = `/api/tasks/${encodeURIComponent(run)}/${encodeURIComponent(task.twin_id)}/image.png`; const stage = h("div", { class: "twin-stage" }, h("img", { src: task.image_url, alt: `This task: ${task.alt}` }), h("img", { class: "twin-top", src: twinUrl, alt: `Twin task ${task.twin_id}`, onerror: () => { card.replaceChildren(h("h3", {}, "Answer-flip twin"), h("p", { class: "twin-cap" }, "The twin image is not available.")); } }), h("div", { class: "twin-divider", "aria-hidden": "true" }), h("div", { class: "twin-labels", "aria-hidden": "true" }, h("span", {}, "This task"), h("span", {}, "Twin"))); const range = h("input", { type: "range", class: "twin-range", min: 0, max: 100, value: 50, "aria-label": "Wipe between this task and its twin", "aria-valuetext": "Split at 50 percent" }); range.addEventListener("input", () => { stage.style.setProperty("--wipe", `${range.value}%`); range.setAttribute("aria-valuetext", `Split at ${range.value} percent: left shows this task, right shows the twin`); }); card.append(stage, range, h("p", { class: "twin-cap" }, "Answer-flip twin: one minimal edit, the answer must change. ", h("a", { href: `#/task/${encodeURIComponent(run)}/${encodeURIComponent(task.twin_id)}`, onclick: (e) => { e.preventDefault(); const i = state.insp.list.findIndex((t) => t.task_id === task.twin_id); history.replaceState(null, "", `#/task/${encodeURIComponent(run)}/${encodeURIComponent(task.twin_id)}`); state.insp.idx = i; renderInspector(task.twin_id); } }, "Open the twin"))); return card; } function toggleProof() { state.proofOn = !state.proofOn; const b = $("#proof-toggle"); if (b) b.setAttribute("aria-pressed", String(state.proofOn)); renderProof(); } function renderProof() { const ins = state.insp; if (!ins || !ins.proof) return; const stage = $(".proof-stage", drawer); const vbox = $("#verdicts"); stage?.querySelector(".proof-svg")?.remove(); if (!state.proofOn) { vbox.replaceChildren(h("p", { class: "proof-off-note" }, "Turn on the proof to overlay what the image-only checker read from the pixels, and whether it agrees with the spec.")); return; } const p = ins.proof; if (p.error) { vbox.replaceChildren(h("p", { class: "proof-off-note" }, `Proof unavailable: ${p.error}`)); return; } stage.append(buildProofSvg(p)); vbox.replaceChildren(...(p.verdicts || []).map((v, i) => verdictChip(v, ins.task, i))); } function buildProofSvg(p) { const svg = s("svg", { class: "proof-svg", viewBox: `0 0 ${p.width} ${p.height}`, preserveAspectRatio: "xMidYMid meet", "aria-hidden": "true" }); const by = (role) => p.shapes.filter((x) => x.role === role); const anim = (el, d) => { el.classList.add("pf-anim"); el.style.setProperty("--d", `${d}ms`); return el; }; const draw = (el, len, d, dur) => { el.style.strokeDasharray = `${len} ${len}`; el.style.strokeDashoffset = String(len); el.classList.add("pf-draw"); el.style.setProperty("--d", `${d}ms`); el.style.setProperty("--dur", `${dur}ms`); return el; }; by("target").forEach((r) => { svg.append(anim(s("rect", { x: r.x, y: r.y, width: r.w, height: r.h, rx: 10, class: "pf-target" }), 0)); if (r.label) { const w = r.label.length * 9.6 + 16; svg.append(anim(s("g", { class: "pf-target-label" }, s("rect", { x: r.x, y: Math.max(0, r.y - 26), width: w, height: 24, rx: 6 }), s("text", { x: r.x + 8, y: Math.max(0, r.y - 26) + 17 }, r.label)), 80)); } }); by("face").forEach((f) => { if (f.type === "circle") { const c = s("circle", { cx: f.cx, cy: f.cy, r: f.r, class: "pf-face", transform: `rotate(-90 ${f.cx} ${f.cy})` }); svg.append(draw(c, 2 * Math.PI * f.r, 150, 700)); } else svg.append(anim(s("rect", { x: f.x, y: f.y, width: f.w, height: f.h, rx: 4, class: "pf-face" }), 150)); }); by("tick").forEach((t, i) => svg.append(anim(s("circle", { cx: t.cx, cy: t.cy, r: 5, class: "pf-tick pf-anim-dot" }), 420 + i * 45))); by("ocr").forEach((o, i) => { const d = 650 + i * 60; svg.append(anim(s("rect", { x: o.x - 3, y: o.y - 3, width: o.w + 6, height: o.h + 6, rx: 3, class: "pf-ocr" }), d)); if (o.label) svg.append(anim(s("text", { x: o.x + o.w / 2, y: o.y - 7, "text-anchor": "middle", class: "pf-ocr-text" }, o.label), d + 40)); }); const tEnd = 650 + by("ocr").length * 60; by("needle").forEach((n) => { const len = Math.hypot(n.x2 - n.x1, n.y2 - n.y1); svg.append(draw(s("line", { x1: n.x1, y1: n.y1, x2: n.x2, y2: n.y2, class: "pf-needle" }), len, Math.max(900, tEnd), 800)); }); by("trace").forEach((t) => { const pts = t.points; let len = 0; for (let i = 1; i < pts.length; i++) len += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]); svg.append(draw(s("polyline", { points: pts.map((q) => q.join(",")).join(" "), class: "pf-trace" }), len, 200, 1600)); const a = pts[0], z = pts[pts.length - 1]; svg.append(anim(s("circle", { cx: a[0], cy: a[1], r: 9, class: "pf-trace-head pf-anim-dot" }), 100)); svg.append(anim(s("circle", { cx: z[0], cy: z[1], r: 11, class: "pf-trace-head pf-anim-dot" }), 1800)); }); return svg; } function verdictChip(v, task, i) { const ok = !!v.agree; let text; if (task.family === "wiring") { text = v.decoded === null ? `Tracer could not follow ${v.target}${v.note ? ` (${v.note})` : ""} · spec ${v.expected}` : `Tracer followed ${v.target} → ${v.decoded} · spec ${v.expected}`; } else if (v.decoded === null || v.decoded === undefined) { text = `${v.target}: decoder found no readable indicator${v.note && v.note !== "ok" ? ` (${v.note.replace(/_/g, " ")})` : ""} · spec: ${typeof v.expected === "number" ? fmtNum(v.expected) : v.expected}`; } else { const unit = v.unit ? ` ${v.unit}` : ""; text = `${v.target}: decoder read ${fmtNum(v.decoded, v.tolerance)}${unit} · spec ${fmtNum(v.expected, v.tolerance)}${v.tolerance ? ` ± ${fmtNum(v.tolerance)}` : ""}${unit}`; if (v.alarm_decoded !== undefined && v.alarm_decoded !== null) text += ` · alarm: read ${v.alarm_decoded ? "yes" : "no"}, spec ${v.alarm_expected ? "yes" : "no"}`; } return h("div", { class: `verdict ${ok ? "ok" : "bad"}`, style: `animation-delay:${reduced() ? 0 : 900 + i * 120}ms`, html: `${ok ? ICON.check : ICON.cross}${esc(text)} · ${ok ? "agrees" : "disagrees"}` }); } // ============================================================== VERIFIER LAB async function initLab() { if (loaded.lab) return; loaded.lab = true; let m; try { m = await getMeta(); } catch (e) { loaded.lab = false; errorBox($("#lab-error"), e, initLab); return; } const grid = $("#fault-grid"); grid.replaceChildren(...m.fault_kinds.map((f, i) => { const info = FAULTS[f.kind] || { name: f.kind, desc: "", icon: "" }; return h("li", {}, h("button", { type: "button", class: "fault-btn", style: `--i:${i}`, "aria-pressed": "false", "data-kind": f.kind, onclick: () => inject(f.kind) }, h("span", { class: "f-top" }, h("span", { class: "f-icon", html: info.icon }), h("span", { class: "f-gate" }, `targets ${gateShort(f.intended_gate)}`)), h("h2", {}, info.name), h("p", {}, info.desc), h("span", { class: "f-cta", "aria-hidden": "true" }, "Plant this defect →"))); })); const rec = m.evidence?.fault_recall || {}; const intended = Object.fromEntries(m.fault_kinds.map((f) => [f.kind, f.intended_gate])); $("#recall-table").replaceChildren(h("div", { class: "tbl-wrap" }, h("table", { class: "tbl" }, h("caption", { class: "sr-only" }, "Planted-defect recall by defect class"), h("thead", {}, h("tr", {}, h("th", { scope: "col" }, "Defect"), h("th", { scope: "col" }, "Intended gate"), h("th", { scope: "col", class: "num" }, "Recall"), h("th", { scope: "col" }, "Status"))), h("tbody", {}, Object.entries(rec).map(([k, v]) => h("tr", {}, h("th", { scope: "row" }, FAULTS[k]?.name || k), h("td", {}, h("span", { class: "mono" }, gateShort(intended[k] || "")), ` ${gateLabel(intended[k] || "")}`), h("td", { class: "num" }, pct(v)), h("td", { html: v >= 1 ? `${ICON.check}All caught` : `${ICON.cross}Missed some` }))))))); } let injecting = false; async function inject(kind) { if (injecting) return; injecting = true; const info = FAULTS[kind] || { name: kind }; $$(".fault-btn").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.kind === kind))); const stageEl = $("#lab-stage"); const status = $("#lab-status"); $("#lab-error").hidden = true; status.textContent = `Planting defect: ${info.name}. Running all gates.`; stageEl.hidden = false; stageEl.replaceChildren( h("div", { class: "lab-images" }, [0, 1].map(() => h("div", { class: "lab-img" }, h("span", { class: "skeleton sk-line", style: "width:40%;margin-bottom:8px" }), h("span", { class: "skeleton sk-img" })))), h("div", {}, h("span", { class: "skeleton sk-title" }), Array.from({ length: 6 }, () => h("span", { class: "skeleton sk-line", style: "margin-bottom:12px" })))); try { const r = await api("/api/faults/inject", { body: { kind } }); const gates = Object.entries(r.gates); const rows = gates.map(([id, g]) => { const li = h("li", { class: "gate-row pending", html: `${ICON.pending}${esc(gateShort(id))}${esc(gateLabel(id))}` }); li._g = g; return li; }); const stampSlot = h("div", { "aria-hidden": "true" }); stageEl.replaceChildren( h("div", { class: "lab-images" }, h("div", { class: "lab-img" }, h("figure", {}, h("figcaption", { html: `${ICON.check.replace('class="vi"', 'class="vi" style="width:16px;height:16px;color:var(--pass)"')} Clean candidate` }), h("div", { class: "frame" }, h("img", { src: r.clean_image, alt: "Clean candidate panel before the defect was planted." })))), h("div", { class: "lab-img defect" }, h("figure", {}, h("figcaption", { html: `${ICON.cross.replace('class="vi"', 'class="vi" style="width:16px;height:16px;color:var(--fail)"')} With planted defect: ${esc(info.name)}` }), h("div", { class: "frame" }, h("img", { src: r.image, alt: `The same panel with a planted defect: ${info.name.toLowerCase()}.` })))), h("p", { class: "lab-q" }, h("strong", {}, "Question: "), r.question)), h("div", { class: "lab-gates" }, h("h2", {}, "Gate battery"), h("ul", { class: "gate-list" }, rows), stampSlot)); if (!reduced()) stageEl.scrollIntoView({ behavior: "smooth", block: "start" }); else stageEl.scrollIntoView({ block: "start" }); await wait(350); for (const li of rows) { li.classList.remove("pending"); li.classList.add("scanning"); await wait(230); const g = li._g; li.classList.remove("scanning"); li.classList.add("checked", g.pass ? "pass" : "fail"); li.innerHTML = `${g.pass ? ICON.check : ICON.cross}${li.innerHTML.replace(/^/, "")}`; li.querySelector(".g-state").textContent = g.pass ? "Pass" : "Fail"; li.querySelector(".g-detail").textContent = g.detail || ""; if (!g.pass) await wait(260); } const first = r.caught_by[0]; const label = r.caught ? `Caught by ${gateShort(first)} · ${gateLabel(first)}` : "Not caught"; const others = r.caught_by.slice(1).map((g) => `${gateShort(g)} ${gateLabel(g)}`).join(", "); stampSlot.removeAttribute("aria-hidden"); stampSlot.append(h("div", { class: `stamp${r.caught ? "" : " missed"}` }, h("small", {}, r.caught ? "Rejected" : "Shipped"), label, others ? h("small", {}, `also ${others}`) : null)); const asDesigned = r.caught_by.includes(r.intended_gate) ? ` The intended gate, ${gateShort(r.intended_gate)}, fired as designed.` : ""; status.textContent = r.caught ? `Defect caught. Rejected by ${r.caught_by.map((g) => `${gateShort(g)} ${gateLabel(g)}`).join(" and ")}.${asDesigned}` : "The defect was not caught by any gate."; } catch (e) { stageEl.hidden = true; errorBox($("#lab-error"), e, () => inject(kind)); status.textContent = `Injection failed: ${e.message}`; } finally { injecting = false; } } // ============================================================== CAPABILITY MAP async function initMap() { if (loaded.map) return; loaded.map = true; try { const [r] = await Promise.all([api("/api/results"), getMeta().catch(() => null)]); if (!r.available) { $("#map-grid").replaceChildren(h("p", { class: "empty" }, "No evaluation results are available. Run the evaluation from the CLI first.")); return; } state.results = r; renderMap(true); } catch (e) { loaded.map = false; $("#map-grid").replaceChildren(); errorBox($("#map-error"), e, initMap); } } function chartCard({ id, title, desc, chart, table, span2 = false, i = 0, extra = null }) { const chartBox = h("div", { class: "chart-body", id: `${id}-chart` }, chart); const tableBox = h("div", { class: "chart-table", id: `${id}-table`, hidden: true }, table); const btn = h("button", { type: "button", class: "btn btn-sm btn-ghost table-toggle", "aria-pressed": "false", "aria-controls": `${id}-chart ${id}-table`, onclick: () => { const on = btn.getAttribute("aria-pressed") !== "true"; btn.setAttribute("aria-pressed", String(on)); btn.textContent = on ? "View as chart" : "View as table"; chartBox.hidden = on; tableBox.hidden = !on; hideTip(); } }, "View as table"); return h("section", { class: `card chart-card${span2 ? " span-2" : ""}`, style: `--i:${i}`, "aria-labelledby": `${id}-h` }, h("div", { class: "chart-head" }, h("div", {}, h("h2", { id: `${id}-h` }, title), desc ? h("p", {}, desc) : null), h("div", { style: "display:flex;gap:8px;flex-wrap:wrap" }, extra, btn)), chartBox, tableBox); } function table(caption, head, rows, numCols = []) { return h("div", { class: "tbl-wrap" }, h("table", { class: "tbl" }, h("caption", {}, caption), h("thead", {}, h("tr", {}, head.map((c, i) => h("th", { scope: "col", class: numCols.includes(i) ? "num" : "" }, c)))), h("tbody", {}, rows.map((r) => h("tr", {}, r.map((c, i) => (i === 0 ? h("th", { scope: "row" }, c) : h("td", { class: numCols.includes(i) ? "num" : "" }, c)))))))); } function renderMap(animate) { const r = state.results; const models = r.models; const grid = $("#map-grid"); mapWidth = chartWidth(); const cards = [ heatmapCard(r, models, 0), lineCard(r, models, 1), scatterCard(r, models, 2), failCard(r, models, 3), statsCard(r, models, 4), ]; grid.replaceChildren(...cards); if (!animate) cards.forEach((c) => c.style.animation = "none"); $$(".series-line", grid).forEach((path, i) => drawIn(path, animate ? 200 + i * 120 : 0, animate)); } let mapWidth = 0; function chartWidth() { const g = $("#map-grid").clientWidth || 1000; const one = window.matchMedia("(max-width: 900px)").matches; const pad = window.matchMedia("(max-width: 640px)").matches ? 34 : 42; return Math.round(clamp((one ? g : (g - 16) / 2) - pad, 280, 760)); } let mapResizeTimer; window.addEventListener("resize", () => { clearTimeout(mapResizeTimer); mapResizeTimer = setTimeout(() => { if (currentView === "map" && state.results && Math.abs(chartWidth() - mapWidth) > 16) renderMap(false); }, 160); }); function drawIn(path, delay, animate) { if (!animate || reduced() || !path.getTotalLength) return; const len = path.getTotalLength(); path.animate([{ strokeDasharray: `${len} ${len}`, strokeDashoffset: len }, { strokeDasharray: `${len} ${len}`, strokeDashoffset: 0 }], { duration: 1100, delay, easing: "cubic-bezier(.16,1,.3,1)", fill: "backwards" }); } // --- (a) heatmap function heatColor(p) { const light = currentTheme() === "light"; const lo = light ? [238, 244, 250] : [20, 33, 58]; const hi = light ? [8, 85, 112] : [38, 190, 220]; const t = Math.pow(clamp(p, 0, 1), 1.3); let c = lo.map((v, i) => Math.round(v + (hi[i] - v) * t)); const lum = (rgb) => { const [R, G, B] = rgb.map((v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); }); return 0.2126 * R + 0.7152 * G + 0.0722 * B; }; const ratio = (rgb, dark) => dark ? (lum(rgb) + 0.05) / 0.05 : 1.05 / (lum(rgb) + 0.05); // WCAG AA (4.5:1) for the value text in every cell: pick black or white text, and if the // mid-scale shade still falls short, nudge the shade toward the text's opposite pole. const useDark = ratio(c, true) >= ratio(c, false); for (let k = 0; k < 40 && ratio(c, useDark) < 4.6; k++) { c = c.map((v) => Math.round(useDark ? v + (255 - v) * 0.06 : v * 0.94)); } return { bg: `rgb(${c.join(",")})`, fg: useDark ? "#000000" : "#FFFFFF" }; } function opOrder(r) { const instOps = state.meta?.families?.instruments?.ops || []; return Object.keys(r.accuracy_by_op).sort((a, b) => { const [fa, oa] = a.split(":"), [fb, ob] = b.split(":"); if (fa !== fb) return fa === "instruments" ? -1 : 1; const ia = instOps.indexOf(oa), ib = instOps.indexOf(ob); return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib) || oa.localeCompare(ob); }); } function heatmapCard(r, models, i) { const ops = opOrder(r); const wrap = h("div", { class: "heat", role: "grid", "aria-label": "Accuracy by operation and model. Use arrow keys to move between cells.", style: `grid-template-columns:minmax(var(--heat-rh),auto) repeat(${models.length}, minmax(var(--heat-col),1fr))` }); wrap.append(h("div", { role: "row", class: "heat-row" }, h("div", { role: "columnheader", class: "heat-colhead" }, h("span", { class: "sr-only" }, "Operation")), models.map((m) => h("div", { role: "columnheader", class: "heat-colhead", title: mName(m) }, swatch(m), h("span", { "aria-hidden": "true" }, mShort(m)), h("span", { class: "sr-only" }, mName(m)))))); const cellGrid = []; let k = 0; ops.forEach((op) => { const [fam, name] = op.split(":"); const row = []; const rowEl = h("div", { role: "row", class: "heat-row" }, h("div", { role: "rowheader", class: "heat-rowhead", title: OP_INFO[name] || "" }, h("small", {}, fam === "wiring" ? "wire" : "inst"), name)); models.forEach((m) => { const v = r.accuracy_by_op[op][m]; let cell; if (!v) cell = h("div", { role: "gridcell", class: "heat-cell na", style: `--i:${k}` }, "n/a"); else { const [p, lo, hi, n] = v; const c = heatColor(p); cell = h("div", { role: "gridcell", class: "heat-cell", style: `background:${c.bg};color:${c.fg};--i:${k}`, "aria-label": `${mName(m)}, ${op}: ${pct(p)} accuracy, 95% CI ${pct(lo)} to ${pct(hi)}, n ${n}` }, pct(p)); bindTip(cell, `${esc(mName(m))}
${esc(op)} · ${esc(OP_INFO[name] || "")}
${pct(p, 1)} correct 95% CI ${pct(lo, 1)}–${pct(hi, 1)} · n = ${n}`); } row.push(cell); rowEl.append(cell); k++; }); cellGrid.push(row); wrap.append(rowEl); }); roving(cellGrid); const lo = heatColor(0).bg, mid = heatColor(0.5).bg, hi = heatColor(1).bg; const chart = h("div", {}, h("div", { class: "heat-scroll" }, wrap), h("div", { class: "heat-scale", "aria-hidden": "true" }, "0%", h("span", { class: "bar", style: `background:linear-gradient(90deg,${lo},${mid},${hi})` }), "100%", h("span", {}, " · accuracy, single-hue scale"))); const tbl = table("Accuracy by operation (95% Wilson CI, n tasks)", ["Operation", ...models.map(mName)], ops.map((op) => [op, ...models.map((m) => { const v = r.accuracy_by_op[op][m]; return v ? `${pct(v[0])} (${pct(v[1])}–${pct(v[2])}, n=${v[3]})` : "n/a"; })]), models.map((_, j) => j + 1)); return chartCard({ id: "heat", title: "Accuracy by operation", desc: "Rows are question programs, columns are models. Hover or focus a cell for its confidence interval and sample size.", chart, table: tbl, span2: true, i }); } // --- (b) difficulty curve let lineFamily = "wiring"; function lineCard(r, models, i) { const fams = Object.keys(r.accuracy_by_level || {}); const body = h("div", {}); const tblBox = h("div", {}); const render = (animate) => { const data = r.accuracy_by_level[lineFamily] || {}; const levels = [...new Set(models.flatMap((m) => Object.keys(data[m] || {}).map(Number)))].sort((a, b) => a - b); body.replaceChildren(lineChart(data, models, levels)); tblBox.replaceChildren(table(`Accuracy by ${lineFamily} difficulty level`, ["Model", ...levels.map((l) => `Level ${l}`)], models.map((m) => [mName(m), ...levels.map((l) => pct(data[m]?.[l] ?? data[m]?.[String(l)]))]), levels.map((_, j) => j + 1))); $$(".series-line", body).forEach((p, j) => drawIn(p, 100 + j * 120, animate)); }; const seg = fams.length > 1 ? h("div", { class: "segmented", role: "radiogroup", "aria-label": "Task family" }, fams.map((f) => h("label", {}, h("input", { type: "radio", name: "line-fam", value: f, checked: f === lineFamily, onchange: () => { lineFamily = f; render(true); updateDesc(); } }), h("span", {}, f[0].toUpperCase() + f.slice(1))))) : null; const card = chartCard({ id: "line", title: "Difficulty curve", desc: "", chart: body, table: tblBox, i, extra: seg }); const updateDesc = () => { const p = card.querySelector(".chart-head p"); p.textContent = lineFamily === "wiring" ? "Accuracy by wiring level (16 tasks per level). More wires and crossings separate the models; Claude Opus 5.5 falls to 6 of 16 at level 6." : "Accuracy by instrument difficulty level. The frontier models stay near the ceiling across all five levels."; }; card.querySelector(".chart-head > div").append(h("p", {})); updateDesc(); render(false); return card; } function lineChart(data, models, levels) { const W = mapWidth || 680, H = Math.round(clamp(W * 0.5, 250, 330)), ml = 44, mr = W < 420 ? 112 : 140, mt = 14, mb = 42; const iw = W - ml - mr, ih = H - mt - mb; const x = (l) => ml + (levels.length > 1 ? ((l - levels[0]) / (levels[levels.length - 1] - levels[0])) * iw : iw / 2); const y = (p) => mt + (1 - p) * ih; const val = (m, l) => data[m]?.[l] ?? data[m]?.[String(l)]; const svg = s("svg", { class: "chart-svg", viewBox: `0 0 ${W} ${H}`, role: "group", "aria-label": "Line chart of accuracy by difficulty level per model. Use arrow keys on the points; a table view is available." }); [0, 0.25, 0.5, 0.75, 1].forEach((t) => { svg.append(s("line", { x1: ml, x2: ml + iw, y1: y(t), y2: y(t), class: "grid" }), s("text", { x: ml - 8, y: y(t) + 4, "text-anchor": "end", class: "tick-label" }, pct(t))); }); levels.forEach((l) => svg.append(s("text", { x: x(l), y: mt + ih + 20, "text-anchor": "middle", class: "tick-label" }, String(l)))); svg.append(s("text", { x: ml + iw / 2, y: H - 4, "text-anchor": "middle", class: "axis-label" }, "Difficulty level")); const ptGrid = []; const ends = []; models.forEach((m) => { const pts = levels.map((l) => [l, val(m, l)]).filter(([, v]) => v !== undefined && v !== null); if (!pts.length) return; svg.append(s("path", { d: pts.map(([l, v], j) => `${j ? "L" : "M"}${x(l).toFixed(1)},${y(v).toFixed(1)}`).join(""), class: "series-line", stroke: mColor(m), style: `stroke:${mColor(m)}` })); const row = []; pts.forEach(([l, v]) => { const c = s("circle", { cx: x(l), cy: y(v), r: 4.5, class: "pt", style: `fill:${mColor(m)}`, role: "img", "aria-label": `${mName(m)}, level ${l}: ${pct(v)}` }); bindTip(c, `${esc(mName(m))}
Level ${l}: ${pct(v, 1)}${lineFamily === "wiring" ? ` (${Math.round(v * 16)} of 16)` : ""}`); row.push(c); }); ptGrid.push(row); const last = pts[pts.length - 1]; ends.push({ m, y: y(last[1]), v: last[1], x: x(last[0]) }); }); // points on top of lines ptGrid.flat().forEach((c) => svg.append(c)); // direct labels with simple collision avoidance ends.sort((a, b) => a.y - b.y); const gap = 17; for (let k = 1; k < ends.length; k++) if (ends[k].y - ends[k - 1].y < gap) ends[k].ly = (ends[k - 1].ly ?? ends[k - 1].y) + gap; ends.forEach((e) => { e.ly = e.ly ?? e.y; }); for (let k = 1; k < ends.length; k++) if (ends[k].ly - ends[k - 1].ly < gap) ends[k].ly = ends[k - 1].ly + gap; const overflow = ends.length ? ends[ends.length - 1].ly - (mt + ih + 6) : 0; if (overflow > 0) ends.forEach((e) => { e.ly -= overflow; }); ends.forEach((e) => { const lx = ml + iw + 14; svg.append(s("path", { d: `M${e.x + 6},${e.y} L${lx - 4},${e.ly}`, style: `stroke:${mColor(e.m)}`, "stroke-width": 1, fill: "none", opacity: 0.7 }), s("rect", { x: lx, y: e.ly - 5, width: 10, height: 10, rx: 2, style: `fill:${mColor(e.m)}` }), s("text", { x: lx + 15, y: e.ly + 4, class: "direct-label" }, mShort(e.m), s("tspan", { class: "direct-val", dx: 6 }, pct(e.v)))); }); roving(ptGrid); const legend = h("ul", { class: "legend", "aria-label": "Legend" }, models.map((m) => h("li", {}, swatch(m), mName(m)))); return h("div", {}, legend, svg); } // --- (c) cost vs accuracy function scatterCard(r, models, i) { const W = mapWidth || 680, H = Math.round(clamp(W * 0.52, 260, 340)), ml = 52, mr = 24, mt = 20, mb = 46; const narrowLabels = W < 560; const iw = W - ml - mr, ih = H - mt - mb; const pts = models.filter((m) => r.cost_per_task[m] && r.overall[m]).map((m) => ({ m, c: r.cost_per_task[m], p: r.overall[m][0], lo: r.overall[m][1], hi: r.overall[m][2], n: r.overall[m][3] })); const lc = pts.map((q) => Math.log10(q.c)); const x0 = Math.floor(Math.min(...lc) - 0.15), x1 = Math.ceil(Math.max(...lc) + 0.15); const yMin = Math.max(0, Math.floor((Math.min(...pts.map((q) => q.lo)) - 0.05) * 10) / 10), yMax = 1; const x = (c) => ml + ((Math.log10(c) - x0) / (x1 - x0)) * iw; const y = (p) => mt + (1 - (p - yMin) / (yMax - yMin)) * ih; const svg = s("svg", { class: "chart-svg", viewBox: `0 0 ${W} ${H}`, role: "group", "aria-label": "Scatter plot of cost per task (log scale) against overall accuracy. A table view is available." }); for (let t = yMin; t <= 1.0001; t += 0.1) svg.append(s("line", { x1: ml, x2: ml + iw, y1: y(t), y2: y(t), class: "grid" }), s("text", { x: ml - 8, y: y(t) + 4, "text-anchor": "end", class: "tick-label" }, pct(t))); for (let e = x0; e <= x1; e++) { [1, 3].forEach((mult) => { const c = mult * Math.pow(10, e); if (Math.log10(c) > x1 + 1e-9) return; svg.append(s("line", { x1: x(c), x2: x(c), y1: mt, y2: mt + ih, class: "grid", opacity: mult === 1 ? 1 : 0.5 })); if (mult === 1 || (x1 - x0 <= 3 && W >= 480)) svg.append(s("text", { x: x(c), y: mt + ih + 18, "text-anchor": "middle", class: "tick-label" }, `$${c >= 0.01 ? c.toFixed(2) : c.toPrecision(1)}`)); }); } svg.append(s("text", { x: ml + iw / 2, y: H - 6, "text-anchor": "middle", class: "axis-label" }, "Measured cost per task (USD, log scale)"), s("text", { x: 14, y: mt + ih / 2, "text-anchor": "middle", class: "axis-label", transform: `rotate(-90 14 ${mt + ih / 2})` }, "Overall accuracy")); // Pareto frontier const sorted = [...pts].sort((a, b) => a.c - b.c); const front = []; sorted.forEach((q) => { if (!front.length || q.p > front[front.length - 1].p) front.push(q); }); if (front.length > 1) svg.append(s("path", { class: "frontier", d: front.map((q, k) => `${k ? "L" : "M"}${x(q.c)},${y(q.p)}`).join("") })); svg.append(s("text", { x: ml + 8, y: mt + 14, class: "annot" }, "↖ cheaper and more accurate")); const dots = []; pts.forEach((q) => { svg.append(s("line", { x1: x(q.c), x2: x(q.c), y1: y(q.lo), y2: y(q.hi), class: "ci", style: `stroke:${mColor(q.m)}` })); const c = s("circle", { cx: x(q.c), cy: y(q.p), r: 7, class: "pt", style: `fill:${mColor(q.m)}`, role: "img", "aria-label": `${mName(q.m)}: ${usd(q.c)} per task, ${pct(q.p, 1)} accuracy` }); bindTip(c, `${esc(mName(q.m))}
${usd(q.c)} per task · ${pct(q.p, 1)}
95% CI ${pct(q.lo, 1)}–${pct(q.hi, 1)} · n = ${q.n}`); dots.push(c); }); dots.forEach((d) => svg.append(d)); // labels: place right of dot unless near the right edge; nudge apart vertically const labs = pts.map((q) => ({ q, x: x(q.c), y: y(q.p), right: x(q.c) < ml + iw - (narrowLabels ? 90 : 150) })).sort((a, b) => a.y - b.y); for (let k = 1; k < labs.length; k++) { const prev = labs.slice(0, k).filter((p) => p.right === labs[k].right && Math.abs(p.x - labs[k].x) < 140); for (const p of prev) if (Math.abs((labs[k].ly ?? labs[k].y) - (p.ly ?? p.y)) < 16) labs[k].ly = (p.ly ?? p.y) + 16; } labs.forEach((L) => { const ly = L.ly ?? L.y; svg.append(s("text", { x: L.right ? L.x + 12 : L.x - 12, y: ly + 4, "text-anchor": L.right ? "start" : "end", class: "direct-label" }, narrowLabels ? mShort(L.q.m) : mName(L.q.m), s("tspan", { class: "direct-val", dx: 6 }, pct(L.q.p)))); }); roving([dots]); const tbl = table("Overall accuracy and measured cost per task", ["Model", "Cost per task", "Accuracy", "95% CI", "n"], pts.map((q) => [mName(q.m), usd(q.c), pct(q.p, 1), `${pct(q.lo, 1)}–${pct(q.hi, 1)}`, String(q.n)]), [1, 2, 3, 4]); const chart = h("div", {}, svg, h("p", { class: "mini-note" }, "Dashed line: the cost/accuracy frontier. A model off the line has a rival that is both cheaper and at least as accurate on this benchmark. Vertical bars are 95% confidence intervals.")); return chartCard({ id: "scatter", title: "Which model should I buy for this job?", desc: "Overall accuracy against the measured API cost per task in the final evaluation.", chart, table: tbl, i }); } // --- (d) why models fail function failCard(r, models, i) { const all = models.flatMap((m) => Object.values(r.attribution[m] || {})); const max = Math.max(1, ...all); const pretty = (k) => { const [op, why] = k.split(":"); return [op, (why || "").replace(/_/g, " ")]; }; const chart = h("div", { class: "fail-grid" }, models.map((m) => { const entries = Object.entries(r.attribution[m] || {}).sort((a, b) => b[1] - a[1]).slice(0, 6); const total = Object.values(r.attribution[m] || {}).reduce((a, b) => a + b, 0); return h("div", { class: "fail-model" }, h("h3", {}, swatch(m), mName(m), h("small", {}, `${total} attributed error${total === 1 ? "" : "s"}`)), entries.length ? entries.map(([k, v], j) => { const [op, why] = pretty(k); return h("div", { class: "fbar" }, h("span", { class: "fl" }, h("span", { class: "mono" }, op), why), h("span", { class: "ft", "aria-hidden": "true" }, h("span", { style: `width:${(100 * v) / max}%;background:${mColor(m)};animation-delay:${j * 60}ms` })), h("span", { class: "fv" }, String(v))); }) : h("p", { class: "muted" }, "No errors to attribute.")); })); const rows = models.flatMap((m) => Object.entries(r.attribution[m] || {}).sort((a, b) => b[1] - a[1]).map(([k, v]) => { const [op, why] = pretty(k); return [mName(m), op, why, String(v)]; })); const tbl = h("div", { class: "tbl-wrap" }, h("table", { class: "tbl" }, h("caption", {}, "Top error attributions per model (count of tasks)"), h("thead", {}, h("tr", {}, ["Model", "Operation", "Attributed cause", "Errors"].map((c, j) => h("th", { scope: "col", class: j === 3 ? "num" : "" }, c)))), h("tbody", {}, rows.map((rw) => h("tr", {}, h("th", { scope: "row" }, rw[0]), h("td", { class: "mono" }, rw[1]), h("td", {}, rw[2]), h("td", { class: "num" }, rw[3])))))); return chartCard({ id: "fail", title: "Why models fail", desc: "Every wrong answer is attributed to a cause, because the spec knows what the right reading was. Same scale across models.", chart, table: tbl, span2: true, i }); } // --- (e) blind baseline, twin consistency, human audit, ablation function statsCard(r, models, i) { const srows = (obj, labelFor) => h("div", { class: "stat-rows" }, models.filter((m) => obj[m]).map((m) => { const [p, lo, hi] = obj[m]; return h("div", { class: "srow" }, h("span", { class: "sm" }, swatch(m), mName(m)), h("span", { class: "strack", "aria-hidden": "true" }, h("span", { style: `width:${p * 100}%;background:${mColor(m)}` }), h("span", { class: "ci-band", style: `left:${lo * 100}%;width:${(hi - lo) * 100}%` })), h("span", { class: "sv" }, pct(p), h("span", { class: "sr-only" }, ` ${labelFor}, 95% CI ${pct(lo)} to ${pct(hi)}`))); })); const blindModels = models.filter((m) => r.blind?.[m]); const chart = h("div", { class: "two-col" }, h("div", {}, h("h3", { class: "mini-h" }, "Text-only blind baseline"), srows(r.blind || {}, "correct without the image"), h("p", { class: "mini-note" }, `Accuracy when the model gets the question but not the image${blindModels.length < models.length ? ` (measured for ${blindModels.length} models)` : ""}. Low is good: the tasks need the pixels.`)), h("div", {}, h("h3", { class: "mini-h" }, "Twin consistency"), srows(r.twin_both_correct || {}, "both twins correct"), h("p", { class: "mini-note" }, "Share of answer-flip pairs where the model gets both the task and its twin right."), r.human ? h("p", { class: "mini-note", style: "margin-top:16px" }, h("strong", { style: "color:var(--text)" }, `Human audit pilot: ${r.human.correct} of ${r.human.n} (${pct(r.human.accuracy)})`), " answered correctly by a person from the image alone.") : null)); const rows = []; models.forEach((m) => { rows.push([mName(m), r.blind?.[m] ? `${pct(r.blind[m][0])} (${pct(r.blind[m][1])}–${pct(r.blind[m][2])})` : "not measured", r.twin_both_correct?.[m] ? `${pct(r.twin_both_correct[m][0])} (${pct(r.twin_both_correct[m][1])}–${pct(r.twin_both_correct[m][2])})` : "not measured"]); }); const tbl = h("div", {}, table("Blind baseline and twin consistency (95% CI)", ["Model", "Blind (text only)", "Both twins correct"], rows, [1, 2]), r.human ? h("p", { class: "mini-note" }, `Human audit pilot: ${r.human.correct} of ${r.human.n} correct (${pct(r.human.accuracy)}).`) : null); const abl = r.ablation && Object.keys(r.ablation).length ? ablationBlock(r.ablation) : null; const card = chartCard({ id: "stats", title: "Sanity checks", desc: "Is the image necessary, and are answers consistent under a minimal edit?", chart, table: tbl, span2: true, i }); if (abl) card.append(abl); return card; } function ablationBlock(abl) { const ms = Object.keys(abl); return h("div", { style: "margin-top:20px" }, h("h3", { class: "mini-h" }, "Variation sensitivity (ablation)"), table("Accuracy on base tasks vs surface (cosmetic) and structural variations, and how often correctness flips", ["Model", "Triples", "Base", "Surface", "Structure", "Flip rate, surface", "Flip rate, structure"], ms.map((m) => { const a = abl[m]; return [mName(m), String(a.n_triples), pct(a.acc_base?.[0]), pct(a.acc_surface?.[0]), pct(a.acc_structure?.[0]), pct(a.correctness_flip_rate_surface?.[0]), pct(a.correctness_flip_rate_structure?.[0])]; }), [1, 2, 3, 4, 5, 6]), h("p", { class: "mini-note" }, "Structural changes flip correctness more often than cosmetic ones: the variation measures perception, not paint.")); } // ============================================================== SHIP IT const est = { n: 1000, reasoning: "low", batch: false, models: new Set() }; const sliderToN = (v) => { const raw = Math.pow(10, 1 + (v * 6) / 100); const mag = Math.pow(10, Math.floor(Math.log10(raw)) - 1); return Math.round(raw / mag) * mag; }; const nToSlider = (n) => clamp(((Math.log10(Math.max(10, n)) - 1) * 100) / 6, 0, 100); async function initShip() { populateExportSelect(); renderCurl(); if (loaded.ship) return; loaded.ship = true; const range = $("#est-n-range"), num = $("#est-n"); range.value = nToSlider(est.n); const syncOut = () => { $("#est-n-out").textContent = `${fmtInt(est.n)} tasks`; range.setAttribute("aria-valuetext", `${fmtInt(est.n)} tasks`); }; syncOut(); range.addEventListener("input", () => { est.n = sliderToN(Number(range.value)); num.value = est.n; syncOut(); scheduleEstimate(); }); num.addEventListener("input", () => { const v = parseInt(num.value, 10); if (Number.isFinite(v) && v >= 1) { est.n = Math.min(v, 10000000); range.value = nToSlider(est.n); syncOut(); scheduleEstimate(); } }); $("#est-form").addEventListener("submit", (e) => e.preventDefault()); $$('input[name="reasoning"]').forEach((r) => r.addEventListener("change", () => { est.reasoning = r.value; scheduleEstimate(); })); const sw = $("#est-batch"); sw.addEventListener("click", () => { est.batch = !est.batch; sw.setAttribute("aria-checked", String(est.batch)); scheduleEstimate(); }); try { const [mods] = await Promise.all([api("/api/models"), getMeta().catch(() => null)]); state.models = mods.models; let defaults = state.results?.models; if (!defaults) { try { defaults = (await api("/api/results")).models; } catch (_) { defaults = []; } } mods.models.forEach((m) => { if (defaults.includes(m.id)) est.models.add(m.id); }); if (!est.models.size) mods.models.slice(0, 2).forEach((m) => est.models.add(m.id)); $("#est-models").replaceChildren(...mods.models.map((m) => h("label", { class: "check" }, h("input", { type: "checkbox", value: m.id, checked: est.models.has(m.id), onchange: (e) => { e.target.checked ? est.models.add(m.id) : est.models.delete(m.id); scheduleEstimate(); } }), h("span", {}, mName(m.id)), h("span", { class: "prov" }, m.provider)))); scheduleEstimate(0); } catch (e) { loaded.ship = false; $("#est-result").replaceChildren(h("div", { class: "error-box" }, h("strong", {}, "Could not load models. "), e.message)); } } let estTimer, estToken = 0; function scheduleEstimate(delay = 220) { clearTimeout(estTimer); estTimer = setTimeout(runEstimate, delay); } async function runEstimate() { const out = $("#est-result"); if (!est.models.size) { out.replaceChildren(h("p", { class: "muted" }, "Select at least one model to estimate.")); return; } const token = ++estToken; out.setAttribute("aria-busy", "true"); try { const r = await api("/api/estimate", { body: { n_tasks: est.n, models: [...est.models], reasoning: est.reasoning, batch: est.batch } }); if (token !== estToken) return; const isMeasured = (b) => /measured/i.test(b || ""); const totalEl = h("span", { class: "big" }, usd(r.usd_total)); out.replaceChildren( h("div", { class: "est-total" }, h("div", {}, h("span", { class: "ctl-label" }, `Evaluate ${fmtInt(r.n_tasks)} tasks on ${r.rows.length} model${r.rows.length === 1 ? "" : "s"}`), totalEl), h("span", { class: "gen" }, `Generation: ${usd(r.generation_usd)} · ≈ ${r.generation_cpu_minutes} CPU-minutes`)), h("div", { class: "tbl-wrap" }, h("table", { class: "tbl" }, h("caption", { class: "sr-only" }, "Estimated evaluation cost per model"), h("thead", {}, h("tr", {}, h("th", { scope: "col" }, "Model"), h("th", { scope: "col", class: "num" }, "Per task"), h("th", { scope: "col", class: "num" }, "Total"), h("th", { scope: "col" }, "Basis"))), h("tbody", {}, r.rows.map((row) => h("tr", {}, h("th", { scope: "row" }, mName(row.model), h("span", { class: "hint", style: "display:block;margin:0" }, row.provider)), h("td", { class: "num" }, usd(row.usd_per_task)), h("td", { class: "num" }, usd(row.usd_total)), h("td", {}, h("span", { class: `basis${isMeasured(row.basis) ? " measured" : ""}`, title: row.basis }, isMeasured(row.basis) ? "measured" : "price-list"))))), h("tfoot", {}, h("tr", {}, h("th", { scope: "row" }, "Total"), h("td", {}), h("td", { class: "num" }, usd(r.usd_total)), h("td", {}))))), h("p", { class: "hint" }, h("strong", {}, "measured"), " = mean cost actually billed in the final evaluation (low reasoning); ", h("strong", {}, "price-list"), " = list-price formula. ", r.assumptions)); } catch (e) { if (token !== estToken) return; out.replaceChildren(h("div", { class: "error-box" }, h("strong", {}, "Estimate failed. "), e.message)); } finally { if (token === estToken) out.removeAttribute("aria-busy"); } } async function populateExportSelect() { const sel = $("#export-select"); if (!sel) return; if (!state.runs.length) await refreshRuns(); const ids = [...new Set([state.lastGenerated, ...state.runs.map((r) => r.run_id), "final-instruments"].filter(Boolean))]; const prev = sel.value; sel.replaceChildren(...ids.map((id) => h("option", { value: id }, id === "final-instruments" ? "final-instruments (frozen evidence set)" : `${id}${id === state.lastGenerated ? " (latest)" : ""}`))); sel.value = state.lastGenerated || (ids.includes(prev) ? prev : ids[0]); if (!sel._bound) { sel.addEventListener("change", renderExportBtns); sel._bound = true; } renderExportBtns(); } function renderExportBtns() { const id = $("#export-select").value; $("#export-run").textContent = state.lastGenerated ? `Latest generated run: ${state.lastGenerated}` : "No batch generated in this session yet; pick any run."; const fmts = [["jsonl", "JSONL + images"], ["harbor", "Harbor 0.25"], ["bundle", "Task bundle"]]; $("#export-btns").replaceChildren(...fmts.map(([f, label]) => h("a", { class: `btn ${f === "jsonl" ? "btn-primary" : "btn-ghost"}`, href: `/api/export/${encodeURIComponent(id)}?format=${f}`, download: `needlepoint-${id}-${f}.zip`, html: `${ICON.download}${label}` }))); } function renderCurl() { const o = location.origin; const lines = [ ["c-m", "# generate 8 certified instrument tasks, reproducibly"], ["", `curl -s -X POST ${o}/api/generate \\`], ["", " -H 'content-type: application/json' \\"], ["", ` -d '{"family":"instruments","n":8,"seed":42,"difficulty":[1,2,3]}'`], ["", ""], ["c-m", "# then download it as JSONL + images"], ["", `curl -OJ "${o}/api/export/?format=jsonl"`], ]; const plain = lines.map((l) => l[1]).join("\n"); $("#curl-snippet").innerHTML = lines.map(([c, t]) => { if (c) return `${esc(t)}`; return esc(t).replace(/^(curl)/, '$1').replace(/('\{.*\}')/, '$1'); }).join("\n"); const btn = $("#copy-curl"); btn.onclick = () => copyText(plain, "curl command"); } // ============================================================== HOW IT WORKS const HOW_NODES = [ ["Seed", "an integer"], ["Spec", "typed, answer known"], ["Render", "deterministic PNG"], ["Question program", "question + answer key"], ["Gates", "incl. image-only decoder"], ["Answer-flip twin", "one minimal edit"], ["Certificate", "seed · hashes · trace"], ["Export", "Harbor · JSONL"], ["Evaluation", "models, attributed errors"], ]; let howMode = null; function initHow() { renderHow(); } function renderHow() { const box = $("#how-diagram"); const narrow = box.clientWidth < 640; const mode = narrow ? "v" : "h"; if (mode === howMode && box.firstChild) return; howMode = mode; const pos = []; let W, H, nw, nh; if (!narrow) { W = 1000; nw = 164; nh = 62; H = 292; const xs = [10, 207, 404, 601, 798]; HOW_NODES.forEach((_, k) => { if (k < 5) pos.push([xs[k], 104]); else pos.push([xs[4 - (k - 5)], 224]); }); } else { W = 340; nw = 210; nh = 56; const gap = 30; HOW_NODES.forEach((_, k) => pos.push([10, 10 + k * (nh + gap)])); H = 10 + HOW_NODES.length * (nh + gap); } const svg = s("svg", { viewBox: `0 0 ${W} ${H}`, role: "img", "aria-label": "Pipeline diagram from seed to evaluation." }, s("defs", {}, s("marker", { id: "dg-arr", viewBox: "0 0 10 10", refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: "auto-start-reverse" }, s("path", { d: "M0,0 L10,5 L0,10 z", class: "dg-arrow" })), s("marker", { id: "dg-arr-r", viewBox: "0 0 10 10", refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: "auto-start-reverse" }, s("path", { d: "M0,0 L10,5 L0,10 z", style: "fill:var(--fail)" })))); const center = (k) => [pos[k][0] + nw / 2, pos[k][1] + nh / 2]; for (let k = 0; k < HOW_NODES.length - 1; k++) { const [ax, ay] = pos[k], [bx, by] = pos[k + 1]; let d; if (!narrow) { if (k < 4) d = `M${ax + nw},${ay + nh / 2} L${bx - 2},${by + nh / 2}`; else if (k === 4) d = `M${ax + nw / 2},${ay + nh} L${bx + nw / 2},${by - 2}`; else d = `M${ax},${ay + nh / 2} L${bx + nw + 2},${by + nh / 2}`; } else d = `M${ax + nw / 2},${ay + nh} L${bx + nw / 2},${by - 2}`; svg.append(s("path", { d, class: "dg-edge", "marker-end": "url(#dg-arr)" }), s("path", { d, class: "dg-flow" })); } // rejection branch from Gates const [gx, gy] = pos[4]; if (!narrow) { svg.append(s("path", { d: `M${gx + nw / 2},${gy} L${gx + nw / 2},${gy - 52}`, class: "dg-reject", "marker-end": "url(#dg-arr-r)" }), s("rect", { x: gx + 2, y: gy - 100, width: nw - 4, height: 44, rx: 10, style: "fill:var(--fail-bg);stroke:var(--fail);stroke-dasharray:3 4" }), s("text", { x: gx + nw / 2, y: gy - 82, "text-anchor": "middle", class: "dg-reject-text" }, "any gate fails"), s("text", { x: gx + nw / 2, y: gy - 66, "text-anchor": "middle", class: "dg-reject-text" }, "→ rejection log")); } else { svg.append(s("path", { d: `M${gx + nw},${gy + nh / 2} L${gx + nw + 28},${gy + nh / 2}`, class: "dg-reject", "marker-end": "url(#dg-arr-r)" }), s("text", { x: gx + nw + 32, y: gy + nh / 2 - 4, class: "dg-reject-text" }, "fail →"), s("text", { x: gx + nw + 32, y: gy + nh / 2 + 10, class: "dg-reject-text" }, "rejected")); } HOW_NODES.forEach(([name, sub], k) => { const [x0, y0] = pos[k]; const key = k === 4; svg.append(s("g", { class: `dg-node${key ? " key" : ""}` }, s("rect", { x: x0, y: y0, width: nw, height: nh, rx: 12 }), s("text", { x: x0 + 10, y: y0 + 15, class: "dg-num" }, String(k + 1).padStart(2, "0")), s("text", { x: x0 + nw / 2, y: y0 + nh / 2 + 2 }, name), s("text", { x: x0 + nw / 2, y: y0 + nh / 2 + 18, class: "dg-sub" }, sub))); }); void center; box.replaceChildren(svg); } let howResize; window.addEventListener("resize", () => { clearTimeout(howResize); howResize = setTimeout(() => { if (currentView === "how") renderHow(); }, 150); }); // ============================================================== boot motionQuery.addEventListener?.("change", () => document.documentElement.classList.toggle("reduce-motion", reduced())); document.documentElement.classList.toggle("reduce-motion", reduced()); getMeta().catch(() => {}); route();