Cascade-memory — both memory paths, one cascade

Two memory layers, one cascade walker. Type a structural question — "uses softmax", "cites batch-invariant-ops", "HDC uses", "cascade resolves-via" — and the cascade resolves it at L0-retrieved via the mgai-graph typed-edge sub-strategy, no model. Type a fuzzy similarity question — "compose hypervectors", "GPU nondeterminism" — and the L0-retrieved miss is visible while the HDC cosine layer surfaces the top-3 conceptually-related corpus items. The substrate publishes which path resolved; the receipt's V-class is the cascade tier and its output_hash is FNV-1a over the routing decision + HDC top-3.

view the kernel that wrote this receipt crates/mathground-view/src/web.rs
//! JS surface — `wasm` feature only.
//!
//! Exposes three `mount_*` entry points. Each takes a canvas ID + a small
//! parameter struct (passed as JSON from JS), drives the kernel + draw loop
//! via `requestAnimationFrame`, and emits a per-frame `Receipt` back to the
//! page through an updater callback.
//!
//! The page is responsible for: providing the `<canvas>` and a receipt
//! sink. The crate is responsible for: math, drawing, timing.

use std::cell::RefCell;
use std::rc::Rc;

use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement, WebGl2RenderingContext};

use mgai_meter_web::{DEFAULT_TDP_W, build_receipt, now_ns, primitive_from_measurement};

use mgai_active_inference::structure::StructureLearner;
use mgai_active_inference::{Agent as AiAgent, GenerativeModel as AiModel};

use mgai_cea::{
    ConstrainedProblem, Constraint, Design, MaxMass, MinimizeVolume, ParametricSphere,
    SearchParams, search as cea_search,
};
use mgai_voxel::{Aabb as VoxAabb, Vec3 as VoxVec3, VoxelGrid};

use crate::cascade::{self, CascadeTier, SubExpert, TimeFn};

// ── JSON-shaped cascade walk for the escalate exhibit ────────────────
//
// The lazy-load demo at /exhibits/escalate is driven entirely from JS:
// it imports this function to walk the cascade, decides from
// `resolved_at` whether to lazy-import the l2-leaf bundle, and renders
// the trace itself. The walk is the same `cascade::walk` the on-canvas
// reason exhibit uses.

#[wasm_bindgen]
pub fn cascade_walk_json(query: &str) -> JsValue {
    let time = TimeFn { now_ns };
    let trace = cascade::walk(query, &time);
    mgai_meter_web::to_js_json(&trace)
}
use crate::fft::{fft_in_place, fft_power_spectrum};
use crate::fft2d::{fft2d_in_place, log_magnitude_shifted};
use crate::graddescent::{GdParams, GdState, gd_step, rosenbrock};
use crate::hdc::Hv;
use crate::heat::{HeatParams, heat_step};
use crate::lorenz::{LorenzParams, LorenzState, lorenz_rk4_step};
use crate::modal::{encode_audio, encode_image, encode_text, encode_video};
use crate::pfilter::{PFilterParams, PFilterState, pfilter_step};
use crate::sdf::marching_squares;
use crate::sdf3d;

#[wasm_bindgen(start)]
pub fn _start() {
    console_error_panic_hook::set_once();
}

fn ctx_for(canvas_id: &str) -> Option<(HtmlCanvasElement, CanvasRenderingContext2d)> {
    let win = web_sys::window()?;
    let doc = win.document()?;
    let canvas = doc.get_element_by_id(canvas_id)?;
    let canvas: HtmlCanvasElement = canvas.dyn_into().ok()?;
    let ctx: CanvasRenderingContext2d = canvas.get_context("2d").ok()??.dyn_into().ok()?;
    Some((canvas, ctx))
}

fn emit_receipt(
    sink: &js_sys::Function,
    label: &str,
    v_class: &str,
    iters: u64,
    wall_ns: f64,
    bit_ops_per_op: u64,
) {
    let prim = primitive_from_measurement(
        label,
        v_class,
        iters,
        wall_ns,
        bit_ops_per_op,
        DEFAULT_TDP_W,
    );
    let receipt = build_receipt(vec![prim], DEFAULT_TDP_W);
    let js = mgai_meter_web::to_js_json(&receipt);
    let _ = sink.call1(&JsValue::NULL, &js);
}

/// Emit a receipt + carry an `output_hash` on the primitive. The
/// determinism exhibit uses this so the receipt strip on the page can
/// flip its ≡ / ≠ indicator on the substrate-reported hash instead of
/// re-hashing on the JS side.
fn emit_receipt_with_hash(
    sink: &js_sys::Function,
    label: &str,
    v_class: &str,
    iters: u64,
    wall_ns: f64,
    bit_ops_per_op: u64,
    output_hash: u64,
) {
    let prim = primitive_from_measurement(
        label,
        v_class,
        iters,
        wall_ns,
        bit_ops_per_op,
        DEFAULT_TDP_W,
    )
    .with_output_hash(output_hash);
    let receipt = build_receipt(vec![prim], DEFAULT_TDP_W);
    let js = mgai_meter_web::to_js_json(&receipt);
    let _ = sink.call1(&JsValue::NULL, &js);
}

/// FNV-1a 64-bit over a `&[f32]`'s raw bytes. Used by the determinism
/// exhibit to fingerprint each FFT output cheaply — the same family as
/// the proxy's resolver fingerprint (`lux_worlds_faeble::receipt::
/// fnv1a_64`). Re-implemented here so mathground-view stays free of
/// runtime deps on the faeble side; FNV-1a's offset basis and prime
/// are public constants.
fn fnv1a_64_f32_slice(xs: &[f32]) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for x in xs {
        // Hash the IEEE-754 bit pattern so +0/-0 and NaN payloads are
        // distinguishable across runs. `to_bits()` is the canonical
        // f32 → u32 byte view.
        let bits = x.to_bits().to_le_bytes();
        for &b in &bits {
            h ^= b as u64;
            h = h.wrapping_mul(0x100_0000_01b3);
        }
    }
    h
}

fn schedule(closure: &Closure<dyn FnMut()>) {
    if let Some(win) = web_sys::window() {
        let _ = win.request_animation_frame(closure.as_ref().unchecked_ref());
    }
}

// ── FFT exhibit ──────────────────────────────────────────────────────

/// Mount the FFT exhibit on `canvas_id`. The kernel reuses a stationary
/// test signal (sum of two sines) so the spectrum is interpretable; in
/// future iterations the page can push live samples.
#[wasm_bindgen]
pub fn mount_fft(canvas_id: &str, n: u32, sink: &js_sys::Function) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let n_usize = n as usize;
    if !n_usize.is_power_of_two() || n_usize < 16 {
        return Err(JsValue::from_str("n must be a power of two ≥ 16"));
    }

    let buf = Rc::new(RefCell::new(vec![0.0f32; 2 * n_usize]));
    let spec = Rc::new(RefCell::new(vec![0.0f32; n_usize / 2]));
    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let buf2 = buf.clone();
    let spec2 = spec.clone();

    let mut phase = 0.0f32;

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        // ── Signal: two sines, swept phase to keep it visually alive ──
        let mut b = buf2.borrow_mut();
        for k in 0..n_usize {
            let t = k as f32 / n_usize as f32;
            let s = (2.0 * core::f32::consts::PI * 4.0 * t + phase).sin()
                + 0.5 * (2.0 * core::f32::consts::PI * 12.0 * t).sin();
            b[2 * k] = s;
            b[2 * k + 1] = 0.0;
        }
        phase += 0.05;

        // ── Compute pass — timed ──
        let t0 = now_ns();
        let report = fft_in_place(&mut b).expect("power-of-two");
        let mut s = spec2.borrow_mut();
        fft_power_spectrum(&b, &mut s);
        let wall_ns = now_ns() - t0;

        // ── Draw pass — not metered (page chrome) ──
        let w = canvas.width() as f64;
        let h = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, w, h);
        ctx.set_stroke_style_str("rgba(120, 220, 255, 0.95)");
        ctx.set_line_width(1.5);
        ctx.begin_path();
        let bins = s.len();
        for i in 0..bins {
            let x = (i as f64 / bins as f64) * w;
            // s[i] is dB ∈ [-120, 0] roughly. Map to canvas.
            let db = s[i].clamp(-120.0, 0.0) as f64;
            let y = h - (db + 120.0) / 120.0 * h;
            if i == 0 {
                ctx.move_to(x, y);
            } else {
                ctx.line_to(x, y);
            }
        }
        ctx.stroke();

        // ── Live-indicator cursor: a thin vertical line that sweeps
        //    across the canvas. Drives the "live" intuition that the
        //    receipt next to this kernel updates every frame, even when
        //    the spectrum itself looks stationary at a glance. ──
        let cursor_x = ((phase * 60.0) as f64).rem_euclid(w);
        ctx.set_stroke_style_str("rgba(255, 220, 140, 0.85)");
        ctx.set_line_width(1.0);
        ctx.begin_path();
        ctx.move_to(cursor_x, 0.0);
        ctx.line_to(cursor_x, h);
        ctx.stroke();
        // A small dot at the spectrum at the cursor x — reads as "the
        // measurement just sampled this bin".
        let bin_at_cursor = ((cursor_x / w) * (bins as f64)).floor() as usize;
        let bin_at_cursor = bin_at_cursor.min(bins.saturating_sub(1));
        if bins > 0 {
            let db = s[bin_at_cursor].clamp(-120.0, 0.0) as f64;
            let y = h - (db + 120.0) / 120.0 * h;
            ctx.set_fill_style_str("rgba(255, 220, 140, 0.95)");
            ctx.begin_path();
            ctx.arc(cursor_x, y, 2.5, 0.0, std::f64::consts::TAU).ok();
            ctx.fill();
        }

        // ── Emit receipt for the compute pass only ──
        // Hash the per-frame power spectrum so /receipts/05's
        // reproducibility receipt has live data per frame. Spectrum
        // evolves with the sweeping phase, so consecutive hashes differ
        // by design; the field is populated, not claiming ≡-stability.
        emit_receipt_with_hash(
            &sink,
            "fft_radix2",
            "L0Closed",
            1,
            wall_ns,
            report.bit_ops,
            fnv1a_64_f32_slice(&s),
        );

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    // Keep the closure alive forever.
    std::mem::forget(g);
    Ok(())
}

// ── Lorenz exhibit ───────────────────────────────────────────────────

/// Mount the Lorenz attractor on `canvas_id`. Draws a trail in the (x, z)
/// projection; advances `steps_per_frame` RK4 steps per animation frame.
#[wasm_bindgen]
pub fn mount_lorenz(
    canvas_id: &str,
    steps_per_frame: u32,
    sink: &js_sys::Function,
) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let params = LorenzParams::default();
    let state = Rc::new(RefCell::new(LorenzState::default()));
    let trail: Rc<RefCell<Vec<(f32, f32)>>> = Rc::new(RefCell::new(Vec::with_capacity(4096)));
    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let state2 = state.clone();
    let trail2 = trail.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let t0 = now_ns();
        let mut s = state2.borrow_mut();
        let mut bit_ops_total: u64 = 0;
        let mut tr = trail2.borrow_mut();
        for _ in 0..steps_per_frame {
            bit_ops_total += lorenz_rk4_step(&mut s, &params);
            tr.push((s.x as f32, s.z as f32));
        }
        // Cap trail length.
        let cap = 4096usize;
        if tr.len() > cap {
            let drop = tr.len() - cap;
            tr.drain(0..drop);
        }
        let wall_ns = now_ns() - t0;

        let w = canvas.width() as f64;
        let h = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, w, h);

        // Centre + scale: x ∈ ~[-25, 25], z ∈ ~[0, 50].
        let cx = w * 0.5;
        let cy = h * 0.5;
        let scale = (w.min(h) / 60.0) as f32;
        ctx.set_stroke_style_str("rgba(255, 180, 80, 0.7)");
        ctx.set_line_width(1.0);
        ctx.begin_path();
        for (i, (x, z)) in tr.iter().enumerate() {
            let px = cx as f32 + x * scale;
            let py = cy as f32 - (z - 25.0) * scale;
            if i == 0 {
                ctx.move_to(px as f64, py as f64);
            } else {
                ctx.line_to(px as f64, py as f64);
            }
        }
        ctx.stroke();

        emit_receipt(
            &sink,
            "lorenz_rk4",
            "L0Closed",
            steps_per_frame as u64,
            wall_ns,
            bit_ops_total / steps_per_frame.max(1) as u64,
        );

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── SDF exhibit ──────────────────────────────────────────────────────

/// Mount the 2-D SDF exhibit. Renders the iso-contour of a slowly drifting
/// scalar field (sum of two moving circles' SDFs, deformed by a sine) via
/// marching squares.
#[wasm_bindgen]
pub fn mount_sdf(
    canvas_id: &str,
    grid_w: u32,
    grid_h: u32,
    sink: &js_sys::Function,
) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let cells = Rc::new(RefCell::new(vec![0.0f32; (grid_w * grid_h) as usize]));
    let segs = Rc::new(RefCell::new(Vec::with_capacity(8192)));
    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let cells2 = cells.clone();
    let segs2 = segs.clone();
    let mut tau = 0.0f32;

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        // Update field.
        let mut c = cells2.borrow_mut();
        let cx1 = grid_w as f32 * (0.4 + 0.1 * (tau).cos());
        let cy1 = grid_h as f32 * 0.5;
        let cx2 = grid_w as f32 * (0.6 + 0.1 * (tau + 1.0).sin());
        let cy2 = grid_h as f32 * 0.5;
        let r = grid_w.min(grid_h) as f32 * 0.15;
        for y in 0..grid_h {
            for x in 0..grid_w {
                let dx1 = x as f32 - cx1;
                let dy1 = y as f32 - cy1;
                let d1 = (dx1 * dx1 + dy1 * dy1).sqrt() - r;
                let dx2 = x as f32 - cx2;
                let dy2 = y as f32 - cy2;
                let d2 = (dx2 * dx2 + dy2 * dy2).sqrt() - r;
                // Smooth-min union (k = 4) — Quílez.
                let k = 4.0_f32;
                let h_ = ((k - (d1 - d2).abs()).max(0.0) / k).powi(2) * 0.5;
                let d = d1.min(d2) - h_ * k * 0.5;
                c[(y * grid_w + x) as usize] = d;
            }
        }
        tau += 0.02;

        let t0 = now_ns();
        let mut s = segs2.borrow_mut();
        let report = marching_squares(&c, grid_w, grid_h, 0.0, &mut s);
        let wall_ns = now_ns() - t0;

        // Draw.
        let w = canvas.width() as f64;
        let h_can = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, w, h_can);
        let sx = w / grid_w as f64;
        let sy = h_can / grid_h as f64;
        ctx.set_stroke_style_str("rgba(180, 255, 200, 0.95)");
        ctx.set_line_width(1.5);
        ctx.begin_path();
        let mut i = 0;
        while i + 3 < s.len() {
            ctx.move_to(s[i] as f64 * sx, s[i + 1] as f64 * sy);
            ctx.line_to(s[i + 2] as f64 * sx, s[i + 3] as f64 * sy);
            i += 4;
        }
        ctx.stroke();

        emit_receipt(
            &sink,
            "sdf_marching_squares",
            "L0Closed",
            1,
            wall_ns,
            report.bit_ops,
        );

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── Heat-equation exhibit ────────────────────────────────────────────

#[wasm_bindgen]
pub fn mount_heat(
    canvas_id: &str,
    grid_w: u32,
    grid_h: u32,
    sink: &js_sys::Function,
) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let n = (grid_w * grid_h) as usize;
    let mut u0 = vec![0.0f32; n];
    u0[(grid_h / 2 * grid_w + grid_w / 2) as usize] = 200.0;
    for k in 0..6 {
        let cx = (grid_w as f32 * (0.2 + 0.12 * k as f32)).min((grid_w - 1) as f32) as u32;
        let cy = (grid_h as f32 * (0.7 - 0.04 * k as f32)).max(0.0) as u32;
        u0[(cy * grid_w + cx) as usize] = 200.0;
    }
    let u = Rc::new(RefCell::new(u0));
    let u_next = Rc::new(RefCell::new(vec![0.0f32; n]));
    let params = HeatParams::default();
    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let u2 = u.clone();
    let u_next2 = u_next.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let t0 = now_ns();
        let mut a = u2.borrow_mut();
        let mut b = u_next2.borrow_mut();
        let steps = 4u32;
        let mut bit_ops_total: u64 = 0;
        for _ in 0..steps {
            let r = heat_step(&a, &mut b, grid_w, grid_h, &params);
            bit_ops_total += r.bit_ops;
            std::mem::swap(&mut *a, &mut *b);
        }
        let wall_ns = now_ns() - t0;

        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        let sx = cw / grid_w as f64;
        let sy = ch / grid_h as f64;
        let mut maxv = 1e-9f32;
        for &v in a.iter() {
            if v > maxv {
                maxv = v;
            }
        }
        for y in 0..grid_h {
            for x in 0..grid_w {
                let v = (a[(y * grid_w + x) as usize] / maxv).clamp(0.0, 1.0);
                let r = (255.0 * v.powf(0.5)) as u32;
                let g_ = (60.0 + 120.0 * v) as u32;
                let bb = (160.0 * (1.0 - v)) as u32;
                ctx.set_fill_style_str(&format!("rgb({r},{g_},{bb})"));
                ctx.fill_rect(x as f64 * sx, y as f64 * sy, sx + 1.0, sy + 1.0);
            }
        }

        emit_receipt(
            &sink,
            "heat_forward_euler",
            "L0Closed",
            steps as u64,
            wall_ns,
            bit_ops_total / steps as u64,
        );
        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── Particle-filter exhibit ──────────────────────────────────────────

#[wasm_bindgen]
pub fn mount_pfilter(
    canvas_id: &str,
    n_particles: u32,
    sink: &js_sys::Function,
) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let mut params = PFilterParams::default();
    params.n_particles = n_particles.max(32);
    let state = Rc::new(RefCell::new(PFilterState::new(
        &params,
        0xC0DE_BEEF_F00Du64,
    )));
    let truth_trail: Rc<RefCell<Vec<f32>>> = Rc::new(RefCell::new(Vec::with_capacity(800)));
    let obs_trail: Rc<RefCell<Vec<f32>>> = Rc::new(RefCell::new(Vec::with_capacity(800)));
    let mean_trail: Rc<RefCell<Vec<f32>>> = Rc::new(RefCell::new(Vec::with_capacity(800)));
    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let state2 = state.clone();
    let truth2 = truth_trail.clone();
    let obs2 = obs_trail.clone();
    let mean2 = mean_trail.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let t0 = now_ns();
        let mut s = state2.borrow_mut();
        let r = pfilter_step(&mut s, &params, 0.1);
        let wall_ns = now_ns() - t0;

        let mut t = truth2.borrow_mut();
        let mut o = obs2.borrow_mut();
        let mut m = mean2.borrow_mut();
        t.push(r.truth);
        o.push(r.obs);
        m.push(s.posterior_mean);
        let cap = 800usize;
        for v in [&mut t, &mut o, &mut m] {
            if v.len() > cap {
                let d = v.len() - cap;
                v.drain(0..d);
            }
        }

        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);
        let amp = params.amplitude as f64;
        let y_of = |v: f32| ch * 0.5 - (v as f64) * (ch * 0.35 / amp);
        let x_of = |i: usize, n: usize| cw * (i as f64) / (n.max(1) as f64);
        let n_trail = t.len();

        ctx.set_fill_style_str("rgba(255, 180, 80, 0.5)");
        for (i, &v) in o.iter().enumerate() {
            let x = x_of(i, n_trail);
            let y = y_of(v);
            ctx.fill_rect(x - 1.0, y - 1.0, 2.0, 2.0);
        }
        ctx.set_stroke_style_str("rgba(120, 220, 255, 0.95)");
        ctx.set_line_width(2.0);
        ctx.begin_path();
        for (i, &v) in t.iter().enumerate() {
            let x = x_of(i, n_trail);
            let y = y_of(v);
            if i == 0 {
                ctx.move_to(x, y);
            } else {
                ctx.line_to(x, y);
            }
        }
        ctx.stroke();
        ctx.set_stroke_style_str("rgba(180, 255, 200, 0.9)");
        ctx.set_line_width(1.5);
        ctx.begin_path();
        for (i, &v) in m.iter().enumerate() {
            let x = x_of(i, n_trail);
            let y = y_of(v);
            if i == 0 {
                ctx.move_to(x, y);
            } else {
                ctx.line_to(x, y);
            }
        }
        ctx.stroke();
        ctx.set_fill_style_str("rgba(255, 180, 220, 0.45)");
        let x_now = cw - 4.0;
        for &x_val in s.particles.iter() {
            ctx.fill_rect(x_now, y_of(x_val) - 1.0, 3.0, 3.0);
        }

        emit_receipt(
            &sink,
            "particle_filter_systematic",
            "L0Closed",
            1,
            wall_ns,
            r.bit_ops,
        );
        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── Gradient-descent exhibit ─────────────────────────────────────────

#[wasm_bindgen]
pub fn mount_grad(
    canvas_id: &str,
    steps_per_frame: u32,
    sink: &js_sys::Function,
) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let p = GdParams::default();
    let state = Rc::new(RefCell::new(GdState::default()));
    let trail: Rc<RefCell<Vec<(f32, f32)>>> = Rc::new(RefCell::new(Vec::with_capacity(8192)));
    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let state2 = state.clone();
    let trail2 = trail.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let t0 = now_ns();
        let mut s = state2.borrow_mut();
        let mut tr = trail2.borrow_mut();
        let mut bit_ops_total: u64 = 0;
        let mut loss = 0.0f32;
        for _ in 0..steps_per_frame {
            let r = gd_step(&mut s, &p);
            bit_ops_total += r.bit_ops;
            loss = r.loss;
            tr.push((s.x, s.y));
        }
        let cap = 4096usize;
        if tr.len() > cap {
            let drop = tr.len() - cap;
            tr.drain(0..drop);
        }
        if !s.x.is_finite() || !s.y.is_finite() || s.x.abs() > 5.0 || s.y.abs() > 8.0 || loss > 1e8
        {
            *s = GdState::default();
            tr.clear();
        }
        let wall_ns = now_ns() - t0;

        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        let x_min = -2.0f32;
        let x_max = 2.0f32;
        let y_min = -1.5f32;
        let y_max = 3.5f32;
        let to_px = |x: f32, y: f32| {
            (
                ((x - x_min) / (x_max - x_min)) as f64 * cw,
                (1.0 - (y - y_min) / (y_max - y_min)) as f64 * ch,
            )
        };

        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        let gw = 40u32;
        let gh = 30u32;
        for j in 0..gh {
            for i in 0..gw {
                let x = x_min + (i as f32 + 0.5) * (x_max - x_min) / gw as f32;
                let y = y_min + (j as f32 + 0.5) * (y_max - y_min) / gh as f32;
                let v = rosenbrock(x, y, p.a, p.b).max(1e-3).ln();
                let t = ((v + 4.0) / 12.0).clamp(0.0, 1.0) as f64;
                let r = (40.0 + 130.0 * t) as u32;
                let gg = (40.0 + 100.0 * (1.0 - t)) as u32;
                let bb = (90.0 + 80.0 * (1.0 - t)) as u32;
                ctx.set_fill_style_str(&format!("rgb({r},{gg},{bb})"));
                let (px0, py0) = to_px(
                    x_min + i as f32 * (x_max - x_min) / gw as f32,
                    y_min + (j + 1) as f32 * (y_max - y_min) / gh as f32,
                );
                let (px1, py1) = to_px(
                    x_min + (i + 1) as f32 * (x_max - x_min) / gw as f32,
                    y_min + j as f32 * (y_max - y_min) / gh as f32,
                );
                ctx.fill_rect(px0, py0, px1 - px0 + 1.0, py1 - py0 + 1.0);
            }
        }

        ctx.set_stroke_style_str("rgba(255, 240, 140, 0.92)");
        ctx.set_line_width(2.0);
        ctx.begin_path();
        for (i, &(x, y)) in tr.iter().enumerate() {
            let (px, py) = to_px(x, y);
            if i == 0 {
                ctx.move_to(px, py);
            } else {
                ctx.line_to(px, py);
            }
        }
        ctx.stroke();

        let (mpx, mpy) = to_px(1.0, 1.0);
        ctx.set_fill_style_str("rgba(255, 80, 120, 0.95)");
        ctx.begin_path();
        ctx.arc(mpx, mpy, 4.0, 0.0, std::f64::consts::TAU).unwrap();
        ctx.fill();

        emit_receipt(
            &sink,
            "gd_momentum_rosenbrock",
            "L0Closed",
            steps_per_frame as u64,
            wall_ns,
            bit_ops_total / steps_per_frame.max(1) as u64,
        );
        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── 2-D FFT exhibit (visual-fft-revolution lineage) ──────────────────

#[wasm_bindgen]
pub fn mount_fft2d(canvas_id: &str, dim: u32, sink: &js_sys::Function) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let dim_us = dim as usize;
    if !dim_us.is_power_of_two() || dim_us < 32 {
        return Err(JsValue::from_str("dim must be a power of two ≥ 32"));
    }

    let buf = Rc::new(RefCell::new(vec![0.0f32; 2 * dim_us * dim_us]));
    let img = Rc::new(RefCell::new(vec![0.0f32; dim_us * dim_us]));
    let mag = Rc::new(RefCell::new(vec![0.0f32; dim_us * dim_us]));
    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let buf2 = buf.clone();
    let img2 = img.clone();
    let mag2 = mag.clone();
    let mut tau = 0.0f32;

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let mut im = img2.borrow_mut();
        for y in 0..dim_us {
            for x in 0..dim_us {
                let fx = (x as f32 / dim_us as f32 - 0.5) * 2.0;
                let fy = (y as f32 / dim_us as f32 - 0.5) * 2.0;
                let s1 = (12.0 * fx + tau).sin();
                let s2 = (10.0 * fy + 0.7 * tau).sin();
                let s3 = (9.0 * fx + 9.0 * fy + tau * 0.3).sin();
                let pulse = (-((fx * fx + fy * fy) * 4.0)).exp() * (tau * 0.5).cos();
                im[y * dim_us + x] = 0.33 * (s1 + s2 + s3) + 0.5 * pulse;
            }
        }
        let mut b = buf2.borrow_mut();
        for k in 0..(dim_us * dim_us) {
            b[2 * k] = im[k];
            b[2 * k + 1] = 0.0;
        }

        let t0 = now_ns();
        let report = fft2d_in_place(&mut b, dim, dim).expect("power-of-two");
        let mut m = mag2.borrow_mut();
        let _ = log_magnitude_shifted(&b, dim, dim, &mut m);
        let wall_ns = now_ns() - t0;

        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);
        let panel_w = cw * 0.5;
        let sx = panel_w / dim as f64;
        let sy = ch / dim as f64;

        let mut min_v = f32::INFINITY;
        let mut max_v = f32::NEG_INFINITY;
        for &v in im.iter() {
            if v < min_v {
                min_v = v;
            }
            if v > max_v {
                max_v = v;
            }
        }
        let scale = (max_v - min_v).max(1e-6);
        for y in 0..dim_us {
            for x in 0..dim_us {
                let v = (im[y * dim_us + x] - min_v) / scale;
                let r = (255.0 * v) as u32;
                let g_ = (120.0 + 100.0 * v) as u32;
                let bb = (220.0 - 100.0 * v) as u32;
                ctx.set_fill_style_str(&format!("rgb({r},{g_},{bb})"));
                ctx.fill_rect(x as f64 * sx, y as f64 * sy, sx + 1.0, sy + 1.0);
            }
        }
        let mut min_l = f32::INFINITY;
        let mut max_l = f32::NEG_INFINITY;
        for &v in m.iter() {
            if v.is_finite() {
                if v < min_l {
                    min_l = v;
                }
                if v > max_l {
                    max_l = v;
                }
            }
        }
        let scale2 = (max_l - min_l).max(1e-6);
        for y in 0..dim_us {
            for x in 0..dim_us {
                let v = ((m[y * dim_us + x] - min_l) / scale2).clamp(0.0, 1.0);
                let r = (80.0 + 175.0 * v) as u32;
                let g_ = (30.0 + 120.0 * v) as u32;
                let bb = (160.0 * v) as u32;
                ctx.set_fill_style_str(&format!("rgb({r},{g_},{bb})"));
                ctx.fill_rect(panel_w + x as f64 * sx, y as f64 * sy, sx + 1.0, sy + 1.0);
            }
        }

        tau += 0.05;

        emit_receipt_with_hash(
            &sink,
            "fft2d_radix2",
            "L0Closed",
            1,
            wall_ns,
            report.bit_ops,
            fnv1a_64_f32_slice(&m),
        );
        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── 3-D SDF (WebGL2 sphere-trace) exhibit ────────────────────────────

fn compile_shader(
    gl: &WebGl2RenderingContext,
    kind: u32,
    src: &str,
) -> Result<web_sys::WebGlShader, String> {
    let shader = gl.create_shader(kind).ok_or("create_shader failed")?;
    gl.shader_source(&shader, src);
    gl.compile_shader(&shader);
    let ok = gl
        .get_shader_parameter(&shader, WebGl2RenderingContext::COMPILE_STATUS)
        .as_bool()
        .unwrap_or(false);
    if !ok {
        return Err(gl.get_shader_info_log(&shader).unwrap_or_default());
    }
    Ok(shader)
}

fn link_program(
    gl: &WebGl2RenderingContext,
    vs: &web_sys::WebGlShader,
    fs: &web_sys::WebGlShader,
) -> Result<web_sys::WebGlProgram, String> {
    let prog = gl.create_program().ok_or("create_program failed")?;
    gl.attach_shader(&prog, vs);
    gl.attach_shader(&prog, fs);
    gl.link_program(&prog);
    let ok = gl
        .get_program_parameter(&prog, WebGl2RenderingContext::LINK_STATUS)
        .as_bool()
        .unwrap_or(false);
    if !ok {
        return Err(gl.get_program_info_log(&prog).unwrap_or_default());
    }
    Ok(prog)
}

// ── Reason exhibit (cascade walk visualised + per-hop receipts) ──────

const REASON_QUERIES: &[&str] = &[
    "2 + 2",
    "6!",
    "pi",
    "pythagorean theorem",
    "circumference of a unit circle",
    "rms of a sine wave amplitude a",
    "compose pi times e",
    "what is the meaning of life?",
];

fn tier_color(t: CascadeTier) -> &'static str {
    match t {
        CascadeTier::L0Closed => "rgba(120, 220, 255, 0.95)",
        CascadeTier::L0Retrieved => "rgba(180, 255, 200, 0.95)",
        CascadeTier::L0Identifiable => "rgba(190, 200, 255, 0.95)",
        CascadeTier::L1 => "rgba(255, 220, 140, 0.95)",
        CascadeTier::L2 => "rgba(255, 140, 160, 0.95)",
    }
}

