// Multiverse board — the archive promoted from a side panel to a // workspace. The analyst's real object of study is not one pipeline // but the SET of configurations they have tried; this view makes that // set first-class: one card per configuration (config_hash group), // laid out as small multiples so outcome distributions are comparable // at a glance (multiverse-analysis framing). // // Encoding decisions, one channel per field: // * card HUE (chip + border tint + dots) = config_hash, same // hash→hue mapping as the timeline (lib/hues.ts) so a // configuration keeps its color across every panel. // * PIPELINE STRIP = the composition itself: 8-px rounded squares // in topological order, colored by node family (source slate, // backend accent, algorithm purple, metric green, sink gray). // Topology order, not canvas x/y — at thumbnail scale layout // jitter is noise, the stage sequence is the signal. // * DOT above a square = this stage's params differ from the // BASELINE configuration (the most-tried one). Diff is computed // per node kind with the same canonicalization the config hash // uses, so node ids and layout never produce false positives. // * OUTCOME STRIP = every archived headline value on a shared 0-1 // scale, mean tick, latest run emphasized. Shared scale across // all cards is the point of small multiples. // * Δmean vs baseline is stated in percentage points and flagged // "(n small)" below 3 replicates on either side — a difference // built on one draw is not evidence, and the UI says so. // * POOLED BAND (Wave J) = when ≥2 runs carry binomial payloads, // their counts pool (Σsuccesses/Σshots, one Wilson interval — see // lib/stats.ts for why that is valid within a configuration) into // a filled band on the same 0-1 strip: a deliberately DIFFERENT // mark than the per-run dots, because dots are single draws and // the band is the interval the pooled evidence supports. The Δ // line compares pooled means when both sides have pools. import { useEffect, useMemo, useRef, useState } from "react"; import { GitCompare, RotateCcw, Workflow } from "lucide-react"; import { useApp } from "../lib/store"; import { listRuns, type RunRecord } from "../lib/runStore"; import type { SharePayload, ShareNode } from "../lib/share"; import { resolveNodeSpec, type NodeSpec } from "../lib/nodeCatalog"; import type { PluginManifest } from "../lib/api"; import { hashHue, hueCss } from "../lib/hues"; import { POOLED_SMALL_N_SHOTS, poolEvidence, runEvidence, type Evidence, type PooledEvidence, } from "../lib/stats"; import { WorkspaceToggle } from "./WorkspaceToggle"; import { DemoArchiveBanner } from "./DemoArchiveBanner"; import { FigureExportButton } from "./FigureExportButton"; import { TipIcon } from "./TipIcon"; import { gloss } from "../lib/glossary"; // --- grouping model --------------------------------------------------------- interface ConfigGroup { hash: string; hue: number; /** Oldest → newest. */ runs: RunRecord[]; latest: RunRecord; latestOk: RunRecord | null; /** Headline values of ok runs, chronological (latest last). */ values: number[]; mean: number | null; /** Wilson interval over the group's pooled binomial counts; null * unless ≥2 ok runs carry binomial payloads (a pool of one is * just that run's own interval — the fidelity card already shows * it). */ pooled: PooledEvidence | null; nErr: number; circuitTag: string; /** Representative graph: latest ok run's, else latest run's. */ graph: SharePayload; } function buildGroups(runs: RunRecord[]): ConfigGroup[] { const byHash = new Map(); runs.forEach((r) => { const arr = byHash.get(r.config_hash) ?? []; arr.push(r); byHash.set(r.config_hash, arr); }); const groups: ConfigGroup[] = []; byHash.forEach((list, hash) => { const sorted = [...list].sort((a, b) => a.created_at - b.created_at); const latest = sorted[sorted.length - 1]; const oks = sorted.filter((r) => r.ok); const latestOk = oks.length > 0 ? oks[oks.length - 1] : null; const values = oks .filter((r) => r.headline_value != null) .map((r) => Math.min(1, Math.max(0, r.headline_value as number))); const evs = oks .map((r) => runEvidence(r.response)) .filter((e): e is Evidence => e != null); groups.push({ hash, hue: hashHue(hash), runs: sorted, latest, latestOk, values, mean: values.length > 0 ? values.reduce((a, b) => a + b, 0) / values.length : null, pooled: evs.length >= 2 ? poolEvidence(evs) : null, nErr: sorted.filter((r) => !r.ok).length, circuitTag: latest.sample_key ?? latest.circuit_name ?? "uploaded circuit", graph: (latestOk ?? latest).graph, }); }); // Display order: most recent activity first. groups.sort((a, b) => b.latest.created_at - a.latest.created_at); return groups; } /** Baseline = the most-populous configuration (most archived runs); * ties break toward the most recently active. "The one you kept * coming back to" is the natural reference point of the multiverse. */ function pickBaseline(groups: ConfigGroup[]): ConfigGroup | null { if (groups.length === 0) return null; return [...groups].sort( (a, b) => b.runs.length - a.runs.length || b.latest.created_at - a.latest.created_at, )[0]; } // --- structural diff vs baseline (light version of CompareView's) ---------- function canonParams(p: Record | undefined): string { const params = p ?? {}; return Object.keys(params) .sort() .map((k) => `${k}=${JSON.stringify(params[k])}`) .join(","); } /** Node kinds whose param multiset differs between the two graphs. * Same canonicalization convention as computeConfigHash / CompareView's * paramDiff: match by kind, compare sorted param fingerprints, so node * ids and canvas layout can never produce a false "differs". */ function diffKinds(a: SharePayload, b: SharePayload): Set { const collect = (g: SharePayload) => { const m = new Map(); g.n.forEach((n) => { const arr = m.get(n.k) ?? []; arr.push(canonParams(n.p)); m.set(n.k, arr); }); m.forEach((v) => v.sort()); return m; }; const A = collect(a); const B = collect(b); const out = new Set(); new Set([...A.keys(), ...B.keys()]).forEach((k) => { const la = A.get(k) ?? []; const lb = B.get(k) ?? []; if (la.length !== lb.length || la.some((v, i) => v !== lb[i])) out.add(k); }); return out; } // --- pipeline schematic ----------------------------------------------------- /** Kahn topological order; x-position breaks ties so parallel branches * keep their canvas left-to-right reading. Cycles / orphans (should * not happen, but archives outlive invariants) append by x. */ function topoOrder(g: SharePayload): ShareNode[] { const indeg = new Map(); g.n.forEach((n) => indeg.set(n.i, 0)); g.e.forEach((e) => { if (indeg.has(e.t)) indeg.set(e.t, (indeg.get(e.t) ?? 0) + 1); }); const out: ShareNode[] = []; const used = new Set(); while (out.length < g.n.length) { const ready = g.n .filter((n) => !used.has(n.i) && (indeg.get(n.i) ?? 0) === 0) .sort((a, b) => a.x - b.x || a.y - b.y); if (ready.length === 0) { g.n .filter((n) => !used.has(n.i)) .sort((a, b) => a.x - b.x) .forEach((n) => { out.push(n); used.add(n.i); }); break; } const n = ready[0]; out.push(n); used.add(n.i); g.e.forEach((e) => { if (e.s === n.i && !used.has(e.t)) indeg.set(e.t, (indeg.get(e.t) ?? 0) - 1); }); } return out; } const FAMILY_FILL: Record = { source: "#64748b", // slate backend: "rgb(var(--color-accent))", algorithm: "rgb(var(--color-accent2))", metric: "rgb(var(--color-ok))", sink: "rgb(var(--color-mute))", }; function PipelineStrip({ graph, differing, plugins, }: { graph: SharePayload; differing: Set | null; plugins: PluginManifest[]; }) { const order = useMemo(() => topoOrder(graph), [graph]); const MAX = 14; const shown = order.slice(0, MAX); const overflow = order.length - shown.length; const SZ = 8; const GAP = 9; const PAD = 2; const w = PAD * 2 + shown.length * SZ + Math.max(0, shown.length - 1) * GAP; return (
n.k).join(" → ")}`} className="shrink-0" > {shown.length > 1 && ( )} {shown.map((n, i) => { const spec = resolveNodeSpec(n.k, plugins); const fam = spec?.family ?? "algorithm"; const x = PAD + i * (SZ + GAP); const differs = differing?.has(n.k) ?? false; return ( {`${spec?.label ?? n.k} (${fam})${differs ? " — settings differ from baseline" : ""}`} {differs && ( settings differ from baseline )} ); })} {overflow > 0 && ( +{overflow} )}
); } // --- outcome distribution --------------------------------------------------- function OutcomeStrip({ values, hue, pooled, }: { values: number[]; hue: number; pooled?: PooledEvidence | null; }) { const W = 220; const H = 26; const X0 = 8; const X1 = W - 8; const px = (v: number) => X0 + v * (X1 - X0); const mean = values.reduce((a, b) => a + b, 0) / values.length; return ( {/* Pooled Wilson interval (Wave J): a filled band UNDER the dot line — a different mark than the dots on purpose (dots = single draws, band = what the pooled counts support). */} {pooled && ( {`pooled 95% interval: ${(pooled.ci95[0] * 100).toFixed(1)}–${(pooled.ci95[1] * 100).toFixed(1)}% (${pooled.successes}/${pooled.shots} pooled counts over ${pooled.nRuns} runs)`} )} {`mean ${(mean * 100).toFixed(2)}%`} {values.map((v, i) => { const last = i === values.length - 1; return ( {`${(v * 100).toFixed(2)}%${last ? " (latest)" : ""}`} ); })} ); } // --- misc ------------------------------------------------------------------- function relTime(ts: number): string { const s = Math.max(0, (Date.now() - ts) / 1000); if (s < 60) return "just now"; if (s < 3600) return `${Math.floor(s / 60)}m ago`; if (s < 86400) return `${Math.floor(s / 3600)}h ago`; if (s < 7 * 86400) return `${Math.floor(s / 86400)}d ago`; return new Date(ts).toLocaleDateString(); } // --- board ------------------------------------------------------------------ export function MultiverseBoard() { const historyVersion = useApp((s) => s.historyVersion); const plugins = useApp((s) => s.plugins); const requestRestore = useApp((s) => s.requestRestore); const setWorkspaceMode = useApp((s) => s.setWorkspaceMode); const compareIds = useApp((s) => s.compareIds); const toggleCompare = useApp((s) => s.toggleCompare); const boardRef = useRef(null); const [runs, setRuns] = useState(null); useEffect(() => { let alive = true; listRuns(200) .then((r) => { if (alive) setRuns(r); }) .catch(() => { if (alive) setRuns([]); }); return () => { alive = false; }; }, [historyVersion]); const groups = useMemo(() => buildGroups(runs ?? []), [runs]); const baseline = useMemo(() => pickBaseline(groups), [groups]); const openConfig = (g: ConfigGroup) => { const src = g.latestOk; if (!src) return; requestRestore({ graph: src.graph, sampleKey: src.sample_key, pinSeed: null, sourceRunId: src.run_id, precisionTarget: src.precision_target ?? null, }); setWorkspaceMode("compose"); }; return (
{/* Header mirrors the FlowCanvas toolbar height so flipping modes doesn't jump the layout. The toggle is duplicated here because the canvas toolbar is covered while this board is up. */}
Multiverse {runs != null && ( <> {" "} · {groups.length} configuration{groups.length === 1 ? "" : "s"} ·{" "} {runs.length} archived run{runs.length === 1 ? "" : "s"} )}
squares = pipeline stages · dot above = differs from baseline · strip = one dot per replicate (0–100%)
{/* Paper-figure export of the whole board (hybrid path). */} boardRef.current} name="multiverse" view="multiverse" />
{runs != null && runs.some((r) => r.demo) && }
{runs == null ? (
Loading archive…
) : groups.length === 0 ? (
No configurations archived yet

The Multiverse view treats every configuration you try as evidence: one card per configuration, with its pipeline schematic and the distribution of outcomes across replicates. Switch to Compose, run a pipeline (try the ×5 replicate runner), then flip back here to compare.

) : (
{groups.map((g) => { const isBaseline = baseline != null && g.hash === baseline.hash; const differing = baseline != null && !isBaseline ? diffKinds(g.graph, baseline.graph) : null; // Wave J: when BOTH sides carry pooled binomial counts, // Δ compares POOLED means (shot-weighted, the honest // estimator) instead of unweighted per-run means, and // the "(n small)" suffix keys on pooled SHOTS: ≥2048 on // both sides ⇒ worst-case Wilson half-width ≤ ±2.2pp, // so a multi-pp Δ is signal, not shot noise (threshold // rationale in lib/stats.ts). Without pools the old // replicate-count heuristic stands. const pooledBoth = !isBaseline && g.pooled != null && baseline?.pooled != null; const nSmall = pooledBoth ? (g.pooled as PooledEvidence).shots < POOLED_SMALL_N_SHOTS || (baseline?.pooled as PooledEvidence).shots < POOLED_SMALL_N_SHOTS : baseline != null && (g.values.length < 3 || baseline.values.length < 3); const delta = pooledBoth ? ((g.pooled as PooledEvidence).point - (baseline?.pooled as PooledEvidence).point) * 100 : !isBaseline && g.mean != null && baseline?.mean != null ? (g.mean - baseline.mean) * 100 : null; const abSelected = g.latestOk != null && compareIds.includes(g.latestOk.run_id); return (
{/* header: circuit + config identity */}
#{g.hash.slice(0, 6)} {g.circuitTag} {isBaseline && ( baseline )}
{/* pipeline schematic */} {/* outcome distribution */} {g.values.length >= 2 ? ( <> {g.pooled && (
pooled μ {(g.pooled.point * 100).toFixed(1)}% ± {(g.pooled.halfWidth * 100).toFixed(1)}pp over{" "} {g.pooled.shots} shots
)} {/* flex-wrap: at the 240px card minimum the Δ-vs- baseline span (~160px) plus μ and ×n exceed the content box; wrapping keeps each stat intact on its own line instead of mid-text folding. */}
μ={((g.mean as number) * 100).toFixed(1)}% ×{g.values.length} {delta != null && ( = 0 ? "text-ok" : "text-warn"}`} title={ pooledBoth ? "Difference of POOLED means (shot-weighted, Wilson-pooled counts) vs the baseline configuration, in percentage points." : "Difference of mean headline metric vs the baseline configuration, in percentage points." } > Δ {delta >= 0 ? "+" : ""} {delta.toFixed(1)}pp vs baseline {nSmall ? " (n small)" : ""} )}
) : g.values.length === 1 ? (
{g.latestOk?.headline_label ?? "metric"}{" "} {(g.values[0] * 100).toFixed(1)}% {" "} · single draw — run more replicates for a distribution {delta != null && ( = 0 ? "text-ok" : "text-warn"}`} > Δ {delta >= 0 ? "+" : ""} {delta.toFixed(1)}pp{nSmall ? " (n small)" : ""} )}
) : (
no metric recorded
)} {/* meta */}
{g.runs.length} run{g.runs.length === 1 ? "" : "s"} · {relTime(g.latest.created_at)} {g.nErr > 0 && ( <> · {g.nErr} errored )}
{/* actions */}
); })}
)}
); }