/* 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(/^