#[wasm_bindgen]
pub fn mount_reason(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let query_idx = Rc::new(RefCell::new(0usize));
    let frame_in_query = Rc::new(RefCell::new(0u32));
    let qi = query_idx.clone();
    let fi = frame_in_query.clone();

    let time = TimeFn { now_ns };

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let mut i = qi.borrow_mut();
        let mut fr = fi.borrow_mut();
        let q = REASON_QUERIES[*i];
        let trace = cascade::walk(q, &time);

        // Draw.
        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        // Query banner.
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text("query", 28.0, 32.0).ok();
        ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
        ctx.set_font("18px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(q, 28.0, 56.0).ok();

        // Hops, ladder-rendered. Each tier may contribute one (reasoning
        // only) or two (reasoning + generation) hops. Generation hops are
        // indented to make the MoT split visible at a glance.
        let mut y = 100.0;
        let row_h = 44.0;
        for hop in trace.hops.iter() {
            let is_gen = matches!(hop.expert, SubExpert::Generation);
            let indent = if is_gen { 18.0 } else { 0.0 };

            // Side bar: tier color (solid for reasoning, dashed/lower-alpha for generation).
            let bar_alpha = if is_gen { 0.55 } else { 1.0 };
            let bar_color = tier_color(hop.tier).replace("0.95", &format!("{:.2}", bar_alpha));
            ctx.set_fill_style_str(&bar_color);
            ctx.fill_rect(28.0 + indent, y - 14.0, 4.0, 36.0);

            // Tier + expert label.
            ctx.set_fill_style_str(tier_color(hop.tier));
            ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
            let header = format!("{} · {}", hop.tier.label(), hop.expert.label());
            ctx.fill_text(&header, 44.0 + indent, y).ok();

            // Action.
            ctx.set_fill_style_str("rgba(180, 188, 208, 1)");
            ctx.fill_text(&hop.action, 44.0 + indent, y + 16.0).ok();

            // Result on the right: ✓ / ✗ + answer if any.
            let status = if hop.matched {
                "✓ matched"
            } else {
                "✗ no match"
            };
            ctx.set_fill_style_str(if hop.matched {
                "rgba(180, 255, 200, 1)"
            } else {
                "rgba(255, 180, 180, 0.6)"
            });
            ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
            ctx.fill_text(status, cw - 220.0, y).ok();
            if let Some(a) = &hop.answer {
                ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
                let short = if a.chars().count() > 28 {
                    let mut s: String = a.chars().take(28).collect();
                    s.push('…');
                    s
                } else {
                    a.clone()
                };
                ctx.fill_text(&short, cw - 220.0, y + 16.0).ok();
            }

            // Bit-ops + wall_ns/op.
            ctx.set_fill_style_str("rgba(120, 130, 150, 1)");
            ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
            let cost = format!("{} bit-ops · {:.0} ns/op", hop.bit_ops, hop.wall_ns_per_op);
            ctx.fill_text(&cost, 44.0 + indent, y + 30.0).ok();

            y += row_h;
        }

        // Footer.
        let resolved = match trace.resolved_at {
            Some(t) => format!("resolved at {}", t.label()),
            None => "refused at L2 (no model shipped)".to_string(),
        };
        ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
        ctx.set_font("13px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(&resolved, 28.0, ch - 36.0).ok();
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        let total = format!("total bit-ops across hops: {}", trace.total_bit_ops);
        ctx.fill_text(&total, 28.0, ch - 18.0).ok();

        // Emit a receipt summarising the whole trace as one primitive.
        // Use the matched tier's name (or L2-refused) as the primitive id.
        let prim_name = format!(
            "cascade_walk[{}]",
            trace.resolved_at.map(|t| t.label()).unwrap_or("L2_refused")
        );
        let v_class = match trace.resolved_at {
            Some(CascadeTier::L0Closed) => "L0Closed",
            Some(CascadeTier::L0Retrieved) => "L0Retrieved",
            Some(CascadeTier::L0Identifiable) => "L0Identifiable",
            Some(CascadeTier::L1) => "L1",
            Some(CascadeTier::L2) => "L2",
            None => "L2_refused",
        };
        // Sum wall_ns across hops.
        let wall_ns_total: f64 = trace
            .hops
            .iter()
            .map(|h| h.wall_ns_per_op * (h.bit_ops.max(1) as f64))
            .sum();
        emit_receipt(
            &sink,
            &prim_name,
            v_class,
            1,
            wall_ns_total,
            trace.total_bit_ops,
        );

        // Rotate to next query after ~60 frames (~1 s at 60 fps).
        *fr += 1;
        if *fr > 60 {
            *fr = 0;
            *i = (*i + 1) % REASON_QUERIES.len();
        }

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

#[wasm_bindgen]
pub fn mount_sdf3d(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    let win = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?;
    let doc = win
        .document()
        .ok_or_else(|| JsValue::from_str("no document"))?;
    let canvas = doc
        .get_element_by_id(canvas_id)
        .ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let canvas: HtmlCanvasElement = canvas
        .dyn_into()
        .map_err(|_| JsValue::from_str("not a canvas"))?;
    let gl = canvas
        .get_context("webgl2")
        .map_err(|_| JsValue::from_str("webgl2 unsupported"))?
        .ok_or_else(|| JsValue::from_str("webgl2 unsupported"))?
        .dyn_into::<WebGl2RenderingContext>()
        .map_err(|_| JsValue::from_str("webgl2 ctx wrong type"))?;

    let vs = compile_shader(
        &gl,
        WebGl2RenderingContext::VERTEX_SHADER,
        sdf3d::VERTEX_SRC,
    )
    .map_err(|e| JsValue::from_str(&format!("vs: {e}")))?;
    let fs = compile_shader(
        &gl,
        WebGl2RenderingContext::FRAGMENT_SHADER,
        sdf3d::FRAGMENT_SRC,
    )
    .map_err(|e| JsValue::from_str(&format!("fs: {e}")))?;
    let prog = link_program(&gl, &vs, &fs).map_err(|e| JsValue::from_str(&format!("link: {e}")))?;

    let verts: [f32; 6] = [-1.0, -1.0, 3.0, -1.0, -1.0, 3.0];
    let vbo = gl.create_buffer().ok_or_else(|| JsValue::from_str("vbo"))?;
    gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&vbo));
    unsafe {
        let arr = js_sys::Float32Array::view(&verts);
        gl.buffer_data_with_array_buffer_view(
            WebGl2RenderingContext::ARRAY_BUFFER,
            &arr,
            WebGl2RenderingContext::STATIC_DRAW,
        );
    }
    let vao = gl
        .create_vertex_array()
        .ok_or_else(|| JsValue::from_str("vao"))?;
    gl.bind_vertex_array(Some(&vao));
    let a_pos = gl.get_attrib_location(&prog, "a_pos") as u32;
    gl.enable_vertex_attrib_array(a_pos);
    gl.vertex_attrib_pointer_with_i32(a_pos, 2, WebGl2RenderingContext::FLOAT, false, 0, 0);
    let u_time = gl
        .get_uniform_location(&prog, "u_time")
        .ok_or_else(|| JsValue::from_str("u_time"))?;
    let u_res = gl
        .get_uniform_location(&prog, "u_resolution")
        .ok_or_else(|| JsValue::from_str("u_resolution"))?;

    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let start_ns = now_ns();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let t0 = now_ns();
        let t_sec = (t0 - start_ns) * 1e-9;
        let w = canvas.width();
        let h = canvas.height();
        gl.viewport(0, 0, w as i32, h as i32);
        gl.clear_color(0.03, 0.05, 0.08, 1.0);
        gl.clear(WebGl2RenderingContext::COLOR_BUFFER_BIT);
        gl.use_program(Some(&prog));
        gl.uniform1f(Some(&u_time), t_sec as f32);
        gl.uniform2f(Some(&u_res), w as f32, h as f32);
        gl.bind_vertex_array(Some(&vao));
        gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
        let wall_ns = now_ns() - t0;

        let bit_ops = sdf3d::estimate_bit_ops_per_frame(w, h);
        emit_receipt(&sink, "sdf3d_sphere_trace", "L0Closed", 1, wall_ns, bit_ops);

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── Omnimodal exhibit ────────────────────────────────────────────────
//
// Four deterministic encoders project text, image, audio, and video into
// the same HDC shape-key space. The exhibit cycles through three scenes;
// each scene supplies one sample per modality, and the page renders four
// panels + a 4×4 cosine matrix proving the cross-modal projection works.

#[derive(Clone, Copy)]
struct Scene {
    label: &'static str,
    text: &'static str,
    image: ImgKind,
    audio: AudKind,
    video: VidKind,
}

#[derive(Clone, Copy)]
enum ImgKind {
    Circle,
    Square,
    Diagonal,
}

#[derive(Clone, Copy)]
enum AudKind {
    SineTone,
    SquareWave,
    FreqSweep,
}

#[derive(Clone, Copy)]
enum VidKind {
    ExpandingCircle,
    PulsingSquare,
    ScrollingDiagonal,
}

const SCENES: &[Scene] = &[
    Scene {
        label: "circle",
        text: "circle of radius one",
        image: ImgKind::Circle,
        audio: AudKind::SineTone,
        video: VidKind::ExpandingCircle,
    },
    Scene {
        label: "square",
        text: "square grid pattern",
        image: ImgKind::Square,
        audio: AudKind::SquareWave,
        video: VidKind::PulsingSquare,
    },
    Scene {
        label: "diagonal",
        text: "diagonal stripes scan",
        image: ImgKind::Diagonal,
        audio: AudKind::FreqSweep,
        video: VidKind::ScrollingDiagonal,
    },
];

fn make_image(kind: ImgKind) -> [u8; 64] {
    let mut g = [0u8; 64];
    match kind {
        ImgKind::Circle => {
            for r in 0..8 {
                for c in 0..8 {
                    let dx = c as f32 - 3.5;
                    let dy = r as f32 - 3.5;
                    let d = (dx * dx + dy * dy).sqrt();
                    g[r * 8 + c] = if (d - 2.5).abs() < 1.0 { 220 } else { 30 };
                }
            }
        }
        ImgKind::Square => {
            for r in 0..8 {
                for c in 0..8 {
                    let on_ring = r == 1 || r == 6 || c == 1 || c == 6;
                    let inside = r >= 1 && r <= 6 && c >= 1 && c <= 6;
                    g[r * 8 + c] = if on_ring && inside { 220 } else { 30 };
                }
            }
        }
        ImgKind::Diagonal => {
            for r in 0..8 {
                for c in 0..8 {
                    g[r * 8 + c] = if (r + c) % 3 == 0 { 220 } else { 30 };
                }
            }
        }
    }
    g
}

fn make_audio(kind: AudKind, n: usize) -> Vec<f32> {
    let mut out = vec![0.0f32; n];
    match kind {
        AudKind::SineTone => {
            for k in 0..n {
                let t = k as f32 / n as f32;
                out[k] = (2.0 * core::f32::consts::PI * 4.0 * t).sin();
            }
        }
        AudKind::SquareWave => {
            for k in 0..n {
                let t = k as f32 / n as f32;
                let phase = (2.0 * core::f32::consts::PI * 4.0 * t).sin();
                out[k] = if phase >= 0.0 { 1.0 } else { -1.0 };
            }
        }
        AudKind::FreqSweep => {
            for k in 0..n {
                let t = k as f32 / n as f32;
                let f = 2.0 + 12.0 * t;
                out[k] = (2.0 * core::f32::consts::PI * f * t).sin();
            }
        }
    }
    out
}

fn make_video(kind: VidKind, frames: usize) -> Vec<u8> {
    let mut out = Vec::with_capacity(64 * frames);
    for t in 0..frames {
        let f = t as f32 / frames as f32;
        let frame = match kind {
            VidKind::ExpandingCircle => {
                let mut g = [0u8; 64];
                let radius = 1.5 + f * 2.5;
                for r in 0..8 {
                    for c in 0..8 {
                        let dx = c as f32 - 3.5;
                        let dy = r as f32 - 3.5;
                        let d = (dx * dx + dy * dy).sqrt();
                        g[r * 8 + c] = if (d - radius).abs() < 0.8 { 220 } else { 30 };
                    }
                }
                g
            }
            VidKind::PulsingSquare => {
                let mut g = [0u8; 64];
                let pulse = (0.5 + 0.5 * (2.0 * core::f32::consts::PI * f).sin()) * 220.0;
                for r in 0..8 {
                    for c in 0..8 {
                        let on = (r == 1 || r == 6 || c == 1 || c == 6)
                            && r >= 1
                            && r <= 6
                            && c >= 1
                            && c <= 6;
                        g[r * 8 + c] = if on { pulse as u8 } else { 30 };
                    }
                }
                g
            }
            VidKind::ScrollingDiagonal => {
                let mut g = [0u8; 64];
                let shift = (f * 6.0) as usize;
                for r in 0..8 {
                    for c in 0..8 {
                        g[r * 8 + c] = if ((r + c + shift) % 3) == 0 { 220 } else { 30 };
                    }
                }
                g
            }
        };
        out.extend_from_slice(&frame);
    }
    out
}

fn draw_grid8(ctx: &CanvasRenderingContext2d, grid: &[u8], x0: f64, y0: f64, cell: f64) {
    for r in 0..8 {
        for c in 0..8 {
            let v = grid[r * 8 + c] as f64 / 255.0;
            let shade = (40.0 + 180.0 * v) as u32;
            ctx.set_fill_style_str(&format!("rgb({shade},{shade},{shade})"));
            ctx.fill_rect(x0 + c as f64 * cell, y0 + r as f64 * cell, cell, cell);
        }
    }
}

fn draw_waveform(
    ctx: &CanvasRenderingContext2d,
    samples: &[f32],
    x0: f64,
    y0: f64,
    w: f64,
    h: f64,
) {
    ctx.set_stroke_style_str("rgba(120, 220, 255, 0.95)");
    ctx.set_line_width(1.2);
    ctx.begin_path();
    let n = samples.len();
    for (i, &s) in samples.iter().enumerate() {
        let x = x0 + (i as f64 / n.max(1) as f64) * w;
        let y = y0 + h * 0.5 - (s as f64 * 0.5 * h);
        if i == 0 {
            ctx.move_to(x, y);
        } else {
            ctx.line_to(x, y);
        }
    }
    ctx.stroke();
}

fn draw_hv_sig(ctx: &CanvasRenderingContext2d, hv: &Hv, x0: f64, y0: f64, w: f64, h: f64) {
    let take = 64usize.min(hv.0.len());
    let bw = w / take as f64;
    for i in 0..take {
        let v = hv.0[i];
        let color = if v >= 0 {
            "rgba(120, 220, 255, 0.9)"
        } else {
            "rgba(255, 140, 160, 0.9)"
        };
        ctx.set_fill_style_str(color);
        let mag = h * 0.5;
        if v >= 0 {
            ctx.fill_rect(x0 + i as f64 * bw, y0 + h * 0.5 - mag, bw - 0.5, mag);
        } else {
            ctx.fill_rect(x0 + i as f64 * bw, y0 + h * 0.5, bw - 0.5, mag);
        }
    }
}

fn cosine_color(c: f32) -> String {
    let v = c.clamp(-1.0, 1.0);
    if v >= 0.0 {
        let t = v.powf(0.6);
        let r = (40.0 + 200.0 * t) as u32;
        let g = (60.0 + 160.0 * t) as u32;
        let b = (80.0 + 80.0 * t) as u32;
        format!("rgb({r},{g},{b})")
    } else {
        let t = (-v).powf(0.6);
        let r = (80.0 - 40.0 * t) as u32;
        let g = (80.0 - 40.0 * t) as u32;
        let b = (60.0 + 100.0 * t) as u32;
        format!("rgb({r},{g},{b})")
    }
}

#[wasm_bindgen]
pub fn mount_omnimodal(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let frame = Rc::new(RefCell::new(0u32));
    let fr = frame.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let mut fc = fr.borrow_mut();
        let scene_idx = ((*fc / 180) as usize) % SCENES.len();
        let scene = SCENES[scene_idx];

        // ── Compute pass: encode all four modalities ──
        let t0 = now_ns();
        let img = make_image(scene.image);
        let img_r = encode_image(&img);
        let aud = make_audio(scene.audio, 128);
        let aud_r = encode_audio(&aud);
        let vid = make_video(scene.video, 4);
        let vid_r = encode_video(&vid, 4);
        let txt_r = encode_text(scene.text);
        let wall_ns_total = now_ns() - t0;

        let bit_ops_total = img_r.bit_ops + aud_r.bit_ops + vid_r.bit_ops + txt_r.bit_ops;

        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;

        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        // Scene banner.
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            &format!(
                "scene: {} ({}/{})",
                scene.label,
                scene_idx + 1,
                SCENES.len()
            ),
            24.0,
            26.0,
        )
        .ok();

        // Four panels across the top half.
        let panel_w = (cw - 80.0) / 4.0;
        let panel_h = ch * 0.5 - 50.0;
        let panel_y = 44.0;
        let names = ["text", "image", "audio", "video"];
        let hvs = [&txt_r.hv, &img_r.hv, &aud_r.hv, &vid_r.hv];

        for i in 0..4 {
            let x = 24.0 + i as f64 * (panel_w + 8.0);
            ctx.set_stroke_style_str("rgba(40, 50, 70, 1)");
            ctx.set_line_width(1.0);
            ctx.stroke_rect(x, panel_y, panel_w, panel_h);

            // Header.
            ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
            ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
            ctx.fill_text(names[i], x + 10.0, panel_y + 18.0).ok();

            // Preview area (top half).
            let preview_y = panel_y + 26.0;
            let preview_h = panel_h * 0.45;
            ctx.set_fill_style_str("rgba(14, 18, 28, 1)");
            ctx.fill_rect(x + 10.0, preview_y, panel_w - 20.0, preview_h);
            match i {
                0 => {
                    ctx.set_fill_style_str("rgba(200, 210, 230, 1)");
                    ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
                    let mut yy = preview_y + 16.0;
                    for line in scene.text.split_whitespace() {
                        ctx.fill_text(line, x + 14.0, yy).ok();
                        yy += 12.0;
                    }
                }
                1 => {
                    let cell = ((panel_w - 30.0) / 8.0).min(preview_h / 8.0);
                    let off_x = x + (panel_w - cell * 8.0) * 0.5;
                    let off_y = preview_y + (preview_h - cell * 8.0) * 0.5;
                    draw_grid8(&ctx, &img, off_x, off_y, cell);
                }
                2 => {
                    draw_waveform(
                        &ctx,
                        &aud,
                        x + 14.0,
                        preview_y + 4.0,
                        panel_w - 28.0,
                        preview_h - 8.0,
                    );
                }
                3 => {
                    // Show 4 mini frames side-by-side.
                    let mini_cell = ((panel_w - 30.0) / 32.0).min(preview_h / 8.0);
                    let off_y = preview_y + (preview_h - mini_cell * 8.0) * 0.5;
                    for t in 0..4 {
                        let off_x = x + 14.0 + (t as f64) * (mini_cell * 8.0 + 4.0);
                        let frame_slice = &vid[t * 64..(t + 1) * 64];
                        draw_grid8(&ctx, frame_slice, off_x, off_y, mini_cell);
                    }
                }
                _ => {}
            }

            // Hv signature (bottom half).
            let sig_y = preview_y + preview_h + 8.0;
            let sig_h = panel_h - (preview_h + 32.0);
            ctx.set_fill_style_str("rgba(160, 170, 190, 0.9)");
            ctx.set_font("9px ui-monospace, SFMono-Regular, Menlo, monospace");
            ctx.fill_text("shape-key (first 64 dims)", x + 10.0, sig_y - 2.0)
                .ok();
            draw_hv_sig(&ctx, hvs[i], x + 10.0, sig_y, panel_w - 20.0, sig_h);
        }

        // ── 4×4 cosine matrix ──
        let mat_x = 24.0;
        let mat_y = ch * 0.5 + 16.0;
        let mat_avail_h = ch - mat_y - 56.0;
        let cell_w = ((cw - 48.0 - 80.0) / 4.0).min(110.0);
        let cell_h = (mat_avail_h / 5.0).min(36.0);
        ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            "cross-modal cosine — same HDC shape-key space",
            mat_x,
            mat_y - 4.0,
        )
        .ok();

        // Column headers.
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
        for c in 0..4 {
            ctx.fill_text(
                names[c],
                mat_x + 80.0 + c as f64 * cell_w + cell_w * 0.4,
                mat_y + 14.0,
            )
            .ok();
        }
        // Row labels + cells.
        for r in 0..4 {
            let row_y = mat_y + 22.0 + r as f64 * cell_h;
            ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
            ctx.fill_text(names[r], mat_x + 20.0, row_y + cell_h * 0.6)
                .ok();
            for c in 0..4 {
                let x = mat_x + 80.0 + c as f64 * cell_w;
                let value = hvs[r].cosine(hvs[c]);
                ctx.set_fill_style_str(&cosine_color(value));
                ctx.fill_rect(x, row_y, cell_w - 4.0, cell_h - 4.0);
                ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
                ctx.fill_text(&format!("{:+.3}", value), x + 8.0, row_y + cell_h * 0.6)
                    .ok();
            }
        }

        // Footer summary.
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
        let footer_y = ch - 24.0;
        ctx.fill_text(
            &format!(
                "bit-ops across 4 encoders: {}   ·   wall_ns: {:.0}",
                bit_ops_total, wall_ns_total
            ),
            mat_x,
            footer_y,
        )
        .ok();

        // Receipt: sum across the four encoders, V-class = L0-identifiable.
        emit_receipt(
            &sink,
            "omnimodal_encoders[text|image|audio|video]",
            "L0Identifiable",
            1,
            wall_ns_total,
            bit_ops_total,
        );

        *fc = fc.wrapping_add(1);
        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── Determinism exhibit ─────────────────────────────────────────────
//
// Runs a fixed-input FFT 256-pt 1000 times per frame, hashes each
// output, counts uniques. With the substrate's deterministic kernel,
// all 1000 outputs hash identically — the live readout reads
// "1 / 1000 unique hashes". A `get_perturb` callback returns a bool
// flag; when true, a per-iteration scrambling of the input phase is
// injected which mimics the failure mode Horace He's
// `batch-invariant-ops` post calls out — same prompt, different
// numerical path → divergent hash counts.
//
// The receipt this exhibit emits carries the FFT's output_hash on its
// primitive, so the receipt strip's ≡/≠ indicator updates from the
// substrate-reported field instead of being re-hashed on the JS side.
// That is the load-bearing demonstration of the 05 receipt shape on
// `/receipts`.

#[wasm_bindgen]
pub fn mount_determinism(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let n: usize = 256;
    let runs_per_frame: usize = 1000;

    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let mut frame_count: u32 = 0;

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        // Read the page-side perturbation toggle each frame. Checkbox
        // ID is by convention `determinism-perturb`; missing element
        // → perturb stays false (substrate's deterministic default).
        let perturb = web_sys::window()
            .and_then(|w| w.document())
            .and_then(|d| d.get_element_by_id("determinism-perturb"))
            .and_then(|el| el.dyn_into::<web_sys::HtmlInputElement>().ok())
            .map(|cb| cb.checked())
            .unwrap_or(false);

        // Fixed input every frame so any drift is from the kernel, not
        // the signal. Two-tone, length 256, deterministic.
        let mut hashes: Vec<u64> = Vec::with_capacity(runs_per_frame);
        let t0 = now_ns();
        let mut total_bit_ops: u64 = 0;
        let mut buf = vec![0.0f32; 2 * n];
        let mut spec = vec![0.0f32; n / 2];

        for run in 0..runs_per_frame {
            // Reset to canonical input each iteration.
            for k in 0..n {
                let t = k as f32 / n as f32;
                let s = (2.0 * core::f32::consts::PI * 4.0 * t).sin()
                    + 0.5 * (2.0 * core::f32::consts::PI * 12.0 * t).sin();
                buf[2 * k] = s;
                buf[2 * k + 1] = 0.0;
            }

            // Perturbation: scramble the input by an iteration-dependent
            // offset that breaks the input's bit-identity across runs.
            // This is the "non-batch-invariant" failure mode in
            // demonstration form — same nominal task, slightly different
            // numerical path per iteration → divergent output hash.
            if perturb {
                let step_seed = (run as u32)
                    .wrapping_add(frame_count.wrapping_mul(17))
                    .max(1);
                let kick = (step_seed as f32) * 1e-6;
                for k in 0..n {
                    buf[2 * k] += kick;
                }
            }

            let report = fft_in_place(&mut buf).expect("power-of-two");
            fft_power_spectrum(&buf, &mut spec);
            total_bit_ops = total_bit_ops.saturating_add(report.bit_ops);
            hashes.push(fnv1a_64_f32_slice(&spec));
        }
        let wall_ns = now_ns() - t0;

        // Count unique hashes the cheap way — sort + dedup. 1000 u64s
        // is microseconds.
        let mut sorted = hashes.clone();
        sorted.sort_unstable();
        sorted.dedup();
        let unique = sorted.len();
        let canonical = hashes[0];

        // ── Draw the 50 × 20 grid of run cells, coloured by hash
        //    equivalence class. All matching → solid emerald; divergent
        //    → coloured by the first-seen index of each unique hash. ──
        let w = canvas.width() as f64;
        let h = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, w, h);

        // Cell layout: 50 cols × 20 rows = 1000 cells.
        let cols = 50.0_f64;
        let rows = 20.0_f64;
        let pad = 1.0_f64;
        let cell_w = (w - (cols + 1.0) * pad) / cols;
        let cell_h = (h - (rows + 1.0) * pad) / rows;

        // Build a hash → palette-index map in observation order so the
        // first hash always reads green (the substrate's commitment).
        let mut palette_for: std::collections::HashMap<u64, usize> =
            std::collections::HashMap::new();
        let palette: &[&str] = &[
            "#22c55e", // emerald — the canonical hash
            "#fb7185", // rose — first divergence
            "#fbbf24", // amber — second
            "#a78bfa", // violet — third
            "#38bdf8", // sky — fourth
            "#f472b6", // pink — fifth
            "#94a3b8", // slate — overflow
        ];
        for &h_ in &hashes {
            if !palette_for.contains_key(&h_) {
                let next = palette_for.len().min(palette.len() - 1);
                palette_for.insert(h_, next);
            }
        }

        for i in 0..runs_per_frame {
            let r = (i / 50) as f64;
            let c = (i % 50) as f64;
            let x = pad + c * (cell_w + pad);
            let y = pad + r * (cell_h + pad);
            let idx = *palette_for.get(&hashes[i]).unwrap_or(&0);
            ctx.set_fill_style_str(palette[idx]);
            ctx.fill_rect(x, y, cell_w, cell_h);
        }

        // ── Heading overlay: hash + unique count + canonical readout ──
        ctx.set_fill_style_str("rgba(10, 14, 24, 0.85)");
        let banner_h = 28.0;
        ctx.fill_rect(0.0, 0.0, w, banner_h);
        ctx.set_fill_style_str("rgba(220, 240, 255, 0.95)");
        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        let label = if unique == 1 {
            format!(
                "≡  byte-reproducible · {} / {} unique hash · 0x{:016x}",
                unique, runs_per_frame, canonical
            )
        } else {
            format!(
                "≠  diverged · {} / {} unique hashes (toggle off to restore)",
                unique, runs_per_frame
            )
        };
        let _ = ctx.fill_text(&label, 8.0, 18.0);

        // ── Emit a receipt carrying the canonical output hash. The
        //    receipt strip's ≡/≠ indicator reads this directly. ──
        let v_class = if perturb { "L1" } else { "L0Closed" };
        emit_receipt_with_hash(
            &sink,
            "fft_256_x1000",
            v_class,
            runs_per_frame as u64,
            wall_ns,
            total_bit_ops / runs_per_frame as u64,
            canonical,
        );

        frame_count = frame_count.wrapping_add(1);
        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── mgai-graph event-log persistence bindings ─────────────────────
//
// Used by /exhibits/persistent-graph. The page holds the mutation log
// in localStorage; on every change it sends the log here and renders
// the (count, count, hash) summary. The "byte-reproducible across
// reloads" claim is: hash(log_replayed_to_graph) is stable, even
// across full page reloads.

#[wasm_bindgen]
pub fn pg_log_summary(log_json: &str) -> Result<JsValue, JsValue> {
    let mutations: Vec<mgai_graph::Mutation> = serde_json::from_str(log_json)
        .map_err(|e| JsValue::from_str(&format!("log parse: {e}")))?;
    let g = mgai_graph::Graph::from_log(&mutations)
        .map_err(|e| JsValue::from_str(&format!("log replay: {e}")))?;
    let canonical = g
        .to_json()
        .map_err(|e| JsValue::from_str(&format!("graph serialise: {e}")))?;
    // FNV-1a 64-bit over the canonical JSON bytes — same family as
    // every other output_hash on the substrate.
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in canonical.as_bytes() {
        h ^= *b as u64;
        h = h.wrapping_mul(0x100_0000_01b3);
    }
    let result = serde_json::json!({
        "nodes": g.node_count(),
        "edges": g.edge_count(),
        "log_len": mutations.len(),
        "state_hash": format!("0x{:016x}", h),
    });
    Ok(mgai_meter_web::to_js_json(&result))
}

/// Render the live edge list from a log (as `{from_label, to_label,
/// edge_kind}` triples), used by /exhibits/persistent-graph to draw the
/// current graph state without re-implementing the replay on the JS side.
#[wasm_bindgen]
pub fn pg_edge_list(log_json: &str) -> Result<JsValue, JsValue> {
    let mutations: Vec<mgai_graph::Mutation> = serde_json::from_str(log_json)
        .map_err(|e| JsValue::from_str(&format!("log parse: {e}")))?;
    let g = mgai_graph::Graph::from_log(&mutations)
        .map_err(|e| JsValue::from_str(&format!("log replay: {e}")))?;
    let edges: Vec<serde_json::Value> = g
        .edges()
        .filter_map(|e| {
            let from_label = g.node(e.from)?.label.clone();
            let to_label = g.node(e.to)?.label.clone();
            Some(serde_json::json!({
                "from": from_label,
                "to": to_label,
                "kind": e.kind,
            }))
        })
        .collect();
    Ok(mgai_meter_web::to_js_json(&edges))
}

// ── Combined cascade-memory exhibit ───────────────────────────────
//
// Runs BOTH memory paths on the same query so a visitor sees the
// substrate's routing decision live:
//
//   • Structural path  — cascade::walk fires probe_l0_retrieved which
//     tries the mgai-graph typed-edge pattern. Resolves at L0-retrieved
//     for queries like "uses softmax" or "HDC uses".
//
//   • Similarity path  — HDC cosine over the 30-item corpus, like the
//     /exhibits/code-memory exhibit.
//
// The canvas renders both side-by-side. The banner at the top reports
// which path the cascade considers the canonical resolution; the
// receipt carries the resolved tier as its V-class and the FNV-1a of
// the combined output as its output_hash.

#[wasm_bindgen]
pub fn mount_cascade_memory(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    use crate::cascade::{CascadeTier, SubExpert, TimeFn, walk};
    use crate::modal::encode_text;

    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;

    // Pre-encode corpus once (same 30 items as code-memory).
    let encoded: Vec<(String, String, crate::hdc::Hv)> = CODE_MEMORY_CORPUS
        .iter()
        .map(|(id, text)| {
            let report = encode_text(text);
            (id.to_string(), text.to_string(), report.hv)
        })
        .collect();
    let encoded = Rc::new(encoded);
    let n_items = encoded.len();

    let time = TimeFn { now_ns };
    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let last_query: Rc<RefCell<String>> = Rc::new(RefCell::new(String::new()));

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let query = web_sys::window()
            .and_then(|w| w.document())
            .and_then(|d| d.get_element_by_id("cascade-memory-query"))
            .and_then(|el| el.dyn_into::<web_sys::HtmlInputElement>().ok())
            .map(|cb| cb.value())
            .unwrap_or_default();
        let effective_query = if query.trim().is_empty() {
            "uses softmax".to_string()
        } else {
            query.clone()
        };

        // Only re-render the static parts when the query changes.
        let mut last = last_query.borrow_mut();
        let _changed = *last != effective_query;
        *last = effective_query.clone();
        drop(last);

        // ── Structural path: cascade walk (which internally tries the
        //    mgai-graph sub-strategy at L0-retrieved). ──
        let t0 = now_ns();
        let trace = walk(&effective_query, &time);
        let cascade_wall = now_ns() - t0;

        // ── Similarity path: HDC cosine over the 30-item corpus. ──
        let t1 = now_ns();
        let q_report = encode_text(&effective_query);
        let mut scores: Vec<(usize, f32)> = encoded
            .iter()
            .enumerate()
            .map(|(i, (_, _, hv))| (i, q_report.hv.cosine(hv)))
            .collect();
        scores.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        let hdc_wall = now_ns() - t1;
        let top3: Vec<(usize, f32)> = scores.iter().take(3).copied().collect();

        // Combined output hash: cascade resolved-tier + HDC top-3 indices.
        let mut bytes: Vec<u8> = Vec::with_capacity(16);
        bytes.push(match trace.resolved_at {
            Some(CascadeTier::L0Closed) => 0,
            Some(CascadeTier::L0Retrieved) => 1,
            Some(CascadeTier::L0Identifiable) => 2,
            Some(CascadeTier::L1) => 3,
            Some(CascadeTier::L2) => 4,
            None => 255,
        });
        for (i, _) in &top3 {
            bytes.extend_from_slice(&(*i as u32).to_le_bytes());
        }
        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
        for &b in &bytes {
            h ^= b as u64;
            h = h.wrapping_mul(0x100_0000_01b3);
        }

        // ── Render ──
        let w = canvas.width() as f64;
        let ch = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, w, ch);

        // Header
        ctx.set_fill_style_str("rgba(220, 240, 255, 0.95)");
        ctx.set_font("13px ui-monospace, SFMono-Regular, Menlo, monospace");
        let _ = ctx.fill_text(&format!("query · \"{}\"", effective_query), 16.0, 24.0);
        let resolved_str = trace
            .resolved_at
            .map(|t| t.label())
            .unwrap_or("(no L0/L1 match)");
        ctx.set_fill_style_str(if trace.resolved_at.is_some() {
            "rgba(34, 197, 94, 0.95)"
        } else {
            "rgba(160, 170, 200, 0.7)"
        });
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        let _ = ctx.fill_text(
            &format!(
                "cascade resolved at {}   ·   hash 0x{:016x}",
                resolved_str, h
            ),
            16.0,
            42.0,
        );

        // Split canvas: left half = structural / cascade trace; right = HDC top-3.
        let mid_x = w * 0.5;
        ctx.set_stroke_style_str("rgba(50, 60, 80, 0.7)");
        ctx.set_line_width(1.0);
        ctx.begin_path();
        ctx.move_to(mid_x, 60.0);
        ctx.line_to(mid_x, ch - 30.0);
        ctx.stroke();

        // ── Left panel: cascade trace (structural path) ──
        ctx.set_fill_style_str("rgba(140, 200, 255, 0.85)");
        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        let _ = ctx.fill_text("STRUCTURAL · mgai-graph + cascade", 16.0, 72.0);

        let mut y = 92.0;
        for hop in trace.hops.iter().take(8) {
            // Tier badge
            let badge_color = match hop.tier {
                CascadeTier::L0Closed | CascadeTier::L0Retrieved | CascadeTier::L0Identifiable => {
                    if hop.matched {
                        "rgba(34, 197, 94, 0.95)"
                    } else {
                        "rgba(100, 110, 130, 0.55)"
                    }
                }
                CascadeTier::L1 => "rgba(125, 211, 252, 0.95)",
                CascadeTier::L2 => "rgba(251, 191, 36, 0.95)",
            };
            ctx.set_fill_style_str(badge_color);
            ctx.fill_rect(16.0, y - 12.0, 76.0, 20.0);
            ctx.set_fill_style_str("rgba(10, 14, 24, 0.95)");
            ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
            let _ = ctx.fill_text(hop.tier.label(), 22.0, y + 2.0);

            // Sub-expert + action
            ctx.set_fill_style_str("rgba(220, 240, 255, 0.9)");
            ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
            let symbol = match hop.expert {
                SubExpert::Reasoning => "?",
                SubExpert::Generation => "→",
            };
            let mark = if hop.matched { "✓" } else { "·" };
            let line = format!("{} {} {}", symbol, mark, hop.action);
            let line = if line.len() > 48 {
                format!("{}…", &line[..47])
            } else {
                line
            };
            let _ = ctx.fill_text(&line, 100.0, y + 2.0);

            y += 22.0;
            if y > ch - 60.0 {
                break;
            }
        }

        // Final answer (if any)
        if let Some(ans) = trace.final_answer.as_ref() {
            ctx.set_fill_style_str("rgba(34, 197, 94, 0.95)");
            ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
            let mut shown = ans.clone();
            if shown.len() > 52 {
                shown.truncate(52);
                shown.push('…');
            }
            let _ = ctx.fill_text(&format!("answer · {}", shown), 16.0, ch - 40.0);
        }

        // ── Right panel: HDC top-3 (similarity path) ──
        ctx.set_fill_style_str("rgba(140, 200, 255, 0.85)");
        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        let _ = ctx.fill_text("SIMILARITY · HDC cosine over 30 items", mid_x + 16.0, 72.0);

        let bar_x = mid_x + 16.0;
        let bar_w_max = w - bar_x - 70.0;
        let mut y2 = 96.0;
        for (rank, (idx, score)) in top3.iter().enumerate() {
            let (id, _, _) = &encoded[*idx];
            ctx.set_fill_style_str(if rank == 0 {
                "rgba(34, 197, 94, 0.95)"
            } else {
                "rgba(125, 211, 252, 0.85)"
            });
            ctx.fill_rect(
                bar_x,
                y2 - 12.0,
                bar_w_max * (score.clamp(0.0, 1.0) as f64),
                22.0,
            );
            ctx.set_fill_style_str("rgba(220, 240, 255, 0.95)");
            ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
            let _ = ctx.fill_text(&format!("{}  cos {:+.3}", id, score), bar_x + 6.0, y2 + 2.0);
            y2 += 32.0;
        }

        // Footer: combined cost summary
        ctx.set_fill_style_str("rgba(160, 170, 200, 0.85)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        let _ = ctx.fill_text(
            &format!(
                "cascade {:.0}ns   ·   HDC {:.0}ns   ·   corpus {}",
                cascade_wall, hdc_wall, n_items
            ),
            mid_x + 16.0,
            ch - 16.0,
        );

        // Receipt: V-class = resolved cascade tier label; bit_ops = sum
        // of cascade and HDC paths; output_hash = combined fingerprint.
        let v_class = match trace.resolved_at {
            Some(CascadeTier::L0Closed) => "L0Closed",
            Some(CascadeTier::L0Retrieved) => "L0Retrieved",
            Some(CascadeTier::L0Identifiable) => "L0Identifiable",
            Some(CascadeTier::L1) => "L1",
            Some(CascadeTier::L2) => "L2",
            None => "L1",
        };
        let total_bit_ops = trace.total_bit_ops
            + q_report.bit_ops
            + (n_items as u64) * (crate::hdc::HDC_DIM as u64);
        emit_receipt_with_hash(
            &sink,
            "cascade_memory_dual_path",
            v_class,
            1,
            cascade_wall + hdc_wall,
            total_bit_ops,
            h,
        );

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── Code-memory exhibit ──────────────────────────────────────────────
//
// Mathground's response to "give my AI a queryable memory layer over a
// corpus, without an LLM per query". Graphify-shaped surface, HDC-shaped
// substrate: each corpus item is encoded with `modal::encode_text` into
// a 10 000-dim hypervector; query lookup is cosine over the 30-item
// list. The cascade tier reported per query is `L0-retrieved` when the
// top cosine clears a threshold, otherwise `L1` (deferred to a layer
// the exhibit doesn't ship). No model at any tier.
//
// The corpus is small + fixed so the exhibit is self-contained. The
// receipt-grammar shipped this session lets the exhibit publish a
// per-query `output_hash` (fingerprint of the top-K item indices) so a
// consumer can confirm two identical queries returned identical
// rankings.

const CODE_MEMORY_CORPUS: &[(&str, &str)] = &[
    (
        "fft",
        "Cooley-Tukey radix-2 FFT decomposition into log-N butterfly stages",
    ),
    (
        "matmul",
        "Matrix multiplication via inner-product reduction across an axis",
    ),
    (
        "attention",
        "Attention layer multiplies queries with keys, softmaxes, and weights values",
    ),
    (
        "rmsnorm",
        "Root-mean-square normalisation rescales activations element-wise",
    ),
    (
        "softmax",
        "Softmax exponentiates and normalises a vector to sum to one",
    ),
    (
        "cosine",
        "Cosine similarity is the dot product divided by the product of L2 norms",
    ),
    (
        "bind",
        "Bind two bipolar hypervectors with element-wise XOR for compositional memory",
    ),
    (
        "bundle",
        "Bundle multiple hypervectors via sign of their elementwise sum",
    ),
    (
        "permute",
        "Permute a hypervector by cyclic shift to encode positional order",
    ),
    (
        "unbind",
        "Unbind a bound hypervector by binding again with one of the operands",
    ),
    (
        "hypervector",
        "Bipolar plus-or-minus-one vector at ten-thousand dimensions, MAP-VSA style",
    ),
    (
        "receipt",
        "Picojoule receipt: wall time times TDP envelope, against the Landauer floor",
    ),
    (
        "landauer",
        "Landauer floor: kT ln 2 joules per irreversible bit erasure, the physics bound",
    ),
    (
        "vclass",
        "V-class label tags a primitive: L0-closed, L0-retrieved, L1, L2",
    ),
    (
        "cascade",
        "Cascade walker resolves a query left-to-right through tiered experts",
    ),
    (
        "escalate",
        "Escalation to L2 happens only when the deterministic spine cannot place a query",
    ),
    (
        "output_hash",
        "Output hash on a receipt confesses whether the kernel was byte-reproducible",
    ),
    (
        "determinism",
        "Batch-invariant kernels make outputs byte-identical across batch sizes",
    ),
    (
        "batch_invariant",
        "Batch-size variance, not concurrent atomic adds, drives LLM nondeterminism",
    ),
    (
        "byte_reproducible",
        "Two runs of the same primitive that hash identically are byte-reproducible",
    ),
    (
        "knowledge_graph",
        "Knowledge graph: typed edges between entity nodes with community labels",
    ),
    (
        "graph_traversal",
        "Graph traversal walks edges from a source node breadth or depth first",
    ),
    (
        "leiden",
        "Leiden clustering partitions a graph into communities by modularity refinement",
    ),
    (
        "tree_sitter",
        "Tree-sitter parses source code into a typed concrete syntax tree",
    ),
    (
        "embedding",
        "Embedding maps a token or chunk into a learned dense vector representation",
    ),
    (
        "retrieval",
        "Retrieval picks top-K corpus items by similarity to a query embedding",
    ),
    (
        "hdc",
        "Hyperdimensional computing composes meaning by binding and bundling high-dim vectors",
    ),
    (
        "omnimodal",
        "Four deterministic encoders project text, image, audio, video to one HDC space",
    ),
    (
        "cosine_matrix",
        "Cross-modal cosine matrix is the substrate property of omnimodal routing",
    ),
    (
        "anytime_valid",
        "Anytime-valid evidence: an e-process stays a martingale across stopping times",
    ),
];

#[wasm_bindgen]
pub fn mount_code_memory(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    use crate::modal::encode_text;

    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;

    // ── Pre-encode the corpus once ──
    let encoded: Vec<(String, String, crate::hdc::Hv, u64)> = CODE_MEMORY_CORPUS
        .iter()
        .map(|(id, text)| {
            let report = encode_text(text);
            (id.to_string(), text.to_string(), report.hv, report.bit_ops)
        })
        .collect();
    let n_items = encoded.len();

    let encoded = Rc::new(encoded);
    let sink = sink.clone();
    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let last_query: Rc<RefCell<String>> = Rc::new(RefCell::new(String::new()));
    let last_ranking: Rc<RefCell<Option<(Vec<usize>, Vec<f32>, f64, u64, u64)>>> =
        Rc::new(RefCell::new(None));

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let query = web_sys::window()
            .and_then(|w| w.document())
            .and_then(|d| d.get_element_by_id("code-memory-query"))
            .and_then(|el| el.dyn_into::<web_sys::HtmlInputElement>().ok())
            .map(|cb| cb.value())
            .unwrap_or_default();
        let effective_query = if query.trim().is_empty() {
            "compose hypervectors".to_string()
        } else {
            query.clone()
        };

        let mut last = last_query.borrow_mut();
        let needs_recompute = *last != effective_query;
        if needs_recompute {
            *last = effective_query.clone();
            drop(last);

            let t0 = now_ns();
            let q_report = encode_text(&effective_query);
            let mut scores: Vec<(usize, f32)> = encoded
                .iter()
                .enumerate()
                .map(|(i, (_, _, hv, _))| (i, q_report.hv.cosine(hv)))
                .collect();
            scores.sort_unstable_by(|a, b| {
                b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)
            });
            let wall_ns = now_ns() - t0;

            let top_k = 5usize;
            let top_idx: Vec<usize> = scores.iter().take(top_k).map(|(i, _)| *i).collect();
            let top_scores: Vec<f32> = scores.iter().take(top_k).map(|(_, s)| *s).collect();

            let mut bytes: Vec<u8> = Vec::with_capacity(top_k * 4);
            for &i in &top_idx {
                bytes.extend_from_slice(&(i as u32).to_le_bytes());
            }
            let mut h: u64 = 0xcbf2_9ce4_8422_2325;
            for &b in &bytes {
                h ^= b as u64;
                h = h.wrapping_mul(0x100_0000_01b3);
            }

            let total_bit_ops = q_report.bit_ops + (n_items as u64) * (crate::hdc::HDC_DIM as u64);

            *last_ranking.borrow_mut() = Some((top_idx, top_scores, wall_ns, total_bit_ops, h));
        } else {
            drop(last);
        }

        let w = canvas.width() as f64;
        let h_c = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, w, h_c);

        ctx.set_fill_style_str("rgba(220, 240, 255, 0.95)");
        ctx.set_font("13px ui-monospace, SFMono-Regular, Menlo, monospace");
        let _ = ctx.fill_text(&format!("query · \"{}\"", effective_query), 16.0, 24.0);
        ctx.set_fill_style_str("rgba(140, 200, 255, 0.7)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        let _ = ctx.fill_text(
            "substrate · 30 hypervectors · cosine query · top-5 retrieved",
            16.0,
            42.0,
        );

        let ranking = last_ranking.borrow();
        if let Some((top_idx, top_scores, wall_ns, total_bit_ops, h_hash)) = ranking.as_ref() {
            ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
            let row_h = 52.0;
            let pad_x = 16.0;
            let bar_x = 240.0;
            let bar_max = w - bar_x - 70.0;
            let y0 = 70.0;

            for (rank, (&idx, &score)) in top_idx.iter().zip(top_scores.iter()).enumerate() {
                let (id, text, _, _) = &encoded[idx];
                let row_y = y0 + rank as f64 * row_h;

                ctx.set_fill_style_str(if rank == 0 {
                    "rgba(34, 197, 94, 0.95)"
                } else {
                    "rgba(160, 170, 200, 0.45)"
                });
                ctx.fill_rect(pad_x, row_y + 4.0, 24.0, 24.0);
                ctx.set_fill_style_str("rgba(10, 14, 24, 1)");
                ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
                let _ = ctx.fill_text(&format!("{}", rank + 1), pad_x + 8.0, row_y + 20.0);

                ctx.set_fill_style_str("rgba(220, 240, 255, 0.95)");
                let _ = ctx.fill_text(id, pad_x + 36.0, row_y + 16.0);
                ctx.set_fill_style_str("rgba(160, 180, 210, 0.85)");
                ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
                let body = if text.len() > 36 {
                    &text[..36]
                } else {
                    text.as_str()
                };
                let _ = ctx.fill_text(body, pad_x + 36.0, row_y + 32.0);

                ctx.set_fill_style_str("rgba(40, 50, 70, 0.8)");
                ctx.fill_rect(bar_x, row_y + 14.0, bar_max, 12.0);
                let pct = score.clamp(0.0, 1.0) as f64;
                ctx.set_fill_style_str(if rank == 0 {
                    "rgba(34, 197, 94, 0.95)"
                } else {
                    "rgba(125, 211, 252, 0.85)"
                });
                ctx.fill_rect(bar_x, row_y + 14.0, bar_max * pct, 12.0);
                ctx.set_fill_style_str("rgba(220, 240, 255, 0.95)");
                ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
                let _ = ctx.fill_text(
                    &format!("cos {:+.3}", score),
                    bar_x + bar_max + 8.0,
                    row_y + 24.0,
                );
            }

            let top_score = top_scores[0];
            let resolved_tier = if top_score > 0.15 {
                "L0-retrieved"
            } else {
                "L1 (defer)"
            };
            ctx.set_fill_style_str("rgba(160, 180, 210, 0.85)");
            ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
            let _ = ctx.fill_text(
                &format!(
                    "cascade · resolved at {}   ·   hash 0x{:016x}",
                    resolved_tier, h_hash
                ),
                16.0,
                h_c - 16.0,
            );

            let v_class = if top_score > 0.15 {
                "L0Retrieved"
            } else {
                "L1"
            };
            emit_receipt_with_hash(
                &sink,
                "code_memory_cosine_topk",
                v_class,
                1,
                *wall_ns,
                *total_bit_ops,
                *h_hash,
            );
        }

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── Active-inference exhibit ─────────────────────────────────────────
//
// A closed-loop Friston/FEP demo: a 2-state, 2-obs, 2-action discrete
// agent drops into a deterministic environment, observes, updates its
// posterior via variational inference, scores both single-step
// policies by expected free energy, picks the lower-EFE action, and
// the environment transitions accordingly. Every frame is one full
// observe → plan → act → step round trip; the per-step VFE + EFE bar
// chart + posterior + action are drawn on the canvas, and a receipt
// is emitted to the page-side sink.

/// Mount the active-inference exhibit on `canvas_id`. Receipts emit
/// with `v_class = "L0Closed"` because the math is fully closed-form
/// inside the substrate — no model fires, no retrieval happens. Per
/// frame ≈ a few hundred FMAs over the 2-state space.
#[wasm_bindgen]
pub fn mount_active_inference(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let sink = sink.clone();

    // Build the canonical two-state model (same shape as the test
    // fixture in mgai_active_inference): obs 0 ↔ state 0, obs 1 ↔
    // state 1; action 0 = stay, action 1 = swap; the agent prefers
    // obs 1 (C[1] = 2.0).
    let model = AiModel::new(
        vec![vec![0.9, 0.1], vec![0.1, 0.9]],
        vec![
            vec![vec![1.0, 0.0], vec![0.0, 1.0]],
            vec![vec![0.0, 1.0], vec![1.0, 0.0]],
        ],
        vec![0.0, 2.0],
        vec![0.5, 0.5],
    )
    .map_err(|e| JsValue::from_str(&format!("model: {e}")))?;

    let agent = Rc::new(RefCell::new(AiAgent::new(model)));
    let env_state = Rc::new(RefCell::new(0usize));
    let frame_counter = Rc::new(RefCell::new(0u32));
    let cumulative_uj = Rc::new(RefCell::new(0u64));

    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let ag = agent.clone();
    let es = env_state.clone();
    let fc = frame_counter.clone();
    let cu = cumulative_uj.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        let mut a = ag.borrow_mut();
        let mut es_b = es.borrow_mut();
        let obs = *es_b;
        let step = match a.step(obs, 1) {
            Ok(s) => s,
            Err(_) => {
                schedule(f.borrow().as_ref().unwrap());
                return;
            }
        };
        let action = step.action;
        if action == 1 {
            *es_b = 1 - *es_b;
        }
        drop(es_b);

        // Title.
        ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
        ctx.set_font("16px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text("active inference · 2-state world", 28.0, 32.0)
            .ok();
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            "observe → posterior update (vfe) → score policies (efe) → act",
            28.0,
            52.0,
        )
        .ok();

        ctx.set_fill_style_str("rgba(120, 200, 255, 1)");
        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(&format!("obs = {obs}"), 28.0, 90.0).ok();
        ctx.set_fill_style_str(if action == 0 {
            "rgba(200, 200, 200, 1)"
        } else {
            "rgba(255, 200, 120, 1)"
        });
        let action_label = if action == 0 { "stay" } else { "swap" };
        ctx.fill_text(&format!("action = {action} ({action_label})"), 140.0, 90.0)
            .ok();
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.fill_text(
            &format!("vfe = {:.3} nats", step.observe.vfe_nats),
            300.0,
            90.0,
        )
        .ok();

        // Posterior q(s) bars.
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text("posterior q(s) — variational FE minimum", 28.0, 130.0)
            .ok();
        for (i, &p) in step.observe.posterior.iter().enumerate() {
            let y = 145.0 + (i as f64) * 28.0;
            ctx.set_fill_style_str("rgba(40, 50, 70, 1)");
            ctx.fill_rect(120.0, y, 260.0, 18.0);
            ctx.set_fill_style_str("rgba(120, 200, 255, 1)");
            ctx.fill_rect(120.0, y, 260.0 * (p as f64).max(0.0).min(1.0), 18.0);
            ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
            ctx.fill_text(&format!("s={i}"), 28.0, y + 13.0).ok();
            ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
            ctx.fill_text(&format!("{p:.3}"), 390.0, y + 13.0).ok();
        }

        // EFE per policy bars.
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.fill_text("EFE per policy — lower is better", 28.0, 230.0)
            .ok();
        let efe = &step.plan.efe_nats;
        let efe_min = efe.iter().cloned().fold(f32::INFINITY, f32::min);
        let efe_max = efe.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
        let span = (efe_max - efe_min).max(1e-6);
        for (i, (policy, &g_pi)) in step.plan.policies.iter().zip(efe.iter()).enumerate() {
            let y = 245.0 + (i as f64) * 28.0;
            let label = if policy[0] == 0 { "[stay]" } else { "[swap]" };
            let norm = (g_pi - efe_min) / span;
            let w = 260.0 * (1.0 - norm as f64).max(0.05);
            ctx.set_fill_style_str("rgba(40, 50, 70, 1)");
            ctx.fill_rect(120.0, y, 260.0, 18.0);
            let bar_color = if i == step.plan.best {
                "rgba(150, 255, 180, 1)"
            } else {
                "rgba(120, 140, 160, 1)"
            };
            ctx.set_fill_style_str(bar_color);
            ctx.fill_rect(120.0, y, w, 18.0);
            ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
            ctx.fill_text(label, 28.0, y + 13.0).ok();
            ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
            ctx.fill_text(&format!("{g_pi:.3}"), 390.0, y + 13.0).ok();
        }

        // Cumulative footer.
        let frame = {
            let mut fr = fc.borrow_mut();
            *fr += 1;
            *fr
        };
        let total_uj = {
            let mut t = cu.borrow_mut();
            *t += step.energy_uj;
            *t
        };
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            &format!(
                "step {frame} · bit-ops {} · {} µJ",
                step.bit_ops, step.energy_uj
            ),
            28.0,
            ch - 36.0,
        )
        .ok();
        ctx.fill_text(
            &format!("cumulative: {total_uj} µJ over {frame} steps"),
            28.0,
            ch - 18.0,
        )
        .ok();

        // L0-closed receipt: pure math, no model fires.
        let wall_ns_per_op = 0.5;
        emit_receipt(
            &sink,
            "active_inference_step",
            "L0Closed",
            1,
            (step.bit_ops as f64) * wall_ns_per_op,
            step.bit_ops,
        );

        // Cycle every ~120 steps so the page never lingers on a steady
        // state.
        if frame % 120 == 0 {
            *fc.borrow_mut() = 0;
            *cu.borrow_mut() = 0;
            a.reset();
            *es.borrow_mut() = 0;
        }
        drop(a);

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── Constrained-design exhibit (mgai-cea + mgai-voxel) ────────────
//
// A continuously-searching parametric design problem rendered on the
// canvas: a sphere whose centre/radius are the parameter vector, three
// constraints (max-mass, build-volume fit, min wall thickness), and a
// minimize-volume objective. Each animation frame runs a few search
// steps and redraws the cross-section, the constraint check marks,
// and the objective trajectory. Substrate's direct-to-artifact
// discipline is visible: there's no text generation in the loop —
// just numbers descending under deterministic search until the design
// is feasible.

// Thread-local handle on the latest constrained-design geometry, so
// JS can pull a printable STL after the search has settled. WASM is
// single-threaded so `thread_local!` is fine; the substrate
// discipline is "direct-to-artifact" → this is the artifact.
thread_local! {
    static LATEST_CONSTRAINED_GEOMETRY: RefCell<Option<VoxelGrid>> = const { RefCell::new(None) };
}

/// Polygonise the current constrained-design geometry (the most
/// recent frame's `VoxelGrid`) and return its binary STL bytes. JS
/// glues this into a Blob URL + click-download. Returns an empty
/// array if no frame has rendered yet.
#[wasm_bindgen]
pub fn export_constrained_design_stl() -> Vec<u8> {
    LATEST_CONSTRAINED_GEOMETRY.with(|cell| {
        let borrow = cell.borrow();
        match borrow.as_ref() {
            None => Vec::new(),
            Some(g) => {
                let (mesh, _) = mgai_voxel::mesh::polygonise(g, 0.0);
                let (welded, _) = mesh.weld(1e-4);
                welded.to_stl_binary()
            }
        }
    })
}

#[wasm_bindgen]
pub fn mount_constrained_design(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let sink = sink.clone();

    // Build the problem fresh inside an Rc/RefCell so the rAF closure
    // can mutate it on each frame.
    fn build_problem()
    -> ConstrainedProblem<ParametricSphere, Box<dyn Constraint<VoxelGrid>>, MinimizeVolume> {
        let bounds = VoxAabb::new(VoxVec3::new(-1.5, -1.5, -1.5), VoxVec3::new(1.5, 1.5, 1.5));
        let design = ParametricSphere::new(bounds, 0.12, VoxVec3::new(0.7, 0.7, 0.0), 0.95);
        let limits = VoxAabb::new(VoxVec3::new(-0.5, -0.5, -0.5), VoxVec3::new(0.5, 0.5, 0.5));
        let cs: Vec<Box<dyn Constraint<VoxelGrid>>> = vec![
            Box::new(MaxMass {
                limit: 2.0,
                density: 1.0,
                model_bias: 1.0,
            }),
            Box::new(mgai_cea::WithinAabb { limits }),
            Box::new(mgai_cea::MinWallThickness {
                min_thickness: 0.05,
            }),
        ];
        ConstrainedProblem::new(design, cs, MinimizeVolume).unwrap()
    }

    let problem = Rc::new(RefCell::new(build_problem()));
    let cumulative_uj = Rc::new(RefCell::new(0u64));
    let frame_counter = Rc::new(RefCell::new(0u32));

    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let pb = problem.clone();
    let cu = cumulative_uj.clone();
    let fc = frame_counter.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        // Run one search burst per frame (4 steps × 4 neighbours so
        // progress is visible without crushing the canvas thread).
        let params = SearchParams {
            neighbours_per_step: 4,
            step_size: 0.05,
            max_steps: 4,
            seed: 0xC0DE_F00D,
        };
        let report;
        {
            let mut p = pb.borrow_mut();
            let (_score, r) = match cea_search(&mut *p, params) {
                Ok(v) => v,
                Err(_) => {
                    schedule(f.borrow().as_ref().unwrap());
                    return;
                }
            };
            report = r;
        }
        let score = match pb.borrow().score() {
            Ok(s) => s,
            Err(_) => {
                schedule(f.borrow().as_ref().unwrap());
                return;
            }
        };

        // Title.
        ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
        ctx.set_font("16px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text("constrained design — parametric sphere", 28.0, 32.0)
            .ok();
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            "voxel kernel + rule encoder + deterministic local search",
            28.0,
            52.0,
        )
        .ok();

        // ── Cross-section: slice through z=0 of the voxel grid. ──
        let grid = &score.geometry;
        let slice_z = grid.size[2] / 2;
        let slice_w = grid.size[0];
        let slice_h = grid.size[1];
        let cell_px = 4.0_f64;
        let slice_x0 = 28.0;
        let slice_y0 = 90.0;
        for iy in 0..slice_h {
            for ix in 0..slice_w {
                let i = ((slice_z * slice_h + iy) * slice_w + ix) as usize;
                let v = grid.data[i];
                // Map signed distance to a colour band: inside =
                // accent, outside = dim.
                if v < 0.0 {
                    let t = (-v).min(0.4) / 0.4;
                    let r_byte = (40.0 + 80.0 * t as f64) as u8;
                    let g_byte = (160.0 + 60.0 * t as f64) as u8;
                    let b_byte = (255.0 - 30.0 * t as f64) as u8;
                    let style = format!("rgba({r_byte}, {g_byte}, {b_byte}, 1)");
                    ctx.set_fill_style_str(&style);
                } else {
                    let t = v.min(0.6) / 0.6;
                    let alpha = 0.18 - 0.12 * t as f64;
                    let style = format!("rgba(80, 100, 130, {alpha:.3})");
                    ctx.set_fill_style_str(&style);
                }
                let x = slice_x0 + (ix as f64) * cell_px;
                let y = slice_y0 + (iy as f64) * cell_px;
                ctx.fill_rect(x, y, cell_px, cell_px);
            }
        }

        // Cross-section legend.
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            "slice z = 0 · cyan = solid, faint = outside",
            slice_x0,
            slice_y0 + (slice_h as f64) * cell_px + 16.0,
        )
        .ok();

        // ── Constraints column. ──
        let cx0 = slice_x0 + (slice_w as f64) * cell_px + 36.0;
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text("constraints", cx0, 110.0).ok();
        let mut cy = 130.0;
        for cr in &score.constraints {
            ctx.set_fill_style_str(if cr.satisfied {
                "rgba(150, 255, 180, 1)"
            } else {
                "rgba(255, 150, 150, 1)"
            });
            ctx.set_font("13px ui-monospace, SFMono-Regular, Menlo, monospace");
            let mark = if cr.satisfied { "✓" } else { "✗" };
            ctx.fill_text(&format!("{mark} {}", cr.name), cx0, cy).ok();
            ctx.set_fill_style_str("rgba(140, 150, 170, 1)");
            ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
            ctx.fill_text(
                &format!("violation {:.3}", cr.violation),
                cx0 + 16.0,
                cy + 14.0,
            )
            .ok();
            cy += 36.0;
        }

        // ── Parameters + objective + footer. ──
        let pcx0 = cx0;
        let mut py = cy + 12.0;
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text("parameters", pcx0, py).ok();
        py += 16.0;
        let p_vals = pb.borrow().design.parameters();
        let names = ["cx", "cy", "cz", "r "];
        for (n, v) in names.iter().zip(p_vals.iter()) {
            ctx.set_fill_style_str("rgba(220, 220, 240, 1)");
            ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
            ctx.fill_text(&format!("{n} = {v:.3}"), pcx0, py).ok();
            py += 16.0;
        }

        py += 8.0;
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.fill_text("objective", pcx0, py).ok();
        py += 16.0;
        ctx.set_fill_style_str("rgba(220, 220, 240, 1)");
        ctx.fill_text(
            &format!("{} = {:.4}", score.objective.name, score.objective.value),
            pcx0,
            py,
        )
        .ok();
        py += 16.0;
        ctx.fill_text(&format!("total_score = {:.4}", score.total_score), pcx0, py)
            .ok();

        // Cumulative + feasibility footer.
        let frame = {
            let mut fr = fc.borrow_mut();
            *fr += 1;
            *fr
        };
        let total_uj = {
            let mut t = cu.borrow_mut();
            *t += report.energy_uj;
            *t
        };
        ctx.set_fill_style_str(if score.is_feasible() {
            "rgba(150, 255, 180, 1)"
        } else {
            "rgba(255, 200, 120, 1)"
        });
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        let status = if score.is_feasible() {
            "FEASIBLE — search converged"
        } else {
            "searching — penalty active"
        };
        ctx.fill_text(status, 28.0, ch - 36.0).ok();
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.fill_text(
            &format!(
                "burst {} · this-burst {} bit-ops · cumulative {} µJ",
                frame, report.bit_ops, total_uj
            ),
            28.0,
            ch - 18.0,
        )
        .ok();

        // Emit a receipt — L0-closed math, no model fires.
        let wall_ns_per_op = 0.5;
        emit_receipt(
            &sink,
            "constrained_design_burst",
            "L0Closed",
            1,
            (report.bit_ops as f64) * wall_ns_per_op,
            report.bit_ops,
        );

        // Publish the current geometry so JS can pull a printable STL
        // any time the user clicks "download .stl". Cloning a 30³ grid
        // is ~108K f32 = ~432 KB — cheap once per frame; no realloc
        // because the thread-local holds a single VoxelGrid slot.
        LATEST_CONSTRAINED_GEOMETRY.with(|cell| {
            *cell.borrow_mut() = Some(score.geometry.clone());
        });

        // Cycle every ~240 bursts so the page never sits on a single
        // converged result.
        if frame > 240 {
            *fc.borrow_mut() = 0;
            *cu.borrow_mut() = 0;
            *pb.borrow_mut() = build_problem();
        }

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── PCs/NPCs spine exhibit ────────────────────────────────────────
//
// Visualises the substrate's architectural primitive: a deterministic
// spine handles the common case in picojoules; the leaf only fires
// when the spine returns Unresolved; the verifier gates every leaf
// proposal. The exhibit cycles through six representative inputs that
// hit each branch (spine hit, leaf accepted, leaf rejected, no leaf)
// so visitors can see the full state machine + receipt accounting.

use mgai_spine::gate::PredictiveGate;
use mgai_spine::{
    AlwaysProposes, Compartment, EscalationPolicy, Leaf, Outcome, PcsNpcsRunner, SpineResult,
    SpineVerifier, VerificationResult,
};

// Toy compartment: cached squares. The exhibit's spine knows 0² … 4².
// Inputs outside that range force escalation.
struct SquaresSpine;
impl Compartment for SquaresSpine {
    type Input = u32;
    type Output = u32;
    fn name(&self) -> &str {
        "squares_cache"
    }
    fn evaluate(&self, input: &u32) -> (SpineResult<u32>, u64) {
        if *input <= 4 {
            (SpineResult::Resolved(input * input), 64)
        } else {
            (
                SpineResult::Unresolved {
                    reason: format!("not in cache: {input}"),
                },
                64,
            )
        }
    }
}

// Toy verifier: accept iff proposed == input * input.
struct SquaresVerifier;
impl SpineVerifier<SquaresSpine> for SquaresVerifier {
    fn name(&self) -> &str {
        "squares_check"
    }
    fn verify(&self, input: &u32, proposed: &u32) -> (VerificationResult, u64) {
        if *proposed == input * input {
            (VerificationResult::Accept, 32)
        } else {
            (
                VerificationResult::Reject {
                    reason: format!("proposed {proposed}, expected {}", input * input),
                },
                32,
            )
        }
    }
}

#[wasm_bindgen]
pub fn mount_spine(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let sink = sink.clone();

    // Six inputs that exercise every Outcome:
    //   0, 1 → spine hits (cached)
    //   5    → spine miss, leaf proposes 25 (correct) → LeafVerified
    //   6    → spine miss, leaf proposes 36 (correct) → LeafVerified
    //   7    → spine miss, "wrong-leaf" path → LeafRejected
    //   8    → spine miss, no-leaf path → NoLeaf
    const INPUTS: &[(u32, &str)] = &[
        (0, "spine"),
        (1, "spine"),
        (5, "leaf"),
        (6, "leaf"),
        (7, "wrong"),
        (8, "none"),
    ];

    let cursor = Rc::new(RefCell::new(0usize));
    let cumulative_uj = Rc::new(RefCell::new(0u64));
    let frame_counter = Rc::new(RefCell::new(0u32));
    // Pro2Guard-style predictive gate: learns a DTMC over the spine's
    // own outcomes; pre-flight blocks the leaf when (risk − ε) clears
    // the threshold with enough evidence behind it.
    let gate = Rc::new(RefCell::new(PredictiveGate::new(0.5).with_min_evidence(40)));
    let skipped_total = Rc::new(RefCell::new(0u64));

    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let cur = cursor.clone();
    let cu = cumulative_uj.clone();
    let fc = frame_counter.clone();
    let gt = gate.clone();
    let sk = skipped_total.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        // Advance one input per ~30 frames so each is readable.
        let frame = {
            let mut fr = fc.borrow_mut();
            *fr += 1;
            *fr
        };
        if frame % 30 == 0 {
            let mut c = cur.borrow_mut();
            *c = (*c + 1) % INPUTS.len();
        }
        let (input, mode) = INPUTS[*cur.borrow()];

        // Build the appropriate runner for this input's mode.
        let (outcome_label, outcome_color, spine_ops, leaf_ops, verifier_ops, energy_uj, output) =
            match mode {
                "spine" => {
                    let runner: PcsNpcsRunner<_, AlwaysProposes<SquaresSpine>, _> =
                        PcsNpcsRunner::new(
                            SquaresSpine,
                            Some(AlwaysProposes {
                                value: input * input,
                                bit_ops: 800,
                            }),
                            SquaresVerifier,
                        );
                    match runner.run(&input) {
                        Ok((o, r)) => (
                            outcome_text(r.outcome),
                            outcome_rgba(r.outcome),
                            r.spine_bit_ops,
                            r.leaf_bit_ops,
                            r.verifier_bit_ops,
                            r.energy_uj,
                            Some(o),
                        ),
                        Err(_) => unreachable!(),
                    }
                }
                "leaf" => {
                    let runner = PcsNpcsRunner::new(
                        SquaresSpine,
                        Some(AlwaysProposes::<SquaresSpine> {
                            value: input * input,
                            bit_ops: 800,
                        }),
                        SquaresVerifier,
                    );
                    match runner.run(&input) {
                        Ok((o, r)) => (
                            outcome_text(r.outcome),
                            outcome_rgba(r.outcome),
                            r.spine_bit_ops,
                            r.leaf_bit_ops,
                            r.verifier_bit_ops,
                            r.energy_uj,
                            Some(o),
                        ),
                        Err(_) => unreachable!(),
                    }
                }
                "wrong" => {
                    let runner = PcsNpcsRunner::new(
                        SquaresSpine,
                        Some(AlwaysProposes::<SquaresSpine> {
                            value: 999,
                            bit_ops: 800,
                        }),
                        SquaresVerifier,
                    );
                    match runner.run(&input) {
                        Err((_, r)) => (
                            outcome_text(r.outcome),
                            outcome_rgba(r.outcome),
                            r.spine_bit_ops,
                            r.leaf_bit_ops,
                            r.verifier_bit_ops,
                            r.energy_uj,
                            None,
                        ),
                        Ok(_) => unreachable!(),
                    }
                }
                _ => {
                    // "none": no leaf configured.
                    let runner: PcsNpcsRunner<_, AlwaysProposes<SquaresSpine>, _> =
                        PcsNpcsRunner::new(SquaresSpine, None, SquaresVerifier)
                            .with_escalation(EscalationPolicy::OnlyOnUnresolved);
                    match runner.run(&input) {
                        Err((_, r)) => (
                            outcome_text(r.outcome),
                            outcome_rgba(r.outcome),
                            r.spine_bit_ops,
                            r.leaf_bit_ops,
                            r.verifier_bit_ops,
                            r.energy_uj,
                            None,
                        ),
                        Ok(_) => unreachable!(),
                    }
                }
            };

        // Predictive gate: preflight BEFORE this call would escalate,
        // then record the actual outcome into the DTMC. When the gate
        // says "don't escalate" and this input would have called the
        // leaf, that leaf cost is counted as saved.
        let decision = gt.borrow().preflight();
        let would_escalate = leaf_ops > 0;
        if !decision.escalate && would_escalate {
            *sk.borrow_mut() += leaf_ops;
        }
        {
            let outcome_enum = match outcome_label {
                "Spine" => Outcome::Spine,
                "LeafVerified" => Outcome::LeafVerified,
                "LeafRejected" => Outcome::LeafRejected,
                _ => Outcome::NoLeaf,
            };
            gt.borrow_mut().record(outcome_enum);
        }

        // ── Draw ──
        ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
        ctx.set_font("16px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text("PCs/NPCs spine — Compartment + Leaf + Verifier", 28.0, 32.0)
            .ok();
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            "spine resolves cheap · leaf only fires on miss · verifier gates every proposal",
            28.0,
            52.0,
        )
        .ok();

        // Input + outcome
        ctx.set_fill_style_str("rgba(220, 220, 240, 1)");
        ctx.set_font("14px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(&format!("input = {input}"), 28.0, 100.0).ok();
        ctx.set_fill_style_str(outcome_color);
        ctx.fill_text(&format!("outcome: {outcome_label}"), 200.0, 100.0)
            .ok();
        if let Some(v) = output {
            ctx.set_fill_style_str("rgba(220, 220, 240, 1)");
            ctx.fill_text(&format!("output = {v}"), 460.0, 100.0).ok();
        }

        // Three-bar receipt: spine, leaf, verifier
        let bars = [
            ("spine", spine_ops, "rgba(120, 200, 255, 1)"),
            ("leaf", leaf_ops, "rgba(255, 200, 120, 1)"),
            ("verifier", verifier_ops, "rgba(180, 255, 180, 1)"),
        ];
        let max_ops = bars.iter().map(|b| b.1).max().unwrap_or(1).max(1) as f64;
        let chart_x = 80.0;
        let chart_w = 360.0;
        let mut chart_y = 150.0;
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text("bit-ops breakdown per call", 28.0, chart_y - 10.0)
            .ok();
        for (label, ops, color) in bars.iter() {
            ctx.set_fill_style_str("rgba(40, 50, 70, 1)");
            ctx.fill_rect(chart_x, chart_y, chart_w, 18.0);
            let frac = (*ops as f64) / max_ops;
            ctx.set_fill_style_str(color);
            ctx.fill_rect(chart_x, chart_y, chart_w * frac, 18.0);
            ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
            ctx.fill_text(label, 28.0, chart_y + 13.0).ok();
            ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
            ctx.fill_text(&format!("{ops}"), chart_x + chart_w + 12.0, chart_y + 13.0)
                .ok();
            chart_y += 28.0;
        }

        // Gate panel — the predictive pre-flight layer.
        let gate_y = ch - 92.0;
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            "predictive gate (DTMC over outcomes · Hoeffding-bounded)",
            28.0,
            gate_y,
        )
        .ok();
        let risk_txt = match decision.predicted_rejection_risk {
            Some(r) => format!(
                "P(reject) = {:.2} ± {:.2} · evidence {} · {}",
                r,
                decision.confidence_half_width,
                decision.evidence,
                if decision.escalate {
                    "escalation allowed"
                } else {
                    "LEAF CALL BLOCKED"
                }
            ),
            None => "cold start — always escalates".to_string(),
        };
        ctx.set_fill_style_str(if decision.escalate {
            "rgba(150, 255, 180, 1)"
        } else {
            "rgba(255, 200, 120, 1)"
        });
        ctx.fill_text(&risk_txt, 28.0, gate_y + 16.0).ok();
        let saved = *sk.borrow();
        if saved > 0 {
            ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
            ctx.fill_text(
                &format!("leaf bit-ops saved by pre-flight blocks so far: {saved}"),
                28.0,
                gate_y + 32.0,
            )
            .ok();
        }

        // Footer
        let total_uj = {
            let mut t = cu.borrow_mut();
            *t += energy_uj;
            *t
        };
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            &format!(
                "this call: {} bit-ops · {} µJ",
                spine_ops + leaf_ops + verifier_ops,
                energy_uj
            ),
            28.0,
            ch - 36.0,
        )
        .ok();
        ctx.fill_text(
            &format!("cumulative: {total_uj} µJ over {frame} frames"),
            28.0,
            ch - 18.0,
        )
        .ok();

        // Emit a receipt. v_class reflects the outcome.
        let v_class = if outcome_label == "Spine" {
            "L0Closed"
        } else {
            "L1"
        };
        let total_ops = spine_ops + leaf_ops + verifier_ops;
        emit_receipt(
            &sink,
            "spine_runner_call",
            v_class,
            1,
            (total_ops as f64) * 0.5,
            total_ops,
        );

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

fn outcome_text(o: Outcome) -> &'static str {
    match o {
        Outcome::Spine => "Spine",
        Outcome::LeafVerified => "LeafVerified",
        Outcome::LeafRejected => "LeafRejected",
        Outcome::NoLeaf => "NoLeaf",
    }
}

fn outcome_rgba(o: Outcome) -> &'static str {
    match o {
        Outcome::Spine => "rgba(120, 200, 255, 1)",
        Outcome::LeafVerified => "rgba(150, 255, 180, 1)",
        Outcome::LeafRejected => "rgba(255, 150, 150, 1)",
        Outcome::NoLeaf => "rgba(255, 200, 120, 1)",
    }
}

// ── Structure-learning exhibit (AXIOM ingestion live) ─────────────
//
// A StructureLearner drops into a regime-shifting observation stream
// with ONE hidden state and grows its own state space as regimes
// appear: Dirichlet conjugate count updates, threshold expansion,
// log-Beta Bayesian-model-reduction merges. Zero gradients, zero
// sampling — every event on the canvas is closed-form and replays
// bit-identically from the same stream.

#[wasm_bindgen]
pub fn mount_structure_learning(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let sink = sink.clone();

    const N_OBS: usize = 3;
    // Regime schedule: blocks of a dominant observation with a pinch
    // of off-regime noise (deterministic: every 11th step is off by
    // one). Three regimes cycle.
    const BLOCK: u32 = 90;

    let learner = Rc::new(RefCell::new(
        StructureLearner::new(N_OBS, 1, 1.0)
            .with_expansion_threshold(0.45)
            .with_merge_every(150),
    ));
    let frame_counter = Rc::new(RefCell::new(0u32));
    let cumulative_uj = Rc::new(RefCell::new(0u64));
    // Rolling event log: (frame, label). Holds the last 6 events.
    let events = Rc::new(RefCell::new(Vec::<(u32, String)>::new()));
    // State-count history for the sparkline (one sample per frame).
    let history = Rc::new(RefCell::new(Vec::<u32>::new()));

    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let lr = learner.clone();
    let fc = frame_counter.clone();
    let cu = cumulative_uj.clone();
    let ev = events.clone();
    let hi = history.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        let frame = {
            let mut fr = fc.borrow_mut();
            *fr += 1;
            *fr
        };

        // Deterministic regime-shifting observation.
        let regime = ((frame / BLOCK) as usize) % N_OBS;
        let obs = if frame % 11 == 0 {
            (regime + 1) % N_OBS
        } else {
            regime
        };

        let receipt_data = {
            let mut l = lr.borrow_mut();
            match l.step(0, obs) {
                Ok(r) => r,
                Err(_) => {
                    schedule(f.borrow().as_ref().unwrap());
                    return;
                }
            }
        };
        if let Some(idx) = receipt_data.grew {
            ev.borrow_mut().push((frame, format!("grew state {idx}")));
        }
        if let Some((kept, gone)) = receipt_data.merged {
            ev.borrow_mut()
                .push((frame, format!("BMR merged {gone} → {kept}")));
        }
        {
            let mut e = ev.borrow_mut();
            let drop_n = e.len().saturating_sub(6);
            if drop_n > 0 {
                e.drain(0..drop_n);
            }
        }
        hi.borrow_mut().push(receipt_data.n_states as u32);

        // ── Draw ──
        ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
        ctx.set_font("16px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            "structure learning — the model grows its own state space",
            28.0,
            32.0,
        )
        .ok();
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            "Dirichlet counts + threshold expansion + log-Beta BMR merge · no gradients, no sampling",
            28.0,
            52.0,
        )
        .ok();

        // Regime + observation banner.
        ctx.set_fill_style_str("rgba(120, 200, 255, 1)");
        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(&format!("regime {regime} · obs {obs}"), 28.0, 86.0)
            .ok();
        ctx.set_fill_style_str("rgba(150, 255, 180, 1)");
        ctx.fill_text(
            &format!("hidden states: {}", receipt_data.n_states),
            220.0,
            86.0,
        )
        .ok();

        // State-count sparkline.
        let hist = hi.borrow();
        let spark_x = 28.0;
        let spark_y = 104.0;
        let spark_w = cw - 56.0;
        let spark_h = 40.0;
        ctx.set_fill_style_str("rgba(40, 50, 70, 0.6)");
        ctx.fill_rect(spark_x, spark_y, spark_w, spark_h);
        let max_states = hist.iter().copied().max().unwrap_or(1).max(1) as f64;
        let n_hist = hist.len().max(1) as f64;
        ctx.set_fill_style_str("rgba(120, 200, 255, 1)");
        for (i, &s) in hist.iter().enumerate() {
            let x = spark_x + (i as f64 / n_hist) * spark_w;
            let h = (s as f64 / max_states) * (spark_h - 4.0);
            ctx.fill_rect(x, spark_y + spark_h - h, (spark_w / n_hist).max(1.0), h);
        }
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text("state count over time", spark_x, spark_y + spark_h + 14.0)
            .ok();
        drop(hist);

        // Likelihood heatmap A[o][s] from the learned counts.
        let l = lr.borrow();
        let n_states = l.model.n_states;
        let cell = 34.0;
        let hm_x = 28.0;
        let hm_y = 192.0;
        // Clamp displayed columns so the heatmap never collides with
        // the event log at cw-280 (defensive; growth is bounded by the
        // data-point seeding fix, but the canvas must not rely on it).
        let max_cols = (((cw - 280.0 - 40.0 - hm_x) / (cell + 3.0)).floor() as usize).max(1);
        let shown_states = n_states.min(max_cols);
        for o in 0..N_OBS {
            for s in 0..shown_states {
                let col_sum: f64 = (0..N_OBS).map(|oo| l.model.a_counts[oo][s]).sum();
                let p = (l.model.a_counts[o][s] / col_sum.max(1e-12)) as f64;
                let g_byte = (60.0 + 180.0 * p) as u8;
                ctx.set_fill_style_str(&format!("rgba(40, {g_byte}, 220, {:.2})", 0.25 + 0.75 * p));
                ctx.fill_rect(
                    hm_x + s as f64 * (cell + 3.0),
                    hm_y + o as f64 * (cell + 3.0),
                    cell,
                    cell,
                );
                ctx.set_fill_style_str("rgba(255,255,255,0.9)");
                ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
                ctx.fill_text(
                    &format!("{:.2}", p),
                    hm_x + s as f64 * (cell + 3.0) + 5.0,
                    hm_y + o as f64 * (cell + 3.0) + 20.0,
                )
                .ok();
            }
        }
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        let hm_label = if shown_states < n_states {
            format!("learned P(obs | state) — showing {shown_states} of {n_states} states")
        } else {
            "learned P(obs | state) — rows obs, cols states".to_string()
        };
        ctx.fill_text(&hm_label, hm_x, hm_y + 3.0 * (cell + 3.0) + 14.0)
            .ok();

        // Posterior bars.
        let post_x = hm_x;
        let post_y = hm_y + 3.0 * (cell + 3.0) + 34.0;
        let max_bars = 8usize;
        for (s, &p) in receipt_data.posterior.iter().take(max_bars).enumerate() {
            let y = post_y + s as f64 * 20.0;
            ctx.set_fill_style_str("rgba(40, 50, 70, 1)");
            ctx.fill_rect(post_x + 40.0, y, 180.0, 14.0);
            ctx.set_fill_style_str("rgba(150, 255, 180, 1)");
            ctx.fill_rect(post_x + 40.0, y, 180.0 * (p as f64).clamp(0.0, 1.0), 14.0);
            ctx.set_fill_style_str("rgba(220, 220, 240, 1)");
            ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
            ctx.fill_text(&format!("q(s{s})"), post_x, y + 11.0).ok();
        }
        drop(l);

        // Event log (right column).
        let ev_x = cw - 280.0;
        let mut ev_y = 192.0;
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text("structure events", ev_x, ev_y - 12.0).ok();
        for (fr, label) in ev.borrow().iter().rev() {
            ctx.set_fill_style_str(if label.starts_with("grew") {
                "rgba(255, 200, 120, 1)"
            } else {
                "rgba(150, 255, 180, 1)"
            });
            ctx.fill_text(&format!("t={fr} · {label}"), ev_x, ev_y).ok();
            ev_y += 18.0;
        }

        // Footer + receipt.
        let total_uj = {
            let mut t = cu.borrow_mut();
            *t += receipt_data.energy_uj;
            *t
        };
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.fill_text(
            &format!(
                "step {frame} · {} bit-ops · cumulative {total_uj} µJ · replaying this stream reproduces this model bit-for-bit",
                receipt_data.bit_ops
            ),
            28.0,
            ch - 18.0,
        )
        .ok();

        emit_receipt(
            &sink,
            "structure_learning_step",
            "L0Closed",
            1,
            (receipt_data.bit_ops as f64) * 0.5,
            receipt_data.bit_ops,
        );

        // Reset cycle so the growth story replays.
        if frame >= BLOCK * 9 {
            *fc.borrow_mut() = 0;
            *cu.borrow_mut() = 0;
            ev.borrow_mut().clear();
            hi.borrow_mut().clear();
            *lr.borrow_mut() = StructureLearner::new(N_OBS, 1, 1.0)
                .with_expansion_threshold(0.45)
                .with_merge_every(150);
        }

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── Factor-graph exhibit (reactive sum-product live) ──────────────
//
// One sweep of flooding-schedule belief propagation per animation
// frame, on the canonical one-step active-inference graph:
//
//   Prior — s_prev — B[action] — s_next — A — obs (observed)
//
// The anytime property is the exhibit: marginals are proper
// distributions after EVERY sweep — watch them settle from uniform
// to the exact posterior as max_delta falls. The scenario (action +
// observation) rotates so convergence replays continuously.

use mgai_factor_graph::{Factor as FgFactor, Graph as FgGraph};

#[wasm_bindgen]
pub fn mount_factor_graph(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let sink = sink.clone();

    // Scenarios: (action label, transition table, observed obs).
    // Tables are [s_prev][s_next]; likelihood is shared.
    fn build(scenario: usize) -> (FgGraph, usize, &'static str, usize) {
        let (label, table, obs_val): (&'static str, Vec<Vec<f64>>, usize) = match scenario % 4 {
            0 => ("stay · obs 0", vec![vec![0.9, 0.1], vec![0.1, 0.9]], 0),
            1 => ("stay · obs 1", vec![vec![0.9, 0.1], vec![0.1, 0.9]], 1),
            2 => ("swap · obs 0", vec![vec![0.1, 0.9], vec![0.9, 0.1]], 0),
            _ => ("swap · obs 1", vec![vec![0.1, 0.9], vec![0.9, 0.1]], 1),
        };
        let mut g = FgGraph::new();
        let s_prev = g.add_variable("s_prev", 2);
        let s_next = g.add_variable("s_next", 2);
        let obs = g.add_variable("obs", 2);
        g.add_factor(FgFactor::Prior {
            var: s_prev,
            probs: vec![0.7, 0.3],
        })
        .unwrap();
        g.add_factor(FgFactor::Pairwise {
            a: s_prev,
            b: s_next,
            table,
        })
        .unwrap();
        g.add_factor(FgFactor::Pairwise {
            a: s_next,
            b: obs,
            table: vec![vec![0.8, 0.2], vec![0.3, 0.7]],
        })
        .unwrap();
        g.observe(obs, obs_val).unwrap();
        (g, s_next, label, obs_val)
    }

    let scenario = Rc::new(RefCell::new(0usize));
    let state = Rc::new(RefCell::new(build(0)));
    let sweep_count = Rc::new(RefCell::new(0u32));
    let converged_hold = Rc::new(RefCell::new(0u32));
    let delta_history = Rc::new(RefCell::new(Vec::<f64>::new()));
    let cumulative_uj = Rc::new(RefCell::new(0u64));

    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();
    let sc = scenario.clone();
    let st = state.clone();
    let sw = sweep_count.clone();
    let chold = converged_hold.clone();
    let dh = delta_history.clone();
    let cu = cumulative_uj.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        // One sweep per frame (slowed: every 12th frame so the
        // settling is visible at 60 fps).
        let frame_gate = {
            let mut s = sw.borrow_mut();
            *s += 1;
            *s % 12 == 0
        };
        let receipt_opt = if frame_gate && *chold.borrow() == 0 {
            let mut s = st.borrow_mut();
            let r = s.0.sweep();
            dh.borrow_mut().push(r.max_delta);
            if r.max_delta < 1e-9 {
                *chold.borrow_mut() = 90; // hold converged ~1.5 s
            }
            Some(r)
        } else {
            None
        };
        // Converged-hold countdown → next scenario.
        {
            let mut h = chold.borrow_mut();
            if *h > 0 {
                *h -= 1;
                if *h == 0 {
                    let mut scv = sc.borrow_mut();
                    *scv += 1;
                    *st.borrow_mut() = build(*scv);
                    dh.borrow_mut().clear();
                }
            }
        }

        let s = st.borrow();
        let (ref graph, s_next, label, obs_val) = *s;

        // Header.
        ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
        ctx.set_font("16px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            "reactive message passing — sum-product on a factor graph",
            28.0,
            32.0,
        )
        .ok();
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(
            "one sweep at a time · marginals stay proper mid-inference · exact on trees",
            28.0,
            52.0,
        )
        .ok();
        ctx.set_fill_style_str("rgba(120, 200, 255, 1)");
        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.fill_text(&format!("scenario: {label}"), 28.0, 84.0)
            .ok();

        // Graph layout: 3 variable nodes + 3 factor squares on a line.
        let node_y = 150.0;
        let xs = [120.0, 400.0, 680.0];
        let names = ["s_prev", "s_next", "obs"];
        // Edges (factor squares between nodes + prior square left).
        ctx.set_stroke_style_str("rgba(100, 120, 150, 1)");
        ctx.begin_path();
        ctx.move_to(60.0, node_y);
        ctx.line_to(xs[2], node_y);
        ctx.stroke();
        // Prior factor square.
        ctx.set_fill_style_str("rgba(255, 200, 120, 1)");
        ctx.fill_rect(52.0, node_y - 8.0, 16.0, 16.0);
        // Pairwise factor squares at midpoints.
        for mid in [(xs[0] + xs[1]) / 2.0, (xs[1] + xs[2]) / 2.0] {
            ctx.fill_rect(mid - 8.0, node_y - 8.0, 16.0, 16.0);
        }
        // Variable nodes + marginal bars.
        for (i, (&x, name)) in xs.iter().zip(names.iter()).enumerate() {
            let observed = i == 2;
            ctx.set_fill_style_str(if observed {
                "rgba(150, 255, 180, 1)"
            } else {
                "rgba(120, 200, 255, 1)"
            });
            ctx.begin_path();
            ctx.arc(x, node_y, 14.0, 0.0, std::f64::consts::TAU).ok();
            ctx.fill();
            ctx.set_fill_style_str("rgba(220, 220, 240, 1)");
            ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
            ctx.fill_text(name, x - 20.0, node_y - 24.0).ok();
            if observed {
                ctx.fill_text(&format!("= {obs_val}"), x - 12.0, node_y + 36.0)
                    .ok();
            }
            // Marginal bars under each unobserved node.
            if let Ok(m) = graph.marginal(i) {
                for (k, &p) in m.iter().enumerate() {
                    let by = node_y + 52.0 + k as f64 * 20.0;
                    ctx.set_fill_style_str("rgba(40, 50, 70, 1)");
                    ctx.fill_rect(x - 60.0, by, 120.0, 14.0);
                    ctx.set_fill_style_str(if i == s_next {
                        "rgba(150, 255, 180, 1)"
                    } else {
                        "rgba(120, 200, 255, 1)"
                    });
                    ctx.fill_rect(x - 60.0, by, 120.0 * p, 14.0);
                    ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
                    ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
                    ctx.fill_text(&format!("{p:.3}"), x + 66.0, by + 11.0).ok();
                }
            }
        }

        // Convergence trace: log10(max_delta) per sweep.
        let hist = dh.borrow();
        let tr_x = 28.0;
        let tr_y = ch - 130.0;
        let tr_w = cw - 56.0;
        let tr_h = 60.0;
        ctx.set_fill_style_str("rgba(40, 50, 70, 0.6)");
        ctx.fill_rect(tr_x, tr_y, tr_w, tr_h);
        ctx.set_fill_style_str("rgba(120, 200, 255, 1)");
        let n = hist.len().max(1) as f64;
        for (i, &d) in hist.iter().enumerate() {
            // map log10 d ∈ [-12, 0] to bar height
            let l = (d.max(1e-12)).log10(); // [-12, 0]
            let hfrac = ((l + 12.0) / 12.0).clamp(0.0, 1.0);
            let bh = hfrac * (tr_h - 4.0);
            let x = tr_x + (i as f64 / n) * tr_w;
            ctx.fill_rect(x, tr_y + tr_h - bh, (tr_w / n).max(2.0), bh);
        }
        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
        ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
        let conv_label = if *chold.borrow() > 0 {
            format!(
                "CONVERGED in {} sweeps — exact posterior; next scenario shortly",
                hist.len()
            )
        } else {
            format!("log₁₀(max message Δ) per sweep — {} so far", hist.len())
        };
        ctx.fill_text(&conv_label, tr_x, tr_y + tr_h + 14.0).ok();
        drop(hist);
        drop(s);

        // Receipt per executed sweep.
        if let Some(r) = receipt_opt {
            let total_uj = {
                let mut t = cu.borrow_mut();
                *t += r.energy_uj;
                *t
            };
            ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
            ctx.fill_text(
                &format!(
                    "sweep: {} messages · {} bit-ops · cumulative {} µJ",
                    r.messages_updated, r.bit_ops, total_uj
                ),
                28.0,
                ch - 18.0,
            )
            .ok();
            emit_receipt(
                &sink,
                "factor_graph_sweep",
                "L0Closed",
                1,
                (r.bit_ops as f64) * 0.5,
                r.bit_ops,
            );
        } else {
            let total_uj = *cu.borrow();
            ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
            ctx.fill_text(&format!("cumulative {total_uj} µJ"), 28.0, ch - 18.0)
                .ok();
        }

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}

// ── Twin sim surface (twin program Phase 2) ───────────────────────
//
// The deterministic kernel (mgai-sim-core) running live in the tab,
// with the program's headline interaction: a replay scrubber where
// the past is RECOMPUTED from the transcript — not stored — and the
// recomputed state hash is checked against the recorded one in front
// of the visitor. Spawns and kicks are typed SimEvents recorded into
// the same transcript, so user input is replayable too.

use mgai_quad_env::{HoverPolicy, QuadObs};
use mgai_sim_core::{SimConfig, SimEvent as TwinEvent, SimWorld as TwinWorld, replay, replay_to};
use mgai_world_model::conservation::{ConservationGate, Law as TwinLaw};

/// The live PD pilot. Its SetMotors decisions are recorded into the
/// kernel transcript like any other event, so a flight scrubs
/// bit-exact with NO controller running at replay time.
struct TwinPilot {
    policy: HoverPolicy,
    body: usize,
    mass: f32,
}

struct TwinState {
    live: TwinWorld,
    recorded_hashes: Vec<u64>,
    /// Some = scrub view: (step, frozen replayed world, hash matched).
    view: Option<(u64, TwinWorld, bool)>,
    cumulative_uj: u64,
    spawn_counter: u32,
    pilot: Option<TwinPilot>,
    wind_on: bool,
    wind_x: f32,
    /// A counterfactual timeline: same transcript prefix (hash-verified
    /// at fork time), exactly one divergent event, then independent
    /// deterministic evolution. fork = (world, fork_step, verified).
    fork: Option<(TwinWorld, u64, bool)>,
    /// Vehicle electrical energy (J) accumulated since the fork, per
    /// timeline — the counterfactual priced in joules.
    elec_live: f64,
    elec_fork: f64,
}

thread_local! {
    static TWIN: RefCell<Option<TwinState>> = const { RefCell::new(None) };
}

fn twin_canonical() -> TwinState {
    let mut live = TwinWorld::new(SimConfig::default())
        .unwrap()
        .with_gate(ConservationGate::new(vec![TwinLaw::EnergyNonIncreasing {
            tol: 0.08,
        }]));
    let ball = |pos: [f32; 3], vel: [f32; 3]| TwinEvent::SpawnSphere {
        pos,
        vel,
        radius: 0.2,
        density: 1000.0,
        restitution: 0.6,
        friction: 0.5,
    };
    live.apply(ball([0.0, 3.0, 0.0], [0.5, 0.0, 0.0])).unwrap();
    live.apply(ball([0.6, 5.0, 0.0], [-0.3, 0.0, 0.0])).unwrap();
    live.apply(ball([-0.8, 6.5, 0.0], [0.2, 0.0, 0.0])).unwrap();
    TwinState {
        live,
        recorded_hashes: Vec::new(),
        view: None,
        cumulative_uj: 0,
        spawn_counter: 0,
        pilot: None,
        wind_on: false,
        wind_x: 0.0,
        fork: None,
        elec_live: 0.0,
        elec_fork: 0.0,
    }
}

/// Spawn a ball. Position derives from the spawn counter — varied but
/// deterministic, so the transcript stays the only source of truth.
#[wasm_bindgen]
pub fn twin_spawn() {
    TWIN.with(|t| {
        if let Some(state) = t.borrow_mut().as_mut() {
            state.spawn_counter += 1;
            let k = state.spawn_counter as f32;
            let x = ((k * 0.737).fract() - 0.5) * 3.0;
            let z = 0.0;
            let _ = state.live.apply(TwinEvent::SpawnSphere {
                pos: [x, 6.0 + (k * 0.39).fract() * 2.0, z],
                vel: [((k * 0.531).fract() - 0.5) * 2.0, 0.0, 0.0],
                radius: 0.15 + (k * 0.211).fract() * 0.15,
                density: 1000.0,
                restitution: 0.55 + (k * 0.173).fract() * 0.3,
                friction: 0.5,
            });
            state.view = None;
        }
    });
}

/// Kick a body (round-robin) with an upward-lateral impulse.
#[wasm_bindgen]
pub fn twin_kick() {
    TWIN.with(|t| {
        if let Some(state) = t.borrow_mut().as_mut() {
            let n = state.live.n_bodies();
            if n == 0 {
                return;
            }
            let body = (state.live.step_index() as usize) % n;
            let s = ((state.live.step_index() as f32) * 0.317).fract() - 0.5;
            let _ = state.live.apply(TwinEvent::ApplyImpulse {
                body,
                impulse: [s * 12.0, 18.0, 0.0],
            });
            state.view = None;
        }
    });
}

/// Train the hover pilot's gains IN THE TAB (called from a worker —
/// it blocks for a few seconds). Deterministic seeded search on a
/// compact curriculum; returns the TrainingReport as JSON. Same seed,
/// same browser, same gains — the training run is a replayable
/// artifact, which is the twin program's headline sentence.
#[wasm_bindgen]
pub fn twin_train(seed: u32, iterations: u32, neighbours: u32) -> String {
    use mgai_quad_env::QuadConfig;
    use mgai_quad_env::train::{Task, TrainConfig, train_gains};
    let curriculum = vec![
        Task::Hover {
            target: [0.5, 2.5, -0.3],
            steps: 600,
            tol_m: 0.18,
        },
        Task::Waypoints {
            targets: vec![[0.0, 2.0, 0.3], [0.8, 3.0, -0.4]],
            steps_per_leg: 600,
            tol_m: 0.2,
        },
    ];
    match train_gains(
        &QuadConfig::default(),
        &curriculum,
        TrainConfig {
            seed: seed as u64,
            iterations,
            neighbours,
            step_frac: 0.25,
            entropy_budget_bits: None,
        },
    ) {
        Ok(r) => serde_json::to_string(&r).unwrap_or_default(),
        Err(e) => format!("{{\"error\":\"{e}\"}}"),
    }
}

/// Apply trained gains (a HoverPolicy JSON, target ignored) to the
/// live pilot. The pilot's future SetMotors decisions — now flown
/// with the trained gains — remain typed transcript events, so the
/// trained flight replays bit-exact like everything else.
#[wasm_bindgen]
pub fn twin_apply_gains(policy_json: &str) -> bool {
    let Ok(trained) = serde_json::from_str::<HoverPolicy>(policy_json) else {
        return false;
    };
    TWIN.with(|t| {
        if let Some(state) = t.borrow_mut().as_mut() {
            if let Some(pilot) = state.pilot.as_mut() {
                let target = pilot.policy.target;
                pilot.policy = HoverPolicy { target, ..trained };
                return true;
            }
        }
        false
    })
}

/// Fork the timeline: rebuild a second world from the live
/// transcript (the shared past is verified by hash equality, not
/// assumed), then apply ONE divergent event — an opposite crosswind.
/// Both timelines then evolve deterministically side by side. This is
/// the event-keyed counterfactual made visible: the divergence you
/// see is DERIVED from one changed event, not hallucinated.
/// Returns true if the shared past verified bit-exact.
#[wasm_bindgen]
pub fn twin_fork() -> bool {
    TWIN.with(|t| {
        let mut borrow = t.borrow_mut();
        let Some(state) = borrow.as_mut() else {
            return false;
        };
        if state.fork.is_some() {
            state.fork = None; // toggle off
            return true;
        }
        // Fork point: the scrubbed step if the visitor rewound the
        // timeline, otherwise the present. Rewinding + forking makes
        // the scrubbed moment the new shared present: both futures
        // grow from it, and the old future is released.
        let step = match &state.view {
            Some((scrub_step, _, _)) => *scrub_step,
            None => state.live.step_index(),
        }
        .max(1);
        let Ok((live_at, hashes)) = replay_to(state.live.transcript(), step) else {
            return false;
        };
        let verified =
            hashes.last().copied() == state.recorded_hashes.get(step as usize - 1).copied();
        let Ok((mut fork_world, _)) = replay_to(state.live.transcript(), step) else {
            return false;
        };
        // The one divergent event: opposite wind.
        let wx = if state.wind_on { -state.wind_x } else { 3.0 };
        let _ = fork_world.apply(TwinEvent::SetWind {
            force: [wx, 0.0, 0.0],
        });
        // Rewind the live timeline to the fork point (its transcript is
        // now the shared prefix) and restart the energy accounts —
        // the comparison is over the two futures.
        state.live = live_at;
        state.recorded_hashes.truncate(step as usize);
        state.elec_live = 0.0;
        state.elec_fork = 0.0;
        state.fork = Some((fork_world, step, verified));
        state.view = None;
        verified
    })
}

/// Verify an EXTERNAL continuity snapshot — the live-host rejoin.
/// Takes the host's atomic snapshot JSON `{step, state_hash,
/// transcript}`, replays the transcript on the deterministic kernel
/// with zero `per_step_hashes` heap allocation, and confirms the
/// recomputed hash matches the host's claim (or, when a multi-day host
/// epoch exceeds `120_000` uncompacted steps, restores the checkpointed
/// bodies and verifies a 2,400-step twin-kernel forward replay in
/// bounded time). Returns JSON `{ok, full_epoch, verified_steps, step,
/// bytes, hash, claimed_hash}`.
#[wasm_bindgen]
pub fn twin_verify_external(snapshot_json: &str) -> String {
    let v: serde_json::Value = match serde_json::from_str(snapshot_json) {
        Ok(v) => v,
        Err(e) => return format!("{{\"ok\":false,\"reason\":\"{e}\"}}"),
    };
    let claimed = v.get("state_hash").and_then(|h| h.as_u64()).unwrap_or(0);
    let step = v.get("step").and_then(|s| s.as_u64()).unwrap_or(0);
    let Some(tr) = v.get("transcript") else {
        return "{\"ok\":false,\"reason\":\"no transcript\"}".into();
    };
    let parsed: mgai_sim_core::Transcript = match serde_json::from_value(tr.clone()) {
        Ok(p) => p,
        Err(e) => return format!("{{\"ok\":false,\"reason\":\"{e}\"}}"),
    };
    let bytes = snapshot_json.len();
    let (rebuilt_hash, verified_steps, full_epoch) =
        match mgai_sim_core::replay_bounded_hash(&parsed, 120_000, 2_400) {
            Ok(r) => r,
            Err(e) => return format!("{{\"ok\":false,\"reason\":\"{e}\"}}"),
        };
    let ok = if full_epoch {
        rebuilt_hash == claimed
    } else {
        true
    };
    format!(
        "{{\"ok\":{ok},\"full_epoch\":{full_epoch},\"verified_steps\":{verified_steps},\"step\":{step},\"bytes\":{bytes},\"hash\":\"{:#018x}\",\"claimed_hash\":\"{:#018x}\"}}",
        rebuilt_hash, claimed
    )
}

/// Rejoin: prove provable continuity in-tab. Serialize the live
/// transcript to a portable string (the artifact you'd carry to any
/// device), rebuild a fresh world from it, and verify the recomputed
/// final hash matches the run you watched. Returns JSON
/// `{ok, steps, bytes, hash}`.
#[wasm_bindgen]
pub fn twin_rejoin() -> String {
    TWIN.with(|t| {
        let borrow = t.borrow();
        let Some(state) = borrow.as_ref() else {
            return "{}".into();
        };
        let Some(&recorded) = state.recorded_hashes.last() else {
            return "{\"ok\":false,\"reason\":\"no run yet\"}".into();
        };
        let json = match serde_json::to_string(state.live.transcript()) {
            Ok(j) => j,
            Err(e) => return format!("{{\"ok\":false,\"reason\":\"{e}\"}}"),
        };
        let bytes = json.len();
        let parsed: mgai_sim_core::Transcript = match serde_json::from_str(&json) {
            Ok(p) => p,
            Err(e) => return format!("{{\"ok\":false,\"reason\":\"{e}\"}}"),
        };
        let rebuilt_hash = match mgai_sim_core::replay_final_hash(&parsed) {
            Ok(h) => h,
            Err(e) => return format!("{{\"ok\":false,\"reason\":\"{e}\"}}"),
        };
        let ok = rebuilt_hash == recorded;
        format!(
            "{{\"ok\":{ok},\"steps\":{},\"bytes\":{bytes},\"hash\":\"{:#018x}\"}}",
            state.recorded_hashes.len(),
            rebuilt_hash
        )
    })
}

/// Toggle a crosswind gust: a typed SetWind event (deterministic
/// force derived from the step index), so the disturbed flight
/// replays bit-exact. Returns the new wind x-force in newtons.
#[wasm_bindgen]
pub fn twin_gust() -> f32 {
    TWIN.with(|t| {
        let mut borrow = t.borrow_mut();
        let Some(state) = borrow.as_mut() else {
            return 0.0;
        };
        let on = state.wind_on;
        let force = if on {
            [0.0, 0.0, 0.0]
        } else {
            // Deterministic strength from the step index — varied but
            // replayable (the transcript records the event, not RNG).
            let k = (state.live.step_index() as f32 * 0.317).fract();
            [2.0 + k * 2.5, 0.0, 0.0]
        };
        let _ = state.live.apply(TwinEvent::SetWind { force });
        state.wind_on = !on;
        state.wind_x = force[0];
        state.view = None;
        force[0]
    })
}

/// Stack-hunt probe: like twin_episode but with a step count.
#[wasm_bindgen]
pub fn twin_episode_n(seed: u32, steps: u32) -> String {
    use mgai_quad_env::{QuadConfig, QuadEnv, run_hover};
    let k = seed as f32;
    let target = [
        ((k * 0.737).fract() - 0.5) * 2.0,
        2.0 + (k * 0.39).fract() * 2.0,
        ((k * 0.531).fract() - 0.5) * 1.5,
    ];
    let mut env = match QuadEnv::new(QuadConfig::default()) {
        Ok(e) => e,
        Err(e) => return format!("{{\"error\":\"{e}\"}}"),
    };
    match run_hover(&mut env, &HoverPolicy::new(target), steps as u64, 0.15) {
        Ok(r) => serde_json::to_string(&r).unwrap_or_default(),
        Err(e) => format!("{{\"error\":\"{e}\"}}"),
    }
}

/// Run one complete quad hover episode (for Worker-batched training:
/// each Web Worker loads this module and calls this with its own
/// seed). Returns the EpisodeReport as JSON — final_hash included, so
/// the page can verify that identical seeds produce identical bits
/// across workers running in parallel.
#[wasm_bindgen]
pub fn twin_episode(seed: u32) -> String {
    use mgai_quad_env::{QuadConfig, QuadEnv, run_hover};
    let k = seed as f32;
    let target = [
        ((k * 0.737).fract() - 0.5) * 2.0,
        2.0 + (k * 0.39).fract() * 2.0,
        ((k * 0.531).fract() - 0.5) * 1.5,
    ];
    let mut env = match QuadEnv::new(QuadConfig::default()) {
        Ok(e) => e,
        Err(e) => return format!("{{\"error\":\"{e}\"}}"),
    };
    match run_hover(&mut env, &HoverPolicy::new(target), 900, 0.15) {
        Ok(r) => serde_json::to_string(&r).unwrap_or_default(),
        Err(e) => format!("{{\"error\":\"{e}\"}}"),
    }
}

/// Launch the quadrotor (once) with the PD pilot targeting (0, 3, 0).
/// The spawn is a typed event; every subsequent SetMotors the pilot
/// issues is too.
#[wasm_bindgen]
pub fn twin_launch_quad() {
    TWIN.with(|t| {
        if let Some(state) = t.borrow_mut().as_mut() {
            if state.pilot.is_some() {
                return;
            }
            let mass_before = state.live.snapshot().mass;
            let body = state.live.n_bodies();
            if state
                .live
                .apply(TwinEvent::SpawnQuad {
                    pos: [-2.5, 0.5, 0.0],
                    vel: [0.0; 3],
                    half_extents: [0.12, 0.03, 0.12],
                    density: 580.0,
                    arm: 0.16,
                })
                .is_err()
            {
                return;
            }
            let mass = state.live.snapshot().mass - mass_before;
            state.pilot = Some(TwinPilot {
                policy: HoverPolicy::new([0.0, 3.0, 0.0]),
                body,
                mass,
            });
            state.view = None;
        }
    });
}

/// Retarget the pilot from a canvas click (pixel coords + canvas
/// size, inverted through the same projection the renderer uses).
#[wasm_bindgen]
pub fn twin_set_target(px: f64, py: f64, cw: f64, ch: f64) {
    TWIN.with(|t| {
        if let Some(state) = t.borrow_mut().as_mut() {
            if let Some(pilot) = state.pilot.as_mut() {
                let x = ((px - 40.0) / (cw - 80.0)) * 8.0 - 4.0;
                let y = (ch - 60.0 - py) / (ch - 160.0) * 8.0;
                pilot.policy.target = [x.clamp(-3.8, 3.8) as f32, y.clamp(0.5, 7.5) as f32, 0.0];
                state.view = None;
            }
        }
    });
}

/// Scrub to a recorded step: recompute the past from the transcript
/// and report whether the recomputed hash matches the recorded one.
/// Returns the match flag (true = bit-exact).
#[wasm_bindgen]
pub fn twin_scrub(step: u32) -> bool {
    TWIN.with(|t| {
        let mut borrow = t.borrow_mut();
        let Some(state) = borrow.as_mut() else {
            return false;
        };
        state.fork = None;
        let target = (step as u64).clamp(1, state.recorded_hashes.len() as u64);
        match replay_to(state.live.transcript(), target) {
            Ok((world, hashes)) => {
                let matched = hashes.last().copied()
                    == state.recorded_hashes.get(target as usize - 1).copied();
                state.view = Some((target, world, matched));
                matched
            }
            Err(_) => false,
        }
    })
}

/// Leave scrub view; the live world resumes stepping.
#[wasm_bindgen]
pub fn twin_resume() {
    TWIN.with(|t| {
        if let Some(state) = t.borrow_mut().as_mut() {
            state.view = None;
        }
    });
}

/// Total recorded steps (the scrubber's max).
#[wasm_bindgen]
pub fn twin_total_steps() -> u32 {
    TWIN.with(|t| {
        t.borrow()
            .as_ref()
            .map(|s| s.recorded_hashes.len() as u32)
            .unwrap_or(0)
    })
}

fn twin_draw_world(
    ctx: &CanvasRenderingContext2d,
    world: &TwinWorld,
    cw: f64,
    ch: f64,
    dim: bool,
    quad: Option<usize>,
    target: Option<[f32; 3]>,
) {
    // Side elevation: world x ∈ [−4, 4] → canvas width; y ∈ [0, 8] →
    // canvas height (inverted).
    let map_x = |x: f32| ((x as f64 + 4.0) / 8.0) * (cw - 80.0) + 40.0;
    let map_y = |y: f32| ch - 60.0 - (y as f64 / 8.0) * (ch - 160.0);
    let scale = (cw - 80.0) / 8.0;
    // Ground.
    ctx.set_stroke_style_str("rgba(100, 120, 150, 1)");
    ctx.begin_path();
    ctx.move_to(40.0, map_y(0.0));
    ctx.line_to(cw - 40.0, map_y(0.0));
    ctx.stroke();
    let alpha = if dim { 0.55 } else { 1.0 };
    if let Some(tg) = target {
        let tx = map_x(tg[0]);
        let ty = map_y(tg[1]);
        ctx.set_stroke_style_str(&format!("rgba(255, 200, 100, {})", alpha * 0.9));
        ctx.begin_path();
        ctx.move_to(tx - 10.0, ty);
        ctx.line_to(tx + 10.0, ty);
        ctx.move_to(tx, ty - 10.0);
        ctx.line_to(tx, ty + 10.0);
        ctx.stroke();
        ctx.begin_path();
        ctx.arc(tx, ty, 14.0, 0.0, std::f64::consts::TAU).ok();
        ctx.stroke();
    }
    for (i, (pos, vel, radius)) in world.body_states().iter().enumerate() {
        let x = map_x(pos[0]);
        let y = map_y(pos[1]);
        let r = (*radius as f64) * scale;
        if quad == Some(i) {
            // Quadrotor: rotor bar perpendicular to the body up-axis,
            // in the elevation plane.
            let up = world.body_up(i).unwrap_or([0.0, 1.0, 0.0]);
            let (bx, by) = (up[1] as f64, up[0] as f64); // ⟂ to up, canvas-y flipped
            let arm = r.max(8.0) * 1.6;
            ctx.set_stroke_style_str(&format!("rgba(120, 230, 255, {alpha})"));
            ctx.set_line_width(3.0);
            ctx.begin_path();
            ctx.move_to(x - bx * arm, y + by * arm);
            ctx.line_to(x + bx * arm, y - by * arm);
            ctx.stroke();
            ctx.set_line_width(1.0);
            ctx.set_fill_style_str(&format!("rgba(120, 230, 255, {alpha})"));
            for s in [-1.0f64, 1.0] {
                ctx.begin_path();
                ctx.arc(
                    x + s * bx * arm,
                    y - s * by * arm,
                    4.5,
                    0.0,
                    std::f64::consts::TAU,
                )
                .ok();
                ctx.fill();
            }
            ctx.begin_path();
            ctx.arc(x, y, 3.5, 0.0, std::f64::consts::TAU).ok();
            ctx.fill();
            continue;
        }
        let hue_shift = (i * 47) % 120;
        ctx.set_fill_style_str(&format!(
            "rgba({}, {}, 255, {alpha})",
            100 + hue_shift,
            180 + (i * 23) % 60
        ));
        ctx.begin_path();
        ctx.arc(x, y, r.max(3.0), 0.0, std::f64::consts::TAU).ok();
        ctx.fill();
        // Velocity vector.
        ctx.set_stroke_style_str(&format!("rgba(255, 220, 150, {alpha})"));
        ctx.begin_path();
        ctx.move_to(x, y);
        ctx.line_to(x + (vel[0] as f64) * 10.0, y - (vel[1] as f64) * 10.0);
        ctx.stroke();
    }
}

#[wasm_bindgen]
pub fn mount_twin(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let sink = sink.clone();
    TWIN.with(|t| {
        let mut b = t.borrow_mut();
        if b.is_none() {
            *b = Some(twin_canonical());
        }
    });

    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        TWIN.with(|t| {
            let mut borrow = t.borrow_mut();
            let Some(state) = borrow.as_mut() else { return };

            // Header.
            ctx.set_fill_style_str("rgba(255, 255, 255, 1)");
            ctx.set_font("16px ui-monospace, SFMono-Regular, Menlo, monospace");
            ctx.fill_text("twin kernel — deterministic, transcripted, joule-metered", 28.0, 32.0).ok();

            match &state.view {
                Some((step, world, matched)) => {
                    // Frozen scrub view: the recomputed past.
                    let quad = state.pilot.as_ref().map(|p| p.body);
                    twin_draw_world(&ctx, world, cw, ch, true, quad, None);
                    ctx.set_font("13px ui-monospace, SFMono-Regular, Menlo, monospace");
                    ctx.set_fill_style_str(if *matched {
                        "rgba(150, 255, 180, 1)"
                    } else {
                        "rgba(255, 120, 120, 1)"
                    });
                    let verdict = if *matched {
                        format!("REPLAY @ step {step} — recomputed from the transcript · hash MATCHES the recorded run ≡ bit-exact")
                    } else {
                        format!("REPLAY @ step {step} — HASH MISMATCH (this would be a determinism bug)")
                    };
                    ctx.fill_text(&verdict, 28.0, 58.0).ok();
                    ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
                    ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
                    ctx.fill_text(
                        "the past is not stored — it is recomputed on every scrub · resume to continue the live run",
                        28.0,
                        ch - 18.0,
                    )
                    .ok();
                }
                None => {
                    // The counterfactual timeline: the same pilot flies
                    // the fork world from ITS state — same policy, one
                    // changed event, derived divergence.
                    if state.fork.is_some() {
                        if let Some(pilot) = &state.pilot {
                            let (fw, _, _) = state.fork.as_mut().unwrap();
                            let states = fw.body_states();
                            if let Some((pos, vel, _)) = states.get(pilot.body) {
                                let obs = QuadObs {
                                    pos: *pos,
                                    vel: *vel,
                                    up: fw.body_up(pilot.body).unwrap_or([0.0, 1.0, 0.0]),
                                    angvel: fw.body_angvel(pilot.body).unwrap_or([0.0; 3]),
                                    step: fw.step_index(),
                                };
                                let thrusts =
                                    pilot.policy.act(&obs, pilot.mass).map(|t| t.clamp(0.0, 6.0));
                                let dt = 1.0 / 120.0f64;
                                state.elec_fork += thrusts
                                    .iter()
                                    .map(|&t| (t as f64).powf(1.5) / 0.35 * dt)
                                    .sum::<f64>();
                                let _ = fw.apply(TwinEvent::SetMotors { body: pilot.body, thrusts });
                            }
                        }
                        let (fw, _, _) = state.fork.as_mut().unwrap();
                        let _ = fw.step();
                    }
                    // The pilot flies: PD action from the current
                    // observation, recorded as a typed SetMotors event.
                    if let Some(pilot) = &state.pilot {
                        let states = state.live.body_states();
                        if let Some((pos, vel, _)) = states.get(pilot.body) {
                            let obs = QuadObs {
                                pos: *pos,
                                vel: *vel,
                                up: state.live.body_up(pilot.body).unwrap_or([0.0, 1.0, 0.0]),
                                angvel: state
                                    .live
                                    .body_angvel(pilot.body)
                                    .unwrap_or([0.0; 3]),
                                step: state.live.step_index(),
                            };
                            let thrusts = pilot.policy.act(&obs, pilot.mass)
                                .map(|t| t.clamp(0.0, 6.0));
                            if state.fork.is_some() {
                                let dt = 1.0 / 120.0f64;
                                state.elec_live += thrusts
                                    .iter()
                                    .map(|&t| (t as f64).powf(1.5) / 0.35 * dt)
                                    .sum::<f64>();
                            }
                            let _ = state.live.apply(TwinEvent::SetMotors {
                                body: pilot.body,
                                thrusts,
                            });
                        }
                    }
                    // Live stepping.
                    if let Ok(receipt) = state.live.step() {
                        state.recorded_hashes.push(receipt.state_hash);
                        state.cumulative_uj += receipt.energy_uj;
                        let quad = state.pilot.as_ref().map(|p| p.body);
                        let target = state.pilot.as_ref().map(|p| p.policy.target);
                        twin_draw_world(&ctx, &state.live, cw, ch, false, quad, target);
                        if let Some((fw, fstep, verified)) = &state.fork {
                            let quad = state.pilot.as_ref().map(|p| p.body);
                            twin_draw_world(&ctx, fw, cw, ch, true, quad, None);
                            ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
                            ctx.set_fill_style_str(if *verified {
                                "rgba(150, 255, 180, 1)"
                            } else {
                                "rgba(255, 120, 120, 1)"
                            });
                            ctx.fill_text(
                                &format!(
                                    "FORK @ step {fstep} — shared past {} · one changed event (opposite wind) · dim = counterfactual, derived not dreamed",
                                    if *verified { "verified ≡ bit-exact" } else { "UNVERIFIED" }
                                ),
                                28.0,
                                112.0,
                            )
                            .ok();
                            ctx.set_fill_style_str("rgba(255, 210, 130, 1)");
                            ctx.fill_text(
                                &format!(
                                    "energy since fork — yours {:.1} J · counterfactual {:.1} J · the other choice costs {:+.1} J",
                                    state.elec_live,
                                    state.elec_fork,
                                    state.elec_fork - state.elec_live
                                ),
                                28.0,
                                130.0,
                            )
                            .ok();
                        }
                        if state.wind_on {
                            ctx.set_stroke_style_str("rgba(140, 200, 255, 0.7)");
                            ctx.set_fill_style_str("rgba(140, 200, 255, 0.9)");
                            let phase = (receipt.step % 40) as f64 / 40.0;
                            for lane in 0..3 {
                                let y = 100.0 + lane as f64 * 26.0;
                                let x = 60.0 + ((phase + lane as f64 * 0.33) % 1.0) * (cw - 160.0);
                                ctx.begin_path();
                                ctx.move_to(x, y);
                                ctx.line_to(x + 26.0, y);
                                ctx.line_to(x + 19.0, y - 4.0);
                                ctx.move_to(x + 26.0, y);
                                ctx.line_to(x + 19.0, y + 4.0);
                                ctx.stroke();
                            }
                            ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
                            ctx.fill_text(
                                &format!("crosswind {:.1} N — a typed event; the pilot leans into it; the books still balance", state.wind_x),
                                28.0,
                                94.0,
                            )
                            .ok();
                        }

                        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
                        ctx.set_fill_style_str("rgba(120, 200, 255, 1)");
                        ctx.fill_text(
                            &format!(
                                "step {} · bodies {} · state hash {:#018x}",
                                receipt.step, receipt.n_bodies, receipt.state_hash
                            ),
                            28.0,
                            58.0,
                        )
                        .ok();
                        if let Some(gate) = &receipt.gate {
                            ctx.set_fill_style_str(if gate.passed {
                                "rgba(150, 255, 180, 1)"
                            } else {
                                "rgba(255, 120, 120, 1)"
                            });
                            let lab = if gate.passed {
                                "conservation gate: energy books balanced".to_string()
                            } else {
                                format!("conservation gate VIOLATION: {:?}", gate.laws)
                            };
                            ctx.fill_text(&lab, 28.0, 76.0).ok();
                        }
                        ctx.set_fill_style_str("rgba(160, 170, 190, 1)");
                        ctx.fill_text(
                            &format!(
                                "cumulative {} µJ · every spawn + kick is a typed event in the transcript",
                                state.cumulative_uj
                            ),
                            28.0,
                            ch - 18.0,
                        )
                        .ok();

                        emit_receipt(
                            &sink,
                            "twin_sim_step",
                            "L0Closed",
                            1,
                            (receipt.bit_ops as f64) * 0.5,
                            receipt.bit_ops,
                        );
                    }
                }
            }
        });

        schedule(f.borrow().as_ref().unwrap());
    }) as Box<dyn FnMut()>));

    schedule(g.borrow().as_ref().unwrap());
    std::mem::forget(g);
    Ok(())
}


// ── Safety Shield Red-Team Arena (`/exhibits/safety-shield`) ─────────

thread_local! {
    static PENDING_REDTEAM_CMD: RefCell<Option<String>> = const { RefCell::new(None) };
}

#[wasm_bindgen]
pub fn safety_shield_inject(cmd: &str) {
    PENDING_REDTEAM_CMD.with(|slot| {
        *slot.borrow_mut() = Some(cmd.to_string());
    });
}

#[wasm_bindgen]
pub fn mount_safety_shield(
    canvas_id: &str,
    steps_per_frame: u32,
    sink: &js_sys::Function,
) -> Result<(), JsValue> {
    use crate::safety_shield::{RedTeamAttack, SafetyShieldArena};

    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let spf = steps_per_frame.clamp(1, 6) as usize;
    let arena = Rc::new(RefCell::new(SafetyShieldArena::new()));
    let sink = sink.clone();

    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let mut st = arena.borrow_mut();

        PENDING_REDTEAM_CMD.with(|slot| {
            if let Some(cmd) = slot.borrow_mut().take() {
                match cmd.as_str() {
                    "poster_spoof" => st.inject_attack(RedTeamAttack::PosterSpoof, 35),
                    "hallucination" => st.inject_attack(RedTeamAttack::HallucinationLunge, 35),
                    "contact_overload" => st.inject_attack(RedTeamAttack::ContactOverload, 25),
                    "vjepa_surprise" => st.inject_attack(RedTeamAttack::VJepaSurprise, 30),
                    "toggle_u_trap" => st.toggle_u_trap_mode(),
                    "reset" => st.reset_episode(),
                    _ => {}
                }
            }
        });

        let t0 = now_ns();
        let mut last_rep = None;
        for _ in 0..spf {
            last_rep = Some(st.step());
        }
        let wall_ns = (now_ns() - t0).max(0.0);

        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;
        let world_w = st.runner.env.width_m;
        let world_h = st.runner.env.height_m;
        let pad_top = 56.0;
        let draw_h = (ch - pad_top - 24.0).max(100.0);
        let sx = cw / world_w;
        let sy = draw_h / world_h;
        let to_px = |wx: f64, wy: f64| -> (f64, f64) { (wx * sx, pad_top + draw_h - wy * sy) };

        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        ctx.set_stroke_style_str("rgba(45, 60, 85, 0.35)");
        ctx.set_line_width(1.0);
        for gx in (0..=20).step_by(2) {
            let (px, _) = to_px(gx as f64, 0.0);
            ctx.begin_path();
            ctx.move_to(px, pad_top);
            ctx.line_to(px, pad_top + draw_h);
            ctx.stroke();
        }
        for gy in (0..=10).step_by(2) {
            let (_, py) = to_px(0.0, gy as f64);
            ctx.begin_path();
            ctx.move_to(0.0, py);
            ctx.line_to(cw, py);
            ctx.stroke();
        }

        for z in &st.runner.env.fuzz_zones {
            let (zx, zy) = to_px(z.x, z.y);
            ctx.set_fill_style_str("rgba(245, 158, 11, 0.22)");
            ctx.begin_path();
            let _ = ctx.arc(zx, zy, z.radius_m * sx, 0.0, core::f64::consts::TAU);
            ctx.fill();
            ctx.set_stroke_style_str("rgba(245, 158, 11, 0.55)");
            ctx.stroke();
        }

        for obs in &st.runner.env.obstacles {
            let (ox, oy) = to_px(obs.x, obs.y);
            ctx.set_stroke_style_str("rgba(248, 113, 113, 0.28)");
            ctx.begin_path();
            let _ = ctx.arc(
                ox,
                oy,
                (obs.radius_m + 0.30 + 0.24) * sx,
                0.0,
                core::f64::consts::TAU,
            );
            ctx.stroke();

            ctx.set_fill_style_str("rgba(220, 38, 38, 0.88)");
            ctx.begin_path();
            let _ = ctx.arc(ox, oy, obs.radius_m * sx, 0.0, core::f64::consts::TAU);
            ctx.fill();
        }

        let (gx, gy) = to_px(st.runner.goal_xy.0, st.runner.goal_xy.1);
        ctx.set_stroke_style_str("rgba(52, 211, 153, 0.95)");
        ctx.set_line_width(2.2);
        ctx.begin_path();
        let _ = ctx.arc(
            gx,
            gy,
            st.runner.goal_tolerance_m * sx,
            0.0,
            core::f64::consts::TAU,
        );
        ctx.stroke();

        if st.u_trap_mode && st.hj_geodesic_preview.len() > 1 {
            ctx.set_stroke_style_str("rgba(244, 114, 182, 0.72)");
            ctx.set_line_width(1.9);
            ctx.begin_path();
            for (idx, &(hx, hy)) in st.hj_geodesic_preview.iter().enumerate() {
                let (px, py) = to_px(hx, hy);
                if idx == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();
        }

        if st.unshielded_trail.len() > 1 {
            ctx.set_stroke_style_str("rgba(248, 113, 113, 0.65)");
            ctx.set_line_width(1.8);
            ctx.begin_path();
            for (idx, &(ux, uy, _)) in st.unshielded_trail.iter().enumerate() {
                let (px, py) = to_px(ux, uy);
                if idx == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();
            for &(ux, uy, hit) in &st.unshielded_trail {
                if hit {
                    let (px, py) = to_px(ux, uy);
                    ctx.set_fill_style_str("rgba(255, 80, 80, 0.9)");
                    ctx.fill_rect(px - 2.5, py - 2.5, 5.0, 5.0);
                }
            }
        }

        for pair in st.shielded_trail.windows(2) {
            let (x0, y0) = to_px(pair[0].0, pair[0].1);
            let (x1, y1) = to_px(pair[1].0, pair[1].1);
            ctx.set_stroke_style_str(if pair[1].2 {
                "rgba(56, 189, 248, 0.95)"
            } else {
                "rgba(251, 146, 60, 0.95)"
            });
            ctx.set_line_width(2.6);
            ctx.begin_path();
            ctx.move_to(x0, y0);
            ctx.line_to(x1, y1);
            ctx.stroke();
        }

        let (urx, ury) = to_px(st.unshielded.x, st.unshielded.y);
        ctx.set_fill_style_str("rgba(239, 68, 68, 0.85)");
        ctx.begin_path();
        let _ = ctx.arc(
            urx,
            ury,
            st.unshielded.radius_m * sx,
            0.0,
            core::f64::consts::TAU,
        );
        ctx.fill();

        let (srx, sry) = to_px(st.runner.robot.x, st.runner.robot.y);
        let is_adv_now = st
            .last_frame
            .as_ref()
            .is_none_or(|fr| fr.active_controller == "ADVANCED");
        ctx.set_fill_style_str(if is_adv_now {
            "rgba(56, 189, 248, 1.0)"
        } else {
            "rgba(251, 146, 60, 1.0)"
        });
        ctx.begin_path();
        let _ = ctx.arc(
            srx,
            sry,
            st.runner.robot.radius_m * sx,
            0.0,
            core::f64::consts::TAU,
        );
        ctx.fill();
        ctx.set_stroke_style_str("rgba(255, 255, 255, 0.95)");
        ctx.set_line_width(2.0);
        ctx.begin_path();
        ctx.move_to(srx, sry);
        ctx.line_to(
            srx + st.runner.robot.theta.cos() * st.runner.robot.radius_m * sx * 1.8,
            sry - st.runner.robot.theta.sin() * st.runner.robot.radius_m * sy * 1.8,
        );
        ctx.stroke();

        ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
        if let (Some(fr), Some(rep)) = (&st.last_frame, &last_rep) {
            ctx.set_fill_style_str("rgba(226, 232, 240, 0.98)");
            let _ = ctx.fill_text(
                &format!(
                    "SHIELDED COLLISIONS: {}   |   UNSHIELDED COLLISIONS: {}   |   CONTROLLER: {}   |   GATE: {}",
                    rep.shielded_collisions,
                    rep.unshielded_collisions,
                    fr.active_controller,
                    if fr.block_stage.is_empty() {
                        "CLEAR"
                    } else {
                        &fr.block_stage
                    }
                ),
                18.0,
                22.0,
            );
            ctx.set_fill_style_str("rgba(148, 163, 184, 0.95)");
            let _ = ctx.fill_text(
                &format!(
                    "v: {:.2} → {:.2} m/s  ·  fuzz: {:.2} (ep {:.2})  ·  PID τ: {:.2}  ·  trust: {:.2}  ·  SHA-256: {}…",
                    fr.v_nom_ms,
                    fr.v_safe_ms,
                    fr.raw_fuzz,
                    fr.epistemic,
                    fr.conformal_threshold,
                    fr.trust_score,
                    rep.head_hash_short
                ),
                18.0,
                42.0,
            );
            ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
            ctx.set_fill_style_str("rgba(148, 163, 184, 0.90)");
            let _ = ctx.fill_text(
                "cyan/amber = Shielded VLA (CBF-QP + Conformal PID + Simplex + HJ + ISO 10218-2)  ·  red = Unshielded VLA",
                18.0,
                ch - 7.0,
            );

            emit_receipt(
                &sink,
                "sota_safety_shield_tick",
                "L0Closed",
                spf as u64,
                wall_ns,
                rep.bit_ops,
            );
        }

        if let Some(cb) = f.borrow().as_ref() {
            schedule(cb);
        }
    }) as Box<dyn FnMut()>));

    if let Some(cb) = g.borrow().as_ref() {
        schedule(cb);
    }
    std::mem::forget(g);
    Ok(())
}

// ── Post-DOM / Post-Python Sovereign Studio (`/studio`) ──────────────

thread_local! {
    static PENDING_STUDIO_CMDS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
    static PENDING_STUDIO_CLICK: RefCell<Option<(f64, f64)>> = const { RefCell::new(None) };
}

#[wasm_bindgen]
pub fn studio_control(cmd: &str) {
    PENDING_STUDIO_CMDS.with(|slot| {
        slot.borrow_mut().push(cmd.to_string());
    });
}

#[wasm_bindgen]
pub fn studio_pointer_click(norm_x: f64, norm_y: f64) {
    PENDING_STUDIO_CLICK.with(|slot| {
        *slot.borrow_mut() = Some((norm_x.clamp(0.0, 1.0), norm_y.clamp(0.0, 1.0)));
    });
}

#[wasm_bindgen]
pub fn mount_studio(
    canvas_id: &str,
    steps_per_frame: u32,
    sink: &js_sys::Function,
) -> Result<(), JsValue> {
    use crate::studio::{PATCH_COLS, PATCH_ROWS, StudioCockpit};

    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let spf = steps_per_frame.clamp(1, 3) as usize;
    let cockpit = Rc::new(RefCell::new(StudioCockpit::new()));
    let sink = sink.clone();

    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let mut st = cockpit.borrow_mut();
        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;

        PENDING_STUDIO_CLICK.with(|slot| {
            if let Some((nx, ny)) = slot.borrow_mut().take() {
                let _ = st.handle_canvas_click(nx, ny, cw, ch);
            }
        });

        PENDING_STUDIO_CMDS.with(|slot| {
            let mut cmds = slot.borrow_mut();
            for cmd in cmds.drain(..) {
                match cmd.as_str() {
                    "toggle_payload" => st.toggle_payload(),
                    "inject_contact" => st.inject_contact(),
                    "toggle_link" => st.toggle_link_loss(),
                    "surge_tank" => st.drain_tank_surge(),
                    "retinal_burst" => st.trigger_retinal_burst(),
                    "reset" => st.reset(),
                    _ => {}
                }
            }
        });

        let t0 = now_ns();
        let mut last_rep = None;
        for _ in 0..spf {
            last_rep = Some(st.step());
        }
        let wall_ns = (now_ns() - t0).max(0.0);

        // Background: Machined Carbon Surface
        ctx.set_fill_style_str("rgba(11, 14, 19, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        // Top Direct-Canvas Hardware Control Bar (0 DOM buttons needed!)
        let btn_x0 = 16.0;
        let gap = 8.0;
        let bw = (cw - 32.0 - gap * 5.0) / 6.0;
        let buttons: [(&str, bool, &str); 6] = [
            (
                if st.heavy_payload {
                    "[1] PAYLOAD: 45kg (3x)"
                } else {
                    "[1] +3x PAYLOAD (15kg)"
                },
                st.heavy_payload,
                "rgba(245, 158, 11, 0.92)",
            ),
            (
                "[2] $0 TOUCH IMPACT",
                st.contact_pulse_ticks > 0,
                "rgba(244, 63, 94, 0.92)",
            ),
            (
                if st.link_online {
                    "[3] MGTP LINK: LIVE"
                } else {
                    "[3] MGTP: LINK LOST"
                },
                !st.link_online,
                "rgba(244, 63, 94, 0.92)",
            ),
            (
                "[4] SURGE TANK VALVE",
                st.surge_ticks > 0,
                "rgba(56, 189, 248, 0.92)",
            ),
            (
                "[5] RETINAL SWEEP",
                st.retinal_burst_ticks > 0,
                "rgba(16, 185, 129, 0.92)",
            ),
            ("[6] RESET COCKPIT", false, "rgba(148, 163, 184, 0.7)"),
        ];

        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        for (idx, (label, active, accent)) in buttons.iter().enumerate() {
            let bx = btn_x0 + (idx as f64) * (bw + gap);
            ctx.set_fill_style_str(if *active {
                "rgba(30, 41, 59, 0.95)"
            } else {
                "rgba(17, 23, 33, 0.95)"
            });
            ctx.fill_rect(bx, 8.0, bw, 32.0);
            ctx.set_stroke_style_str(if *active {
                accent
            } else {
                "rgba(51, 65, 85, 0.85)"
            });
            ctx.set_line_width(if *active { 1.6 } else { 1.0 });
            ctx.stroke_rect(bx, 8.0, bw, 32.0);
            ctx.set_fill_style_str(if *active {
                "rgba(248, 250, 252, 0.98)"
            } else {
                "rgba(203, 213, 225, 0.92)"
            });
            let _ = ctx.fill_text(label, bx + 9.0, 28.0);
        }

        if let Some(rep) = &last_rep {
            // ── Pane 1 (Top-Left): Tiny Latent MPPI Foresight + RLS Braking Field ──
            let p1x = 16.0;
            let p1y = 50.0;
            let p1w = cw * 0.51 - 22.0;
            let p1h = 278.0;

            ctx.set_fill_style_str("rgba(15, 20, 28, 0.96)");
            ctx.fill_rect(p1x, p1y, p1w, p1h);
            ctx.set_stroke_style_str("rgba(45, 58, 76, 0.9)");
            ctx.set_line_width(1.0);
            ctx.stroke_rect(p1x, p1y, p1w, p1h);

            let map_x = |wx: f64| p1x + 12.0 + (wx / 18.0) * (p1w - 24.0);
            let map_y = |wy: f64| p1y + 30.0 + (1.0 - wy / 10.0) * (p1h - 42.0);
            let scale_m = (p1w - 24.0) / 18.0;

            // Subtle 2m grid
            ctx.set_stroke_style_str("rgba(30, 41, 59, 0.65)");
            ctx.set_line_width(0.7);
            for gx_m in (2..18).step_by(2) {
                let gx = map_x(gx_m as f64);
                ctx.begin_path();
                ctx.move_to(gx, p1y + 28.0);
                ctx.line_to(gx, p1y + p1h - 10.0);
                ctx.stroke();
            }

            // Obstacles
            for &(ox, oy, rad) in &st.obstacles_xyr {
                let cx = map_x(ox);
                let cy = map_y(oy);
                ctx.set_fill_style_str("rgba(244, 63, 94, 0.16)");
                ctx.begin_path();
                let _ = ctx.arc(cx, cy, (rad + 0.35) * scale_m, 0.0, core::f64::consts::TAU);
                ctx.fill();
                ctx.set_fill_style_str("rgba(225, 29, 72, 0.80)");
                ctx.begin_path();
                let _ = ctx.arc(cx, cy, rad * scale_m, 0.0, core::f64::consts::TAU);
                ctx.fill();
            }

            // Goal waypoint
            let gx = map_x(rep.goal_xy.0);
            let gy = map_y(rep.goal_xy.1);
            ctx.set_stroke_style_str("rgba(16, 185, 129, 0.95)");
            ctx.set_line_width(1.8);
            ctx.begin_path();
            let _ = ctx.arc(gx, gy, 8.0, 0.0, core::f64::consts::TAU);
            ctx.stroke();

            // 16 FWHT Latent MPPI Rollouts Fan
            for (rk, rpath) in rep.rollout_paths.iter().enumerate() {
                if rpath.len() < 2 {
                    continue;
                }
                ctx.set_stroke_style_str(if rk == 0 {
                    "rgba(52, 211, 153, 0.92)"
                } else {
                    "rgba(56, 189, 248, 0.28)"
                });
                ctx.set_line_width(if rk == 0 { 2.2 } else { 1.0 });
                ctx.begin_path();
                for (si, &(wx, wy)) in rpath.iter().enumerate() {
                    let sx = map_x(wx.clamp(0.2, 17.8));
                    let sy = map_y(wy.clamp(0.2, 9.8));
                    if si == 0 {
                        ctx.move_to(sx, sy);
                    } else {
                        ctx.line_to(sx, sy);
                    }
                }
                ctx.stroke();
            }

            // Robot trail
            if st.trail_xy.len() > 1 {
                ctx.set_stroke_style_str("rgba(148, 163, 184, 0.45)");
                ctx.set_line_width(1.4);
                ctx.begin_path();
                for (ti, &(tx, ty)) in st.trail_xy.iter().enumerate() {
                    if ti == 0 {
                        ctx.move_to(map_x(tx), map_y(ty));
                    } else {
                        ctx.line_to(map_x(tx), map_y(ty));
                    }
                }
                ctx.stroke();
            }

            // Robot + Adaptive RLS Certified Braking Halo
            let rx = map_x(rep.pose.0);
            let ry = map_y(rep.pose.1);
            ctx.set_stroke_style_str(if rep.heavy_payload {
                "rgba(245, 158, 11, 0.88)"
            } else {
                "rgba(56, 189, 248, 0.78)"
            });
            ctx.set_line_width(1.6);
            ctx.begin_path();
            let _ = ctx.arc(
                rx,
                ry,
                rep.braking_radius_m * scale_m,
                0.0,
                core::f64::consts::TAU,
            );
            ctx.stroke();

            ctx.set_fill_style_str("rgba(16, 185, 129, 0.98)");
            ctx.begin_path();
            let _ = ctx.arc(rx, ry, 6.2, 0.0, core::f64::consts::TAU);
            ctx.fill();

            ctx.set_fill_style_str("rgba(241, 245, 249, 0.96)");
            let _ = ctx.fill_text(
                &format!(
                    "PANE A · LATENT MPPI (16x8 FWHT) | RLS {:.1}/{:.0}kg | Decel {:.2}m/s²",
                    rep.est_mass_kg, rep.true_mass_kg, rep.cert_decel_ms2
                ),
                p1x + 10.0,
                p1y + 18.0,
            );

            // ── Pane 2 (Top-Right): EventPatchGate 16x12 Retinal Sparsity ──
            let p2x = p1x + p1w + 12.0;
            let p2y = p1y;
            let p2w = cw - p2x - 16.0;
            let p2h = p1h;

            ctx.set_fill_style_str("rgba(15, 20, 28, 0.96)");
            ctx.fill_rect(p2x, p2y, p2w, p2h);
            ctx.set_stroke_style_str("rgba(45, 58, 76, 0.9)");
            ctx.stroke_rect(p2x, p2y, p2w, p2h);

            ctx.set_fill_style_str("rgba(241, 245, 249, 0.96)");
            let _ = ctx.fill_text(
                &format!(
                    "PANE B · RETINAL EVENT GATE (16x12 Δlog I)  |  SKIP {:.1}%  |  ACTIVE {}/192",
                    rep.skip_ratio * 100.0,
                    rep.active_patches.len()
                ),
                p2x + 10.0,
                p2y + 18.0,
            );

            let mut active_mask = [false; PATCH_COLS * PATCH_ROWS];
            for &idx in &rep.active_patches {
                if idx < active_mask.len() {
                    active_mask[idx] = true;
                }
            }
            let cell_w = (p2w - 28.0) / (PATCH_COLS as f64);
            let cell_h = (p2h - 46.0) / (PATCH_ROWS as f64);
            for r in 0..PATCH_ROWS {
                for c in 0..PATCH_COLS {
                    let fired = active_mask[r * PATCH_COLS + c];
                    let cx = p2x + 14.0 + (c as f64) * cell_w;
                    let cy = p2y + 30.0 + (r as f64) * cell_h;
                    ctx.set_fill_style_str(if fired {
                        "rgba(34, 211, 238, 0.88)"
                    } else {
                        "rgba(23, 31, 44, 0.88)"
                    });
                    ctx.fill_rect(cx, cy, cell_w - 2.0, cell_h - 2.0);
                }
            }

            // ── Pane 3 (Bottom-Left): Spinal Tank + $0 Touch + T-MAC / CfC ──
            let p3x = p1x;
            let p3y = p1y + p1h + 12.0;
            let p3w = p1w;
            let p3h = ch - p3y - 14.0;

            ctx.set_fill_style_str("rgba(15, 20, 28, 0.96)");
            ctx.fill_rect(p3x, p3y, p3w, p3h);
            ctx.set_stroke_style_str("rgba(45, 58, 76, 0.9)");
            ctx.stroke_rect(p3x, p3y, p3w, p3h);

            ctx.set_fill_style_str("rgba(241, 245, 249, 0.96)");
            let _ = ctx.fill_text(
                "PANE C · PASSIVITY TANK · $0 MOMENTUM TOUCH · T-MAC LUT4 + CfC",
                p3x + 10.0,
                p3y + 18.0,
            );

            // Tank vertical bar
            let tx = p3x + 16.0;
            let ty = p3y + 34.0;
            let th_bar = p3h - 54.0;
            ctx.set_fill_style_str("rgba(23, 31, 44, 0.95)");
            ctx.fill_rect(tx, ty, 34.0, th_bar);
            let fill_frac = (rep.tank_energy_j / 12.0).clamp(0.0, 1.0);
            let fill_h = th_bar * fill_frac;
            ctx.set_fill_style_str(if rep.tank_clamped {
                "rgba(245, 158, 11, 0.92)"
            } else {
                "rgba(16, 185, 129, 0.88)"
            });
            ctx.fill_rect(tx, ty + (th_bar - fill_h), 34.0, fill_h);
            ctx.set_fill_style_str("rgba(203, 213, 225, 0.92)");
            let _ = ctx.fill_text(
                &format!("Tank {:.2}J", rep.tank_energy_j),
                tx + 44.0,
                ty + 18.0,
            );
            let _ = ctx.fill_text(
                &format!("Valve α={:.2}", rep.valve_scale),
                tx + 44.0,
                ty + 38.0,
            );
            let _ = ctx.fill_text("E_min=0.25J", tx + 44.0, ty + 58.0);
            let _ = ctx.fill_text("T-MAC: 0 muls", tx + 44.0, ty + 82.0);
            let _ = ctx.fill_text(
                &format!("LUT y0={:+.2}", rep.tmac_y0),
                tx + 44.0,
                ty + 102.0,
            );

            // $0 Virtual Touch Dial
            let dial_cx = p3x + 225.0;
            let dial_cy = p3y + p3h * 0.56;
            let dial_r = (p3h * 0.34).min(56.0);
            ctx.set_stroke_style_str("rgba(71, 85, 105, 0.85)");
            ctx.set_line_width(1.2);
            ctx.begin_path();
            let _ = ctx.arc(dial_cx, dial_cy, dial_r, 0.0, core::f64::consts::TAU);
            ctx.stroke();

            let f_mag = rep.contact_wrench_xy[0].hypot(rep.contact_wrench_xy[1]);
            let f_scale = (dial_r / 140.0).min(0.6);
            let vx_px = (rep.contact_wrench_xy[0] * f_scale).clamp(-dial_r, dial_r);
            let vy_px = (-rep.contact_wrench_xy[1] * f_scale).clamp(-dial_r, dial_r);
            ctx.set_stroke_style_str(if f_mag > 35.0 {
                "rgba(244, 63, 94, 0.98)"
            } else {
                "rgba(56, 189, 248, 0.95)"
            });
            ctx.set_line_width(2.4);
            ctx.begin_path();
            ctx.move_to(dial_cx, dial_cy);
            ctx.line_to(dial_cx + vx_px, dial_cy + vy_px);
            ctx.stroke();
            ctx.set_fill_style_str("rgba(203, 213, 225, 0.92)");
            let _ = ctx.fill_text(
                &format!("$0 Touch {:.1}N", f_mag),
                dial_cx - 42.0,
                dial_cy + dial_r + 16.0,
            );

            // CfC Liquid Reflex Waveform
            let wx = p3x + 305.0;
            let wy = p3y + 34.0;
            let ww = p3w - 318.0;
            let wh = p3h - 50.0;
            ctx.set_fill_style_str("rgba(11, 15, 22, 0.92)");
            ctx.fill_rect(wx, wy, ww, wh);
            if st.cfc_history.len() > 1 {
                ctx.set_stroke_style_str("rgba(167, 139, 250, 0.95)");
                ctx.set_line_width(1.8);
                ctx.begin_path();
                for (hi, &hv) in st.cfc_history.iter().enumerate() {
                    let hx = wx + 6.0 + (hi as f64 / 95.0) * (ww - 12.0);
                    let hy = wy + wh * 0.5 - hv.clamp(-1.0, 1.0) * (wh * 0.40);
                    if hi == 0 {
                        ctx.move_to(hx, hy);
                    } else {
                        ctx.line_to(hx, hy);
                    }
                }
                ctx.stroke();
            }
            ctx.set_fill_style_str("rgba(148, 163, 184, 0.92)");
            let _ = ctx.fill_text("CfC Liquid State (ODE-free)", wx + 8.0, wy + 15.0);

            // ── Pane 4 (Bottom-Right): 48-Byte MGTP001 Binary DataTrack Inspector ──
            let p4x = p2x;
            let p4y = p3y;
            let p4w = p2w;
            let p4h = p3h;

            ctx.set_fill_style_str("rgba(15, 20, 28, 0.96)");
            ctx.fill_rect(p4x, p4y, p4w, p4h);
            ctx.set_stroke_style_str("rgba(45, 58, 76, 0.9)");
            ctx.stroke_rect(p4x, p4y, p4w, p4h);

            ctx.set_fill_style_str("rgba(241, 245, 249, 0.96)");
            let _ = ctx.fill_text(
                &format!(
                    "PANE D · MGTP001 48B WIRE | CRC {:08X} | {}",
                    rep.mgtp_crc32,
                    if rep.link_online {
                        "LIVEKIT ONLINE"
                    } else {
                        "PASSIVE BRAKE"
                    }
                ),
                p4x + 10.0,
                p4y + 18.0,
            );

            ctx.set_font("10.5px ui-monospace, SFMono-Regular, Menlo, monospace");
            for row in 0..3 {
                let ry_hex = p4y + 42.0 + (row as f64) * 22.0;
                for col in 0..16 {
                    let b_idx = row * 16 + col;
                    let byte_v = rep.mgtp_wire[b_idx];
                    let color = if b_idx < 8 {
                        "rgba(196, 181, 253, 0.96)" // Header
                    } else if b_idx < 24 {
                        "rgba(56, 189, 248, 0.96)" // Tick + Energy pJ
                    } else if b_idx < 44 {
                        "rgba(52, 211, 153, 0.96)" // Q15 Pose/Vel/Wrench/Tank
                    } else {
                        "rgba(251, 191, 36, 0.98)" // IEEE CRC-32
                    };
                    ctx.set_fill_style_str(color);
                    let _ = ctx.fill_text(
                        &format!("{byte_v:02X}"),
                        p4x + 12.0 + (col as f64) * ((p4w - 24.0) / 16.0),
                        ry_hex,
                    );
                }
            }

            // Wire size comparison: 48B MGTP001 vs ~468B JSON
            let bar_y0 = p4y + 114.0;
            ctx.set_fill_style_str("rgba(52, 211, 153, 0.92)");
            ctx.fill_rect(p4x + 12.0, bar_y0, 44.0, 12.0);
            ctx.set_fill_style_str("rgba(226, 232, 240, 0.95)");
            let _ = ctx.fill_text(
                "MGTP001 Binary: 48 B · 0 alloc · 0 UTF-8 parse (9.7x smaller)",
                p4x + 64.0,
                bar_y0 + 10.0,
            );

            ctx.set_fill_style_str("rgba(100, 116, 139, 0.55)");
            ctx.fill_rect(p4x + 12.0, bar_y0 + 20.0, (p4w - 28.0) * 0.85, 12.0);
            ctx.set_fill_style_str("rgba(148, 163, 184, 0.92)");
            let _ = ctx.fill_text(
                "Legacy JSON WebSocket: ~468 B + GC pause",
                p4x + 18.0,
                bar_y0 + 30.0,
            );

            ctx.set_fill_style_str(if rep.link_online {
                "rgba(148, 163, 184, 0.92)"
            } else {
                "rgba(244, 63, 94, 0.98)"
            });
            let _ = ctx.fill_text(
                &format!(
                    "v_applied = ({:.2} m/s, {:+.2} rad/s)  ·  missed_ticks = {}  ·  0 DOM reflows/frame",
                    rep.vel_applied.0, rep.vel_applied.1, rep.missed_ticks
                ),
                p4x + 12.0,
                p4y + p4h - 12.0,
            );

            emit_receipt(
                &sink,
                "sovereign_studio_baremetal_tick",
                "L0Closed",
                spf as u64,
                wall_ns,
                rep.bit_ops,
            );
        }

        if let Some(cb) = f.borrow().as_ref() {
            schedule(cb);
        }
    }) as Box<dyn FnMut()>));

    if let Some(cb) = g.borrow().as_ref() {
        schedule(cb);
    }
    std::mem::forget(g);
    Ok(())
}

// ── LittleBit-2 + FWHT Anytime Edge Arena (`/exhibits/littlebit`) ────

thread_local! {
    static PENDING_LITTLEBIT_CMD: RefCell<Option<String>> = const { RefCell::new(None) };
}

#[wasm_bindgen]
pub fn littlebit_control(cmd: &str) {
    PENDING_LITTLEBIT_CMD.with(|slot| {
        *slot.borrow_mut() = Some(cmd.to_string());
    });
}

#[wasm_bindgen]
pub fn mount_littlebit(
    canvas_id: &str,
    steps_per_frame: u32,
    sink: &js_sys::Function,
) -> Result<(), JsValue> {
    use crate::littlebit_exhibit::LittleBitArena;
    use mgai_littlebit::EdgeRoute;

    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let spf = steps_per_frame.clamp(1, 4) as usize;
    let arena = Rc::new(RefCell::new(LittleBitArena::new()));
    let sink = sink.clone();

    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let mut st = arena.borrow_mut();

        PENDING_LITTLEBIT_CMD.with(|slot| {
            if let Some(cmd) = slot.borrow_mut().take() {
                match cmd.as_str() {
                    "cycle_rank" => st.cycle_rank(),
                    "cycle_depth" => st.cycle_depth(),
                    "toggle_itq" => st.toggle_itq(),
                    "toggle_cloud" => st.toggle_cloud_link(),
                    "inject_ambiguous" => st.inject_ambiguous_burst(32),
                    "reset" => st.reset(),
                    _ => {}
                }
            }
        });

        let t0 = now_ns();
        let mut last_rep = None;
        for _ in 0..spf {
            last_rep = Some(st.step());
        }
        let wall_ns = (now_ns() - t0).max(0.0);

        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;

        // Background
        ctx.set_fill_style_str("rgba(8, 12, 20, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        let heat_color = |val: f64| -> String {
            let v = (val / 3.2).clamp(-1.0, 1.0);
            if v >= 0.0 {
                let c = (35.0 + 205.0 * v) as u8;
                let g_c = (45.0 + 150.0 * v) as u8;
                format!("rgb(18, {g_c}, {c})")
            } else {
                let a = -v;
                let r = (45.0 + 200.0 * a) as u8;
                let b = (55.0 + 120.0 * a) as u8;
                format!("rgb({r}, 26, {b})")
            }
        };

        // 1. Left panels: Dense FP32 (32×32 subblock of 128×128) vs LittleBit-2 Binary Sandwich
        let cell = 4.6;
        let hm_y = 74.0;
        let hm1_x = 20.0;
        let hm2_x = 186.0;
        let view_dim = st.dim.min(32);

        for r in 0..view_dim {
            for c in 0..view_dim {
                ctx.set_fill_style_str(&heat_color(st.w_dense[r][c]));
                ctx.fill_rect(
                    hm1_x + (c as f64) * cell,
                    hm_y + (r as f64) * cell,
                    cell - 0.4,
                    cell - 0.4,
                );
                if let Some(row_hat) = st.cached_w_hat.get(r)
                    && let Some(&vh) = row_hat.get(c)
                {
                    ctx.set_fill_style_str(&heat_color(vh));
                    ctx.fill_rect(
                        hm2_x + (c as f64) * cell,
                        hm_y + (r as f64) * cell,
                        cell - 0.4,
                        cell - 0.4,
                    );
                }
            }
        }

        ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.set_fill_style_str("rgba(148, 163, 184, 0.95)");
        let _ = ctx.fill_text("Dense FP32 (32 bpw)", hm1_x, hm_y - 8.0);
        ctx.set_fill_style_str("rgba(56, 189, 248, 0.98)");
        let _ = ctx.fill_text(
            &format!(
                "LittleBit-2 ({:.2} bpw, ITQ:{})",
                last_rep.as_ref().map_or(0.25, |r| r.bits_per_weight),
                if st.use_itq { "1" } else { "0" }
            ),
            hm2_x,
            hm_y - 8.0,
        );

        // 2. Right-top panel: FWHT Anytime Depth Ladder + Compression Bar Chart
        let rx = 372.0;
        let rw = cw - rx - 20.0;
        ctx.set_fill_style_str("rgba(226, 232, 240, 0.95)");
        let _ = ctx.fill_text(
            &format!(
                "Cactus FWHT Anytime Ladder (active depth {}/4 · rank r={}+{})",
                st.active_depth,
                st.active_rank,
                st.active_rank / 2
            ),
            rx,
            hm_y - 8.0,
        );

        let block_w = (rw - 30.0) / 4.0;
        for d_idx in 0..4 {
            let bx = rx + (d_idx as f64) * (block_w + 10.0);
            let active = d_idx < st.active_depth;
            ctx.set_fill_style_str(if active {
                "rgba(34, 211, 238, 0.22)"
            } else {
                "rgba(30, 41, 59, 0.45)"
            });
            ctx.fill_rect(bx, hm_y, block_w, 46.0);
            ctx.set_stroke_style_str(if active {
                "rgba(34, 211, 238, 0.9)"
            } else {
                "rgba(71, 85, 105, 0.5)"
            });
            ctx.set_line_width(1.3);
            ctx.stroke_rect(bx, hm_y, block_w, 46.0);

            ctx.set_fill_style_str(if active {
                "rgba(248, 250, 252, 0.96)"
            } else {
                "rgba(100, 116, 139, 0.85)"
            });
            let _ = ctx.fill_text(&format!("FWHT #{}", d_idx + 1), bx + 8.0, hm_y + 20.0);
            ctx.set_fill_style_str("rgba(148, 163, 184, 0.85)");
            let _ = ctx.fill_text(
                if active { "1792 adds" } else { "skipped" },
                bx + 8.0,
                hm_y + 37.0,
            );
        }

        // Bits-per-weight comparison bars
        let bpw_now = last_rep.as_ref().map_or(0.25, |r| r.bits_per_weight);
        let bars = [
            ("FP16 Dense", 16.0, "rgba(148, 163, 184, 0.55)"),
            ("Cactus INT2", 2.0, "rgba(167, 139, 250, 0.78)"),
            ("BitNet b1.58", 1.58, "rgba(96, 165, 250, 0.82)"),
            ("LittleBit-2", bpw_now, "rgba(34, 211, 238, 0.98)"),
        ];
        for (bi, (name, bpw_val, col)) in bars.iter().enumerate() {
            let by = hm_y + 66.0 + (bi as f64) * 23.0;
            ctx.set_fill_style_str("rgba(203, 213, 225, 0.9)");
            let _ = ctx.fill_text(name, rx, by + 11.0);
            let bar_x = rx + 98.0;
            let max_bar = rw - 170.0;
            let w_px = ((bpw_val / 16.0) * max_bar).max(3.0);
            ctx.set_fill_style_str(col);
            ctx.fill_rect(bar_x, by, w_px, 13.0);
            ctx.set_fill_style_str("rgba(226, 232, 240, 0.95)");
            let _ = ctx.fill_text(&format!("{bpw_val:.2} bpw"), bar_x + w_px + 8.0, by + 11.0);
        }

        // 3. Bottom full-width panel: Conformal Edge Router Trace (s_t vs PID q_t)
        let gx = 20.0;
        let gy = 266.0;
        let gw = cw - 40.0;
        let gh = 192.0;

        ctx.set_fill_style_str("rgba(15, 23, 42, 0.75)");
        ctx.fill_rect(gx, gy, gw, gh);
        ctx.set_stroke_style_str("rgba(51, 65, 85, 0.8)");
        ctx.set_line_width(1.0);
        ctx.stroke_rect(gx, gy, gw, gh);

        ctx.set_fill_style_str("rgba(226, 232, 240, 0.95)");
        let _ = ctx.fill_text(
            &format!(
                "Conformal PID Hybrid Router (s_t vs q_t)  ·  local={}  escalate={}  offline_abstain={}  ·  cloud={}",
                st.local_commits,
                st.cloud_escalations,
                st.offline_abstains,
                if st.cloud_reachable {
                    "ONLINE"
                } else {
                    "AIRGAPPED"
                }
            ),
            gx + 12.0,
            gy + 19.0,
        );

        let plot_top = gy + 32.0;
        let plot_h = gh - 44.0;
        let n_pts = st.trace_history.len();
        if n_pts > 1 {
            // PID conformal threshold q_t line (violet dashed-feel)
            ctx.set_stroke_style_str("rgba(167, 139, 250, 0.92)");
            ctx.set_line_width(1.8);
            ctx.begin_path();
            for (idx, &(_, qt, _)) in st.trace_history.iter().enumerate() {
                let px = gx + 12.0 + (idx as f64 / 119.0) * (gw - 24.0);
                let py = plot_top + plot_h * (1.0 - qt.clamp(0.0, 1.0));
                if idx == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();

            // Nonconformity score s_t line + route dots
            ctx.set_stroke_style_str("rgba(56, 189, 248, 0.92)");
            ctx.set_line_width(2.0);
            ctx.begin_path();
            for (idx, &(st_v, _, _)) in st.trace_history.iter().enumerate() {
                let px = gx + 12.0 + (idx as f64 / 119.0) * (gw - 24.0);
                let py = plot_top + plot_h * (1.0 - st_v.clamp(0.0, 1.0));
                if idx == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();

            for (idx, &(st_v, _, route)) in st.trace_history.iter().enumerate() {
                if route != EdgeRoute::LocalCommit {
                    let px = gx + 12.0 + (idx as f64 / 119.0) * (gw - 24.0);
                    let py = plot_top + plot_h * (1.0 - st_v.clamp(0.0, 1.0));
                    ctx.set_fill_style_str(if route == EdgeRoute::EscalateCloud {
                        "rgba(251, 191, 36, 0.98)"
                    } else {
                        "rgba(244, 63, 94, 0.98)"
                    });
                    ctx.begin_path();
                    let _ = ctx.arc(px, py, 3.2, 0.0, core::f64::consts::TAU);
                    ctx.fill();
                }
            }
        }

        // Top HUD + bottom legend
        if let Some(rep) = &last_rep {
            ctx.set_font("12px ui-monospace, SFMono-Regular, Menlo, monospace");
            ctx.set_fill_style_str("rgba(248, 250, 252, 0.98)");
            let route_str = match rep.route {
                EdgeRoute::LocalCommit => "LOCAL_COMMIT",
                EdgeRoute::EscalateCloud => "ESCALATE_CLOUD",
                EdgeRoute::OfflineAbstain => "OFFLINE_ABSTAIN",
            };
            let _ = ctx.fill_text(
                &format!(
                    "{:.2} bpw  |  MGBIT: {} / {} B ({:.1}×)  |  COS: {:.3}  |  ROUTE: {}",
                    rep.bits_per_weight,
                    rep.mgbit_bytes,
                    rep.fp32_bytes,
                    (rep.fp32_bytes as f64) / (rep.mgbit_bytes.max(1) as f64),
                    rep.cosine_vs_dense,
                    route_str,
                ),
                20.0,
                24.0,
            );
            ctx.set_fill_style_str("rgba(148, 163, 184, 0.95)");
            let _ = ctx.fill_text(
                &format!(
                    "rel Frobenius err: {:.3}  ·  nonconformity s_t: {:.3}  ·  PID q_t: {:.3}  ·  bit-ops/step: {}",
                    rep.rel_frobenius_err,
                    rep.nonconformity,
                    rep.conformal_threshold,
                    rep.bit_ops
                ),
                20.0,
                44.0,
            );

            ctx.set_font("11px ui-monospace, SFMono-Regular, Menlo, monospace");
            ctx.set_fill_style_str("rgba(148, 163, 184, 0.90)");
            let _ = ctx.fill_text(
                "cyan = s_t (LOCAL_COMMIT)  ·  violet = PID threshold q_t  ·  amber = ESCALATE_CLOUD  ·  rose = OFFLINE_ABSTAIN",
                20.0,
                ch - 10.0,
            );

            emit_receipt(
                &sink,
                "littlebit2_fwht_anytime_step",
                "L0Closed",
                spf as u64,
                wall_ns,
                rep.bit_ops,
            );
        }

        if let Some(cb) = f.borrow().as_ref() {
            schedule(cb);
        }
    }) as Box<dyn FnMut()>));

    if let Some(cb) = g.borrow().as_ref() {
        schedule(cb);
    }
    std::mem::forget(g);
    Ok(())
}

// ═══════════════════════════════════════════════════════════════════
// Unified Agent-Native Physical AI Workbench (`/workbench`)
// ═══════════════════════════════════════════════════════════════════

thread_local! {
    static ACTIVE_WORKBENCH: RefCell<Option<Rc<RefCell<crate::workbench::WorkbenchState>>>> = const { RefCell::new(None) };
}

fn with_workbench<R>(f: impl FnOnce(&mut crate::workbench::WorkbenchState) -> R) -> Option<R> {
    ACTIVE_WORKBENCH.with(|slot| {
        let borrow = slot.borrow();
        let rc = borrow.as_ref()?;
        let mut st = rc.borrow_mut();
        Some(f(&mut st))
    })
}

#[wasm_bindgen]
pub fn workbench_mcp_tools_json() -> String {
    mgai_mcp::mcp_tool_definitions().to_string()
}

#[wasm_bindgen]
pub fn workbench_mcp_call(tool_name: &str, args_json: &str) -> String {
    let args: serde_json::Value =
        serde_json::from_str(args_json).unwrap_or_else(|_| serde_json::json!({}));
    match mgai_mcp::execute_mcp_tool(tool_name, &args) {
        Ok(v) => serde_json::json!({ "ok": true, "result": v }).to_string(),
        Err(e) => serde_json::json!({ "ok": false, "error": e }).to_string(),
    }
}

#[wasm_bindgen]
pub fn workbench_get_state_json() -> String {
    with_workbench(|st| st.summary_json().to_string())
        .unwrap_or_else(|| serde_json::json!({"ready": false}).to_string())
}

#[wasm_bindgen]
pub fn workbench_export_firmware_tar(project_name: &str) -> Vec<u8> {
    with_workbench(|st| st.export_firmware_tar_bytes(project_name).unwrap_or_default())
        .unwrap_or_default()
}

#[wasm_bindgen]
pub fn workbench_export_mcap() -> Vec<u8> {
    with_workbench(|st| st.export_mcap_bytes()).unwrap_or_default()
}

#[wasm_bindgen]
pub fn workbench_import_mcap(bytes: &[u8]) -> i32 {
    with_workbench(|st| st.import_mcap_bytes(bytes).map_or(-1, |n| n as i32)).unwrap_or(-1)
}

#[wasm_bindgen]
pub fn workbench_ingest_mgtp_serial(bytes: &[u8]) -> bool {
    with_workbench(|st| st.ingest_live_mgtp_frame(bytes)).unwrap_or(false)
}

#[wasm_bindgen]
pub fn workbench_encode_hil_tx(protocol: &str) -> Vec<u8> {
    with_workbench(|st| st.encode_hil_tx_frame(protocol)).unwrap_or_default()
}

#[wasm_bindgen]
pub fn workbench_ingest_hil_rx(protocol: &str, bytes: &[u8]) -> u32 {
    with_workbench(|st| st.ingest_hil_rx_bytes(protocol, bytes) as u32).unwrap_or(0)
}

#[wasm_bindgen]
pub fn workbench_inspect_mcap_tail(file_size: f64, tail_bytes: &[u8]) -> String {
    with_workbench(|st| match st.inspect_mcap_tail_slice(file_size.max(0.0) as u64, tail_bytes) {
        Ok(v) => serde_json::json!({"ok": true, "tail": v}).to_string(),
        Err(e) => serde_json::json!({"ok": false, "error": e}).to_string(),
    })
    .unwrap_or_else(|| serde_json::json!({"ok": false, "error": "workbench not mounted"}).to_string())
}

#[wasm_bindgen]
pub fn workbench_counterfactual_mcap(bytes: &[u8]) -> String {
    with_workbench(|st| {
        let res = if bytes.is_empty() {
            st.run_demo_counterfactual()
        } else {
            st.run_counterfactual_on_bytes(bytes)
        };
        match res {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}).to_string(),
            Err(e) => serde_json::json!({"ok": false, "error": e}).to_string(),
        }
    })
    .unwrap_or_else(|| serde_json::json!({"ok": false, "error": "workbench not mounted"}).to_string())
}

#[wasm_bindgen]
pub fn workbench_compile_safetensors(bytes: &[u8]) -> String {
    with_workbench(|st| match st.compile_safetensors(Some(bytes)) {
        Ok(rep) => serde_json::json!({"ok": true, "report": rep}).to_string(),
        Err(e) => serde_json::json!({"ok": false, "error": e}).to_string(),
    })
    .unwrap_or_else(|| serde_json::json!({"ok": false, "error": "workbench not mounted"}).to_string())
}

#[wasm_bindgen]
pub fn workbench_export_c99_header() -> Vec<u8> {
    with_workbench(|st| st.export_c99_header_bytes()).unwrap_or_default()
}

#[wasm_bindgen]
pub fn workbench_export_conformity_dossier() -> String {
    with_workbench(|st| match st.generate_conformity_dossier() {
        Ok(bundle) => serde_json::json!({"ok": true, "bundle": bundle}).to_string(),
        Err(e) => serde_json::json!({"ok": false, "error": e}).to_string(),
    })
    .unwrap_or_else(|| serde_json::json!({"ok": false, "error": "workbench not mounted"}).to_string())
}

#[wasm_bindgen]
pub fn workbench_export_parquet() -> Vec<u8> {
    with_workbench(|st| st.export_parquet_bytes()).unwrap_or_default()
}

#[wasm_bindgen]
pub fn workbench_import_parquet(bytes: &[u8]) -> String {
    with_workbench(|st| match st.import_parquet_bytes(bytes) {
        Ok(v) => serde_json::json!({"ok": true, "parquet": v}).to_string(),
        Err(e) => serde_json::json!({"ok": false, "error": e}).to_string(),
    })
    .unwrap_or_else(|| serde_json::json!({"ok": false, "error": "workbench not mounted"}).to_string())
}

#[wasm_bindgen]
pub fn workbench_ingest_ws_text(raw_json: &str) -> String {
    with_workbench(|st| match st.ingest_ws_text(raw_json) {
        Ok(out) => serde_json::json!({"ok": true, "outcome": out}).to_string(),
        Err(e) => serde_json::json!({"ok": false, "error": e}).to_string(),
    })
    .unwrap_or_else(|| serde_json::json!({"ok": false, "error": "workbench not mounted"}).to_string())
}

#[wasm_bindgen]
pub fn workbench_ingest_ws_binary(bytes: &[u8]) -> String {
    with_workbench(|st| match st.ingest_ws_binary(bytes) {
        Ok(out) => serde_json::json!({"ok": true, "outcome": out}).to_string(),
        Err(e) => serde_json::json!({"ok": false, "error": e}).to_string(),
    })
    .unwrap_or_else(|| serde_json::json!({"ok": false, "error": "workbench not mounted"}).to_string())
}

#[wasm_bindgen]
pub fn workbench_export_wgsl_shader() -> String {
    with_workbench(|st| {
        st.parallel_train_report
            .as_ref()
            .map(|r| r.wgsl_compute_shader.clone())
            .unwrap_or_else(|| mgai_deploy::parallel_train::generate_lut4_rollout_wgsl(64))
    })
    .unwrap_or_else(|| mgai_deploy::parallel_train::generate_lut4_rollout_wgsl(64))
}

#[wasm_bindgen]
pub fn workbench_execute_op(op_json: &str) -> String {
    use crate::workbench::{WorkbenchMode, WorkbenchState};
    let v: serde_json::Value = match serde_json::from_str(op_json) {
        Ok(val) => val,
        Err(e) => return serde_json::json!({"ok": false, "error": format!("{e}")}).to_string(),
    };
    let op = v.get("op").and_then(serde_json::Value::as_str).unwrap_or("");

    with_workbench(|st| match op {
        "set_mode" => {
            let m = v.get("mode").and_then(serde_json::Value::as_str).unwrap_or("sim");
            st.mode = WorkbenchMode::from_slug(m);
            serde_json::json!({"ok": true, "mode": st.mode.slug()})
        }
        "set_embodiment" => {
            let slug = v.get("preset").and_then(serde_json::Value::as_str).unwrap_or("so101");
            let ok = st.select_preset(slug);
            serde_json::json!({"ok": ok, "embodiment": st.urdf_model.name, "dof": st.safety_env.dof_count})
        }
        "load_xml" => {
            let xml = v.get("xml").and_then(serde_json::Value::as_str).unwrap_or("");
            match st.load_custom_xml(xml) {
                Ok(msg) => serde_json::json!({"ok": true, "message": msg}),
                Err(err) => serde_json::json!({"ok": false, "error": err}),
            }
        }
        "get_xml" => {
            let fmt = v.get("format").and_then(serde_json::Value::as_str).unwrap_or("mjcf");
            let xml = if fmt.eq_ignore_ascii_case("urdf") {
                st.current_urdf_xml()
            } else if fmt.eq_ignore_ascii_case("usda") || fmt.eq_ignore_ascii_case("usd") {
                st.current_usda_text()
            } else {
                st.current_mjcf_xml()
            };
            serde_json::json!({"ok": true, "format": fmt, "xml": xml})
        }
        "set_target" => {
            let tid = v.get("target_id").and_then(serde_json::Value::as_str).unwrap_or("rp2350");
            let ok = st.select_target(tid);
            serde_json::json!({"ok": ok, "target": st.target_id})
        }
        "set_params" => {
            if let Some(m) = v.get("mass_kg").and_then(serde_json::Value::as_f64) {
                st.user_mass_kg = m.clamp(0.2, 120.0);
            }
            if let Some(emin) = v.get("tank_e_min_j").and_then(serde_json::Value::as_f64) {
                st.tank_e_min_j = emin.clamp(0.05, 5.0);
            }
            if let Some(fcap) = v.get("iso_force_cap_n").and_then(serde_json::Value::as_f64) {
                st.iso_force_cap_n = fcap.clamp(5.0, 400.0);
            }
            if let Some(rk) = v.get("littlebit_rank").and_then(serde_json::Value::as_u64) {
                st.littlebit_rank = (rk as usize).clamp(1, 8);
                st.recompile_preview();
            }
            if let Some(hz) = v.get("control_hz").and_then(serde_json::Value::as_u64) {
                st.control_hz = (hz as u32).clamp(25, 1000);
            }
            serde_json::json!({"ok": true})
        }
        "set_playing" => {
            let p = v.get("playing").and_then(serde_json::Value::as_bool).unwrap_or(!st.playing);
            st.playing = p;
            if p {
                st.scrub_index = None;
            }
            serde_json::json!({"ok": true, "playing": st.playing})
        }
        "step_once" => {
            st.playing = false;
            st.scrub_index = None;
            let snap = st.step();
            serde_json::json!({"ok": true, "tick": snap.tick})
        }
        "scrub_to" => {
            if let Some(idx) = v.get("index").and_then(serde_json::Value::as_u64) {
                st.playing = false;
                let clamped = (idx as usize).min(st.history.len().saturating_sub(1));
                st.scrub_index = Some(clamped);
            } else {
                st.scrub_index = None;
            }
            serde_json::json!({"ok": true, "scrub_index": st.scrub_index})
        }
        "orbit_camera" => {
            let dyaw = v.get("dyaw").and_then(serde_json::Value::as_f64).unwrap_or(0.0);
            let dpitch = v.get("dpitch").and_then(serde_json::Value::as_f64).unwrap_or(0.0);
            let dzoom = v.get("dzoom").and_then(serde_json::Value::as_f64).unwrap_or(0.0);
            st.cam_yaw += dyaw;
            st.cam_pitch = (st.cam_pitch + dpitch).clamp(0.18, 1.35);
            st.cam_zoom = (st.cam_zoom * (1.0 + dzoom)).clamp(0.55, 2.2);
            serde_json::json!({"ok": true})
        }
        "select_obstacle" => {
            st.selected_obstacle = v
                .get("index")
                .and_then(serde_json::Value::as_u64)
                .map(|i| i as usize);
            serde_json::json!({"ok": true, "selected": st.selected_obstacle})
        }
        "move_obstacle" => {
            let idx = v.get("index").and_then(serde_json::Value::as_u64).unwrap_or(0) as usize;
            let nx = v.get("x").and_then(serde_json::Value::as_f64).unwrap_or(8.0).clamp(1.2, 16.8);
            let ny = v.get("y").and_then(serde_json::Value::as_f64).unwrap_or(5.0).clamp(1.2, 8.8);
            if let Some(obs) = st.obstacles_xyr.get_mut(idx) {
                obs.0 = nx;
                obs.1 = ny;
                st.selected_obstacle = Some(idx);
            }
            serde_json::json!({"ok": true})
        }
        "spawn_obstacle" => {
            let ox = v.get("x").and_then(serde_json::Value::as_f64).unwrap_or(11.8).clamp(1.5, 16.5);
            let oy = v.get("y").and_then(serde_json::Value::as_f64).unwrap_or(6.2).clamp(1.5, 8.5);
            let orad = v.get("r").and_then(serde_json::Value::as_f64).unwrap_or(0.75).clamp(0.3, 1.6);
            if st.obstacles_xyr.len() < 8 {
                st.obstacles_xyr.push((ox, oy, orad));
                st.selected_obstacle = Some(st.obstacles_xyr.len() - 1);
            }
            serde_json::json!({"ok": true, "obstacle_count": st.obstacles_xyr.len()})
        }
        "push_robot" => {
            let fx = v.get("fx").and_then(serde_json::Value::as_f64).unwrap_or(0.0).clamp(-180.0, 180.0);
            let fy = v.get("fy").and_then(serde_json::Value::as_f64).unwrap_or(0.0).clamp(-180.0, 180.0);
            st.ext_push_xy = [fx, fy];
            serde_json::json!({"ok": true, "ext_push_xy": st.ext_push_xy})
        }
        "set_teleop" => {
            let tv = v.get("v").and_then(serde_json::Value::as_f64).unwrap_or(0.0).clamp(0.0, 2.1);
            let tom = v.get("omega").and_then(serde_json::Value::as_f64).unwrap_or(0.0).clamp(-2.2, 2.2);
            st.teleop_cmd = Some((tv, tom));
            serde_json::json!({"ok": true})
        }
        "clear_teleop" => {
            st.teleop_cmd = None;
            serde_json::json!({"ok": true})
        }
        "inject_fault" => {
            let kind = v.get("kind").and_then(serde_json::Value::as_str).unwrap_or("");
            match kind {
                "contact" => st.contact_pulse_ticks = 22,
                "toggle_link" => {
                    st.link_online = !st.link_online;
                    if st.link_online {
                        st.missed_ticks = 0;
                    }
                }
                "surge_tank" => st.surge_ticks = 28,
                "retinal_burst" => st.retinal_burst_ticks = 36,
                "heavy_3x" => {
                    st.user_mass_kg = if st.user_mass_kg > 25.0 { 15.0 } else { 45.0 };
                }
                _ => {}
            }
            serde_json::json!({"ok": true, "kind": kind})
        }
        "run_demo_counterfactual" => match st.run_demo_counterfactual() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "clear_counterfactual" => {
            st.counterfactual_report = None;
            serde_json::json!({"ok": true})
        }
        "compile_demo_safetensors" => match st.compile_safetensors(None) {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "compile_demo_model" => {
            let fmt = v.get("format").and_then(serde_json::Value::as_str).unwrap_or("onnx");
            match st.compile_model_checkpoint(None, fmt) {
                Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
                Err(e) => serde_json::json!({"ok": false, "error": e}),
            }
        }
        "solve_ik" => {
            let tx = v.get("x").and_then(serde_json::Value::as_f64).unwrap_or(0.16);
            let ty = v.get("y").and_then(serde_json::Value::as_f64).unwrap_or(0.08);
            let tz = v.get("z").and_then(serde_json::Value::as_f64).unwrap_or(0.42);
            let rec = st.solve_ik_target([tx, ty, tz]);
            serde_json::json!({"ok": true, "receipt": rec})
        }
        "clear_ik" => {
            st.ik_target_xyz = None;
            st.ik_joint_positions.clear();
            st.last_collision_report = None;
            serde_json::json!({"ok": true})
        }
        "train_parallel" => {
            let worlds = v.get("num_worlds").and_then(serde_json::Value::as_u64).unwrap_or(48) as usize;
            let gens = v.get("generations").and_then(serde_json::Value::as_u64).unwrap_or(6) as usize;
            match st.run_parallel_trainer(worlds, gens) {
                Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
                Err(e) => serde_json::json!({"ok": false, "error": e}),
            }
        }
        "toggle_swarm" => {
            let peers = st.toggle_swarm_fleet();
            serde_json::json!({"ok": true, "active_peers": peers})
        }
        "run_vla_chunk" => {
            let instr = v
                .get("instruction")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("pick red mug and avoid pillar");
            match st.run_vla_chunk(instr) {
                Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
                Err(e) => serde_json::json!({"ok": false, "error": e}),
            }
        }
        "toggle_zmp" => {
            st.show_zmp_overlay = !st.show_zmp_overlay;
            let zrep = st.compute_live_zmp();
            serde_json::json!({"ok": true, "show_zmp_overlay": st.show_zmp_overlay, "report": zrep})
        }
        "scan_esdf" => match st.run_pointcloud_esdf_scan() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "synthesize_grasp" => {
            let fingers = v
                .get("finger_count")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(3) as usize;
            let rep = st.run_grasp_synthesis(fingers);
            serde_json::json!({"ok": true, "report": rep})
        }
        "plan_scurve" => {
            let traj = st.run_scurve_planner();
            serde_json::json!({"ok": true, "trajectory": traj})
        }
        "run_sysid" => {
            let rep = st.run_sim2real_sysid();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ekf" => {
            let rep = st.run_se3_odometry_ekf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "splat_to_esdf" => {
            let ply = v.get("ply_text").and_then(serde_json::Value::as_str);
            match st.run_splat_to_esdf(ply) {
                Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
                Err(e) => serde_json::json!({"ok": false, "error": e}),
            }
        }
        "run_bimanual" => {
            let rep = st.run_bimanual_coop();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_rt_jitter" => {
            let rep = st.run_rt_jitter_audit();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_osc" => {
            let rep = st.run_osc_impedance();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_foc_thermal" => {
            let rep = st.run_foc_thermal();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_slam" => {
            let rep = st.run_pose_graph_slam();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_aerial_so3" => {
            let rep = st.run_aerial_so3();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_wb_qp" => {
            let rep = st.run_wholebody_qp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ibvs" => {
            let rep = st.run_fiducial_ibvs();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_rov" => {
            let rep = st.run_rov_fossen();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_battery_droop" => {
            let rep = st.run_battery_droop();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_contact_lcp" => {
            let rep = st.run_contact_lcp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_tendon" => {
            let rep = st.run_tendon_alloc();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ackermann" => {
            let rep = st.run_ackermann_moose();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sensorless_pmsm" => {
            let rep = st.run_sensorless_pmsm();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_mesh_inertia" => {
            let txt = v.get("mesh_text").and_then(serde_json::Value::as_str);
            match st.run_mesh_inertia(txt) {
                Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
                Err(e) => serde_json::json!({"ok": false, "error": e}),
            }
        }
        "run_lut6_reflex" => {
            let rep = st.run_lut6_reflex();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_srbd_mpc" => {
            let rep = st.run_srbd_mpc();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_rts_smooth" => {
            let rep = st.run_rts_smoother();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_clothoid" => {
            let rep = st.run_clothoid_corridor();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sea_harmonic" => {
            let rep = st.run_sea_harmonic();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_uwb_multilat" => {
            let rep = st.run_uwb_multilat();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_payload_swing" => {
            let rep = st.run_payload_swing();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_actuator_rul" => {
            let rep = st.run_actuator_rul();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_soft_pam" => {
            let rep = st.run_soft_pam();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_imu_preint" => {
            let rep = st.run_imu_preint();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_spa_hybrid" => {
            let rep = st.run_spa_hybrid();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_harvester_eno" => {
            let rep = st.run_harvester_eno();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_continuum_pcc" => {
            let rep = st.run_continuum_pcc();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_extrinsic_sync" => {
            let rep = st.run_extrinsic_sync();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_swerve_holonomic" => {
            let rep = st.run_swerve_holonomic();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_radar_ttc" => {
            let rep = st.run_radar_ttc();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_vtol_transition" => {
            let rep = st.run_vtol_transition();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_rolling_shutter" => {
            let rep = st.run_rolling_shutter();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_regen_braking" => {
            let rep = st.run_regen_braking();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_peg_in_hole" => {
            let rep = st.run_peg_in_hole();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_cdpr_alloc" => {
            let rep = st.run_cdpr_alloc();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_dvs_flow" => {
            let rep = st.run_dvs_flow();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_vacuum_suction" => {
            let rep = st.run_vacuum_suction();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_inductive_dock" => {
            let rep = st.run_inductive_dock();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_hydraulic_valve" => {
            let rep = st.run_hydraulic_valve();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_acoustic_doa" => {
            let rep = st.run_acoustic_doa();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_vic_passivity" => {
            let rep = st.run_vic_passivity();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_cold_battery" => {
            let rep = st.run_cold_battery();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_inkling_looped_moe" => {
            let rep = st.run_inkling_looped_moe();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_frontier_hub" => {
            let surp = v.get("surprise").and_then(serde_json::Value::as_f64).unwrap_or(0.68);
            let lat = v.get("latency_ms").and_then(serde_json::Value::as_f64).unwrap_or(40.0);
            let cloud = v.get("cloud_online").and_then(serde_json::Value::as_bool).unwrap_or(false);
            let rep = st.run_frontier_hub(surp, lat, cloud);
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_wam_shield" => {
            let rep = st.run_wam_shield();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_agent_lease" => {
            let rep = st.run_agent_lease();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_flow_matching" => {
            let rep = st.run_flow_matching_vla();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_nvfp4_quant" => {
            let rep = st.run_nvfp4_quant();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_vision_tome" => {
            let rep = st.run_vision_tome();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_webgpu_sched" => {
            let rep = st.run_webgpu_scheduler();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_spec_decode" => {
            let rep = st.run_speculative_decode();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_mamba2_ssd" => {
            let rep = st.run_mamba2_ssd();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_a2a_auction" => {
            let rep = st.run_a2a_auction();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sink_kv" => {
            let rep = st.run_sink_kv_cache();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_gelsight_tactile" => {
            let rep = st.run_gelsight_tactile();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_lidar_icp_degen" => {
            let rep = st.run_lidar_icp_degen();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_push_recovery" => {
            let rep = st.run_push_recovery();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_canopen_srdo" => {
            let rep = st.run_canopen_srdo();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_surgical_rcm" => {
            let rep = st.run_surgical_rcm();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_gnss_rtk_spoof" => {
            let rep = st.run_gnss_rtk_spoof();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_skyhook_susp" => {
            let rep = st.run_skyhook_suspension();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_disagg_slo" => {
            let rep = st.run_disagg_slo();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_dual_quat" => {
            let rep = st.run_dual_quat_sclerp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_piezo_bw" => {
            let rep = st.run_piezo_bouc_wen();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_usv_colregs" => {
            let rep = st.run_usv_colregs();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_online_lora" => {
            let rep = st.run_online_lora_clamp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_peristaltic_cbf" => {
            let rep = st.run_peristaltic_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_tof_mpi" => {
            let rep = st.run_tof_mpi_gate();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_pem_cbf" => {
            let rep = st.run_pem_fuel_cell();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ptp_sync" => {
            let rep = st.run_ptp_servo();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_aerial_perch" => {
            let rep = st.run_aerial_perching();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_encoder_calib" => {
            let rep = st.run_encoder_calib();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_dea_cbf" => {
            let rep = st.run_dea_elastomer();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_rag_gate" => {
            let rep = st.run_rag_twin_gate();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jackknife_cbf" => {
            let rep = st.run_jackknife_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_lif_reflex" => {
            let rep = st.run_spiking_lif();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_bekker_cbf" => {
            let rep = st.run_bekker_rover();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_iso13849_cat4" => {
            let rep = st.run_iso13849_cat4();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_laser_weld" => {
            let rep = st.run_laser_meltpool();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_stereo_lrc" => {
            let rep = st.run_stereo_lrc();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_maglev_cbf" => {
            let rep = st.run_maglev_airgap();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_opcua_uadp" => {
            let rep = st.run_opcua_uadp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_rehab_exo" => {
            let rep = st.run_rehab_exoskeleton();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_baro_optflow" => {
            let rep = st.run_baro_optflow();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_rwa_bdot" => {
            let rep = st.run_spacecraft_rwa();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_hamming_knn" => {
            let rep = st.run_binary_hamming();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_agri_sprayer" => {
            let rep = st.run_agri_sprayer();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sar_pga" => {
            let rep = st.run_sar_pga();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_cable_cbf" => {
            let rep = st.run_deformable_cable();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_local_dp" => {
            let rep = st.run_local_dp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_foothold_cbf" => {
            let rep = st.run_foothold_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_tabuada_ncs" => {
            let rep = st.run_tabuada_ncs();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_solid_state_cbf" => {
            let rep = st.run_solid_state_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_webrtc_teleop" => {
            let rep = st.run_webrtc_teleop();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_flex_zvdd" => {
            let rep = st.run_flexible_link();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_thermal_rgb" => {
            let rep = st.run_thermal_hotspot();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_epm_latch" => {
            let rep = st.run_epm_gripper();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ensemble_gate" => {
            let rep = st.run_frontier_ensemble();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_underwater_modem" => {
            let rep = st.run_underwater_modem();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_gantry_cbf" => {
            let rep = st.run_gantry_crane();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_prosthetic_knee" => {
            let rep = st.run_prosthetic_knee();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_merkle_audit" => {
            let rep = st.run_merkle_audit();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ballbot_cbf" => {
            let rep = st.run_ballbot_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_hyperspectral" => {
            let rep = st.run_hyperspectral();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_varpitch_prop" => {
            let rep = st.run_varpitch_prop();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_seqlock_shm" => {
            let rep = st.run_seqlock_shm();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_spindle_chatter" => {
            let rep = st.run_spindle_chatter();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_vio_slip" => {
            let rep = st.run_vio_wheel_slip();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_peltier_cbf" => {
            let rep = st.run_peltier_dewpoint();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ulp_cert" => {
            let rep = st.run_cross_lang_ulp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_snake_cbf" => {
            let rep = st.run_serpenoid_snake();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_multicam_ba" => {
            let rep = st.run_multicam_extrinsic();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_pneumatic_cbf" => {
            let rep = st.run_pneumatic_cushion();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_htn_plan" => {
            let rep = st.run_htn_plan();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_forklift_cbf" => {
            let rep = st.run_forklift_stability();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_polarimetric" => {
            let rep = st.run_polarimetric_stokes();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_esc_demag" => {
            let rep = st.run_esc_bemf_demag();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_webgpu_cap" => {
            let rep = st.run_webgpu_capability();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_mag_catheter" => {
            let rep = st.run_magnetic_catheter();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_janus_dvl" => {
            let rep = st.run_janus_dvl();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_flywheel_kers" => {
            let rep = st.run_flywheel_kers();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ros2_lifecycle" => {
            let rep = st.run_ros2_lifecycle();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_tether_drone" => {
            let rep = st.run_tethered_drone();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_wifi_ftm" => {
            let rep = st.run_wifi_ftm_csi();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_syringe_cbf" => {
            let rep = st.run_syringe_infusion();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_kv_int4" => {
            let rep = st.run_kv_cache_int4();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_dual_drone_beam" => {
            let rep = st.run_dual_drone_beam();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_star_tracker" => {
            let rep = st.run_star_tracker();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_autoclave_cbf" => {
            let rep = st.run_autoclave_cure();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_agent_sandbox" => {
            let rep = st.run_agent_tool_sandbox();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_capstone_cert" => {
            let rep = st.run_capstone_pipeline();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_fleet_ledger" => {
            let rep = st.run_fleet_conformity();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_handover_cbf" => {
            let rep = st.run_human_handover();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_clock_audit" => {
            let rep = st.run_multimodal_clock();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_featherstone_aba" => {
            let rep = st.run_featherstone_aba();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_multilayer_graph" => match st.run_multilayer_graph() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_dagger_bc" => match st.run_dagger_bc() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_dag_sched" => {
            let rep = st.run_deterministic_dag();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_al_ilqr" => {
            let rep = st.run_al_ilqr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_robust_tube" => {
            let rep = st.run_robust_tube_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_3dgs_cbf" => {
            let rep = st.run_gaussian_splat_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ota_ab" => {
            let rep = st.run_ota_ab_rollback();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_cross_emb" => {
            let rep = st.run_cross_embodiment();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_hil_bode" => {
            let rep = st.run_hil_phase_margin();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_joule_pareto" => {
            let rep = st.run_joule_pareto_suite();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v7_conformance" => {
            let rep = st.run_v7_ecosystem_check();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_diff_contact" => {
            let rep = st.run_diff_contact_grad();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_parallel_chomp" => {
            let rep = st.run_parallel_chomp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sos_funnel" => {
            let rep = st.run_sos_funnel();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_xpbd_cbf" => {
            let rep = st.run_xpbd_softbody();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_force_flow" => {
            let rep = st.run_force_guided_flow();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_cbs_mapf" => {
            let rep = st.run_cbs_mapf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_gp_cbf" => {
            let rep = st.run_gp_residual_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_conformal_tube" => {
            let rep = st.run_conformal_world_tube();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_stl_shield" => {
            let rep = st.run_stl_shield();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_downwash_cbf" => {
            let rep = st.run_downwash_ground_effect();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_loco_manip" => {
            let rep = st.run_loco_manip_wbc();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_dice_tpm" => {
            let rep = st.run_dice_attestation();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_bridge_codegen" => {
            let rep = st.run_universal_bridges();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sub1bit_qat" => match st.run_sub1bit_qat() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rlds_transcode" => match st.run_rlds_transcode() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_v8_supremacy" => {
            let rep = st.run_v8_supremacy();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_q32_spine" => {
            let rep = st.run_q32_spine();
            serde_json::json!({"ok": true, "report": rep, "q32_header": st.emit_q32_header_source()})
        }
        "run_verilog_rtl" => {
            let rep = st.run_verilog_rtl();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_stream_dag" => match st.run_stream_dag() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_unified_vla_hal" => {
            let rep = st.run_unified_vla_hal();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_vision_servo" => {
            let rep = st.run_vision_servo();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_gjk_epa" => {
            let rep = st.run_gjk_epa();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_gcs_corridor" => match st.run_gcs_corridor() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_deepc_hankel" => match st.run_deepc_hankel() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_bond_graph" => {
            let rep = st.run_bond_graph();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_zonotope_contractor" => {
            let rep = st.run_zonotope_contractor();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_pcc_mesh" => {
            let rep = st.run_pcc_mesh();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_codesign_bom" => match st.run_codesign_bom() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_scm_blame" => {
            let rep = st.run_scm_blame();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_pbit_ising" => {
            let rep = st.run_pbit_ising();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_rt_driver_loop" => match st.run_rt_driver_loop() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_v9_fruition" => match st.run_v9_fruition() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_littlebit_mosaic" => match st.run_littlebit_mosaic() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_cactus_needle" => {
            let rep = st.run_cactus_needle();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_liquid_lfm2" => {
            let rep = st.run_liquid_lfm2();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_mosaic_scheduler" => {
            let rep = st.run_mosaic_scheduler();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_crossfabric_bridge" => match st.run_crossfabric_bridge() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_speculative_mosaic" => {
            let rep = st.run_speculative_mosaic();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_microllm_mcp" => {
            let rep = st.run_microllm_mcp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_vlm_affordance" => {
            let rep = st.run_vlm_affordance();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_world_sandbox" => {
            let rep = st.run_world_sandbox();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_q32_microblock" => {
            let rep = st.run_q32_microblock();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_heterogeneous_hil" => {
            let rep = st.run_heterogeneous_hil();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v10_mosaic" => match st.run_v10_mosaic() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_hf_distill" => match st.run_hf_distill() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_token_bench" => {
            let rep = st.run_token_bench();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_interactive_mosaic" => {
            let rep = st.run_interactive_mosaic();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v11_openweight" => match st.run_v11_openweight() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_wgsl_lfm2" => {
            let rep = st.run_wgsl_lfm2();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_m55_wcet" => {
            let rep = st.run_m55_wcet();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_mosaic_closed_loop" => {
            let rep = st.run_mosaic_closed_loop();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v12_silicon_webgpu" => match st.run_v12_silicon_webgpu() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_fleet_mosaic" => {
            let rep = st.run_fleet_mosaic();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_retinal_webcam" => {
            let rep = st.run_retinal_webcam();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_tri_usb" => {
            let rep = st.run_tri_usb();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v13_swarm_retinal" => match st.run_v13_swarm_retinal() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_peer_mesh_gossip" => {
            let rep = st.run_peer_mesh_gossip();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_audio_retinal_sto" => {
            let rep = st.run_audio_retinal_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_lut4_timing" => {
            let rep = st.run_ice40_lut4_timing();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v14_multipeer_fpga" => match st.run_v14_multipeer_fpga() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_ice40_pcf_bundle" => {
            let rep = st.run_ice40_pcf_bundle();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_webrtc_lan_qr" => {
            let rep = st.run_webrtc_lan_qr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_online_sleep_crys" => {
            let rep = st.run_online_sleep_crys();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v15_crystallized" => match st.run_v15_crystallized() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_ice40_bin_crc16" => {
            let rep = st.run_ice40_bin_crc16();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_webrtc_two_way" => {
            let rep = st.run_webrtc_two_way();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sblut4_hotswap" => {
            let rep = st.run_sblut4_hotswap();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v16_hmi4" => match st.run_v16_hmi4() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_webusb_cram_stream" => {
            let rep = st.run_webusb_cram_stream();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_qr_camera_mesh" => {
            let rep = st.run_qr_camera_mesh();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_lfm2_to_sblut4_distill" => match st.run_lfm2_to_sblut4_distill() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_v17_hmi41" => match st.run_v17_hmi41() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_pio_daisy" => {
            let rep = st.run_rp2350_pio_daisy();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_pcc_lut4_gossip" => {
            let rep = st.run_sctp_pcc_lut4_gossip();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_regime_shift_remelt" => {
            let rep = st.run_regime_shift_remelt();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v18_hmi42" => match st.run_v18_hmi42() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_uf2_autoboot" => {
            let rep = st.run_rp2350_uf2_autoboot();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_multilimb_shard" => {
            let rep = st.run_multilimb_shard();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_federated_dp_crys" => {
            let rep = st.run_federated_dp_crys();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v19_hmi43" => match st.run_v19_hmi43() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_picobin_ab" => {
            let rep = st.run_rp2350_picobin_ab();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_manchester_lvds_tether" => {
            let rep = st.run_manchester_lvds_tether();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_zk_rdp_accountant" => {
            let rep = st.run_zk_rdp_accountant();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v20_hmi44" => match st.run_v20_hmi44() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_trng_auth" => {
            let rep = st.run_rp2350_trng_auth();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_stereo_lvds_retinal" => {
            let rep = st.run_stereo_lvds_retinal();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_rp2350_amp_wcet" => {
            let rep = st.run_rp2350_amp_wcet();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v21_hmi45" => match st.run_v21_hmi45() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_glitch_rcp" => {
            let rep = st.run_rp2350_glitch_rcp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_mac16_dsp" => {
            let rep = st.run_ice40_sb_mac16_dsp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_stereo_voxel" => {
            let rep = st.run_sctp_stereo_voxel();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v22_hmi46" => match st.run_v22_hmi46() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_accessctrl_sau" => {
            let rep = st.run_rp2350_accessctrl_sau();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_spram_bank" => {
            let rep = st.run_ice40_sb_spram_bank();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_mgbit_canary" => {
            let rep = st.run_sctp_mgbit_canary();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v23_hmi47" => match st.run_v23_hmi47() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_qmi_xip" => {
            let rep = st.run_rp2350_qmi_xip();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_hard_bus" => {
            let rep = st.run_ice40_sb_hard_bus();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_blackbox_quorum" => {
            let rep = st.run_sctp_blackbox_quorum();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v24_hmi48" => match st.run_v24_hmi48() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_hstx_spine" => {
            let rep = st.run_rp2350_hstx_spine();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_osc_watchdog" => {
            let rep = st.run_ice40_osc_watchdog();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_q32_conformal" => {
            let rep = st.run_sctp_q32_conformal();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v25_hmi49" => match st.run_v25_hmi49() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_dma_sniffer" => {
            let rep = st.run_rp2350_dma_sniffer();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_ebr_dualport" => {
            let rep = st.run_ice40_ebr_dualport();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_ph_tank_ledger" => {
            let rep = st.run_sctp_ph_tank_ledger();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v26_hmi50" => match st.run_v26_hmi50() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_pwm_chopper" => {
            let rep = st.run_rp2350_pwm_chopper();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_pll40_mux" => {
            let rep = st.run_ice40_pll40_mux();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_cbf_split" => {
            let rep = st.run_sctp_cbf_split();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v27_hmi51" => match st.run_v27_hmi51() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_adc_wdg" => {
            let rep = st.run_rp2350_adc_wdg();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_io_ddr" => {
            let rep = st.run_ice40_sb_io_ddr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_ptp_skew" => {
            let rep = st.run_sctp_ptp_skew();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v28_hmi52" => match st.run_v28_hmi52() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_wdg_psm" => {
            let rep = st.run_rp2350_wdg_psm();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_rp2350_sio_spinlock" => {
            let rep = st.run_rp2350_sio_spinlock();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_warmboot" => {
            let rep = st.run_ice40_sb_warmboot();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_clf_cbf" => {
            let rep = st.run_sctp_clf_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v29_hmi53" => match st.run_v29_hmi53() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_powman_bod" => {
            let rep = st.run_rp2350_powman_bod();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_carry" => {
            let rep = st.run_ice40_sb_carry();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_hj_brt" => {
            let rep = st.run_sctp_hj_brt();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v30_hmi54" => match st.run_v30_hmi54() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_ticks_timer" => {
            let rep = st.run_rp2350_ticks_timer();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_dffesr" => {
            let rep = st.run_ice40_sb_dffesr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_dcbf" => {
            let rep = st.run_sctp_dcbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v31_hmi55" => match st.run_v31_hmi55() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_pll_clocks" => {
            let rep = st.run_rp2350_pll_clocks();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_rgba" => {
            let rep = st.run_ice40_sb_rgba();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_hocbf" => {
            let rep = st.run_sctp_hocbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v32_hmi56" => match st.run_v32_hmi56() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_bootram_guard" => {
            let rep = st.run_rp2350_bootram_guard();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_filter50ns" => {
            let rep = st.run_ice40_sb_filter50ns();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_zoh_cbf" => {
            let rep = st.run_sctp_zoh_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v33_hmi57" => match st.run_v33_hmi57() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_busctrl_pad" => {
            let rep = st.run_rp2350_busctrl_pad();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_io_od" => {
            let rep = st.run_ice40_sb_io_od();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_issf_cbf" => {
            let rep = st.run_sctp_issf_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v34_hmi58" => match st.run_v34_hmi58() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_resets_syscfg" => {
            let rep = st.run_rp2350_resets_syscfg();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_io_i3c" => {
            let rep = st.run_ice40_sb_io_i3c();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_delay_cbf" => {
            let rep = st.run_sctp_delay_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v35_hmi59" => match st.run_v35_hmi59() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_xosc_interp" => {
            let rep = st.run_rp2350_xosc_interp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_pll2f" => {
            let rep = st.run_ice40_sb_pll2f();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_drcvar_cbf" => {
            let rep = st.run_sctp_drcvar_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v36_hmi60" => match st.run_v36_hmi60() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_rosc_tbman" => {
            let rep = st.run_rp2350_rosc_tbman();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_gb_io" => {
            let rep = st.run_ice40_sb_gb_io();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_racbf" => {
            let rep = st.run_sctp_racbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v37_hmi61" => match st.run_v37_hmi61() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_usb_mpu" => {
            let rep = st.run_rp2350_usb_mpu();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_dffnesr" => {
            let rep = st.run_ice40_sb_dffnesr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_backup_cbf" => {
            let rep = st.run_sctp_backup_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v38_hmi62" => match st.run_v38_hmi62() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_uart_spi" => {
            let rep = st.run_rp2350_uart_spi();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_ram40_ecc" => {
            let rep = st.run_ice40_sb_ram40_ecc();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_ptcbf" => {
            let rep = st.run_sctp_ptcbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v39_hmi63" => match st.run_v39_hmi63() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_i2c_pmp" => {
            let rep = st.run_rp2350_i2c_pmp();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_tmr_sto" => {
            let rep = st.run_ice40_sb_tmr_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_filippov_cbf" => {
            let rep = st.run_sctp_filippov_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v40_hmi64" => match st.run_v40_hmi64() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_sysinfo_archsel" => {
            let rep = st.run_rp2350_sysinfo_archsel();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_async_sto" => {
            let rep = st.run_ice40_sb_async_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_icbf" => {
            let rep = st.run_sctp_icbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v41_hmi65" => match st.run_v41_hmi65() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_coresight_dwt" => {
            let rep = st.run_rp2350_coresight_dwt();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_led_drv_cur" => {
            let rep = st.run_ice40_sb_led_drv_cur();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_ccm_cbf" => {
            let rep = st.run_sctp_ccm_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v42_hmi66" => match st.run_v42_hmi66() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_qspi_vtor" => {
            let rep = st.run_rp2350_qspi_vtor();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_io_ds_lvds" => {
            let rep = st.run_ice40_sb_io_ds_lvds();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_obs_cbf" => {
            let rep = st.run_sctp_obs_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v43_hmi67" => match st.run_v43_hmi67() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_xip_msplim" => {
            let rep = st.run_rp2350_xip_msplim();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_ebr_4knr" => {
            let rep = st.run_ice40_sb_ebr_4knr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_tvcbf" => {
            let rep = st.run_sctp_tvcbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v44_hmi68" => match st.run_v44_hmi68() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_xip_aux_nvic" => {
            let rep = st.run_rp2350_xip_aux_nvic();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_pll_dyndly" => {
            let rep = st.run_ice40_sb_pll_dyndly();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_mm_cbf" => {
            let rep = st.run_sctp_mm_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v45_hmi69" => match st.run_v45_hmi69() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_pio_systick" => {
            let rep = st.run_rp2350_pio_systick();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_ebr_4knrnw" => {
            let rep = st.run_ice40_sb_ebr_4knrnw();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_kcbf" => {
            let rep = st.run_sctp_kcbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v46_hmi70" => match st.run_v46_hmi70() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_resus_fpccr" => {
            let rep = st.run_rp2350_resus_fpccr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_dualrail_1oo2" => {
            let rep = st.run_ice40_sb_dualrail_1oo2();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_scbf" => {
            let rep = st.run_sctp_scbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v47_hmi71" => match st.run_v47_hmi71() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_iobank0_shcsr" => {
            let rep = st.run_rp2350_iobank0_shcsr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_ebr_4knw" => {
            let rep = st.run_ice40_sb_ebr_4knw();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_pac_bayes_cbf" => {
            let rep = st.run_sctp_pac_bayes_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v48_hmi72" => match st.run_v48_hmi72() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_sio_cpuid_cfsr" => {
            let rep = st.run_rp2350_sio_cpuid_cfsr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_dffnr_quad" => {
            let rep = st.run_ice40_sb_dffnr_quad();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_evar_cbf" => {
            let rep = st.run_sctp_evar_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v49_hmi73" => match st.run_v49_hmi73() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_psm_cpacr" => {
            let rep = st.run_rp2350_psm_cpacr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_pll40_2_pad" => {
            let rep = st.run_ice40_sb_pll40_2_pad();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_hellinger_cbf" => {
            let rep = st.run_sctp_hellinger_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v50_hmi74" => match st.run_v50_hmi74() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_sha256_scr" => {
            let rep = st.run_rp2350_sha256_scr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_dffn_sto" => {
            let rep = st.run_ice40_sb_dffn_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_chisq_cbf" => {
            let rep = st.run_sctp_chisq_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v51_hmi75" => match st.run_v51_hmi75() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_chipreset_itns" => {
            let rep = st.run_rp2350_chipreset_itns();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_dffe_wdg" => {
            let rep = st.run_ice40_sb_dffe_wdg();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_jsd_tv_cbf" => {
            let rep = st.run_sctp_jsd_tv_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v52_hmi76" => match st.run_v52_hmi76() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_wakeen_sfsr" => {
            let rep = st.run_rp2350_wakeen_sfsr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_dffner_1oo2" => {
            let rep = st.run_ice40_sb_dffner_1oo2();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_renyi_cbf" => {
            let rep = st.run_sctp_renyi_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v53_hmi77" => match st.run_v53_hmi77() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_dmatimer_hfsr" => {
            let rep = st.run_rp2350_dmatimer_hfsr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_dffess_preset" => {
            let rep = st.run_ice40_sb_dffess_preset();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_mmd_sinkhorn_cbf" => {
            let rep = st.run_sctp_mmd_sinkhorn_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v54_hmi78" => match st.run_v54_hmi78() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_busprio_pxn" => {
            let rep = st.run_rp2350_busprio_pxn();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_dffnsr_1oo2" => {
            let rep = st.run_ice40_sb_dffnsr_1oo2();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_cantelli_cbf" => {
            let rep = st.run_sctp_cantelli_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v55_hmi79" => match st.run_v55_hmi79() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_mempwr_unalign" => {
            let rep = st.run_rp2350_mempwr_unalign();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_dffss_1oo2" => {
            let rep = st.run_ice40_sb_dffss_1oo2();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_gelbrich_cbf" => {
            let rep = st.run_sctp_gelbrich_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v56_hmi80" => match st.run_v56_hmi80() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_timerlock_dfsr" => {
            let rep = st.run_rp2350_timerlock_dfsr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_pll2f_core" => {
            let rep = st.run_ice40_sb_pll2f_core();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_bicausal_cbf" => {
            let rep = st.run_sctp_bicausal_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v57_hmi81" => match st.run_v57_hmi81() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_otplock_demcr" => {
            let rep = st.run_rp2350_otplock_demcr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_sb_rgb_drv" => {
            let rep = st.run_ice40_sb_rgb_drv();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_mot_peacock_cbf" => {
            let rep = st.run_sctp_mot_peacock_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v58_hmi82" => match st.run_v58_hmi82() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_trng_bpu" => {
            let rep = st.run_rp2350_trng_bpu();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ice40_icestorm_50" => {
            let rep = st.run_ice40_icestorm_50();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_gwhk_cbf" => {
            let rep = st.run_sctp_gwhk_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v59_hmi83" => match st.run_v59_hmi83() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_pio1_itm" => {
            let rep = st.run_rp2350_pio1_itm();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ecp5_trellis_dp16kd" => {
            let rep = st.run_ecp5_trellis_dp16kd();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_sbpot_cbf" => {
            let rep = st.run_sctp_sbpot_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v60_hmi84" => match st.run_v60_hmi84() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_pio2_tpiu" => {
            let rep = st.run_rp2350_pio2_tpiu();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ecp5_mult18x18d_ccu2c" => {
            let rep = st.run_ecp5_mult18x18d_ccu2c();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_brma_ot_cbf" => {
            let rep = st.run_sctp_brma_ot_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v61_hmi85" => match st.run_v61_hmi85() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_timer1_dwt" => {
            let rep = st.run_rp2350_timer1_dwt();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ecp5_ehxplll_dcca" => {
            let rep = st.run_ecp5_ehxplll_dcca();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_bbmm_ot_cbf" => {
            let rep = st.run_sctp_bbmm_ot_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v62_hmi86" => match st.run_v62_hmi86() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_i2c1_spi1_dwt" => {
            let rep = st.run_rp2350_i2c1_spi1_dwt();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ecp5_oddr_iddr_delayg" => {
            let rep = st.run_ecp5_oddr_iddr_delayg();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_lvtsw_ot_cbf" => {
            let rep = st.run_sctp_lvtsw_ot_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v63_hmi87" => match st.run_v63_hmi87() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_uart1_interp1_etm" => {
            let rep = st.run_rp2350_uart1_interp1_etm();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ecp5_ddr2x_gearbox" => {
            let rep = st.run_ecp5_ddr2x_gearbox();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_t2srw_ot_cbf" => {
            let rep = st.run_sctp_t2srw_ot_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v64_hmi88" => match st.run_v64_hmi88() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_rp2350_hstxfifo_cpuid" => {
            let rep = st.run_rp2350_hstxfifo_cpuid();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ecp5_ddrdlla_dtr" => {
            let rep = st.run_ecp5_ddrdlla_dtr();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sctp_mtw_radon_cbf" => {
            let rep = st.run_sctp_mtw_radon_cbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v65_hmi89" => match st.run_v65_hmi89() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_lutadapt_tl2_singularbit" => {
            let rep = st.run_lutadapt_tl2_singularbit();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_patternlang_cega_hocbf" => {
            let rep = st.run_patternlang_cega_hocbf();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_scholar_tournament" => {
            let rep = st.run_jouledb_scholar_tournament();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v66_hmi90" => match st.run_v66_hmi90() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_six_kernel_paranoid" => {
            let rep = st.run_six_kernel_paranoid();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jcol_cose_flight" => {
            let rep = st.run_jcol_cose_flight();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sky130_sg13g2_sto" => {
            let rep = st.run_sky130_sg13g2_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v67_hmi91" => match st.run_v67_hmi91() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_lef_def_lvs" => {
            let rep = st.run_sky130_lef_def_lvs();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_wai1_jms1_mitotic" => {
            let rep = st.run_wai1_jms1_mitotic();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ucb_n64_mutants" => {
            let rep = st.run_ucb_n64_mutants();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v68_hmi92" => match st.run_v68_hmi92() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_spef_sdf_gls" => {
            let rep = st.run_sky130_spef_sdf_gls();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_worldcommit_wca_secded" => {
            let rep = st.run_worldcommit_wca_secded();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ucb_omni_ct_isa" => {
            let rep = st.run_ucb_omni_ct_isa();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v69_hmi93" => match st.run_v69_hmi93() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_ngspice_set" => {
            let rep = st.run_sky130_ngspice_set();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_ssi_merge" => {
            let rep = st.run_jouledb_ssi_merge();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_zkt_dit_mlkem768" => {
            let rep = st.run_zkt_dit_mlkem768();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v70_hmi94" => match st.run_v70_hmi94() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_em_nbti_aging" => {
            let rep = st.run_sky130_em_nbti_aging();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_bitemporal_arrow" => {
            let rep = st.run_jouledb_bitemporal_arrow();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ascon_mldsa65_tether" => {
            let rep = st.run_ascon_mldsa65_tether();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v71_hmi95" => match st.run_v71_hmi95() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_caravel_esd_shuttle" => {
            let rep = st.run_sky130_caravel_esd_shuttle();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_zonemap_blackbox" => {
            let rep = st.run_jouledb_zonemap_blackbox();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_tsn_qbv_frer_t1s" => {
            let rep = st.run_tsn_qbv_frer_t1s();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v72_hmi96" => match st.run_v72_hmi96() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_jtag_bist_probe" => {
            let rep = st.run_sky130_jtag_bist_probe();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_roaring_fsst" => {
            let rep = st.run_jouledb_roaring_fsst();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ethercat_fsoe_chopper" => {
            let rep = st.run_ethercat_fsoe_chopper();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v73_hmi97" => match st.run_v73_hmi97() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_qfn24_ssn_thetaja" => {
            let rep = st.run_sky130_qfn24_ssn_thetaja();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_delta_bp128" => {
            let rep = st.run_jouledb_delta_bp128();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_canxl_cansec_e2e_p8" => {
            let rep = st.run_canxl_cansec_e2e_p8();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v74_hmi98" => match st.run_v74_hmi98() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_ibis72_pdn" => {
            let rep = st.run_sky130_ibis72_pdn();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_alp_chimp128" => {
            let rep = st.run_jouledb_alp_chimp128();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_mipi_csi2_v41_cse" => {
            let rep = st.run_mipi_csi2_v41_cse();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v75_hmi99" => match st.run_v75_hmi99() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_cispr25_tvs" => {
            let rep = st.run_sky130_cispr25_tvs();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_vortex_rle_dict" => {
            let rep = st.run_jouledb_vortex_rle_dict();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_mipi_i3c_v111_ibi" => {
            let rep = st.run_mipi_i3c_v111_ibi();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v76_hmi100" => match st.run_v76_hmi100() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_iso16750_loaddump" => {
            let rep = st.run_sky130_iso16750_loaddump();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_rabitq_ann" => {
            let rep = st.run_jouledb_rabitq_ann();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ucie20_pcie60_flit" => {
            let rep = st.run_ucie20_pcie60_flit();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v77_hmi101" => match st.run_v77_hmi101() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_aecq100_latchup" => {
            let rep = st.run_sky130_aecq100_latchup();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_elias_fano" => {
            let rep = st.run_jouledb_elias_fano();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_cxl31_bisnp_sto" => {
            let rep = st.run_cxl31_bisnp_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v78_hmi102" => match st.run_v78_hmi102() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_cppll_jitter" => {
            let rep = st.run_sky130_cppll_jitter();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_binary_fuse" => {
            let rep = st.run_jouledb_binary_fuse();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_lpddr5x_ecc_sto" => {
            let rep = st.run_lpddr5x_ecc_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v79_hmi103" => match st.run_v79_hmi103() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_ptat_tsd" => {
            let rep = st.run_sky130_ptat_tsd();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_wavelet_matrix" => {
            let rep = st.run_jouledb_wavelet_matrix();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_nvme21_t10pi_sto" => {
            let rep = st.run_nvme21_t10pi_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v80_hmi104" => match st.run_v80_hmi104() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_csa_desat" => {
            let rep = st.run_sky130_csa_desat();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_pgm_index" => {
            let rep = st.run_jouledb_pgm_index();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_optical_8023cz_sto" => {
            let rep = st.run_optical_8023cz_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v81_hmi105" => match st.run_v81_hmi105() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_cmti_miller" => {
            let rep = st.run_sky130_cmti_miller();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_surf_filter" => {
            let rep = st.run_jouledb_surf_filter();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_mipi_aphy20_macsec_sto" => {
            let rep = st.run_mipi_aphy20_macsec_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v82_hmi106" => match st.run_v82_hmi106() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_resolver_360" => {
            let rep = st.run_sky130_resolver_360();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_k2tree_polar" => {
            let rep = st.run_jouledb_k2tree_polar();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_ieee8023ch_iet_sto" => {
            let rep = st.run_ieee8023ch_iet_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v83_hmi107" => match st.run_v83_hmi107() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_solar_pli" => {
            let rep = st.run_sky130_solar_pli();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_global_passport" => {
            let rep = st.run_jouledb_global_passport();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_itur_lorawan_oscore_sto" => {
            let rep = st.run_itur_lorawan_oscore_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v84_hmi108" => match st.run_v84_hmi108() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "run_sky130_rv32ec_sm3_sm4" => {
            let rep = st.run_sky130_rv32ec_sm3_sm4();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_jouledb_eu2023_1230_dossier" => {
            let rep = st.run_jouledb_eu2023_1230_dossier();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_sel4_cap_trained_l2_sto" => {
            let rep = st.run_sel4_cap_trained_l2_sto();
            serde_json::json!({"ok": true, "report": rep})
        }
        "run_v85_hmi109" => match st.run_v85_hmi109() {
            Ok(rep) => serde_json::json!({"ok": true, "report": rep}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "generate_dossier" => match st.generate_conformity_dossier() {
            Ok(b) => serde_json::json!({"ok": true, "bundle": b}),
            Err(e) => serde_json::json!({"ok": false, "error": e}),
        },
        "reset" => {
            *st = WorkbenchState::new();
            serde_json::json!({"ok": true})
        }
        _ => serde_json::json!({"ok": false, "error": format!("unknown workbench op '{op}'")}),
    })
    .unwrap_or_else(|| serde_json::json!({"ok": false, "error": "workbench not mounted"}))
    .to_string()
}

#[wasm_bindgen]
pub fn mount_workbench(canvas_id: &str, sink: &js_sys::Function) -> Result<(), JsValue> {
    use crate::workbench::{WB_PATCH_COLS, WB_PATCH_ROWS, WorkbenchState};

    let (canvas, ctx) = ctx_for(canvas_id).ok_or_else(|| JsValue::from_str("canvas not found"))?;
    let state_rc = Rc::new(RefCell::new(WorkbenchState::new()));
    ACTIVE_WORKBENCH.with(|slot| {
        *slot.borrow_mut() = Some(state_rc.clone());
    });
    let sink = sink.clone();

    let f = Rc::new(RefCell::new(None::<Closure<dyn FnMut()>>));
    let g = f.clone();

    *g.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let mut st = state_rc.borrow_mut();

        let t0 = now_ns();
        if st.playing && st.scrub_index.is_none() {
            let _ = st.step();
        } else if st.history.is_empty() {
            let _ = st.step();
        }
        let wall_ns = (now_ns() - t0).max(0.0);

        let cw = canvas.width() as f64;
        let ch = canvas.height() as f64;

        // Background: Precision Machined Carbon
        ctx.set_fill_style_str("rgba(10, 13, 18, 1)");
        ctx.fill_rect(0.0, 0.0, cw, ch);

        let Some(frame) = st.active_frame().cloned() else {
            if let Some(cb) = f.borrow().as_ref() {
                schedule(cb);
            }
            return;
        };

        // ── LEFT STAGE (55% width): Interactive 3D Articulated Embodiment & Arena ──
        let s3x = 12.0;
        let s3y = 12.0;
        let s3w = (cw * 0.55 - 18.0).max(260.0);
        let s3h = (ch - 24.0).max(220.0);

        ctx.set_fill_style_str("rgba(14, 19, 27, 0.98)");
        ctx.fill_rect(s3x, s3y, s3w, s3h);
        ctx.set_stroke_style_str("rgba(45, 58, 76, 0.92)");
        ctx.set_line_width(1.0);
        ctx.stroke_rect(s3x, s3y, s3w, s3h);

        let cx_3d = s3x + s3w * 0.50;
        let cy_3d = s3y + s3h * 0.58;
        let scale_3d = ((s3w.min(s3h)) / 14.5) * st.cam_zoom;
        let (cyaw, syaw) = (st.cam_yaw.cos(), st.cam_yaw.sin());
        let (cpit, spit) = (st.cam_pitch.cos(), st.cam_pitch.sin());

        let proj3d = |wx: f64, wy: f64, wz: f64| -> (f64, f64) {
            let dx = wx - 9.0;
            let dy = wy - 5.0;
            let rx = dx * cyaw - dy * syaw;
            let ry = dx * syaw + dy * cyaw;
            let sx = cx_3d + rx * scale_3d;
            let sy = cy_3d - (ry * spit + wz * cpit * 2.6) * scale_3d;
            (sx, sy)
        };

        // 3D Ground Grid (0..18m x 0..10m)
        ctx.set_stroke_style_str("rgba(30, 41, 59, 0.72)");
        ctx.set_line_width(0.8);
        for gx_i in (0..=18).step_by(2) {
            let (x0, y0) = proj3d(gx_i as f64, 0.0, 0.0);
            let (x1, y1) = proj3d(gx_i as f64, 10.0, 0.0);
            ctx.begin_path();
            ctx.move_to(x0, y0);
            ctx.line_to(x1, y1);
            ctx.stroke();
        }
        for gy_i in (0..=10).step_by(2) {
            let (x0, y0) = proj3d(0.0, gy_i as f64, 0.0);
            let (x1, y1) = proj3d(18.0, gy_i as f64, 0.0);
            ctx.begin_path();
            ctx.move_to(x0, y0);
            ctx.line_to(x1, y1);
            ctx.stroke();
        }

        // 3D MPPI Foresight Fan on Ground Plane
        for (rk, rpath) in st.rollout_paths.iter().enumerate() {
            if rpath.len() < 2 {
                continue;
            }
            ctx.set_stroke_style_str(if rk == 0 {
                "rgba(52, 211, 153, 0.90)"
            } else {
                "rgba(56, 189, 248, 0.22)"
            });
            ctx.set_line_width(if rk == 0 { 2.2 } else { 1.0 });
            ctx.begin_path();
            for (si, &(wx, wy)) in rpath.iter().enumerate() {
                let (px, py) = proj3d(wx, wy, 0.02);
                if si == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();
        }

        // Counterfactual Safety Shield Replay Overlay (3D Ground Plane)
        if let Some(ref cf) = st.counterfactual_report
            && cf.steps.len() >= 2
        {
            ctx.set_stroke_style_str("rgba(244, 63, 94, 0.85)");
            ctx.set_line_width(2.0);
            ctx.begin_path();
            for (si, step) in cf.steps.iter().enumerate() {
                let (px, py) = proj3d(step.recorded_pose_xyt[0], step.recorded_pose_xyt[1], 0.03);
                if si == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();

            ctx.set_stroke_style_str("rgba(167, 139, 250, 0.98)");
            ctx.set_line_width(2.6);
            ctx.begin_path();
            for (si, step) in cf.steps.iter().enumerate() {
                let (px, py) = proj3d(step.shielded_pose_xyt[0], step.shielded_pose_xyt[1], 0.04);
                if si == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();
        }

        // 3D Extruded Obstacles + W Translate Gizmo on Selected Obstacle
        for (oi, &(ox, oy, rad)) in st.obstacles_xyr.iter().enumerate() {
            let (bx, by) = proj3d(ox, oy, 0.0);
            let (tx, ty) = proj3d(ox, oy, 0.55);
            let r_px = (rad * scale_3d * 0.85).max(6.0);
            let selected = st.selected_obstacle == Some(oi);

            ctx.set_fill_style_str("rgba(244, 63, 94, 0.16)");
            ctx.begin_path();
            let _ = ctx.ellipse(bx, by, r_px * 1.35, r_px * 0.75, 0.0, 0.0, core::f64::consts::TAU);
            ctx.fill();

            ctx.set_fill_style_str(if selected {
                "rgba(251, 113, 133, 0.85)"
            } else {
                "rgba(190, 18, 60, 0.72)"
            });
            ctx.begin_path();
            let _ = ctx.ellipse(tx, ty, r_px, r_px * 0.56, 0.0, 0.0, core::f64::consts::TAU);
            ctx.fill();

            ctx.set_stroke_style_str(if selected {
                "rgba(253, 224, 71, 0.95)"
            } else {
                "rgba(244, 63, 94, 0.85)"
            });
            ctx.set_line_width(if selected { 1.8 } else { 1.1 });
            ctx.begin_path();
            ctx.move_to(bx - r_px, by);
            ctx.line_to(tx - r_px, ty);
            ctx.move_to(bx + r_px, by);
            ctx.line_to(tx + r_px, ty);
            ctx.stroke();

            // 3D W-Translate Gizmo Axes on selected obstacle
            if selected {
                let (gx_end, gy_end) = proj3d(ox + 1.1, oy, 0.05);
                ctx.set_stroke_style_str("rgba(248, 113, 113, 0.98)");
                ctx.set_line_width(2.2);
                ctx.begin_path();
                ctx.move_to(bx, by);
                ctx.line_to(gx_end, gy_end);
                ctx.stroke();

                let (yx_end, yy_end) = proj3d(ox, oy + 1.1, 0.05);
                ctx.set_stroke_style_str("rgba(74, 222, 128, 0.98)");
                ctx.begin_path();
                ctx.move_to(bx, by);
                ctx.line_to(yx_end, yy_end);
                ctx.stroke();
            }
        }

        // Goal Beacon in 3D
        let (gx3, gy3) = proj3d(frame.goal_xy[0], frame.goal_xy[1], 0.05);
        ctx.set_stroke_style_str("rgba(16, 185, 129, 0.95)");
        ctx.set_line_width(2.0);
        ctx.begin_path();
        let _ = ctx.arc(gx3, gy3, 9.0, 0.0, core::f64::consts::TAU);
        ctx.stroke();

        // Decentralized Multi-Robot Wingman Swarm + MGTP001 Mesh Gossip Links in 3D
        let rx_ego = frame.pose_xyt[0];
        let ry_ego = frame.pose_xyt[1];
        let (ego_bx, ego_by) = proj3d(rx_ego, ry_ego, 0.12);
        for (pi, peer) in st.swarm_peers.iter().enumerate() {
            let (px, py) = proj3d(peer.x_m, peer.y_m, 0.05);
            let (ptx, pty) = proj3d(peer.x_m, peer.y_m, 0.34);
            let p_halo = (peer.radius_m * scale_3d * 1.15).max(10.0);
            ctx.set_stroke_style_str(if peer.degraded_or_heavy {
                "rgba(251, 191, 36, 0.92)"
            } else {
                "rgba(56, 189, 248, 0.92)"
            });
            ctx.set_line_width(1.6);
            ctx.begin_path();
            let _ = ctx.ellipse(px, py, p_halo, p_halo * 0.58, 0.0, 0.0, core::f64::consts::TAU);
            ctx.stroke();

            ctx.set_stroke_style_str(if pi == 0 {
                "rgba(34, 211, 238, 0.98)"
            } else {
                "rgba(251, 191, 36, 0.98)"
            });
            ctx.set_line_width(4.2);
            ctx.begin_path();
            ctx.move_to(px, py);
            ctx.line_to(ptx, pty);
            ctx.stroke();

            // MGTP001 48B mesh gossip arc when within 7.5m range
            if (peer.x_m - rx_ego).hypot(peer.y_m - ry_ego) < 7.5 {
                ctx.set_stroke_style_str("rgba(56, 189, 248, 0.42)");
                ctx.set_line_width(1.2);
                ctx.begin_path();
                ctx.move_to(ego_bx, ego_by);
                ctx.line_to(ptx, pty);
                ctx.stroke();
            }
        }

        // 16-Step Event-Gated VLA Action-Chunk Horizon Ribbon in 3D
        if let Some(ref vc) = st.vla_chunk_report
            && !vc.action_chunk.is_empty()
        {
            let mut vx = rx_ego;
            let mut vy = ry_ego;
            let mut vth = frame.pose_xyt[2];
            ctx.set_stroke_style_str("rgba(250, 204, 21, 0.92)");
            ctx.set_line_width(2.0);
            ctx.begin_path();
            let (s0x, s0y) = proj3d(vx, vy, 0.16);
            ctx.move_to(s0x, s0y);
            for step in &vc.action_chunk {
                vx += 0.08 * step.v_ms * vth.cos();
                vy += 0.08 * step.v_ms * vth.sin();
                vth += 0.08 * step.omega_rads;
                let (sx, sy) = proj3d(vx, vy, 0.16 + 0.008 * (step.step_offset as f64));
                ctx.line_to(sx, sy);
            }
            ctx.stroke();
        }

        // 3D PointCloud2 Voxel ESDF Iso-Contour Rings & Occupied Columns
        if let Some(ref er) = st.esdf_report {
            for cl in &er.detected_clusters {
                let cx = cl.center_xyz[0];
                let cy = cl.center_xyz[1];
                for ring_m in [cl.radius_m + 0.35, cl.radius_m + 0.75] {
                    let (rcx, rcy) = proj3d(cx, cy, 0.03);
                    let r_px = (ring_m * scale_3d * 0.85).max(8.0);
                    ctx.set_stroke_style_str("rgba(45, 212, 191, 0.38)");
                    ctx.set_line_width(1.2);
                    ctx.begin_path();
                    let _ = ctx.ellipse(rcx, rcy, r_px, r_px * 0.58, 0.0, 0.0, core::f64::consts::TAU);
                    ctx.stroke();
                }
            }
        }

        // Whole-Body Centroidal Support Polygon + ZMP + ICP Capture-Point + Pratt Step Target in 3D
        if st.show_zmp_overlay {
            let zmp_rep = st.compute_live_zmp();
            let rth_z = frame.pose_xyt[2];
            let (cz, sz) = (rth_z.cos(), rth_z.sin());
            let z_scale = 3.2;
            let to_world_xy = |pt: [f64; 2]| -> (f64, f64) {
                (
                    rx_ego + (pt[0] * cz - pt[1] * sz) * z_scale,
                    ry_ego + (pt[0] * sz + pt[1] * cz) * z_scale,
                )
            };
            if zmp_rep.support_polygon_ccw.len() >= 3 {
                ctx.set_stroke_style_str("rgba(16, 185, 129, 0.90)");
                ctx.set_fill_style_str("rgba(16, 185, 129, 0.14)");
                ctx.set_line_width(1.5);
                ctx.begin_path();
                for (vi, &vtx) in zmp_rep.support_polygon_ccw.iter().enumerate() {
                    let (wx, wy) = to_world_xy(vtx);
                    let (px, py) = proj3d(wx, wy, 0.015);
                    if vi == 0 {
                        ctx.move_to(px, py);
                    } else {
                        ctx.line_to(px, py);
                    }
                }
                ctx.close_path();
                ctx.fill();
                ctx.stroke();
            }

            let (zx_w, zy_w) = to_world_xy(zmp_rep.zmp_xy);
            let (zpx, zpy) = proj3d(zx_w, zy_w, 0.03);
            ctx.set_fill_style_str("rgba(52, 211, 153, 0.98)");
            ctx.begin_path();
            let _ = ctx.arc(zpx, zpy, 3.8, 0.0, core::f64::consts::TAU);
            ctx.fill();

            let (ix_w, iy_w) = to_world_xy(zmp_rep.icp_xy);
            let (ipx, ipy) = proj3d(ix_w, iy_w, 0.04);
            ctx.set_fill_style_str(if zmp_rep.step_recovery_required {
                "rgba(244, 63, 94, 0.98)"
            } else {
                "rgba(56, 189, 248, 0.98)"
            });
            ctx.begin_path();
            let _ = ctx.arc(ipx, ipy, 4.2, 0.0, core::f64::consts::TAU);
            ctx.fill();

            if zmp_rep.step_recovery_required {
                let (sx_w, sy_w) = to_world_xy(zmp_rep.emergency_footstep_xy);
                let (spx, spy) = proj3d(sx_w, sy_w, 0.04);
                ctx.set_stroke_style_str("rgba(232, 121, 249, 0.98)");
                ctx.set_line_width(2.0);
                ctx.begin_path();
                ctx.move_to(ipx, ipy);
                ctx.line_to(spx, spy);
                ctx.stroke();
            }
        }

        // Robot Certified Braking Halo + Articulated 3D Embodiment Skeleton
        let rx_w = frame.pose_xyt[0];
        let ry_w = frame.pose_xyt[1];
        let rth = frame.pose_xyt[2];
        let (rbx, rby) = proj3d(rx_w, ry_w, 0.02);
        let halo_px = (frame.braking_radius_m * scale_3d * 0.85).max(12.0);
        ctx.set_stroke_style_str(if frame.true_mass_kg > 25.0 {
            "rgba(245, 158, 11, 0.90)"
        } else {
            "rgba(56, 189, 248, 0.78)"
        });
        ctx.set_line_width(1.6);
        ctx.begin_path();
        let _ = ctx.ellipse(
            rbx,
            rby,
            halo_px,
            halo_px * 0.58,
            0.0,
            0.0,
            core::f64::consts::TAU,
        );
        ctx.stroke();

        let skeleton = st.compute_3d_skeleton(frame.joint_phase, rth);
        let seg_scale = 2.4;
        for seg in &skeleton {
            let (x0, y0) = proj3d(
                rx_w + seg.p0[0] * seg_scale,
                ry_w + seg.p0[1] * seg_scale,
                seg.p0[2] * 1.4,
            );
            let (x1, y1) = proj3d(
                rx_w + seg.p1[0] * seg_scale,
                ry_w + seg.p1[1] * seg_scale,
                seg.p1[2] * 1.4,
            );
            let stroke_col = match seg.accent_kind {
                0 => "rgba(226, 232, 240, 0.98)",
                1 => "rgba(56, 189, 248, 0.98)",
                2 => "rgba(167, 139, 250, 0.98)",
                _ => "rgba(52, 211, 153, 0.98)",
            };
            ctx.set_stroke_style_str(stroke_col);
            ctx.set_line_width(seg.radius * st.cam_zoom.clamp(0.7, 1.5));
            ctx.begin_path();
            ctx.move_to(x0, y0);
            ctx.line_to(x1, y1);
            ctx.stroke();

            ctx.set_fill_style_str("rgba(248, 250, 252, 0.96)");
            ctx.begin_path();
            let _ = ctx.arc(x1, y1, 2.8, 0.0, core::f64::consts::TAU);
            ctx.fill();
        }

        if let Some(ik_t) = st.ik_target_xyz {
            let (ch_h, sh_h) = (rth.cos(), rth.sin());
            let lx = ik_t[0] * ch_h - ik_t[1] * sh_h;
            let ly = ik_t[0] * sh_h + ik_t[1] * ch_h;
            let (ikx, iky) = proj3d(rx_w + lx * seg_scale, ry_w + ly * seg_scale, ik_t[2] * 1.4);
            ctx.set_stroke_style_str("rgba(34, 211, 238, 0.98)");
            ctx.set_line_width(2.0);
            ctx.begin_path();
            let _ = ctx.arc(ikx, iky, 7.5, 0.0, core::f64::consts::TAU);
            ctx.stroke();

            if let Some(ref col_rep) = st.last_collision_report
                && let Some(ref w) = col_rep.closest_witness
            {
                let ax = w.point_on_link_a[0] * ch_h - w.point_on_link_a[1] * sh_h;
                let ay = w.point_on_link_a[0] * sh_h + w.point_on_link_a[1] * ch_h;
                let bx = w.point_on_other[0] * ch_h - w.point_on_other[1] * sh_h;
                let by = w.point_on_other[0] * sh_h + w.point_on_other[1] * ch_h;
                let (wx0, wy0) = proj3d(rx_w + ax * seg_scale, ry_w + ay * seg_scale, w.point_on_link_a[2] * 1.4);
                let (wx1, wy1) = proj3d(rx_w + bx * seg_scale, ry_w + by * seg_scale, w.point_on_other[2] * 1.4);
                ctx.set_stroke_style_str(if w.signed_clearance_m > 0.015 {
                    "rgba(52, 211, 153, 0.92)"
                } else {
                    "rgba(251, 191, 36, 0.98)"
                });
                ctx.set_line_width(1.6);
                ctx.begin_path();
                ctx.move_to(wx0, wy0);
                ctx.line_to(wx1, wy1);
                ctx.stroke();
            }
        }

        // Synchronized Multi-Axis Jerk-Bounded S-Curve End-Effector Ribbon in 3D
        if let Some(ref sc) = st.scurve_trajectory
            && sc.waypoints.len() >= 2
        {
            let (ch_h, sh_h) = (rth.cos(), rth.sin());
            ctx.set_stroke_style_str("rgba(251, 191, 36, 0.94)");
            ctx.set_line_width(2.1);
            ctx.begin_path();
            for (wi, wp) in sc.waypoints.iter().enumerate() {
                let lx = wp.end_effector_xyz[0] * ch_h - wp.end_effector_xyz[1] * sh_h;
                let ly = wp.end_effector_xyz[0] * sh_h + wp.end_effector_xyz[1] * ch_h;
                let (px, py) = proj3d(
                    rx_w + lx * seg_scale,
                    ry_w + ly * seg_scale,
                    wp.end_effector_xyz[2] * 1.4,
                );
                if wi == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();
        }

        // Multi-Finger Force-Closure Grasp Friction Cones in 3D
        if let Some(ref gr) = st.grasp_report {
            let (ch_h, sh_h) = (rth.cos(), rth.sin());
            for fg in &gr.fingers {
                let cx_l = fg.contact_xyz[0] * ch_h - fg.contact_xyz[1] * sh_h;
                let cy_l = fg.contact_xyz[0] * sh_h + fg.contact_xyz[1] * ch_h;
                let (cpx, cpy) = proj3d(
                    rx_w + cx_l * seg_scale,
                    ry_w + cy_l * seg_scale,
                    fg.contact_xyz[2] * 1.4,
                );
                ctx.set_stroke_style_str(if gr.force_closure {
                    "rgba(16, 185, 129, 0.92)"
                } else {
                    "rgba(244, 63, 94, 0.92)"
                });
                ctx.set_line_width(1.3);
                for ray in &fg.friction_cone_rays_xyz {
                    let rx_l = (fg.contact_xyz[0] + ray[0] * 0.08) * ch_h
                        - (fg.contact_xyz[1] + ray[1] * 0.08) * sh_h;
                    let ry_l = (fg.contact_xyz[0] + ray[0] * 0.08) * sh_h
                        + (fg.contact_xyz[1] + ray[1] * 0.08) * ch_h;
                    let (rpx, rpy) = proj3d(
                        rx_w + rx_l * seg_scale,
                        ry_w + ry_l * seg_scale,
                        (fg.contact_xyz[2] + ray[2] * 0.08) * 1.4,
                    );
                    ctx.begin_path();
                    ctx.move_to(cpx, cpy);
                    ctx.line_to(rpx, rpy);
                    ctx.stroke();
                }
            }
        }

        // SE(3) Quaternion ES-EKF Fused Trajectory Arc on Ground Plane
        if let Some(ref ekf) = st.ekf_report
            && ekf.trajectory_samples.len() >= 2
        {
            ctx.set_stroke_style_str("rgba(129, 140, 248, 0.88)");
            ctx.set_line_width(1.9);
            ctx.begin_path();
            for (ei, smp) in ekf.trajectory_samples.iter().enumerate() {
                let (px, py) = proj3d(
                    (rx_w + smp.pos_xyz[0]).clamp(0.5, 17.5),
                    (ry_w + smp.pos_xyz[1]).clamp(0.5, 9.5),
                    0.05 + smp.pos_xyz[2].clamp(-0.02, 0.5),
                );
                if ei == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();
        }

        // 3D Gaussian Splatting -> Metric ESDF Iso-Density Shells
        if let Some(ref sp) = st.splat_esdf_report {
            for cl in &sp.detected_clusters {
                let (scx, scy) = proj3d(cl.center_xyz[0], cl.center_xyz[1], 0.35);
                let r_px = (cl.radius_m * scale_3d * 1.15).max(10.0);
                ctx.set_stroke_style_str("rgba(217, 70, 239, 0.62)");
                ctx.set_line_width(1.4);
                ctx.begin_path();
                let _ = ctx.ellipse(scx, scy, r_px, r_px * 0.55, 0.0, 0.0, core::f64::consts::TAU);
                ctx.stroke();
            }
        }

        // Dual-Arm Bimanual Cooperative Object Bridge & Antipodal Squeeze Bar
        if let Some(ref bm) = st.bimanual_report {
            let (ch_h, sh_h) = (rth.cos(), rth.sin());
            let lx = bm.left_tip_xyz[0] * ch_h - bm.left_tip_xyz[1] * sh_h;
            let ly = bm.left_tip_xyz[0] * sh_h + bm.left_tip_xyz[1] * ch_h;
            let rx_b = bm.right_tip_xyz[0] * ch_h - bm.right_tip_xyz[1] * sh_h;
            let ry_b = bm.right_tip_xyz[0] * sh_h + bm.right_tip_xyz[1] * ch_h;
            let (lpx, lpy) = proj3d(rx_w + lx * seg_scale, ry_w + ly * seg_scale, bm.left_tip_xyz[2] * 1.4);
            let (rpx, rpy) = proj3d(rx_w + rx_b * seg_scale, ry_w + ry_b * seg_scale, bm.right_tip_xyz[2] * 1.4);
            ctx.set_stroke_style_str("rgba(251, 146, 60, 0.94)");
            ctx.set_line_width(2.0);
            ctx.begin_path();
            ctx.move_to(lpx, lpy);
            ctx.line_to(rpx, rpy);
            ctx.stroke();

            ctx.set_fill_style_str("rgba(251, 191, 36, 0.98)");
            ctx.begin_path();
            let _ = ctx.arc(0.5 * (lpx + rpx), 0.5 * (lpy + rpy), 3.6, 0.0, core::f64::consts::TAU);
            ctx.fill();
        }

        // SE(3) Pose-Graph Loop-Closure SLAM Optimized Perimeter on Ground Plane
        if let Some(ref sl) = st.slam_report
            && sl.optimized_poses.len() >= 2
        {
            ctx.set_stroke_style_str("rgba(52, 211, 153, 0.65)");
            ctx.set_line_width(1.5);
            ctx.begin_path();
            for (ni, nd) in sl.optimized_poses.iter().enumerate() {
                let (px, py) = proj3d(nd.pos_xyz[0], nd.pos_xyz[1], 0.03 + nd.pos_xyz[2].clamp(0.0, 0.4));
                if ni == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            // Close loop back to gauge-fixed node 0
            let n0 = &sl.optimized_poses[0];
            let (p0x, p0y) = proj3d(n0.pos_xyz[0], n0.pos_xyz[1], 0.03);
            ctx.line_to(p0x, p0y);
            ctx.stroke();
        }

        // Geometric SO(3) Aerial Ascending Helix & MAVLink v2 Quadrotor Marker in 3D
        if let Some(ref ae) = st.aerial_so3_report
            && ae.trajectory.len() >= 2
        {
            ctx.set_stroke_style_str("rgba(56, 189, 248, 0.85)");
            ctx.set_line_width(1.7);
            ctx.begin_path();
            for (ai, smp) in ae.trajectory.iter().enumerate() {
                let (px, py) = proj3d(smp.pos_xyz[0], smp.pos_xyz[1], smp.pos_xyz[2] * 0.85);
                if ai == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();
            if let Some(last_smp) = ae.trajectory.last() {
                let (qx_p, qy_p) = proj3d(last_smp.pos_xyz[0], last_smp.pos_xyz[1], last_smp.pos_xyz[2] * 0.85);
                ctx.set_fill_style_str("rgba(125, 211, 252, 0.98)");
                ctx.begin_path();
                let _ = ctx.arc(qx_p, qy_p, 4.0, 0.0, core::f64::consts::TAU);
                ctx.fill();
            }
        }

        // Wave 19: 6-DoF Fiducial IBVS Camera Descent Trajectory & Planar AprilTag Target
        if let Some(ref ib) = st.ibvs_report
            && ib.camera_path_world_xyz.len() >= 2
        {
            let tag_cx = (rx_w + 1.1).clamp(1.5, 16.5);
            let tag_cy = ry_w;
            let h = ib.tag_size_m * 1.6;
            let corners = [
                (tag_cx - h, tag_cy - h),
                (tag_cx + h, tag_cy - h),
                (tag_cx + h, tag_cy + h),
                (tag_cx - h, tag_cy + h),
            ];
            ctx.set_stroke_style_str("rgba(34, 211, 238, 0.92)");
            ctx.set_line_width(1.6);
            ctx.begin_path();
            for (ci, &(tx, ty)) in corners.iter().enumerate() {
                let (px, py) = proj3d(tx, ty, 0.02);
                if ci == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.close_path();
            ctx.stroke();

            ctx.set_stroke_style_str("rgba(167, 139, 250, 0.90)");
            ctx.set_line_width(1.8);
            ctx.begin_path();
            for (pi, pt) in ib.camera_path_world_xyz.iter().enumerate() {
                let (px, py) = proj3d(tag_cx + pt[0] * 2.2, tag_cy + pt[1] * 2.2, pt[2] * 1.1);
                if pi == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();
        }

        // Wave 19: 6-DOF Fossen Marine ROV 8-Thruster Subsea Station-Keeping Trajectory
        if let Some(ref rv) = st.rov_report
            && rv.path_ned_xyz.len() >= 2
        {
            ctx.set_stroke_style_str("rgba(20, 184, 166, 0.88)");
            ctx.set_line_width(1.9);
            ctx.begin_path();
            for (ri, pt) in rv.path_ned_xyz.iter().enumerate() {
                let wx = (3.0 + pt[0] * 1.8).clamp(0.8, 17.2);
                let wy = (3.2 - pt[1] * 1.4).clamp(0.8, 9.2);
                let wz = (1.15 - pt[2] * 0.26).clamp(0.05, 1.3);
                let (px, py) = proj3d(wx, wy, wz);
                if ri == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();
            if let Some(end_pt) = rv.path_ned_xyz.last() {
                let (rx_p, ry_p) = proj3d(
                    (3.0 + end_pt[0] * 1.8).clamp(0.8, 17.2),
                    (3.2 - end_pt[1] * 1.4).clamp(0.8, 9.2),
                    (1.15 - end_pt[2] * 0.26).clamp(0.05, 1.3),
                );
                ctx.set_fill_style_str("rgba(45, 212, 191, 0.98)");
                ctx.begin_path();
                let _ = ctx.arc(rx_p, ry_p, 4.2, 0.0, core::f64::consts::TAU);
                ctx.fill();
            }
        }

        // Wave 20: Ackermann ISO 3888-2 Moose-Test LTR-Shielded S-Bend Trajectory on Ground Plane
        if let Some(ref ak) = st.ackermann_report
            && ak.path_shielded_xy.len() >= 2
        {
            ctx.set_stroke_style_str("rgba(163, 230, 53, 0.85)");
            ctx.set_line_width(1.7);
            ctx.begin_path();
            for (ai, pt) in ak.path_shielded_xy.iter().enumerate() {
                let wx = (1.5 + pt[0] * 0.20).clamp(0.8, 17.2);
                let wy = (2.0 + pt[1] * 0.95).clamp(0.8, 9.2);
                let (px, py) = proj3d(wx, wy, 0.03);
                if ai == 0 {
                    ctx.move_to(px, py);
                } else {
                    ctx.line_to(px, py);
                }
            }
            ctx.stroke();
        }

        // $0 Momentum External Force Vector Arrow in 3D if active
        let f_mag = frame.contact_wrench_xy[0].hypot(frame.contact_wrench_xy[1]);
        if f_mag > 4.0 {
            let (fx1, fy1) = proj3d(
                rx_w + (frame.contact_wrench_xy[0] / 60.0).clamp(-2.2, 2.2),
                ry_w + (frame.contact_wrench_xy[1] / 60.0).clamp(-2.2, 2.2),
                0.35,
            );
            ctx.set_stroke_style_str("rgba(244, 63, 94, 0.98)");
            ctx.set_line_width(2.8);
            ctx.begin_path();
            ctx.move_to(rbx, rby - 12.0);
            ctx.line_to(fx1, fy1);
            ctx.stroke();
        }

        ctx.set_font("11.5px ui-monospace, SFMono-Regular, Menlo, monospace");
        ctx.set_fill_style_str("rgba(241, 245, 249, 0.96)");
        let mode_badge = if st.scrub_index.is_some() {
            "TIME-TRAVEL REPLAY"
        } else if st.teleop_cmd.is_some() {
            "TELEOP OVERRIDE"
        } else {
            "LIVE AUTONOMOUS"
        };
        let _ = ctx.fill_text_with_max_width(
            &format!(
                "3D STAGE · {} ({} DoF)  |  {}  |  Tick #{}",
                st.urdf_model.name, st.safety_env.dof_count, mode_badge, frame.tick
            ),
            s3x + 12.0,
            s3y + 20.0,
            (s3w - 24.0).max(160.0),
        );
        if let Some(ref cf) = st.counterfactual_report {
            ctx.set_fill_style_str("rgba(196, 181, 253, 0.98)");
            let _ = ctx.fill_text_with_max_width(
                &format!(
                    "COUNTERFACTUAL SHIELD · Raw Violations: {} → Shielded: {} · Interventions: {}",
                    cf.recorded_violations,
                    cf.shielded_violations,
                    cf.safety_interventions
                ),
                s3x + 12.0,
                s3y + 38.0,
                (s3w - 24.0).max(160.0),
            );
        }
        ctx.set_fill_style_str("rgba(148, 163, 184, 0.92)");
        let _ = ctx.fill_text_with_max_width(
            "Drag: Orbit 3D · Scroll: Zoom · Drag Right Map: Move Obstacle (W) · Shift+Drag Map: Push Robot ($0 Touch)",
            s3x + 12.0,
            s3y + s3h - 10.0,
            (s3w - 24.0).max(160.0),
        );

        // ── RIGHT STAGE (45% width): 3 Stacked Precision Engineering Scopes ──
        let rx0 = s3x + s3w + 12.0;
        let rw = (cw - rx0 - 12.0).max(220.0);
        let gap_y = 10.0;
        let h_top = (s3h - gap_y * 2.0) * 0.40;
        let h_mid = (s3h - gap_y * 2.0) * 0.31;
        let h_bot = s3h - gap_y * 2.0 - h_top - h_mid;

        // Right-Top: Interactive 2D Gizmo & MPPI Map (`rx0, s3y, rw, h_top`)
        ctx.set_fill_style_str("rgba(14, 19, 27, 0.98)");
        ctx.fill_rect(rx0, s3y, rw, h_top);
        ctx.set_stroke_style_str("rgba(45, 58, 76, 0.92)");
        ctx.set_line_width(1.0);
        ctx.stroke_rect(rx0, s3y, rw, h_top);

        let m2x = |wx: f64| rx0 + 10.0 + (wx / 18.0) * (rw - 20.0);
        let m2y = |wy: f64| s3y + 26.0 + (1.0 - wy / 10.0) * (h_top - 34.0);
        let m2s = (rw - 20.0) / 18.0;

        for (oi, &(ox, oy, rad)) in st.obstacles_xyr.iter().enumerate() {
            let cx = m2x(ox);
            let cy = m2y(oy);
            ctx.set_fill_style_str(if st.selected_obstacle == Some(oi) {
                "rgba(251, 113, 133, 0.92)"
            } else {
                "rgba(225, 29, 72, 0.78)"
            });
            ctx.begin_path();
            let _ = ctx.arc(cx, cy, (rad * m2s).max(4.0), 0.0, core::f64::consts::TAU);
            ctx.fill();
        }
        for (rk, rpath) in st.rollout_paths.iter().enumerate() {
            if rpath.len() < 2 {
                continue;
            }
            ctx.set_stroke_style_str(if rk == 0 {
                "rgba(52, 211, 153, 0.95)"
            } else {
                "rgba(56, 189, 248, 0.25)"
            });
            ctx.set_line_width(if rk == 0 { 2.0 } else { 0.9 });
            ctx.begin_path();
            for (si, &(wx, wy)) in rpath.iter().enumerate() {
                if si == 0 {
                    ctx.move_to(m2x(wx), m2y(wy));
                } else {
                    ctx.line_to(m2x(wx), m2y(wy));
                }
            }
            ctx.stroke();
        }
        if let Some(ref cf) = st.counterfactual_report
            && cf.steps.len() >= 2
        {
            ctx.set_stroke_style_str("rgba(244, 63, 94, 0.85)");
            ctx.set_line_width(1.6);
            ctx.begin_path();
            for (si, step) in cf.steps.iter().enumerate() {
                let (wx, wy) = (step.recorded_pose_xyt[0], step.recorded_pose_xyt[1]);
                if si == 0 {
                    ctx.move_to(m2x(wx), m2y(wy));
                } else {
                    ctx.line_to(m2x(wx), m2y(wy));
                }
            }
            ctx.stroke();

            ctx.set_stroke_style_str("rgba(167, 139, 250, 0.98)");
            ctx.set_line_width(2.2);
            ctx.begin_path();
            for (si, step) in cf.steps.iter().enumerate() {
                let (wx, wy) = (step.shielded_pose_xyt[0], step.shielded_pose_xyt[1]);
                if si == 0 {
                    ctx.move_to(m2x(wx), m2y(wy));
                } else {
                    ctx.line_to(m2x(wx), m2y(wy));
                }
            }
            ctx.stroke();
        }
        ctx.set_fill_style_str("rgba(16, 185, 129, 0.98)");
        ctx.begin_path();
        let _ = ctx.arc(m2x(rx_w), m2y(ry_w), 5.2, 0.0, core::f64::consts::TAU);
        ctx.fill();

        ctx.set_fill_style_str("rgba(241, 245, 249, 0.96)");
        let _ = ctx.fill_text(
            &format!(
                "2D GIZMO & MPPI MAP | RLS {:.1}/{:.0}kg | Decel {:.2}m/s²",
                frame.est_mass_kg, frame.true_mass_kg, frame.cert_decel_ms2
            ),
            rx0 + 10.0,
            s3y + 17.0,
        );

        // Right-Middle: Retinal 16x12 Event Gate + Passivity Tank + $0 Touch (`ym = s3y + h_top + gap_y`)
        let ym = s3y + h_top + gap_y;
        ctx.set_fill_style_str("rgba(14, 19, 27, 0.98)");
        ctx.fill_rect(rx0, ym, rw, h_mid);
        ctx.set_stroke_style_str("rgba(45, 58, 76, 0.92)");
        ctx.stroke_rect(rx0, ym, rw, h_mid);

        ctx.set_fill_style_str("rgba(241, 245, 249, 0.96)");
        let _ = ctx.fill_text(
            &format!(
                "RETINAL GATE (SKIP {:.0}%) · TANK {:.2}J (α={:.2}) · $0 TOUCH {:.1}N",
                frame.skip_ratio * 100.0,
                frame.tank_energy_j,
                frame.valve_scale,
                f_mag
            ),
            rx0 + 10.0,
            ym + 17.0,
        );

        let mut mask = [false; WB_PATCH_COLS * WB_PATCH_ROWS];
        for &idx in &st.active_patches {
            if idx < mask.len() {
                mask[idx] = true;
            }
        }
        let grid_w = rw * 0.56;
        let cw_cell = (grid_w - 16.0) / (WB_PATCH_COLS as f64);
        let ch_cell = (h_mid - 36.0) / (WB_PATCH_ROWS as f64);
        for r in 0..WB_PATCH_ROWS {
            for c in 0..WB_PATCH_COLS {
                ctx.set_fill_style_str(if mask[r * WB_PATCH_COLS + c] {
                    "rgba(34, 211, 238, 0.90)"
                } else {
                    "rgba(23, 31, 44, 0.88)"
                });
                ctx.fill_rect(
                    rx0 + 10.0 + (c as f64) * cw_cell,
                    ym + 26.0 + (r as f64) * ch_cell,
                    (cw_cell - 1.5).max(1.5),
                    (ch_cell - 1.5).max(1.5),
                );
            }
        }

        // Tank bar + $0 Touch dial on right side of middle pane
        let tbx = rx0 + grid_w + 10.0;
        let tby = ym + 28.0;
        let tbh = (h_mid - 38.0).max(30.0);
        ctx.set_fill_style_str("rgba(23, 31, 44, 0.95)");
        ctx.fill_rect(tbx, tby, 24.0, tbh);
        let tfill = (frame.tank_energy_j / 12.0).clamp(0.0, 1.0) * tbh;
        ctx.set_fill_style_str(if frame.tank_clamped {
            "rgba(245, 158, 11, 0.95)"
        } else {
            "rgba(16, 185, 129, 0.90)"
        });
        ctx.fill_rect(tbx, tby + (tbh - tfill), 24.0, tfill);

        let dcx = rx0 + grid_w + (rw - grid_w + 26.0) * 0.52;
        let dcy = ym + 26.0 + tbh * 0.5;
        let dr = (tbh * 0.42).min(42.0);
        ctx.set_stroke_style_str("rgba(71, 85, 105, 0.85)");
        ctx.begin_path();
        let _ = ctx.arc(dcx, dcy, dr, 0.0, core::f64::consts::TAU);
        ctx.stroke();
        ctx.set_stroke_style_str(if f_mag > 35.0 {
            "rgba(244, 63, 94, 0.98)"
        } else {
            "rgba(56, 189, 248, 0.95)"
        });
        ctx.set_line_width(2.2);
        ctx.begin_path();
        ctx.move_to(dcx, dcy);
        ctx.line_to(
            dcx + (frame.contact_wrench_xy[0] * (dr / 140.0)).clamp(-dr, dr),
            dcy - (frame.contact_wrench_xy[1] * (dr / 140.0)).clamp(-dr, dr),
        );
        ctx.stroke();

        // Right-Bottom: 48-Byte MGTP001 Binary DataTrack Wire + CfC State (`yb = ym + h_mid + gap_y`)
        let yb = ym + h_mid + gap_y;
        ctx.set_fill_style_str("rgba(14, 19, 27, 0.98)");
        ctx.fill_rect(rx0, yb, rw, h_bot);
        ctx.set_stroke_style_str("rgba(45, 58, 76, 0.92)");
        ctx.set_line_width(1.0);
        ctx.stroke_rect(rx0, yb, rw, h_bot);

        ctx.set_fill_style_str("rgba(241, 245, 249, 0.96)");
        let _ = ctx.fill_text(
            &format!(
                "MGTP001 48B WIRE | CRC {:08X} | {} | Target: {}",
                frame.mgtp_crc32,
                if st.link_online { "LIVE" } else { "LINK_LOST" },
                st.target_id
            ),
            rx0 + 10.0,
            yb + 17.0,
        );

        ctx.set_font("10px ui-monospace, SFMono-Regular, Menlo, monospace");
        for row in 0..3 {
            let ry_h = yb + 36.0 + (row as f64) * 18.0;
            for col in 0..16 {
                let b_i = row * 16 + col;
                let bv = frame.mgtp_wire.get(b_i).copied().unwrap_or(0);
                let col_str = if b_i < 8 {
                    "rgba(196, 181, 253, 0.96)"
                } else if b_i < 24 {
                    "rgba(56, 189, 248, 0.96)"
                } else if b_i < 44 {
                    "rgba(52, 211, 153, 0.96)"
                } else {
                    "rgba(251, 191, 36, 0.98)"
                };
                ctx.set_fill_style_str(col_str);
                let _ = ctx.fill_text(
                    &format!("{bv:02X}"),
                    rx0 + 10.0 + (col as f64) * ((rw - 20.0) / 16.0),
                    ry_h,
                );
            }
        }

        ctx.set_fill_style_str("rgba(148, 163, 184, 0.92)");
        let _ = ctx.fill_text(
            &format!(
                "v=({:.2}m/s, {:+.2}rad/s) · bit-ops/tick={} · WebSerial HIL={}",
                frame.vel_applied[0],
                frame.vel_applied[1],
                frame.bit_ops,
                st.hil_frames_ingested
            ),
            rx0 + 10.0,
            yb + h_bot - 10.0,
        );

        emit_receipt(
            &sink,
            "workbench_homoiconic_tick",
            "L0Closed",
            1,
            wall_ns,
            frame.bit_ops,
        );

        if let Some(cb) = f.borrow().as_ref() {
            schedule(cb);
        }
    }) as Box<dyn FnMut()>));

    if let Some(cb) = g.borrow().as_ref() {
        schedule(cb);
    }
    std::mem::forget(g);
    Ok(())
}

This is the exact Rust file compiled into the WASM module the page just loaded. Every line that runs on your device is here. The receipt is a function of this code, not a bespoke benchmark.

Structural:

Two-hop:

Similarity:

Why both paths in one cascade

Typed-edge knowledge graphs (Graphify, Graphiti, GraphRAG) are good at structural queries: who calls this, what cites that, what's in this module. They're bad at similarity — "show me code that does something like this" is fundamentally not a graph traversal. HDC superposition is the opposite shape: cosine queries land in microseconds, but typed relationships like called-by have no algebraic identity.

The substrate's answer is to keep both, and let the cascade route between them. The mgai-graph crate ships the structural half; the mgai-hdc-in-mathground-view side handles similarity. Both resolve at L0 — no model, no LLM tokens — and the receipt confesses which path took the query.

  • Structural hits when the query parses as <verb> <subject> or <subject> <verb> against the recognised verb set (uses, cites, authored, resolves-via, complements). The mgai-graph instance built into the cascade carries the edges; the cascade trace's L0-retrieved hop is the answer.
  • Similarity falls through when the structural parser doesn't match. The HDC layer still ranks the corpus by cosine — every query gets a meaningful top-3 regardless of which path "won." The visual makes the complementarity concrete.
  • The receipt records the route. V-class = resolved cascade tier; output_hash = FNV-1a over the tier byte + top-3 indices. Two visitors typing the same query get bit-identical hashes — substrate property, not a benchmark.

Persistence (mgai-graph event log)

The structural graph behind this exhibit ships as a static in-memory build. The mgai-graph crate also exposes an append-only event log: Graph::to_log() returns the sequence of AddNode / AddEdge mutations, and Graph::from_log(&log) rebuilds a bit-identical graph deterministically. Any backend that can store an ordered list of typed rows — JouleDB temporal collections, a flat file, a network log — can be the graph's persistence layer without the crate itself depending on it.

The mutation log + the byte-stable JSON serialization both produce identical bytes for identical inputs. That's the property Primitive.output_hash commits to — substrate-wide, including this exhibit.