Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/facett

facett-demo/tests/mega_matrix.rs

//! **The mega matrix** (D5) — a true multi-dimensional **functional** matrix over
//! EVERY component `facett-demo` wires, the heavy sibling of the single golden
//! [`snapshot`](../snapshot.rs) PNG.
//!
//! Where `snapshot.rs` proves *one* themed layout renders to pixels, this proves
//! *every component behaves* across three crossed axes:
//!
//! | axis          | values                                                        |
//! |---------------|---------------------------------------------------------------|
//! | **component** | every facet the demo's `LEGEND` wires (64: 63 cells + menu)    |
//! | **data**      | `Populated` (real injected data) · `Empty` (clean empty shell) |
//! | **palette**   | all of [`Theme::ALL`] (7 striking palettes)                    |
//!
//! For **each (component × data × palette) cell** we inject real values, render
//! the component **headless** with that palette active, and **assert the real
//! rendered data** (LAW 1 — never merely "didn't panic"):
//!
//! 1. **data** — `Populated` asserts the component's readable signal is *present*
//!    (rows / nodes / series / fields / selection counts `> 0`); `Empty` asserts a
//!    clean empty render (signal `== 0`, no panic, no garbage).
//! 2. **palette** — asserts the component **consumed the active palette**: switching
//!    palette changes the palette it *emits in its readable data*
//!    ([`facett::core::theme::probe`], recorded by `theme(ui)` during the paint, or
//!    the egui `Visuals` text colour for the Visuals-themed facets), never a private
//!    default.
//!
//! ## The coverage gate (like the MCP one)
//! [`coverage_gate_every_demo_component_is_in_the_matrix`] cross-checks the matrix
//! registry against the demo's `LEGEND`: **add a component to the demo but forget
//! the matrix and this test goes RED.** Proven by [`coverage_gate_catches_a_fake`],
//! which injects a fake LEGEND key and asserts the gate would reject it.
//!
//! Run: `cargo test -p facett-demo --test mega_matrix`
//! Docs: `.nornir/mega-matrix.md`.

use std::collections::BTreeSet;

use arrow_array::RecordBatch;
use arrow_schema::{DataType, Field, Schema};
use facett::Facet;
use facett::Theme;
use facett::card::{Card, CardField, CardView, FieldValue};
use facett::form::FormView;
use facett::graph::{DepEdge, DepGraphView, DepNode, GraphView, hash_color, scene_from_labeled_edges};
use facett::graph3d::{CodeGraph, CodeVault, DnaHelix, DnaRung, Graph3D, Layout3D, RabbitLogo3D, SystemMap, TimeHelix, TimePoint};
use facett::map::MapView;
use facett_helix::{HelixView, Scene as HelixScene};
use facett::menu::{Command, CommandPalette};
use facett::pipeline::{PipelineView, Status};
use facett::plot::PlotView;
use facett::plotters::{BoxPlotView, CandlestickView, HeatmapView, Ohlc, Tile, TreemapView, ViolinView};
use facett::pop::{ProgressItem, ProgressView};
use facett::geomap::{GeoMap, Hotspot, OsmView};
use facett::geomap::osm2d::sample_dataset;
use facett::icebergview::{IcebergView, Snapshot as IceSnapshot, SnapshotMeta};
use facett::docview::DocView;
use facett::log::{Kind, LogView};
use facett::stat::{StatGridView, StatRow};
use facett::table::{PreviewTable, WarehouseTableView};
use facett::tabbar::{BarControl, TabBarView, TabItem};
use facett::matrix::{status as mstatus, MatrixView, TestResultRow, ASPECT_DEFAULT};
use facett_map3d::Map3D;
use facett::syschart::{SysEdge, SysNode, SystemChart};
use facett_graphview::{DecoratedGraphView, MetroView};
use facett_graphpan::GraphPanView;
use facett_jobview::{JobEntry, JobList, JobStatus};
use facett_security::{Artifact, SecurityReport, SecurityView};
use facett::console::{Console, Cursor};
use facett::filedialog::{DialogMode, Entry as FileEntry, FileDialog};
use facett::video::{FrameSequence, VideoPlayer};
use facett_git::{GitView, RepoSnapshot};
use facett_warehousedeck::{ChartSpec, Color32 as WhColor32, GraphSpec, PaneData, WarehouseDeck};
use facett_demo::demo_layers::LayersDemo;
use facett_zoneui::{ContainerStatus as ContainerStatusT, JeraCentral, Zone as ZoneT, ZonePane};
use facett_demo::demo_graph3d_given::{self, demo_graph3d_given};
use facett_demo::falkor_tab::FalkorTab;
use facett_demo::graphview_tab::{self, GraphviewTab};
use facett_demo::vg_lab_tab::{self, VgLabTab};
use facett_demo::velo_l1_tab::{self, VeloL1Tab};
use facett_demo::pop_tab::{self, PopGraphTab};
use facett_demo::errcode_tab;
use serde_json::{json, Value};

use facett_demo::{LEGEND, data};

/// The `(name, status)` steps + index edges a [`PipelineView`] is built from.
type PipelineSteps = (Vec<(String, Status)>, Vec<(usize, usize)>);

// ─────────────────────────────────────────────────────────────────────────────
// Axis: data state.
// ─────────────────────────────────────────────────────────────────────────────

/// The **data** axis: a component is exercised both full and empty.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DataState {
    /// Real, representative data injected — the readable signal must be present.
    Populated,
    /// No data — a clean empty render (no panic, signal goes to zero).
    Empty,
}

impl DataState {
    fn label(self) -> &'static str {
        match self {
            DataState::Populated => "populated",
            DataState::Empty => "empty",
        }
    }
    const ALL: [DataState; 2] = [DataState::Populated, DataState::Empty];
}

// ─────────────────────────────────────────────────────────────────────────────
// Headless render of a component with a palette active, capturing what it
// painted AND which palette it consumed (the readable palette witness).
// ─────────────────────────────────────────────────────────────────────────────

/// What one cell's render produced: the component's `state_json` and the palette
/// it actually painted with (its *emitted* palette, read back from the probe or
/// the active egui `Visuals` — never a private default).
struct Painted {
    state: Value,
    /// The palette name the component consumed during its paint, if it read the
    /// theme via `theme(ui)` (the custom-painted facets do). `None` for facets that
    /// theme purely through egui `Visuals` — those are checked via `visuals_text`.
    probed_palette: Option<&'static str>,
    /// The active `Visuals` override-text colour at paint time — the palette's
    /// `text` for a Visuals-themed facet, so we can prove palette consumption even
    /// when the facet never calls `theme(ui)`.
    visuals_text: Option<egui::Color32>,
}

/// Render `facet` once, with `theme` pinned active, at `size`. Resets the palette
/// probe first so `probed_palette` reflects only this facet's paint.
fn render_with_palette(facet: &mut dyn Facet, theme: Theme, size: (f32, f32)) -> Painted {
    let ctx = egui::Context::default();
    facett::set_theme(&ctx, theme);
    facett::core::theme::probe::reset();
    let mut visuals_text = None;
    let input = egui::RawInput {
        screen_rect: Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(size.0, size.1))),
        ..Default::default()
    };
    ctx.run_ui(input, |ui| {
        egui::CentralPanel::default().show(ui, |ui| {
            // Re-pin every frame (egui clears temp data between passes) so the
            // facet sees the palette via both `theme(ui)` and `Visuals`.
            facett::set_theme(ui.ctx(), theme);
            facet.ui(ui);
            visuals_text = ui.visuals().override_text_color;
        });
    }).textures_delta.clear();
    Painted { state: facet.state_json(), probed_palette: facett::core::theme::probe::painted(), visuals_text }
}

/// Assert the cell **consumed the active palette** — the palette axis check. Either
/// the facet recorded the palette through `theme(ui)` (probe), or its egui
/// `Visuals` text colour equals the palette's `text` (the Visuals-themed facets).
/// A facet painting a private default would fail both.
fn assert_consumed_palette(p: &Painted, theme: Theme, who: &str) {
    let by_probe = p.probed_palette == Some(theme.name);
    let by_visuals = p.visuals_text == Some(theme.text);
    assert!(
        by_probe || by_visuals,
        "[{who}] did not consume palette `{}`: probe={:?} (want {:?}), visuals_text={:?} (want {:?})",
        theme.name,
        p.probed_palette,
        theme.name,
        p.visuals_text,
        Some(theme.text),
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// The matrix registry: one cell-builder per demo component.
//
// Each `MatrixCell` knows how to build the component **populated** and **empty**,
// and how to assert the readable signal in each data state. The `key` must equal
// the component's `LEGEND` key — the coverage gate enforces it.
// ─────────────────────────────────────────────────────────────────────────────

/// Build a boxed `Facet` for a given data state.
type Build = fn(DataState) -> Box<dyn Facet>;
/// Assert the readable signal for a render in a given data state.
type Check = fn(&Value, DataState, &str);

struct MatrixCell {
    /// The component's `LEGEND` key (coverage-gated to match the demo).
    key: &'static str,
    /// A one-line note: the readable-data signal this cell asserts.
    signal: &'static str,
    build: Build,
    check: Check,
}

/// `> 0` for populated, `== 0` for empty — the canonical count assertion.
fn count_for(state: DataState, n: u64, who: &str, field: &str) {
    match state {
        DataState::Populated => assert!(n > 0, "[{who}] populated `{field}` must be > 0, got {n}"),
        DataState::Empty => assert_eq!(n, 0, "[{who}] empty `{field}` must be 0, got {n}"),
    }
}

/// An empty RecordBatch with the fleet schema (0 rows) — so grid/table render an
/// empty-but-well-formed table rather than a malformed one.
fn empty_fleet_batch() -> RecordBatch {
    let schema = Schema::new(vec![
        Field::new("id", DataType::Int64, false),
        Field::new("name", DataType::Utf8, false),
        Field::new("region", DataType::Utf8, false),
        Field::new("status", DataType::Utf8, false),
        Field::new("score", DataType::Float64, false),
    ]);
    RecordBatch::new_empty(std::sync::Arc::new(schema))
}

/// An **empty** [`facett_binview::BinaryDataSeam`] — the no-data twin of
/// `StubBinaryData` for the `Binary analysis` cell's Empty state (no crates, a
/// default checksec, no history/diff).
struct EmptyBinaryData;
impl facett_binview::BinaryDataSeam for EmptyBinaryData {
    fn source(&self) -> &str {
        "empty (matrix)"
    }
    fn artifact_name(&self) -> String {
        String::new()
    }
    fn checksec(&self) -> facett_binview::Checksec {
        facett_binview::Checksec::default()
    }
    fn crate_sizes(&self) -> Vec<facett_binview::CrateSize> {
        Vec::new()
    }
}

/// An **empty** [`facett_coderoom_view::CoderoomDataSeam`] — the no-data twin of
/// `StubCoderoomData` for the `World coderoom` cell's Empty state.
struct EmptyCoderoomData;
impl facett_coderoom_view::CoderoomDataSeam for EmptyCoderoomData {
    fn source(&self) -> &str {
        "empty (matrix)"
    }
    fn crates(&self) -> Vec<facett_coderoom_view::CrateNode> {
        Vec::new()
    }
    fn compat_edges(&self) -> Vec<facett_coderoom_view::CompatEdge> {
        Vec::new()
    }
    fn what_breaks(&self, _target: &str) -> Option<facett_coderoom_view::WhatBreaks> {
        None
    }
}

/// The full cell registry — **every** component the demo wires, in `LEGEND` order.
fn cells() -> Vec<MatrixCell> {
    vec![
        MatrixCell {
            key: facett_demo::flow_tab::TITLE,
            signal: "original flow nodes and links",
            build: |s| {
                let graph = match s {
                    DataState::Populated => facett::flow::Graph::hub_demo(100),
                    DataState::Empty => facett::flow::Graph { nodes: Vec::new(), edges: Vec::new() },
                };
                Box::new(facett::flow::FlowGraph::new("matrix-flow", graph).unwrap())
            },
            check: |v, s, who| {
                count_for(s, v["graph"]["nodes"].as_array().unwrap().len() as u64, who, "nodes");
                count_for(s, v["graph"]["edges"].as_array().unwrap().len() as u64, who, "edges");
            },
        },
        // ── graph (Scene, circular) ──────────────────────────────────────────
        MatrixCell {
            key: "graph",
            signal: "nodes count",
            build: |s| {
                let scene = match s {
                    DataState::Populated => scene_from_labeled_edges(data::DEPS.iter().map(|&(a, b)| {
                        (a as i64, b as i64, data::SUBSYSTEMS[a].0.to_string(), data::SUBSYSTEMS[b].0.to_string())
                    })),
                    DataState::Empty => scene_from_labeled_edges(std::iter::empty::<(i64, i64, String, String)>()),
                };
                Box::new(GraphView::new(scene).with_title("graph").empty_hint("no services"))
            },
            check: |v, s, who| count_for(s, v["nodes"].as_u64().unwrap(), who, "nodes"),
        },
        // ── helix (the TIME-HELIX DAG — coils winding along a release-time axis) ──
        // Self-contained demo scene (`HelixView::demo` = crate-coils with nodes);
        // empty = an empty `Scene` (0 coils). Readable signal: total_nodes across
        // all coils. (Coverage-gate cell — helix was in LEGEND but had no matrix cell.)
        MatrixCell {
            key: "helix",
            signal: "total_nodes across coils",
            build: |s| -> Box<dyn Facet> {
                match s {
                    DataState::Populated => Box::new(HelixView::demo()),
                    DataState::Empty => Box::new(HelixView::new("helix", HelixScene::new())),
                }
            },
            check: |v, s, who| count_for(s, v["total_nodes"].as_u64().unwrap(), who, "total_nodes"),
        },
        // ── dna (the DNA double-helix — each record = a base-pair rung) ──────────
        // A *parametric* 3-D facet like rabbit3d: the genome ladder is the same in
        // both data states (it exercises the helix geometry, not the fleet data), so
        // its readable signal — the rung count + the design-spec axis→field mapping —
        // is always present. Clock pinned so the spin is deterministic.
        MatrixCell {
            key: "dna",
            signal: "rung count + axis→field mapping (parametric double-helix)",
            build: |_s| {
                let rungs: Vec<DnaRung> = (0..24)
                    .map(|i| {
                        let t = i as f32 / 24.0;
                        DnaRung::new(format!("bp{i}"), egui::Color32::from_rgb(60, 200, 90), i as f32, 0.5 + 0.4 * t, (t * 6.0).cos())
                    })
                    .collect();
                Box::new(DnaHelix::new("dna", rungs).with_clock(1.0))
            },
            check: |v, _s, who| {
                assert_eq!(v["rungs"].as_u64(), Some(24), "[{who}] the DNA ladder carries its 24 base-pair rungs");
                assert_eq!(v["axis_mapping"]["axial"], "z (progression / index)", "[{who}] z ← axial position");
                assert_eq!(v["axis_mapping"]["radius"], "x (magnitude)", "[{who}] x ← rung radius");
                assert!(v["axis_mapping"]["lean"].as_str().unwrap().contains("y"), "[{who}] y ← base-pair lean");
            },
        },
        // ── timehelix (the Doctor-Who time vortex — layers down a tunnel axis) ────
        // A *parametric* 3-D facet: the 8-subsystem × N-release vortex is the same in
        // both data states, so its readable signal — the layer count + the exponential
        // depth-fade constant + the z=depth invariant — is always present.
        MatrixCell {
            key: "timehelix",
            signal: "layer count + depth-fade k + z=depth mapping (parametric vortex)",
            build: |_s| {
                let mut pts = Vec::new();
                let mut edges = Vec::new();
                for l in 0..10 {
                    for sidx in 0..8 {
                        let idx = pts.len();
                        pts.push(TimePoint::new(format!("l{l}s{sidx}"), egui::Color32::from_rgb(0, 200, 220), sidx as f32 / 8.0, 0.5, l));
                        if l > 0 {
                            edges.push((idx - 8, idx));
                        }
                    }
                }
                Box::new(TimeHelix::new("timehelix", pts).with_edges(edges).with_clock(1.0))
            },
            check: |v, _s, who| {
                assert_eq!(v["layers"].as_u64(), Some(10), "[{who}] the vortex stacks its 10 layers");
                assert_eq!(v["points"].as_u64(), Some(80), "[{who}] 8 points per disc × 10 discs");
                assert!(v["depth_fade_k"].as_f64().unwrap() > 0.0, "[{who}] the exponential depth fade is on");
                assert_eq!(v["axis_mapping"]["depth"], "z (layer / version / time)", "[{who}] z always stays depth");
            },
        },
        // ── graphview (the CONSOLIDATED graph engine, through the L0 kernel) ──
        // A *parametric* showcase like rabbit3d: the synthetic layered service-mesh
        // is the same in both data states (it exercises the render kernel, not the
        // demo's fleet data), so its readable signal — the lowered L0 instance count
        // (one marker quad per node) — is always > 0. The render-path string proves
        // it routes through `facett_core::render` L0 Canvas.
        MatrixCell {
            key: "graphview",
            signal: "L0 marker quads (one per node) + render-path",
            build: |_s| Box::new(GraphviewTab::new(graphview_tab::TITLE)),
            check: |v, _s, who| {
                assert_eq!(v["engine"], "facett-graphview", "[{who}] graphview is driven by the engine");
                assert!(v["render_path"].as_str().unwrap().contains("L0 Canvas"), "[{who}] routes through the L0 kernel");
                let nodes = v["nodes"].as_u64().unwrap();
                let quads = v["l0_quads"].as_u64().unwrap();
                assert!(nodes > 0 && quads == nodes, "[{who}] one L0 marker quad per node, got nodes={nodes} quads={quads}");
            },
        },
        // ── V.G (the GRAPH NAVIGATOR — facett-graphnav mounted on the population
        // graph). A *parametric* surface like graphview: the population sample is the
        // same in both data states (it drives the navigator, not the fleet data), so
        // its readable signal — a non-empty canvas + a node table with a row per node —
        // is always present. Proves the tab's canvas + Arrow-table wiring is live.
        MatrixCell {
            key: "Graphs",
            signal: "canvas nodes + Arrow node-table rows (one per node)",
            build: |_s| Box::new(VgLabTab::new(vg_lab_tab::TITLE)),
            check: |v, _s, who| {
                let nodes = v["canvas"]["total_nodes"].as_u64().unwrap();
                assert!(nodes > 0, "[{who}] the V.G navigator has a non-empty graph");
                assert_eq!(v["vglab"]["node_grid_rows"].as_u64().unwrap(), nodes, "[{who}] the node table has a row per node");
                assert!(v["stats"]["edges"].as_u64().unwrap() > 0, "[{who}] the stats panel reports edges");
            },
        },
        // ── Universe (the GPU star-field) — populated = a generated SBM universe,
        // empty = nothing generated yet. The lane is read, never assumed: with no
        // renderer it must say "no GPU", never pretend a CPU painter drew.
        MatrixCell {
            key: "Universe",
            signal: "generated universe node count + the honest lane",
            build: |s| {
                use facett_demo::universe_tab::UniverseTab;
                match s {
                    DataState::Populated => {
                        let mut u = UniverseTab::unbuilt();
                        u.select(facett_demo::graphgen::Source::Gen(facett_graphview::generate::GenKind::Sbm), 1_000, 1);
                        Box::new(u)
                    }
                    DataState::Empty => Box::new(UniverseTab::unbuilt()),
                }
            },
            check: |v, s, who| {
                count_for(s, v["nodes"].as_u64().unwrap(), who, "universe.nodes");
                let lane = v["lane"].as_str().unwrap();
                assert!(["gpu", "no GPU", "not drawn"].contains(&lane), "[{who}] universe lane is honest: {lane}");
                assert_eq!(v["gpu_cloud"].as_bool().unwrap(), lane == "gpu", "[{who}] gpu_cloud follows the lane");
            },
        },
        // ── metro (the subway-line test-coverage view) ───────────────────────
        // A *parametric* surface like rabbit3d/graphview: the synthetic two-line
        // coverage map is the same in both data states (it exercises the transit-map
        // render, not the demo's fleet data), so its readable signal — the line count
        // (2) + the green verdict (1 green, 1 red) — is always present. The unlit
        // emitter on line B is honest coverage data, NOT an error: asserted as the red
        // line + its one named unlit stop.
        MatrixCell {
            key: "metro",
            signal: "line count + green verdict (1 green / 1 red, 1 unlit emitter)",
            build: |_s| {
                let mut v = MetroView::local();
                v.set_title("metro");
                Box::new(v)
            },
            check: |v, _s, who| {
                assert_eq!(v["lines"].as_u64(), Some(2), "[{who}] metro draws the two-line demo map");
                assert_eq!(v["green_lines"].as_u64(), Some(1), "[{who}] one line is fully lit/green");
                assert_eq!(v["green"], false, "[{who}] the demo map seeds a deliberate coverage gap");
                let lines = v["line"].as_array().unwrap();
                assert_eq!(lines.len(), 2, "[{who}] two metro lines");
                assert!(lines.iter().any(|l| l["green"] == true), "[{who}] one green line");
                let red = lines.iter().find(|l| l["green"] == false).expect("a red line");
                assert_eq!(red["unlit"].as_array().unwrap().len(), 1, "[{who}] the red line names its one unlit emitter");
            },
        },
        // ── Velo L1 (L0 SDF base vs L0 + L1 vello overlay) ────────────────────
        // A parametric showcase (the synthetic SDF scene is the same in both data
        // states — it exercises the render lanes, not fleet data), so its readable
        // signal — the L0 instance count + the 2-category backend decision — is
        // always present. The L1 lane itself needs a GPU + the `l1-vello` feature; the
        // headless cell asserts the always-available L0 lane + the surfaced decision.
        MatrixCell {
            key: "Velo L1",
            signal: "L0 instance count + 2-category backend decision",
            build: |_s| Box::new(VeloL1Tab::new(velo_l1_tab::TITLE)),
            check: |v, _s, who| {
                assert_eq!(v["component"], "VeloL1Tab", "[{who}] is the Velo L1 tab");
                assert!(v["render_path"].as_str().unwrap().contains("L0 SDF"), "[{who}] routes the L0 base");
                let quads = v["l0_quads"].as_u64().unwrap();
                assert!(quads > velo_l1_tab::NODES as u64, "[{who}] lowered real L0 SDF quads, got {quads}");
                assert!(v["category"] == "CPU" || v["category"] == "CPU+GPU", "[{who}] surfaces the 2-category decision");
            },
        },
        // ── Sverige (THE population showcase — three linked knut-popsim graphs) ─
        // A parametric showcase: the population is sampled deterministically off
        // knut-popsim regardless of the demo's fleet data, so its readable signal —
        // the analytic 11M-scale stats + the three views each with a real
        // visible<=cap LOD split — is always present. The honest-scale contract +
        // the LOD caps are asserted as data (you can't see 100M nodes from outside).
        MatrixCell {
            key: "Sverige",
            signal: "analytic 11M stats + 3 linked views (LOD visible<=cap)",
            build: |_s| Box::new(PopGraphTab::new(pop_tab::TITLE)),
            check: |v, _s, who| {
                assert_eq!(v["component"], "PopGraphTab", "[{who}] is the population tab");
                assert!(v["source"].as_str().unwrap().contains("knut-popsim"), "[{who}] driven by knut-popsim");
                assert!(v["stats"]["total_nodes"].as_u64().unwrap() > 50_000_000, "[{who}] 11M people → tens of millions of nodes (analytic)");
                let views = v["views"].as_array().unwrap();
                assert_eq!(views.len(), 3, "[{who}] three linked population views");
                for view in views {
                    let vis = view["visible_nodes"].as_u64().unwrap();
                    assert!(vis <= pop_tab::RENDER_CAP as u64, "[{who}] view {} honours the LOD cap, got {vis}", view["view"]);
                }
                assert!(views.iter().any(|vw| vw["view"] == "kommun" && vw["visible_nodes"] == 14), "[{who}] kommun view aggregates to 14 nodes");
            },
        },
        // ── graph3d (3D force cloud) ─────────────────────────────────────────
        MatrixCell {
            key: "graph3d",
            signal: "nodes count",
            build: |s| {
                let (nodes, edges) = match s {
                    DataState::Populated => (
                        data::SUBSYSTEMS.iter().map(|(l, _)| (l.to_string(), hash_color(l))).collect(),
                        data::DEPS.to_vec(),
                    ),
                    DataState::Empty => (Vec::new(), Vec::new()),
                };
                Box::new(Graph3D::new(nodes, edges, Layout3D::Force).with_title("graph3d"))
            },
            check: |v, s, who| count_for(s, v["nodes"].as_u64().unwrap(), who, "nodes"),
        },
        // ── graph3d-given (the HOST-placed cloud, Layout3D::Given) ───────────
        // The readable signal here is NOT the node count — a cloud with nodes is
        // exactly what a no-op `Given` would also produce (the grid fallback would
        // quietly draw it). The signal is `given_positions`: how many positions the
        // HOST actually handed over, plus the `layout` it is drawn with and the
        // `layout_fallback` that would name a degradation. Ignore the placement and
        // this cell goes RED.
        MatrixCell {
            key: "graph3d-given",
            signal: "host positions supplied (given_positions) + layout `given`, no fallback",
            build: |s| match s {
                DataState::Populated => Box::new(demo_graph3d_given()),
                // The empty shell keeps the SAME layout choice with no placement —
                // vacuously complete (0 positions cover 0 nodes), so it must not
                // claim a fallback either.
                DataState::Empty => {
                    Box::new(Graph3D::new(Vec::new(), Vec::new(), Layout3D::Given).with_title(demo_graph3d_given::TITLE))
                }
            },
            check: |v, s, who| {
                assert_eq!(v["layout"], "given", "[{who}] the HOST placement layout is the one selected");
                let nodes = v["nodes"].as_u64().unwrap();
                count_for(s, nodes, who, "nodes");
                let given = v["given_positions"].as_u64().unwrap();
                count_for(s, given, who, "given_positions");
                assert_eq!(given, nodes, "[{who}] one host position per node — a placement that covers the cloud");
                if s == DataState::Populated {
                    assert_eq!(
                        given, demo_graph3d_given::NODES as u64,
                        "[{who}] every sensor of the road network is placed by the host",
                    );
                }
                assert!(
                    v["layout_fallback"].is_null(),
                    "[{who}] a complete placement is DRAWN as given — no grid fallback, got {}",
                    v["layout_fallback"],
                );
            },
        },
        // ── rabbit3d (the 3D znippy rabbit LOGO) ─────────────────────────────
        // A *parametric* logo, not data-driven: the extruded mesh is the same in
        // both data states (it's the mascot, the synthetic 3D test data), so its
        // readable signal — the triangle count — is always > 0.
        MatrixCell {
            key: "rabbit3d",
            signal: "triangle count (parametric logo)",
            build: |_s| Box::new(RabbitLogo3D::new("rabbit3d").with_clock(1.0)),
            check: |v, _s, who| {
                let tris = v["triangles"].as_u64().unwrap();
                assert!(tris > 50, "[{who}] the 3D rabbit logo always has its extruded mesh, got {tris} triangles");
            },
        },
        // ── avocado3d (the facett-model3d glTF model viewer) ─────────────────
        // A *parametric* glTF model, not data-driven: the embedded (CC0 Khronos)
        // avocado mesh is the same in both data states, so its readable signal —
        // the triangle count + the green tint at the default status — is always
        // present.
        MatrixCell {
            key: "avocado3d",
            signal: "triangle count + status tint (parametric glTF)",
            build: |_s| Box::new(facett_model3d::Model3D::avocado("avocado3d").with_clock(1.0)),
            check: |v, _s, who| {
                let tris = v["triangles"].as_u64().unwrap();
                assert!(tris > 50, "[{who}] the glTF model always carries its embedded mesh, got {tris} triangles");
                let tint: Vec<u64> = v["status_rgb"].as_array().unwrap().iter().map(|c| c.as_u64().unwrap()).collect();
                assert!(tint[1] > tint[0], "[{who}] default status is healthy → green-dominant tint, got {tint:?}");
            },
        },
        // ── nav (the facett-app NavShell — app-framework backbone) ───────────
        // A *parametric* shell, not data-driven: the NavModel is the same in both
        // data states. Readable signal — the active route + breadcrumb — is always
        // present, and navigation moves it.
        MatrixCell {
            key: "nav",
            signal: "active route + breadcrumb (parametric shell)",
            build: |_s| {
                use facett_app::{NavItem, NavModel, NavShell};
                let model = NavModel::new([
                    NavItem::new("home", "Home"),
                    NavItem::new("data", "Data").children([NavItem::new("data.table", "Table").route("table")]),
                ]);
                let mut shell = NavShell::new("nav", model);
                shell.navigate("table"); // exercise the router
                Box::new(shell)
            },
            check: |v, _s, who| {
                assert_eq!(v["route"], "table", "[{who}] router navigated to the table route");
                let crumb = v["breadcrumb"].as_array().unwrap();
                assert_eq!(crumb.len(), 2, "[{who}] breadcrumb is the Data›Table path, got {crumb:?}");
                assert_eq!(v["router"]["can_back"], true, "[{who}] history records the navigation");
            },
        },
        // ── shell (the facett-app AppShell — Fas 2 app composition) ──────────
        // A *parametric* shell hosting panes; the NavModel is the same in both
        // data states. Readable signal — active route + mounted panes — is always
        // present, and navigation moves it.
        MatrixCell {
            key: "shell",
            signal: "active route + mounted panes (parametric AppShell)",
            build: |_s| {
                use facett_app::{AppShell, NavItem, NavModel};
                let model = NavModel::new([
                    NavItem::new("home", "Home"),
                    NavItem::new("models", "Models").children([NavItem::new("m.a", "A").route("a")]),
                ]);
                let mut shell = AppShell::new("shell", model).with_body("home", "home").with_body("a", "pane A");
                shell.navigate("a"); // exercise the router
                Box::new(shell)
            },
            check: |v, _s, who| {
                assert_eq!(v["route"], "a", "[{who}] AppShell navigated to route a");
                let crumb = v["breadcrumb"].as_array().unwrap();
                assert_eq!(crumb.len(), 2, "[{who}] breadcrumb is Models›A, got {crumb:?}");
                assert_eq!(v["router"]["can_back"], true, "[{who}] history records the navigation");
            },
        },
        // ── overlay (the facett-app modal + toast system — Fas 3) ────────────
        // A *parametric* overlay surface; seeded with an open dialog + queued
        // toasts so the readable signal (modal open + toast count) is always there.
        MatrixCell {
            key: "overlay",
            signal: "modal open + toast count (parametric overlays)",
            build: |_s| {
                let mut o = facett_demo::overlay_demo::OverlayDemo::new();
                o.seed_for_demo();
                Box::new(o)
            },
            check: |v, _s, who| {
                assert_eq!(v["modal"]["open"], true, "[{who}] the seeded dialog is open");
                assert!(v["toasts"]["count"].as_u64().unwrap() >= 2, "[{who}] toasts queued, got {}", v["toasts"]["count"]);
            },
        },
        // ── widgets (the facett-app input/data widgets — Fas 4) ──────────────
        // A *parametric* gallery; the readable signal (pager page-count + stepper
        // value) is always present.
        MatrixCell {
            key: "widgets",
            signal: "pager page-count + stepper value (parametric widgets)",
            build: |_s| Box::new(facett_demo::widget_gallery::WidgetGallery::new()),
            check: |v, _s, who| {
                assert_eq!(v["pager"]["page_count"], 10, "[{who}] 95 rows / 10 → 10 pages");
                assert_eq!(v["stepper"]["value"], 3, "[{who}] stepper seeded at 3");
            },
        },
        // ── primitives (the #22-Part-B shared reducers: dragdrop/time_axis/action_bus) ──
        // Parametric: Populated seeds a 3-card board; Empty is a bare board (0 cards).
        // Readable signal: the on-board card_count, plus the two new caps it advertises.
        MatrixCell {
            key: "primitives",
            signal: "dragdrop card_count + draggable/time_scrollable caps",
            build: |s| -> Box<dyn Facet> {
                match s {
                    DataState::Populated => Box::new(facett_demo::primitives_tab::PrimitivesDemo::new()),
                    DataState::Empty => Box::new(facett_demo::primitives_tab::PrimitivesDemo::empty()),
                }
            },
            check: |v, s, who| {
                assert_eq!(v["caps"]["draggable"], true, "[{who}] advertises the draggable cap");
                assert_eq!(v["caps"]["time_scrollable"], true, "[{who}] advertises the time_scrollable cap");
                count_for(s, v["card_count"].as_u64().unwrap(), who, "card_count");
            },
        },
        // ── depgraph (layered DAG) ───────────────────────────────────────────
        MatrixCell {
            key: "depgraph",
            signal: "nodes count",
            build: |s| {
                let (nodes, edges): (Vec<DepNode>, Vec<DepEdge>) = match s {
                    DataState::Populated => (
                        data::SUBSYSTEMS
                            .iter()
                            .map(|(l, sub)| DepNode { label: l.to_string(), sublabel: Some(sub.to_string()), color: hash_color(l) })
                            .collect(),
                        data::DEPS.iter().map(|&(a, b)| DepEdge { from: a, to: b, via: vec![data::SUBSYSTEMS[b].1.to_string()] }).collect(),
                    ),
                    DataState::Empty => (Vec::new(), Vec::new()),
                };
                Box::new(DepGraphView::new(nodes, edges).with_title("depgraph"))
            },
            check: |v, s, who| count_for(s, v["nodes"].as_u64().unwrap(), who, "nodes"),
        },
        // ── pipeline (animated DAG + statuses) ───────────────────────────────
        MatrixCell {
            key: "pipeline",
            signal: "status counts (idle+running+done+failed)",
            build: |s| {
                let (steps, edges): PipelineSteps = match s {
                    DataState::Populated => (
                        data::SUBSYSTEMS
                            .iter()
                            .enumerate()
                            .map(|(i, (l, _))| {
                                let status = match i % 4 {
                                    0 => Status::Done,
                                    1 => Status::Running,
                                    2 => Status::Idle,
                                    _ => Status::Failed,
                                };
                                (l.to_string(), status)
                            })
                            .collect(),
                        data::DEPS.to_vec(),
                    ),
                    DataState::Empty => (Vec::new(), Vec::new()),
                };
                Box::new(PipelineView::new("pipeline", steps, edges).with_animation(true))
            },
            check: |v, s, who| {
                let st = &v["statuses"];
                let total = st["idle"].as_u64().unwrap()
                    + st["running"].as_u64().unwrap()
                    + st["done"].as_u64().unwrap()
                    + st["failed"].as_u64().unwrap();
                count_for(s, total, who, "statuses total");
            },
        },
        // ── synthetic-sdp (~100 fun-named pipelines, animated data-flow wave) ──
        MatrixCell {
            key: "synthetic-sdp",
            signal: "stage count (the animated SDP wave's node_count)",
            build: |s| {
                use facett_demo::synthetic_sdp::{SyntheticDag, SyntheticSdpView};
                let view = match s {
                    // Populated = the full ~100-stage world, clock pinned just inside
                    // the first beat so the wave is mid-flight (sources running).
                    DataState::Populated => SyntheticSdpView::new("synthetic-sdp").with_clock(0.01),
                    // Empty = a degenerate 0-stage world (the empty render path).
                    DataState::Empty => {
                        SyntheticSdpView::with_dag("synthetic-sdp", SyntheticDag { names: vec![], layer_of: vec![], edges: vec![] })
                    }
                };
                Box::new(view)
            },
            check: |v, s, who| count_for(s, v["node_count"].as_u64().unwrap(), who, "node_count"),
        },
        // ── SDP (the Spark Declarative Pipelines editor) ──────────────────────
        // Populated = the seeded bronze→silver→gold medallion pipeline (4 flows,
        // valid); Empty = a 0-flow editor (the empty render path). Readable signal =
        // the flow count; populated also validates (every dep resolves).
        MatrixCell {
            key: "SDP",
            signal: "flow count (+ valid verdict when populated)",
            build: |s| {
                use facett_demo::sdp_tab::SdpTab;
                let tab = match s {
                    DataState::Populated => SdpTab::new(),
                    DataState::Empty => SdpTab::empty(),
                };
                Box::new(tab)
            },
            check: |v, s, who| {
                count_for(s, v["flows"].as_array().unwrap().len() as u64, who, "flows");
                if s == DataState::Populated {
                    assert_eq!(v["valid"], true, "[{who}] the seeded medallion pipeline validates");
                }
            },
        },
        // ── brokkr (the CI/build-pipeline builder) ────────────────────────────
        // Populated = the seeded demo pipeline (stages + steps, valid); Empty = a
        // 0-stage builder (the empty render path). Readable signal = the stage count;
        // populated also validates (well-formed `needs` DAG, no dup/empty steps).
        MatrixCell {
            key: "brokkr",
            signal: "stage count (+ valid verdict when populated)",
            build: |s| {
                use facett_demo::brokkr_tab::BrokkrTab;
                let tab = match s {
                    DataState::Populated => BrokkrTab::new(),
                    DataState::Empty => BrokkrTab::empty(),
                };
                Box::new(tab)
            },
            check: |v, s, who| {
                count_for(s, v["stage_count"].as_u64().unwrap(), who, "stage_count");
                if s == DataState::Populated {
                    assert_eq!(v["valid"], true, "[{who}] the seeded demo pipeline validates");
                }
            },
        },
        // ── runa (the dwarves forge pipeline on the REUSED node-DAG viewer) ────
        // Populated = the seeded korp-ci pipeline (3 stages, mapped through the
        // RunaPipelineAdapter, with a live run-status overlay); Empty = an empty
        // (0-stage) runa pipeline (the empty render path). Readable signal = the
        // stage-status total (idle+running+done+failed) the viewer laid out.
        MatrixCell {
            key: "runa",
            signal: "status counts (the runa Stage DAG mapped onto the reused viewer)",
            build: |s| {
                use facett_demo::runa_tab;
                let view = match s {
                    DataState::Populated => runa_tab::pipeline_view(),
                    DataState::Empty => runa_tab::empty_pipeline_view(),
                };
                Box::new(view)
            },
            check: |v, s, who| {
                let st = &v["statuses"];
                let total = st["idle"].as_u64().unwrap()
                    + st["running"].as_u64().unwrap()
                    + st["done"].as_u64().unwrap()
                    + st["failed"].as_u64().unwrap();
                count_for(s, total, who, "statuses total");
            },
        },
        MatrixCell {
            key: "releaseview",
            signal: "crate node count (the constellation DAG in three converging states: LOCAL · SPARRING · CRATES_IO)",
            build: |s| {
                use facett_demo::releaseview_tab;
                let view = match s {
                    DataState::Populated => releaseview_tab::populated_view(),
                    DataState::Empty => releaseview_tab::empty_view(),
                };
                Box::new(view)
            },
            check: |v, s, who| {
                count_for(s, v["node_count"].as_u64().unwrap(), who, "node_count");
                if s == DataState::Populated {
                    assert_eq!(v["planes"].as_array().unwrap().len(), 3, "[{who}] three converging planes");
                    assert_eq!(v["converged"], false, "[{who}] the seed starts diverged");
                }
            },
        },
        // ── timeline (the net-new swimlane Gantt) ─────────────────────────────
        // Populated = the `local()` demo timeline (executor/job/task lanes incl. a
        // phase-segmented task lane); Empty = a model with no bars (the empty render
        // path). Readable signal = the laid-out bar count.
        MatrixCell {
            key: "timeline",
            signal: "laid-out bar count (+ phase-segment flag when populated)",
            build: |s| {
                use facett_timeline::{TimelineModel, TimelineView};
                let view = match s {
                    DataState::Populated => TimelineView::local(),
                    DataState::Empty => TimelineView::new("timeline", TimelineModel::new(0.0, 1.0)),
                };
                Box::new(view)
            },
            check: |v, s, who| {
                count_for(s, v["bar_count"].as_u64().unwrap(), who, "bar_count");
                if s == DataState::Populated {
                    assert_eq!(v["has_segments"], true, "[{who}] the populated timeline has a phase-segmented task lane");
                }
            },
        },
        // ── plandag (the net-new metric-bearing operator DAG) ─────────────────
        // Populated = the `local()` AQE plan (metric bodies + cost-heat + a final
        // plan); Empty = an empty plan version (the empty render path). Readable
        // signal = the resolved node count; populated also carries cost-heat as data.
        MatrixCell {
            key: "plandag",
            signal: "resolved operator-node count (+ cost-heat as data when populated)",
            build: |s| {
                use facett_plandag::{PlanDagView, PlanModel, PlanVersion};
                let view = match s {
                    DataState::Populated => PlanDagView::local(),
                    DataState::Empty => PlanDagView::new("plandag", PlanModel::new(PlanVersion::new("initial", vec![], vec![]))),
                };
                Box::new(view)
            },
            check: |v, s, who| {
                count_for(s, v["node_count"].as_u64().unwrap(), who, "node_count");
                if s == DataState::Populated {
                    let nodes = v["nodes"].as_array().unwrap();
                    assert!(nodes.iter().all(|n| n["heat"].is_number()), "[{who}] every node carries cost-heat as data");
                    assert!(nodes.iter().any(|n| (n["heat"].as_f64().unwrap() - 1.0).abs() < 1e-6), "[{who}] a hottest operator exists");
                }
            },
        },
        // ── grid (flagship Arrow grid) ───────────────────────────────────────
        MatrixCell {
            key: "grid",
            signal: "rows count",
            build: |s| {
                let batch = match s {
                    DataState::Populated => data::fleet_batch(&data::fleet()),
                    DataState::Empty => empty_fleet_batch(),
                };
                Box::new(
                    facett::grid::Grid::from_record_batch("grid", &batch)
                        .with_totals(true)
                        .with_density(facett::grid::Density::Comfortable),
                )
            },
            check: |v, s, who| count_for(s, v["rows"].as_u64().unwrap(), who, "rows"),
        },
        // ── table (scrollable Arrow table) ───────────────────────────────────
        MatrixCell {
            key: "table",
            signal: "rows count + selection",
            build: |s| {
                let batch = match s {
                    DataState::Populated => data::fleet_batch(&data::fleet()),
                    DataState::Empty => empty_fleet_batch(),
                };
                let mut table = facett::arrow::table_from_batch(&batch, "table");
                if s == DataState::Populated {
                    table.select_row(0);
                }
                Box::new(table)
            },
            check: |v, s, who| {
                count_for(s, v["rows"].as_u64().unwrap(), who, "rows");
                // Populated injects a real selection; empty has none.
                let sel = v["selected"].as_array().unwrap().len() as u64;
                match s {
                    DataState::Populated => assert!(sel > 0, "[{who}] populated table has a selection"),
                    DataState::Empty => assert_eq!(sel, 0, "[{who}] empty table has no selection"),
                }
            },
        },
        // ── card (typed field grid) ──────────────────────────────────────────
        MatrixCell {
            key: "card",
            signal: "card field count",
            build: |s| {
                let card = match s {
                    DataState::Populated => vessel_card(&data::fleet()[0]),
                    DataState::Empty => Card::new("Empty"),
                };
                Box::new(CardView::new("card", card))
            },
            check: |v, s, who| {
                let fields = v["card"]["fields"].as_array().unwrap().len() as u64;
                count_for(s, fields, who, "card fields");
            },
        },
        // ── form (bound edit form over a card) ───────────────────────────────
        MatrixCell {
            key: "form",
            signal: "form valid flag + (dirty drives the themed status line)",
            build: |s| {
                let card = match s {
                    DataState::Populated => vessel_card(&data::fleet()[1]),
                    DataState::Empty => Card::new("Empty"),
                };
                // Drop into edit mode by exposing model_mut so the form paints its
                // widgets (and, when populated, reads the theme for its status line).
                let mut form = FormView::new("form", card);
                if s == DataState::Populated {
                    // Make the form dirty so it paints the themed "● unsaved" line,
                    // which reads `theme(ui)` → records the consumed palette.
                    let m = form.model_mut();
                    if let Some(f) = m.fields.first_mut() {
                        f.value = FieldValue::Text("edited".into());
                    }
                    form.revalidate();
                }
                Box::new(form)
            },
            check: |v, s, who| {
                // The form is always "valid" here (the Card has no hard rules), but
                // populated is dirty and empty is clean — a real, injected signal.
                assert_eq!(v["valid"], true, "[{who}] form validates clean");
                match s {
                    DataState::Populated => assert_eq!(v["dirty"], true, "[{who}] populated form is dirty (edited)"),
                    DataState::Empty => assert_eq!(v["dirty"], false, "[{who}] empty form is clean"),
                }
            },
        },
        // ── pop (labelled progress rows) ─────────────────────────────────────
        MatrixCell {
            key: "pop",
            signal: "progress items + done",
            build: |s| {
                let mut pop = ProgressView::new("pop");
                if s == DataState::Populated {
                    pop.phase = "ingesting AIS".into();
                    for (i, region) in data::REGIONS.iter().enumerate() {
                        pop.items.push(ProgressItem { label: format!("{region} feed"), done: 250 + i as u64 * 180, total: 1000 });
                    }
                }
                Box::new(pop)
            },
            check: |v, s, who| {
                count_for(s, v["items"].as_array().unwrap().len() as u64, who, "items");
                count_for(s, v["done"].as_u64().unwrap(), who, "done");
            },
        },
        // ── plot (line series) ───────────────────────────────────────────────
        MatrixCell {
            key: "plot",
            signal: "series count",
            build: |s| {
                let series = match s {
                    DataState::Populated => data::telemetry(),
                    DataState::Empty => Vec::new(),
                };
                Box::new(PlotView::line("plot", series))
            },
            check: |v, s, who| count_for(s, v["series"].as_array().unwrap().len() as u64, who, "series"),
        },
        // ── boxplot (distribution) ───────────────────────────────────────────
        MatrixCell {
            key: "boxplot",
            signal: "group count",
            build: |s| {
                let groups = match s {
                    DataState::Populated => data::score_groups(&data::fleet()),
                    DataState::Empty => Vec::new(),
                };
                Box::new(BoxPlotView::new("boxplot", groups))
            },
            check: |v, s, who| count_for(s, v["groups"].as_array().unwrap().len() as u64, who, "groups"),
        },
        // ── violin (density) ─────────────────────────────────────────────────
        MatrixCell {
            key: "violin",
            signal: "group count",
            build: |s| {
                let groups = match s {
                    DataState::Populated => data::score_groups(&data::fleet()),
                    DataState::Empty => Vec::new(),
                };
                Box::new(ViolinView::new("violin", groups))
            },
            check: |v, s, who| count_for(s, v["groups"].as_array().unwrap().len() as u64, who, "groups"),
        },
        // ── heatmap (region × status) ────────────────────────────────────────
        MatrixCell {
            key: "heatmap",
            signal: "cell count",
            build: |s| match s {
                DataState::Populated => {
                    let (rows, cols, rl, cl, hd) = data::region_status_matrix(&data::fleet());
                    Box::new(HeatmapView::new("heatmap", rows, cols, hd).with_labels(rl, cl))
                }
                DataState::Empty => Box::new(HeatmapView::new("heatmap", 0, 0, Vec::new())),
            },
            check: |v, s, who| count_for(s, v["cells"].as_u64().unwrap(), who, "cells"),
        },
        // ── treemap (tonnage tiles) ──────────────────────────────────────────
        MatrixCell {
            key: "treemap",
            signal: "tile count",
            build: |s| {
                let tiles = match s {
                    DataState::Populated => data::region_tonnage(&data::fleet()).into_iter().map(|(l, val)| Tile::new(l, val)).collect(),
                    DataState::Empty => Vec::new(),
                };
                Box::new(TreemapView::new("treemap", tiles))
            },
            check: |v, s, who| count_for(s, v["tiles"].as_u64().unwrap(), who, "tiles"),
        },
        // ── candles (OHLC candlesticks) ──────────────────────────────────────
        MatrixCell {
            key: "candles",
            signal: "bar count",
            build: |s| {
                let bars = match s {
                    DataState::Populated => data::candles()
                        .into_iter()
                        .enumerate()
                        .map(|(i, (o, h, l, c))| Ohlc::new(format!("s{i}"), o, h, l, c))
                        .collect(),
                    DataState::Empty => Vec::new(),
                };
                Box::new(CandlestickView::new("candles", bars))
            },
            check: |v, s, who| count_for(s, v["bars"].as_u64().unwrap(), who, "bars"),
        },
        // ── map (geo points) ─────────────────────────────────────────────────
        MatrixCell {
            key: "map",
            signal: "points count",
            build: |s| {
                let pts = match s {
                    DataState::Populated => data::geo_points(&data::fleet()),
                    DataState::Empty => Vec::new(),
                };
                Box::new(MapView::new("map", pts))
            },
            check: |v, s, who| count_for(s, v["points"].as_u64().unwrap(), who, "points"),
        },
        // ── syschart (peer system-map, badges, click-select) ─────────────────
        MatrixCell {
            key: "syschart",
            signal: "nodes count",
            build: |s| {
                let (nodes, edges): (Vec<SysNode>, Vec<SysEdge>) = match s {
                    DataState::Populated => (
                        data::sys_nodes(&data::fleet())
                            .into_iter()
                            .map(|(id, _sub, badge, pos)| SysNode::new(id, id, hash_color(id), pos).badge(badge))
                            .collect(),
                        data::sys_edges().into_iter().map(|(a, b)| SysEdge::new(a, b)).collect(),
                    ),
                    DataState::Empty => (Vec::new(), Vec::new()),
                };
                Box::new(SystemChart::new("syschart", nodes, edges))
            },
            check: |v, s, who| count_for(s, v["nodes"].as_array().unwrap().len() as u64, who, "nodes"),
        },
        // ── geomap (scrollable/zoomable: points + hotspots) ──────────────────
        MatrixCell {
            key: "geomap",
            signal: "points count",
            build: |s| {
                let (points, hotspots) = match s {
                    DataState::Populated => (
                        data::geo_points(&data::fleet()),
                        data::geo_hotspots(&data::fleet())
                            .into_iter()
                            .map(|(lon, lat, count, label)| Hotspot::new(lon, lat, count, label))
                            .collect(),
                    ),
                    DataState::Empty => (Vec::new(), Vec::new()),
                };
                Box::new(GeoMap::new("geomap", points, hotspots))
            },
            check: |v, s, who| count_for(s, v["points"].as_u64().unwrap(), who, "points"),
        },
        // ── OSM 2D (state-of-the-art slippy viewer) ──────────────────────────
        // Populated = a synthetic liechtenstein-ish sample (points + typed ways);
        // empty = no geometry. Readable signal = the point count. (The CPU painter
        // lane is what renders headless; the GPU fast-path needs a real GPU.)
        MatrixCell {
            key: "OSM 2D",
            signal: "points count",
            build: |s| {
                let (points, ways) = match s {
                    DataState::Populated => sample_dataset(2_000),
                    DataState::Empty => (Vec::new(), Vec::new()),
                };
                Box::new(OsmView::from_geometry("OSM 2D", points, ways))
            },
            check: |v, s, who| count_for(s, v["points"].as_u64().unwrap(), who, "points"),
        },
        // ── OSM 3D (extruded, lit, orbiting city) ────────────────────────────
        // Populated = the synthetic extruded rabbit-skyline (real prisms); empty =
        // no ways → just the terrain plane. Readable signal = the *footprint*
        // (tile) count: populated lifts ≥5 (rabbit loops + terrain), empty has
        // exactly 1 (the terrain quad). A fixed clock makes the orbit reproducible.
        MatrixCell {
            key: "OSM 3D",
            signal: "footprint (tile) count",
            build: |s| {
                let m = match s {
                    DataState::Populated => Map3D::synthetic("OSM 3D"),
                    DataState::Empty => Map3D::from_geometry("OSM 3D", &[]),
                };
                Box::new(m.with_clock(1.0))
            },
            check: |v, s, who| {
                let tiles = v["tiles"].as_u64().unwrap();
                match s {
                    // Populated extrudes the rabbit loops + terrain (≥5 footprints).
                    DataState::Populated => assert!(tiles >= 5, "[{who}] populated OSM 3D extrudes a city, got {tiles} footprints"),
                    // Empty still has the terrain plane (exactly 1 footprint) — a
                    // graceful, non-blank floor, never zero geometry.
                    DataState::Empty => assert_eq!(tiles, 1, "[{who}] empty OSM 3D is just the terrain plane"),
                }
            },
        },
        // ── icebergview (snapshot time-travel browser) ───────────────────────
        MatrixCell {
            key: "icebergview",
            signal: "snapshots count",
            build: |s| {
                let snaps = match s {
                    DataState::Populated => data::iceberg_snapshots(&data::fleet())
                        .into_iter()
                        .map(|(id, ts, batch)| {
                            let rows = batch.num_rows() as u64;
                            IceSnapshot::new(SnapshotMeta::new(id, ts, rows), vec![batch])
                        })
                        .collect(),
                    DataState::Empty => Vec::new(),
                };
                Box::new(IcebergView::new("icebergview", "fleet", snaps).with_page_size(16))
            },
            check: |v, s, who| count_for(s, v["snapshots"].as_array().unwrap().len() as u64, who, "snapshots"),
        },
        // ── docview (vector-SVG documentation viewer) ────────────────────────
        // Populated = the bundled sample manual (real vector SVG pages parsed by
        // usvg); empty = no pages → a graceful "no document" render. Readable
        // signal = the page count.
        MatrixCell {
            key: "docview",
            signal: "page count",
            build: |s| {
                let v = match s {
                    DataState::Populated => {
                        let (pages, toc) = data::sample_manual();
                        DocView::from_svgs("docview", pages, toc)
                    }
                    DataState::Empty => DocView::new("docview", Vec::new(), Vec::new()),
                };
                Box::new(v)
            },
            check: |v, s, who| count_for(s, v["page_count"].as_u64().unwrap(), who, "pages"),
        },
        // ── log (timestamped event-log / console pane) ───────────────────────
        // Populated = a seeded trail (incl. one error line); empty = an empty ring.
        // Readable signal = the entry count + the error tally (the header badge).
        MatrixCell {
            key: "log",
            signal: "entry count + error tally",
            build: |s| {
                let mut v = match s {
                    DataState::Populated => LogView::local(),
                    DataState::Empty => LogView::new("log"),
                };
                v.set_title("log");
                Box::new(v)
            },
            check: |v, s, who| {
                count_for(s, v["count"].as_u64().unwrap(), who, "count");
                // Populated seeds exactly one ERROR line; empty has none (an empty
                // log is NOT an error — it's a quiescent pane).
                let errs = v["errors"].as_u64().unwrap();
                match s {
                    DataState::Populated => assert_eq!(errs, 1, "[{who}] local trail seeds one error line"),
                    DataState::Empty => assert_eq!(errs, 0, "[{who}] empty log has no errors"),
                }
                // The CLICK kind tally is a real number either way (0 when empty).
                let _ = Kind::Click;
            },
        },
        // ── stat (inline-bar stat grid + sparklines + verdict chips) ─────────
        // Populated = a per-tool stat table (with sparklines + verdicts); empty =
        // no rows. Readable signal = the row count + the max (bar normalizer).
        MatrixCell {
            key: "stat",
            signal: "row count + bar normalizer (max) + verdicts",
            build: |s| {
                let mut v = match s {
                    DataState::Populated => StatGridView::local(),
                    DataState::Empty => StatGridView::new("stat"),
                };
                // an explicit row to make the populated verdict assertion concrete.
                if matches!(s, DataState::Populated) {
                    v.rows.push(StatRow::new("explicit", 7.0).with_status("pass"));
                }
                v.set_title("stat");
                Box::new(v)
            },
            check: |v, s, who| {
                count_for(s, v["rows"].as_u64().unwrap(), who, "rows");
                if matches!(s, DataState::Populated) {
                    let stats = v["stats"].as_array().unwrap();
                    assert!(stats.iter().any(|r| r["verdict"] == "PASS"), "[{who}] a PASS verdict is present");
                }
            },
        },
        // ── warehouse (multi-table browser: picker + grid OR auto bar-chart) ──
        // Populated = two seeded tables (one numeric → chart-able); empty = no
        // tables. Readable signal = the table count + the selected preview shape.
        MatrixCell {
            key: "warehouse",
            signal: "table count + selected preview shape (+ numeric columns)",
            build: |s| {
                let mut v = match s {
                    DataState::Populated => WarehouseTableView::local(),
                    DataState::Empty => WarehouseTableView::new("warehouse")
                        .with_table("empty_tbl", PreviewTable::new(vec!["c".into()], Vec::new())),
                };
                v.set_title("warehouse");
                Box::new(v)
            },
            check: |v, s, who| {
                let n = v["table_count"].as_u64().unwrap();
                match s {
                    DataState::Populated => {
                        assert_eq!(n, 2, "[{who}] local seeds two tables");
                        // the bench_runs `ms` column is detected numeric → chart-able.
                        assert_eq!(v["preview"]["numeric_columns"], serde_json::json!([1]), "[{who}] numeric col detected");
                    }
                    DataState::Empty => {
                        assert_eq!(n, 1, "[{who}] one empty-shaped table");
                        assert_eq!(v["preview"]["rows"], 0, "[{who}] the empty table has zero rows");
                    }
                }
            },
        },
        // ── tabbar (themed 2-row nav toolbar) ────────────────────────────────
        // Populated = a 6-tab bar + 3 controls; empty = no tabs. Readable signal =
        // the tab count + the declared-control count + exactly one active tab.
        MatrixCell {
            key: "tabbar",
            signal: "tab count + control count + exactly one active tab",
            build: |s| {
                let mut v = match s {
                    DataState::Populated => TabBarView::local(),
                    DataState::Empty => TabBarView::new("tabbar")
                        .with_tabs(Vec::<TabItem>::new())
                        .with_control(BarControl::button("noop")),
                };
                v.set_title("tabbar");
                Box::new(v)
            },
            check: |v, s, who| {
                let tabs = v["tabs"].as_array().unwrap();
                count_for(s, tabs.len() as u64, who, "tabs");
                match s {
                    DataState::Populated => {
                        assert_eq!(tabs.len(), 6, "[{who}] local seeds six tabs");
                        assert_eq!(v["controls"].as_array().unwrap().len(), 3, "[{who}] workspace+palette+live");
                        let active = tabs.iter().filter(|t| t["active"] == true).count();
                        assert_eq!(active, 1, "[{who}] exactly one active tab");
                        assert_eq!(v["active"], "DepGraph", "[{who}] local active tab");
                    }
                    DataState::Empty => {
                        assert!(tabs.is_empty(), "[{who}] empty bar has no tabs");
                        // an empty bar still reports its declared control honestly.
                        assert_eq!(v["controls"].as_array().unwrap().len(), 1, "[{who}] the lone declared control");
                    }
                }
            },
        },
        // ── decograph (pan/zoom DAG + decorations overlay) ───────────────────
        // Populated = a 4-node DAG with a ring + a badge + a cut edge; empty = no
        // nodes. Readable signal = node count + ring/badge/decoration-edge counts.
        MatrixCell {
            key: "decograph",
            signal: "node count + ring/badge counts + decoration (cut) edge",
            build: |s| {
                let mut v = match s {
                    DataState::Populated => DecoratedGraphView::local(),
                    DataState::Empty => DecoratedGraphView::new("decograph"),
                };
                v.set_title("decograph");
                Box::new(v)
            },
            check: |v, s, who| {
                count_for(s, v["node_count"].as_u64().unwrap(), who, "node_count");
                match s {
                    DataState::Populated => {
                        assert_eq!(v["node_count"], 4, "[{who}] local seeds a 4-node DAG");
                        assert_eq!(v["rings"], 1, "[{who}] one status ring");
                        assert_eq!(v["badges"], 1, "[{who}] one corner badge");
                        assert_eq!(v["decoration_edges"], 1, "[{who}] one dashed cut edge");
                    }
                    DataState::Empty => {
                        assert_eq!(v["rings"], 0, "[{who}] no rings on an empty graph");
                        assert_eq!(v["decoration_edges"], 0, "[{who}] no overlay edges");
                    }
                }
            },
        },
        // ── falkor (FalkorDB graph-DB browser — Cypher → laid-out GraphModel) ────
        // Populated = the stubbed in-memory runner's nordisk constellation (7 nodes /
        // 7 edges, NO live redis); empty = an idle browser (no query run). Readable
        // signal = node count; when populated, the two categorical labels + the
        // "no redis" runner marker are asserted, proving the pane rendered a real
        // graph from the stubbed CypherRunner seam.
        MatrixCell {
            key: "falkor",
            signal: "node count + label breakdown + in-memory (no-redis) runner",
            build: |s| -> Box<dyn Facet> {
                match s {
                    DataState::Populated => Box::new(FalkorTab::new("falkor")),
                    DataState::Empty => Box::new(FalkorTab::empty("falkor")),
                }
            },
            check: |v, s, who| {
                count_for(s, v["node_count"].as_u64().unwrap(), who, "node_count");
                assert_eq!(v["runner"], "in-memory CannedRunner (no redis)", "[{who}] no live redis");
                match s {
                    DataState::Populated => {
                        assert_eq!(v["node_count"], 7, "[{who}] the demo constellation");
                        assert_eq!(v["edge_count"], 7, "[{who}] its edges");
                        assert_eq!(v["status"], "ok", "[{who}] the stubbed runner answered");
                        assert_eq!(v["label_count"], 2, "[{who}] Repo + Crate categorical labels");
                    }
                    DataState::Empty => {
                        assert_eq!(v["edge_count"], 0, "[{who}] empty browser paints no edges");
                        assert_eq!(v["status"], "idle", "[{who}] no query run yet");
                    }
                }
            },
        },
        // ── matrix (per-repo × per-aspect test-matrix grid) ──────────────────
        // Populated = 3 ran repos + 1 expected-but-unrun (real green + red cells);
        // empty = no rows. Readable signal = repo count + green/red/blank totals.
        MatrixCell {
            key: "matrix",
            signal: "repo count + green/red totals + a not-run repo",
            build: |s| {
                let mut v = match s {
                    DataState::Populated => MatrixView::local(),
                    DataState::Empty => MatrixView::new("matrix"),
                };
                // an explicit failing row so the populated red-total assertion is concrete.
                if matches!(s, DataState::Populated) {
                    v = v.with_expected(
                        ["alpha".to_string()].to_vec(),
                        ASPECT_DEFAULT,
                    ).with_rows(vec![TestResultRow {
                        run_id: "x".into(),
                        repo: "alpha".into(),
                        suite: "alpha".into(),
                        test_name: "a::boom".into(),
                        status: mstatus::FAIL.into(),
                        duration_ms: 1.0,
                        ts_micros: 100,
                        message: "boom".into(),
                        aspect: "unit".into(),
                        metric: 0.0,
                    }]);
                }
                v.set_title("matrix");
                Box::new(v)
            },
            check: |v, s, who| {
                count_for(s, v["repo_count"].as_u64().unwrap(), who, "repo_count");
                match s {
                    DataState::Populated => {
                        // a real failing unit cell → non-zero red total.
                        assert!(v["total_red"].as_u64().unwrap() >= 1, "[{who}] a failing cell → red>0");
                        // the explicit alpha repo's unit cell is red.
                        let alpha = v["rows"].as_array().unwrap().iter().find(|r| r["repo"] == "alpha").unwrap();
                        let unit = alpha["cells"].as_array().unwrap().iter().find(|c| c["aspect"] == "unit").unwrap();
                        assert_eq!(unit["red"], true, "[{who}] alpha unit cell is red");
                    }
                    DataState::Empty => {
                        assert_eq!(v["total_green"], 0, "[{who}] empty grid has no greens");
                        assert_eq!(v["total_red"], 0, "[{who}] empty grid has no reds");
                    }
                }
            },
        },
        // ── graphpan (bare pan/zoom graph canvas) ────────────────────────────
        // Populated = the local 4-node DAG (ring + badge + dashed cut edge); empty =
        // no nodes. Readable signal = node count; plus, when populated, the canvas
        // renders headlessly so its world→screen transform is asserted (node `a` at
        // world (0,0) lands on the painted origin; node `d` at world (520,0) lands
        // 520px to its right under zoom 1 / pan 0).
        MatrixCell {
            key: "graphpan",
            signal: "node count + pan/zoom world→screen transform of a known node",
            build: |s| {
                let mut v = match s {
                    DataState::Populated => GraphPanView::local(),
                    DataState::Empty => GraphPanView::new("graphpan"),
                };
                v.set_title("graphpan");
                Box::new(v)
            },
            check: |v, s, who| {
                count_for(s, v["node_count"].as_u64().unwrap(), who, "node_count");
                match s {
                    DataState::Populated => {
                        assert_eq!(v["node_count"], 4, "[{who}] local seeds a 4-node DAG");
                        assert_eq!(v["decoration_edges"], 1, "[{who}] one dashed cut edge");
                        assert_eq!(v["rings"], 1, "[{who}] one status ring");
                        assert_eq!(v["badges"], 1, "[{who}] one corner badge");
                        // The headless render recorded a real paint origin → the
                        // world→screen transform is observable.
                        let origin = v["origin"].as_array().expect("[populated] canvas painted, origin recorded");
                        let (ox, oy) = (origin[0].as_f64().unwrap(), origin[1].as_f64().unwrap());
                        let nodes = v["nodes"].as_array().unwrap();
                        let a = nodes.iter().find(|n| n["id"] == "a").unwrap();
                        let a_s = a["screen"].as_array().unwrap();
                        assert!((a_s[0].as_f64().unwrap() - ox).abs() < 0.001, "[{who}] node a (world 0,0) lands on the origin");
                        assert!((a_s[1].as_f64().unwrap() - oy).abs() < 0.001, "[{who}] node a y = origin y");
                        let d = nodes.iter().find(|n| n["id"] == "d").unwrap();
                        let d_s = d["screen"].as_array().unwrap();
                        assert!((d_s[0].as_f64().unwrap() - (ox + 520.0)).abs() < 0.001, "[{who}] node d is 520px right of origin (zoom 1, pan 0)");
                        assert_eq!(v["transform"]["zoom"], 1.0, "[{who}] default zoom is 1");
                    }
                    DataState::Empty => {
                        assert_eq!(v["decoration_edges"], 0, "[{who}] no overlay edges");
                        assert_eq!(v["rings"], 0, "[{who}] no rings on an empty canvas");
                    }
                }
            },
        },
        // ── jobs (hierarchical streaming job tree) ───────────────────────────
        // Populated = a parent populate job with two child clones (one done, one
        // running) + a flat bench job; empty = no jobs. Readable signal = job count;
        // when populated the hierarchy summary (parents/children) is asserted, so the
        // parent→child nesting the tree draws is observable, not just a flat count.
        MatrixCell {
            key: "jobs",
            signal: "job count + parent/child hierarchy summary",
            build: |s| {
                let mut v = JobList::new("jobs");
                if let DataState::Populated = s {
                    let pid = "pop";
                    let child = |id: &str, name: &str, st: JobStatus| JobEntry {
                        target: name.into(),
                        parent_id: Some(pid.to_string()),
                        ..JobEntry::new(id, "workspace_clone", st)
                    };
                    v.set_jobs(vec![
                        JobEntry {
                            target: "nordisk".into(),
                            ..JobEntry::new(pid, "workspace_populate", JobStatus::Running)
                        },
                        child("c1", "nornir", JobStatus::Done),
                        child("c2", "facett", JobStatus::Running),
                        JobEntry {
                            target: "skade".into(),
                            ..JobEntry::new("bench", "bench_run", JobStatus::Done)
                        },
                    ]);
                }
                Box::new(v)
            },
            check: |v, s, who| {
                count_for(s, v["count"].as_u64().unwrap(), who, "count");
                match s {
                    DataState::Populated => {
                        assert_eq!(v["count"], 4, "[{who}] one parent + two children + one flat job");
                        assert_eq!(v["parents"], 1, "[{who}] one parent (has children)");
                        assert_eq!(v["children"], 2, "[{who}] two child jobs nest under the parent");
                        assert!(v["running"].as_u64().unwrap() >= 1, "[{who}] at least one job running");
                    }
                    DataState::Empty => {
                        assert_eq!(v["parents"], 0, "[{who}] no parents on an empty tree");
                        assert_eq!(v["children"], 0, "[{who}] no children on an empty tree");
                    }
                }
            },
        },
        // ── security (the supply-chain security report view) ──────────────────
        // Populated = a real BLOCK report (a Critical KEV CVE + a High + a Medium +
        // an Info advisory); empty = a CLEAN report (Pass, no findings). The readable
        // signal is the finding count; when populated the verdict + worst severity +
        // KEV tally + worst-first lead row are asserted, so the verdict the pane
        // paints is observable AS DATA, not pixels. When empty the verdict goes to
        // Pass and the count to zero (a clean render, no panic).
        MatrixCell {
            key: "security",
            signal: "finding count + verdict/severity/KEV (populated = BLOCK, empty = PASS)",
            build: |s| {
                let mut v = match s {
                    DataState::Populated => SecurityView::local(),
                    DataState::Empty => SecurityView::new(
                        "security",
                        SecurityReport::clean(Artifact::new("cargo", "clean-crate", "1.0.0", "0000000000000000"), "2026-06-30T12:00:00Z"),
                    ),
                };
                v.set_title("security");
                Box::new(v)
            },
            check: |v, s, who| {
                count_for(s, v["findings_total"].as_u64().unwrap(), who, "findings_total");
                match s {
                    DataState::Populated => {
                        assert_eq!(v["verdict"], "BLOCK", "[{who}] the populated report blocks");
                        assert_eq!(v["max_severity"], "CRIT", "[{who}] worst finding is Critical");
                        assert_eq!(v["kev_count"], 1, "[{who}] one KEV-listed finding");
                        let findings = v["findings"].as_array().unwrap();
                        assert_eq!(findings.len(), 4, "[{who}] all four findings ride into state_json");
                        assert_eq!(findings[0]["severity"], "CRIT", "[{who}] worst-first: Critical leads");
                        assert_eq!(findings[0]["kev"], true, "[{who}] the lead finding is KEV-listed");
                        let ranks: Vec<u64> = findings.iter().map(|f| f["severity_rank"].as_u64().unwrap()).collect();
                        assert!(ranks.windows(2).all(|w| w[0] >= w[1]), "[{who}] findings sorted worst-first: {ranks:?}");
                    }
                    DataState::Empty => {
                        assert_eq!(v["verdict"], "PASS", "[{who}] a clean report passes");
                        assert_eq!(v["max_severity"], Value::Null, "[{who}] no severity on a clean report");
                        assert_eq!(v["kev_count"], 0, "[{who}] no KEV findings when clean");
                    }
                }
            },
        },
        // ── console (themed terminal/shell — ANSI → palette) ──────────────────
        MatrixCell {
            key: "console",
            signal: "line count",
            build: |s| {
                let mut v = Console::new("console").with_cursor(Cursor::Block);
                if matches!(s, DataState::Populated) {
                    for l in ["\u{1b}[32mok\u{1b}[0m compiling", "line two", "\u{1b}[31merror\u{1b}[0m nope", "done"] {
                        v.push_line(l);
                    }
                }
                Box::new(v)
            },
            check: |v, s, who| count_for(s, v["lines"].as_u64().unwrap(), who, "lines"),
        },
        // ── filedialog (Open File — INJECTED listing) ─────────────────────────
        MatrixCell {
            key: "Open File",
            signal: "visible entry count",
            build: |s| {
                let mut v = FileDialog::new(DialogMode::Open, "/repo");
                if matches!(s, DataState::Populated) {
                    v.set_entries(vec![
                        FileEntry::dir("src"),
                        FileEntry::file("Cargo.toml"),
                        FileEntry::file("README.md"),
                    ]);
                }
                Box::new(v)
            },
            check: |v, s, who| count_for(s, v["visible"].as_array().unwrap().len() as u64, who, "visible"),
        },
        // ── video (themed player over a synthetic frame source) ───────────────
        MatrixCell {
            key: "video",
            signal: "frame count",
            build: |s| {
                let src = match s {
                    DataState::Populated => FrameSequence::test_pattern(12, 32, 18),
                    DataState::Empty => FrameSequence::new(24.0),
                };
                Box::new(VideoPlayer::new("video", src))
            },
            check: |v, s, who| count_for(s, v["frames"].as_u64().unwrap(), who, "frames"),
        },
        // ── Git (repo facet — branches / commits / tree) ──────────────────────
        MatrixCell {
            key: "Git",
            signal: "commit count",
            build: |s| match s {
                DataState::Populated => Box::new(GitView::demo()),
                DataState::Empty => Box::new(GitView::new(RepoSnapshot {
                    workdir: "/repo".into(),
                    branches: Vec::new(),
                    commits: Vec::new(),
                    tree: Vec::new(),
                })),
            },
            check: |v, s, who| count_for(s, v["commits"].as_u64().unwrap(), who, "commits"),
        },
        // ── warehousedeck (multi-pane lakehouse dashboard) ────────────────────
        MatrixCell {
            key: "warehousedeck",
            signal: "pane count",
            build: |s| {
                let mut d = WarehouseDeck::new("warehousedeck");
                if matches!(s, DataState::Populated) {
                    d.add(
                        "g",
                        PaneData::Graph(GraphSpec::new(
                            vec![("a".into(), WhColor32::RED), ("b".into(), WhColor32::GREEN)],
                            vec![(0, 1)],
                        )),
                    )
                    .add("c", PaneData::Chart(ChartSpec::line(vec![("s".into(), vec![(0.0, 1.0), (1.0, 2.0)])])))
                    .add("notes", PaneData::Blob { text: "one\ntwo".into() });
                }
                Box::new(d)
            },
            check: |v, s, who| count_for(s, v["pane_count"].as_u64().unwrap(), who, "pane_count"),
        },
        // ── zone (the shared zone-populate PANE — facett-zoneui::ZonePane) ────
        // Populated: the demo pane previewing its 2 default containers. Empty: a pane
        // with an empty default-infra provider → 0 containers, a clean empty render.
        MatrixCell {
            key: "zone",
            signal: "default-infra container count",
            build: |s| match s {
                DataState::Populated => Box::new(facett_demo::demo_zoneui::zone_pane()),
                DataState::Empty => Box::new(
                    ZonePane::new("zone").with_default_infra(|_z: ZoneT| Vec::<ContainerStatusT>::new()),
                ),
            },
            check: |v, s, who| count_for(s, v["containers"].as_array().unwrap().len() as u64, who, "containers"),
        },
        // ── Jobs (the shared Jobs CENTRAL panel — facett-zoneui::JeraCentral, the
        // jera edda job engine surfaced to the user as "Jobs") ─────────────────
        // Populated: the demo panel with its zoned jobs. Empty: no jobs → 0 rows.
        // `key` is coverage-gated to the LEGEND label, so it is the user-facing "Jobs".
        MatrixCell {
            key: "Jobs",
            signal: "zoned-job count",
            build: |s| match s {
                DataState::Populated => Box::new(facett_demo::demo_zoneui::jera_central()),
                DataState::Empty => Box::new(JeraCentral::from_jobs("Jobs", Vec::new())),
            },
            check: |v, s, who| count_for(s, v["jobs"].as_array().unwrap().len() as u64, who, "jobs"),
        },
        // ── Layers (Google-Maps-style layer toggles over a live 2D map) ──────
        // A fixed hand-built demo basemap (roads/water/landuse/buildings + POIs), the
        // same in both data states (like the parametric 3D facets), so its readable
        // signal — the total base-way + POI counts — is always present.
        MatrixCell {
            key: "Layers",
            signal: "base-way + POI count (fixed demo basemap)",
            build: |_s| Box::new(LayersDemo::new()),
            check: |v, _s, who| {
                let ways = v["total_ways"].as_u64().unwrap();
                let pois = v["total_pois"].as_u64().unwrap();
                assert!(ways > 0, "[{who}] the layer-toggle demo carries its base map, got {ways} ways");
                assert!(pois > 0, "[{who}] the layer-toggle demo carries its POIs, got {pois} POIs");
            },
        },
        // ── codevault (the Wreck-It-Ralph Code Vault — 3-D warehouse boxes) ───
        // Populated: the demo's nordisk-warehouse vault (12 boxes, 12 connectors, one
        // glitch). Empty: an empty CodeGraph → 0 boxes, a clean empty render.
        MatrixCell {
            key: "codevault",
            signal: "box count (+ one glitch when populated)",
            build: |s| match s {
                DataState::Populated => Box::new(facett_demo::demo_codevault::demo_vault()),
                DataState::Empty => {
                    Box::new(CodeVault::new(CodeGraph::new(Vec::new(), Vec::new()), Layout3D::Force).with_title("codevault"))
                }
            },
            check: |v, s, who| {
                count_for(s, v["boxes"].as_u64().unwrap(), who, "boxes");
                if matches!(s, DataState::Populated) {
                    assert_eq!(v["glitch_count"], 1, "[{who}] the vault flickers exactly one reported-problem crate");
                    assert_eq!(v["emissive"], true, "[{who}] the shiny glowing transparent box material");
                }
            },
        },
        // ── System Map (the 🫧 real-liquid system map — glass pipes with real liquid) ──
        // Populated: the demo's SHIPPED nordisk constellation (7 glass tanks, 8 glass
        // pipes) — the real-liquid map (`demo_systemmap_liquid`, the opt-in `with_liquid`),
        // so it carries a `liquid` engine (one containable liquid tube per edge) on TOP
        // of the always-present dye `fluid`. Empty: an empty SystemMap → 0 components /
        // 0 pipes, a clean empty render. Readable signal: the component (tank) count.
        // The translucent glass material (`glass_alpha < 1`) is asserted intrinsic.
        MatrixCell {
            key: "System Map",
            signal: "component (glass-tank) count + translucent glass pipes carrying real liquid",
            build: |s| match s {
                DataState::Populated => Box::new(facett_demo::demo_systemmap::demo_systemmap_liquid()),
                DataState::Empty => Box::new(SystemMap::new(Vec::new(), Vec::new(), Layout3D::Force).with_title("System Map")),
            },
            check: |v, s, who| {
                count_for(s, v["components"].as_u64().unwrap(), who, "components");
                assert!(v["glass_alpha"].as_f64().unwrap() < 1.0, "[{who}] the pipes are translucent glass");
                if matches!(s, DataState::Populated) {
                    assert_eq!(v["pipes"], 8, "[{who}] eight glass pipes");
                    assert_eq!(v["fluid"]["pipes"], 8, "[{who}] one dye fluid pipe per edge");
                    // The SHIPPED tab now carries REAL LIQUID: one containable liquid tube
                    // per edge, charged (volume > 0) and contained (nothing over-full).
                    assert_eq!(v["liquid"]["pipes"], 8, "[{who}] one real-liquid tube per edge (the shipped map)");
                    assert!(v["liquid"]["total_volume"].as_f64().unwrap() > 1.0, "[{who}] the shipped map is charged with liquid");
                    assert!(v["liquid"]["max_fill"].as_f64().unwrap() <= 1.0, "[{who}] the liquid is contained (nothing over-full)");
                }
            },
        },
        // ── scene (the DECLARATIVE UI-SCENE shell) ───────────────────────────────
        // Populated: the demo's own shell described as a facett_app::scene::Scene —
        // a menubar + a tree of panes, rendered through facett-app's Router/TabView/
        // menu. Empty: a minimal one-slot scene. Readable signal: the pane count.
        // Intrinsic invariants: every content (leaf) pane is foldable; the two
        // master/detail Splits are DRAGGABLE (live ratios, not static); the activity
        // rail is a responsive DRAWER; and the shell RON round-trips byte-stable. Both
        // data states use the SAME SceneDemo (the shell is fixed); the "empty" axis
        // asserts the same declarative invariants hold.
        MatrixCell {
            key: "scene",
            signal: "declared panes + foldable leaves + 2 draggable splits + drawer rail + byte-stable RON",
            build: |_s| Box::new(facett_demo::scene_demo::SceneDemo::new()),
            check: |v, _s, who| {
                let panes = v["panes"].as_array().unwrap().len() as u64;
                assert!(panes > 0, "[{who}] the shell scene declares panes");
                let foldable = v["foldable"].as_array().unwrap();
                for want in ["activity", "canvas", "stats", "trend"] {
                    assert!(foldable.iter().any(|f| f == want), "[{who}] the `{want}` content pane is foldable");
                }
                // The corrected (non-fold-only) scope: draggable splits + a drawer rail.
                let splits = v["draggable_splits"].as_array().unwrap();
                assert!(splits.iter().any(|s| s == "root") && splits.iter().any(|s| s == "workspace"), "[{who}] the master/detail splits are draggable");
                assert!(v["drawers"].as_array().unwrap().iter().any(|d| d == "activity"), "[{who}] the activity rail is a drawer");
                assert_eq!(v["component"], "SceneDemo", "[{who}] is the declarative shell");
                assert_eq!(v["scene"], "facett-demo", "[{who}] the scene is named for the app");
            },
        },
        // ── the 7 flow/workspace widgets reached through the umbrella `facett` ──
        // Each is a first-class `impl Facet` with a shared `local()` fixture;
        // populated = `local()`, empty = the no-data constructor. The readable
        // signal is the widget's own count going > 0 (populated) / 0 (empty).
        // ── Bygglov (facett-gantt) ────────────────────────────────────────────
        MatrixCell {
            key: "Bygglov",
            signal: "task count",
            build: |s| match s {
                DataState::Populated => Box::new(facett::gantt::Gantt::local()),
                DataState::Empty => Box::new(facett::gantt::Gantt::new("Bygglov", Vec::new())),
            },
            check: |v, s, who| count_for(s, v["task_count"].as_u64().unwrap(), who, "task_count"),
        },
        // ── Support (facett-kanban) ───────────────────────────────────────────
        MatrixCell {
            key: "Support",
            signal: "card count",
            build: |s| match s {
                DataState::Populated => Box::new(facett::kanban::Board::local()),
                DataState::Empty => Box::new(facett::kanban::Board::new("Support", Vec::new())),
            },
            check: |v, s, who| count_for(s, v["card_count"].as_u64().unwrap(), who, "card_count"),
        },
        // ── Frister (facett-calendar) ─────────────────────────────────────────
        MatrixCell {
            key: "Frister",
            signal: "event count",
            build: |s| match s {
                DataState::Populated => Box::new(facett::calendar::Calendar::local()),
                DataState::Empty => Box::new(facett::calendar::Calendar::new("Frister", 2026, 6)),
            },
            check: |v, s, who| count_for(s, v["events"].as_array().unwrap().len() as u64, who, "events"),
        },
        // ── Notifications (facett-toast) ──────────────────────────────────────
        MatrixCell {
            key: "Notifications",
            signal: "toast count",
            build: |s| match s {
                DataState::Populated => Box::new(facett::toast::Toasts::local()),
                DataState::Empty => Box::new(facett::toast::Toasts::new()),
            },
            check: |v, s, who| count_for(s, v["count"].as_u64().unwrap(), who, "count"),
        },
        // ── Anteckning (facett-markdown) ──────────────────────────────────────
        MatrixCell {
            key: "Anteckning",
            signal: "char count",
            build: |s| match s {
                DataState::Populated => Box::new(facett::markdown::Markdown::local()),
                DataState::Empty => Box::new(facett::markdown::Markdown::new("Anteckning")),
            },
            check: |v, s, who| count_for(s, v["chars"].as_u64().unwrap(), who, "chars"),
        },
        // ── Search (facett-search) ────────────────────────────────────────────
        MatrixCell {
            key: "Search",
            signal: "parsed clause count",
            build: |s| match s {
                DataState::Populated => Box::new(facett::search::SearchBar::local()),
                DataState::Empty => Box::new(facett::search::SearchBar::new("Search")),
            },
            check: |v, s, who| count_for(s, v["parsed"]["clauses"].as_array().unwrap().len() as u64, who, "parsed clauses"),
        },
        // ── Attachments (facett-file) ─────────────────────────────────────────
        MatrixCell {
            key: "Attachments",
            signal: "file count",
            build: |s| match s {
                DataState::Populated => Box::new(facett::file::Files::local()),
                DataState::Empty => Box::new(facett::file::Files::new()),
            },
            check: |v, s, who| count_for(s, v["count"].as_u64().unwrap(), who, "count"),
        },
        // ── The 2026-08-20 roster completion — one cell per newly-wired component.
        //    Populated = the same in-crate fixture the deck mounts; empty = the
        //    crate's own no-data constructor (or an empty stub seam). ──────────────
        // ── cicd (facett-cicd) — the CI/CD forge panel ────────────────────────────
        MatrixCell {
            key: "cicd",
            signal: "pipeline count (summary.pipelines)",
            build: |s| match s {
                DataState::Populated => {
                    let mut p = facett_cicd::CicdPanel::demo();
                    p.title = "cicd".to_string(); // the deck/LEGEND key (as in DemoState::new)
                    Box::new(p)
                }
                DataState::Empty => Box::new(facett_cicd::CicdPanel::new("cicd", Vec::new())),
            },
            check: |v, s, who| count_for(s, v["summary"]["pipelines"].as_u64().unwrap(), who, "summary.pipelines"),
        },
        // ── brokkrview (facett-brokkrview) — the brokkr RUN viewer ────────────────
        MatrixCell {
            key: "brokkrview",
            signal: "DAG node count",
            build: |s| match s {
                DataState::Populated => Box::new(facett_brokkrview::BrokkrView::demo("brokkrview")),
                DataState::Empty => Box::new(facett_brokkrview::BrokkrView::new(
                    "brokkrview",
                    Vec::new(),
                    facett_brokkrview::TreeView::default(),
                    facett_brokkrview::DagView::default(),
                )),
            },
            check: |v, s, who| count_for(s, v["dag"]["nodes"].as_array().unwrap().len() as u64, who, "dag.nodes"),
        },
        // ── lineage (facett-lineage) — the data-lineage browser ───────────────────
        MatrixCell {
            key: "lineage",
            signal: "lineage event count",
            build: |s| match s {
                DataState::Populated => Box::new(facett_lineage::LineageView::demo()),
                DataState::Empty => Box::new(facett_lineage::LineageView::from_rows("lineage", Vec::new())),
            },
            check: |v, s, who| count_for(s, v["lineage"]["events"].as_u64().unwrap(), who, "lineage.events"),
        },
        // ── Fleet (facett-fleet-view) — the fleet gate board ──────────────────────
        MatrixCell {
            key: "Fleet",
            signal: "member count",
            build: |s| match s {
                DataState::Populated => Box::new(facett_fleet_view::FleetView::local()),
                DataState::Empty => Box::new(facett_fleet_view::FleetView::new("Fleet")),
            },
            check: |v, s, who| count_for(s, v["member_count"].as_u64().unwrap(), who, "member_count"),
        },
        // ── holger (facett-holger) — the registry & artifact browser ──────────────
        MatrixCell {
            key: "holger — registry & artifact browser",
            signal: "repo count",
            build: |s| match s {
                DataState::Populated => Box::new(facett_holger::RegistryBrowser::default()),
                DataState::Empty => Box::new(facett_holger::RegistryBrowser::from_model(
                    facett_holger::RegistryModel::default(),
                )),
            },
            check: |v, s, who| count_for(s, v["repo_count"].as_u64().unwrap(), who, "repo_count"),
        },
        // ── Ingest (facett-korp) — the collector roster ───────────────────────────
        MatrixCell {
            key: "Ingest",
            signal: "collector count",
            build: |s| match s {
                DataState::Populated => Box::new(facett_korp::IngestPane::demo()),
                DataState::Empty => Box::new(facett_korp::IngestPane::new("Ingest", Vec::new())),
            },
            check: |v, s, who| count_for(s, v["count"].as_u64().unwrap(), who, "count"),
        },
        // ── Sign in (facett-auth-ui) — the device-code grant, driven end-to-end ───
        // Populated = the stub grant COMPLETED (begin → poll → signed in), so the
        // readable signal is the signed-in subject; empty = the fresh signed-out
        // pane. Both states also pin the crate's invariant: no token value key.
        MatrixCell {
            key: "Sign in",
            signal: "signed-in subject (and NEVER a token value)",
            build: |s| match s {
                DataState::Populated => {
                    let mut p = facett_auth_ui::LoginPane::new(Box::new(
                        facett_auth_ui::StubLogin::new("dev@nordisk.dev"),
                    ));
                    p.begin(); // → AwaitingUser (user code + verification URL)
                    p.poll(); // the stub approves after 1 poll → SignedIn
                    Box::new(p)
                }
                DataState::Empty => Box::new(facett_auth_ui::LoginPane::new(Box::new(
                    facett_auth_ui::StubLogin::new("dev@nordisk.dev"),
                ))),
            },
            check: |v, s, who| {
                match s {
                    DataState::Populated => {
                        assert_eq!(v["state"], "signed_in", "[{who}] the stub grant completed");
                        assert_eq!(v["subject"], "dev@nordisk.dev", "[{who}] the signed-in subject is readable");
                    }
                    DataState::Empty => assert_eq!(v["state"], "signed_out", "[{who}] the fresh pane is signed out"),
                }
                // The crate's RED-when-broken invariant, asserted on every cell: the
                // seam exposes credential NAMES only — no token/secret/value key.
                for k in ["token", "secret", "value"] {
                    assert!(v.get(k).is_none(), "[{who}] state_json must never carry a `{k}` key");
                }
            },
        },
        // ── Binary analysis (facett-binview) ──────────────────────────────────────
        MatrixCell {
            key: "Binary analysis",
            signal: "crate_count (bloat treemap tiles)",
            build: |s| match s {
                DataState::Populated => Box::new(facett_binview::BinaryPane::new(Box::new(
                    facett_binview::StubBinaryData,
                ))),
                DataState::Empty => Box::new(facett_binview::BinaryPane::new(Box::new(EmptyBinaryData))),
            },
            check: |v, s, who| count_for(s, v["crate_count"].as_u64().unwrap(), who, "crate_count"),
        },
        // ── World coderoom (facett-coderoom-view) ─────────────────────────────────
        MatrixCell {
            key: "World coderoom",
            signal: "crate node count",
            build: |s| match s {
                DataState::Populated => Box::new(facett_coderoom_view::CoderoomPane::new(Box::new(
                    facett_coderoom_view::StubCoderoomData,
                ))),
                DataState::Empty => Box::new(facett_coderoom_view::CoderoomPane::new(Box::new(EmptyCoderoomData))),
            },
            check: |v, s, who| count_for(s, v["crates"].as_array().unwrap().len() as u64, who, "crates"),
        },
        // ── Claude (facett-claude) — the conversation pane over the echo backend ──
        // Populated = the demo's own seeding helper (`facett_demo::seeded_claude` —
        // one writer, the deck mounts the identical fixture), so the readable signal
        // is a real round-trip turn count.
        MatrixCell {
            key: "Claude",
            signal: "turn count (a seeded echo round-trip)",
            build: |s| match s {
                DataState::Populated => Box::new(facett_demo::seeded_claude()),
                DataState::Empty => Box::new(facett_claude::ClaudePane::new("Claude")),
            },
            check: |v, s, who| {
                count_for(s, v["turns"].as_u64().unwrap(), who, "turns");
                if s == DataState::Populated {
                    let last = v["last_assistant"].as_str().unwrap_or("");
                    assert!(
                        last.starts_with("[offline"),
                        "[{who}] the assistant turn is the honest offline echo, got {last:?}"
                    );
                }
            },
        },
        // ── About (facett-about via the demo-local about_tab wrapper) ─────────────
        MatrixCell {
            key: "About",
            signal: "framework bullet count (the identity card's sections)",
            build: |s| match s {
                DataState::Populated => Box::new(facett_demo::about_tab::AboutTab::new(facett_demo::about_tab::TITLE)),
                DataState::Empty => Box::new(facett_demo::about_tab::AboutTab::empty(facett_demo::about_tab::TITLE)),
            },
            check: |v, s, who| count_for(s, v["framework"].as_array().unwrap().len() as u64, who, "framework"),
        },
        // ── Deploy key (facett-deploykey, NATIVE-ONLY tab; this matrix is native) ──
        MatrixCell {
            key: "Deploy key",
            signal: "remotes_known (the probe fleet)",
            build: |s| match s {
                DataState::Populated => Box::new(facett_deploykey::DeployKeyDeck::demo()),
                DataState::Empty => Box::new(facett_deploykey::DeployKeyDeck::default()),
            },
            check: |v, s, who| {
                count_for(s, v["remotes_known"].as_u64().unwrap(), who, "remotes_known");
                if s == DataState::Empty {
                    // The crate's own honesty law: an empty deck says NOTHING WAS
                    // CHECKED, never green.
                    assert_eq!(v["green"], false, "[{who}] an empty deploy-key deck is not green");
                }
            },
        },
        // ── Build Thing (facett-buildthing, NATIVE-ONLY tab; this matrix is native) ─
        MatrixCell {
            key: "Build Thing",
            signal: "role-group count (the variant menu)",
            build: |s| match s {
                DataState::Populated => Box::new(facett_buildthing::demo()),
                DataState::Empty => Box::new(facett_buildthing::empty_deck()),
            },
            check: |v, s, who| count_for(s, v["roles"].as_array().unwrap().len() as u64, who, "roles"),
        },
        // ── GFX v2 (the renderer-track showcase: items 4 / 6 / 8) ─────────────────
        // A *parametric* surface: the scene is real WGS-84 Swedish geography compiled
        // in via `knut_popsim::geo`, so it is the same in both data states (it
        // exercises the render lanes, not the demo's fleet data).
        //
        // The readable signal is deliberately NOT "it rendered". It is the two things
        // that would be false if the lanes were broken while still painting: that the
        // 2D view satisfies EVERY 2D constraint (item 6's derivation actually landing
        // on the constraint surface, rather than a nearly-2D view that forgot one),
        // and that the pick lane's honesty fields are present so a dead device lane
        // cannot report as a working one.
        MatrixCell {
            key: "GFX v2",
            signal: "constrained-2D invariants + the pick lane's honesty fields (parametric real geography)",
            build: |_s| Box::new(facett_demo::gfx_v2::GfxV2Tab::new(facett_demo::gfx_v2::TITLE)),
            check: |v, _s, who| {
                // The scene is real and non-trivial — a 3-element fixture cannot make
                // labels collide or a pick tie-break wrong.
                let places = v["scene"]["places"].as_u64().unwrap();
                assert!(places > 500, "[{who}] the scene is real geography, got {places} places");
                assert_eq!(v["scene"]["cities"], 14, "[{who}] the 14 real population centres");
                // Names repeat hard, which is what exercises the label lane's
                // name-repeat slots at all.
                let names = v["scene"]["distinct_names"].as_u64().unwrap();
                assert!(names > 0 && places > names * 20, "[{who}] {places} places over {names} names");

                // ITEM 6: the derived 2D view is on the constraint surface, and the
                // stored 3D view is NOT — an assertion that passed on both would be
                // sitting on an identity value and could not tell them apart.
                assert_eq!(v["view"]["two_d"]["is_constrained_2d"], true, "[{who}] the derived 2D view is constrained");
                assert_eq!(v["view"]["two_d"]["tilt_deg"], 0.0, "[{who}] tilt collapsed");
                assert_eq!(v["view"]["two_d"]["ortho"], true, "[{who}] projection collapsed to ortho");
                assert_eq!(v["view"]["two_d"]["any_post"], false, "[{who}] the post-FX bypass is derived from the view");
                assert_eq!(v["view"]["three_d"]["is_constrained_2d"], false, "[{who}] the stored view is a real 3D view");
                assert_eq!(v["view"]["three_d"]["ortho"], false, "[{who}] and it is perspective");

                // ITEM 8 + 4: the honesty fields exist. `state_json` must always be
                // able to say a lane did NOT run; that is what stops a CPU fallback
                // from reading as a GPU success.
                assert!(v["pick"].get("declined").is_some(), "[{who}] declined clicks are reported");
                assert!(v["pick"].get("host_installed").is_some(), "[{who}] the pick host latch is reported");
                assert!(v["gpu"].get("adapter").is_some(), "[{who}] the adapter field exists");
                assert!(v["labels"].get("lane").is_some(), "[{who}] the label lane names itself");
                // Headless with no armed device: it must SAY cpu, not imply gpu.
                assert_eq!(v["labels"]["lane"], "cpu", "[{who}] un-armed, the label lane reports cpu");
                assert_eq!(v["gpu"]["armed"], false, "[{who}] un-armed, `armed` says so");
            },
        },
        // ── Errors (the facett UI ERROR-CODE showcase) ────────────────────────────
        // A *parametric* surface: the catalog it renders is
        // `facett_core::errcode::REGISTRY` — compiled in, so it is the same in both
        // data states (it exercises the code registry, not the demo's fleet data).
        // Readable signal: the registry size + the invariant that the on-screen
        // MATRIX carries exactly one row per registered code, plus the Phase-2
        // reaction pairs. (Coverage-gate cell — `Errors` shipped in `0b12255` with a
        // LEGEND row and a deck tab but NO matrix cell, which is what left both
        // coverage gates red at 75-vs-73.)
        MatrixCell {
            key: "Errors",
            signal: "code_count + one matrix row per registered code (parametric registry)",
            build: |_s| Box::new(errcode_tab::ErrCodeTab::new(errcode_tab::TITLE)),
            check: |v, _s, who| {
                let code_count = v["code_count"].as_u64().unwrap();
                assert!(code_count > 0, "[{who}] the error-code registry is non-empty, got {code_count}");
                // The rendered MATRIX is the registry, not a subset: one row per code.
                let rows = v["matrix"].as_array().expect("matrix is an array").len() as u64;
                assert_eq!(rows, code_count, "[{who}] one matrix row per registry code");
                assert!(v["component_count"].as_u64().unwrap() > 0, "[{who}] codes are grouped under components");
                // Phase 2: the (code × mount) reaction matrix the consumer tests generate from.
                assert!(v["reaction_pairs"].as_u64().unwrap() > 0, "[{who}] the reaction matrix is populated");
                assert_eq!(v["scheme"], "facet-<component>-<n>", "[{who}] the stable code scheme is reported");
            },
        },
        // ── Manual (the real in-app facett MANUAL — embedded book) ────────────────
        // A *parametric* surface: the Markdown + typeset SVG book is compiled in by
        // `build.rs`, so it is the same in both data states. Readable signal: the
        // embedded doc count + the invariant that the sidebar's hit list and the
        // reading area's section list are consistent with it. (Coverage-gate cell —
        // same `0b12255` gap as `Errors`; `Manual` had NO test coverage at all.)
        MatrixCell {
            key: "Manual",
            signal: "doc_count + hits/sections consistency (parametric embedded book)",
            build: |_s| Box::new(facett_manual::ManualPane::embedded("facett")),
            check: |v, _s, who| {
                assert_eq!(v["app"], "facett", "[{who}] the pane reports the app it documents");
                assert_eq!(v["embedded"], true, "[{who}] the book is compiled in, not read off disk");
                let doc_count = v["doc_count"].as_u64().unwrap();
                assert!(doc_count > 0, "[{who}] the embedded manual carries docs, got {doc_count}");
                let docs = v["docs"].as_array().expect("docs is an array").len() as u64;
                assert_eq!(docs, doc_count, "[{who}] the doc slug list is the whole book");
                // With an empty query every doc matches, so the sidebar lists them all.
                assert_eq!(v["query"], "", "[{who}] a fresh pane has no search filter");
                let hits = v["hits"].as_array().expect("hits is an array").len() as u64;
                assert_eq!(hits, doc_count, "[{who}] an empty query hits every doc");
                // Paged (the default) renders exactly the one selected section.
                assert_eq!(v["view_mode"], "paged", "[{who}] the default reading mode is paged");
                let sections = v["sections"].as_array().expect("sections is an array");
                assert_eq!(sections.len(), 1, "[{who}] Paged renders exactly one section");
                assert_eq!(sections[0], v["selected"], "[{who}] the rendered section IS the selected doc");
            },
        },
    ]
}

/// Build a detail card mirroring the demo's own `vessel_card` (one field per kind).
fn vessel_card(v: &data::Vessel) -> Card {
    Card::new(format!("Vessel {}", v.name))
        .with_id(format!("vessel-{}", v.id))
        .field(CardField::new("Name", FieldValue::Text(v.name.clone())))
        .field(CardField::new("Id", FieldValue::Number(v.id as f64)))
        .field(CardField::new(
            "Status",
            FieldValue::Enum { state: v.status.to_string(), options: data::STATUSES.iter().map(|s| s.to_string()).collect() },
        ))
        .field(CardField::new("Captain", FieldValue::User(v.crew.to_string())))
        .field(CardField::new("Mission", FieldValue::Progress(v.progress as f32)))
}

// ─────────────────────────────────────────────────────────────────────────────
// The menu (facett-menu) is a `CommandPalette`, NOT a `Facet`, so it's not in the
// deck/registry — but it IS a demo component (`LEGEND` key "menu"). It gets its
// own functional matrix below + is counted in the coverage gate.
// ─────────────────────────────────────────────────────────────────────────────

fn demo_commands() -> Vec<Command> {
    vec![
        Command::new("palette.cycle", "Cycle palette", "View").shortcut("Ctrl+P"),
        Command::new("fx.glow", "Toggle glow", "View").shortcut("Ctrl+G"),
        Command::new("export.csv", "Export grid as CSV", "Data").shortcut("Ctrl+E"),
    ]
}

// ─────────────────────────────────────────────────────────────────────────────
// THE MATRIX TEST.
// ─────────────────────────────────────────────────────────────────────────────

/// Drive the full **component × data × palette** matrix. Every cell injects real
/// values, renders headless with the palette active, and asserts the real rendered
/// data (the count signal) **and** that the palette was consumed. Reports per-cell
/// pass + the total cell count.
/// **The palette goldens were blessed with the DEV-ID chip painted, so every test in this
/// binary pins the gate open.**
///
/// The chip is on by default in a debug build and off in a release one (it ships behind
/// `FACETT_DEVID=1`), so a golden recorded in debug can only match in debug. MEASURED
/// 2026-08-31: `cargo test --release --workspace` failed
/// `screenshot_proof_populated_layout_across_every_palette` with **2 044 of 921 600 px
/// (0.22 %), max channel delta 134** — one missing chip, and a red that says nothing about
/// the palettes this file exists to prove.
///
/// Every `#[test]` here calls this, not only the one that renders the gallery. The gate is
/// process-global and decided ONCE: whichever test touches it first wins, and `force_gate`
/// panics rather than silently hand back the wrong gate. Calling it everywhere makes the
/// order libtest picks irrelevant, and it costs nothing.
fn force_devid_on() {
    facett_core::devid::force_gate(true);
}

#[test]
fn mega_matrix_component_x_data_x_palette() {
    force_devid_on();
    let cells = cells();
    let palettes: Vec<Theme> = Theme::ALL.iter().map(|c| c()).collect();

    let n_components = cells.len() + 1; // + the menu (handled separately below)
    let n_data = DataState::ALL.len();
    let n_palettes = palettes.len();

    let mut passed = 0usize;
    let mut rows: Vec<String> = Vec::new();

    // ── the Facet cells ──────────────────────────────────────────────────────
    for cell in &cells {
        for &state in &DataState::ALL {
            for theme in &palettes {
                let who = format!("{} / {} / {}", cell.key, state.label(), theme.name);
                let mut facet = (cell.build)(state);
                let painted = render_with_palette(facet.as_mut(), *theme, (800.0, 600.0));

                // 1. data signal — real rendered counts, not "didn't panic".
                (cell.check)(&painted.state, state, &who);
                // 2. palette consumption — the emitted palette, not a default.
                assert_consumed_palette(&painted, *theme, &who);

                passed += 1;
                rows.push(format!(
                    "  ✓ {:<10} {:<10} {:<16} signal={:<6} palette_ok",
                    cell.key,
                    state.label(),
                    theme.name,
                    cell.signal.split_whitespace().next().unwrap_or("?"),
                ));
            }
        }
    }

    // ── the menu cell (CommandPalette, not a Facet) ──────────────────────────
    // Data axis: populated = real commands (an empty query hits every enabled one);
    // empty = no commands. Palette axis: the palette is pinned on the ctx; the menu
    // reads it via ctx data when it paints. We assert the readable command/hit
    // counts and that the ctx carries the active palette (its consumption surface).
    for &state in &DataState::ALL {
        for theme in &palettes {
            let who = format!("menu / {} / {}", state.label(), theme.name);
            let commands = match state {
                DataState::Populated => demo_commands(),
                DataState::Empty => Vec::new(),
            };
            let mut menu = CommandPalette::default();
            menu.open(); // show the overlay so it paints from the active palette
            // Render the open palette with the theme active.
            let ctx = egui::Context::default();
            facett::set_theme(&ctx, *theme);
            ctx.run_ui(egui::RawInput::default(), |ui| {
                facett::set_theme(ui.ctx(), *theme);
                menu.ui(ui.ctx(), &commands);
            }).textures_delta.clear();
            let state_json = menu.state_json(&commands);

            let cmd_count = state_json["commands"].as_array().unwrap().len() as u64;
            let hit_count = state_json["hits"].as_array().unwrap().len() as u64;
            count_for(state, cmd_count, &who, "commands");
            match state {
                DataState::Populated => assert!(hit_count > 0, "[{who}] populated menu surfaces command hits"),
                DataState::Empty => assert_eq!(hit_count, 0, "[{who}] no commands → no hits"),
            }
            // Palette consumption: the active palette is the one on the ctx the menu
            // painted from (it reads `facett_theme` from ctx data, not `theme(ui)`).
            let ctx_palette = ctx.data(|d| d.get_temp::<Theme>(egui::Id::new("facett_theme")).map(|t| t.name));
            assert_eq!(ctx_palette, Some(theme.name), "[{who}] menu's ctx carries the active palette");

            passed += 1;
            rows.push(format!("  ✓ {:<10} {:<10} {:<16} signal=commands palette_ok", "menu", state.label(), theme.name));
        }
    }

    let total = n_components * n_data * n_palettes;

    // Report the matrix dimensions + per-cell passes + the total.
    eprintln!("\n══ facett-demo MEGA MATRIX ══");
    eprintln!("axes: {n_components} components × {n_data} data states × {n_palettes} palettes = {total} cells");
    for r in &rows {
        eprintln!("{r}");
    }
    eprintln!("── {passed}/{total} cells PASSED ──\n");

    assert_eq!(passed, total, "every matrix cell must pass");
    assert_eq!(total, n_components * n_data * n_palettes);
    // The matrix is real and non-trivial.
    assert!(total >= 16 * 2 * 7, "expected at least 16×2×7 cells, got {total}");
    // Feed the `nornir test` matrix: ok iff every component×data×palette cell passed.
    #[cfg(feature = "testmatrix")]
    facett::core::testmatrix::emit(
        "facett_demo.mega_matrix",
        "all_cells_pass",
        passed == total,
        &format!("{passed}/{total} cells ({n_components} components × {n_data} data × {n_palettes} palettes)"),
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// THE COVERAGE GATE — like the MCP one: the matrix must cover EVERY demo
// component. Add a component to the demo's LEGEND but forget the matrix → RED.
// ─────────────────────────────────────────────────────────────────────────────

/// Every key the matrix covers: the Facet cells + the menu.
fn matrix_keys() -> BTreeSet<&'static str> {
    let mut keys: BTreeSet<&'static str> = cells().iter().map(|c| c.key).collect();
    keys.insert("menu");
    keys
}

/// The demo's declared component set (`LEGEND` keys) — the source of truth.
fn legend_keys() -> BTreeSet<&'static str> {
    LEGEND.iter().map(|(k, _)| *k).collect()
}

#[test]
fn coverage_gate_every_demo_component_is_in_the_matrix() {
    force_devid_on();
    let legend = legend_keys();
    let matrix = matrix_keys();

    // Forgot a component in the matrix? (added to the demo, not here) → RED.
    let missing: Vec<&&str> = legend.difference(&matrix).collect();
    assert!(missing.is_empty(), "demo components NOT in the mega matrix (add them): {missing:?}");

    // A matrix cell for a component the demo dropped? → RED (stale matrix).
    let extra: Vec<&&str> = matrix.difference(&legend).collect();
    assert!(extra.is_empty(), "mega-matrix cells for components NOT in the demo LEGEND (stale): {extra:?}");

    assert_eq!(matrix, legend, "the matrix must cover EXACTLY the demo's components");
    // ── the roster count, kept honest against the deck ────────────────────────
    // A bare `assert_eq!(legend.len(), N)` with a hand-typed N is what went stale
    // here: `0b12255` added the `Errors` + `Manual` tabs to the deck AND to LEGEND,
    // `src/lib.rs`'s own `EXPECTED_FACET_COUNT` was bumped to match, and this number
    // was not — so the gate reported "73" while the demo shipped 75. Derive it from
    // the ONE roster `src/lib.rs` already maintains instead of retyping it (LAW:
    // reuse, do not twin), so the two can never drift apart again.
    //
    // `EXPECTED_FACET_COUNT` counts the deck's Facet tabs; LEGEND is those plus the
    // `menu` command palette, which is not a Facet and not in the deck.
    assert_eq!(
        legend.len(),
        facett_demo::EXPECTED_FACET_COUNT + 1,
        "LEGEND must be the deck's {} facets + the `menu` command palette; \
         if you added a component, add its deck tab, its LEGEND row, its mega-matrix cell \
         AND bump EXPECTED_FACET_COUNT in src/lib.rs",
        facett_demo::EXPECTED_FACET_COUNT,
    );
    // (The hand-typed `assert_eq!(legend.len(), 73, …)` that used to sit here is
    // GONE, not merely corrected. It is the exact guard that went stale — a second
    // copy of a number `src/lib.rs` already owned — and re-typing 75 would only
    // arm the same trap for whoever adds tab 76. The derived assertion above is
    // the by-construction replacement.)
}

/// **Proves the two coverage-gate cells' CHECKS bite** — the other half of the gate.
///
/// The coverage gate only proves a component has *a* cell. It says nothing about
/// whether that cell's `check` could ever fail: a cell whose check asserts nothing
/// specific satisfies the gate while watching nothing, which is precisely how
/// `Errors` and `Manual` could have been "covered" without being tested. So this
/// feeds each cell's check the WRONG facet's `state_json` and asserts it panics.
///
/// Red-when-broken: weaken either check to something both facets satisfy (drop the
/// `rows == code_count` invariant, assert only "didn't panic") and this test fails,
/// because the substituted state stops being rejected.
#[test]
fn the_coverage_gate_cells_checks_actually_bite() {
    force_devid_on();
    let cells = cells();
    let find = |key: &str| cells.iter().find(|c| c.key == key).unwrap_or_else(|| panic!("no `{key}` cell"));
    let errors = find("Errors");
    let manual = find("Manual");
    let theme = Theme::ALL[0]();

    // Render each cell's real facet once and keep its emitted state.
    let errors_state = render_with_palette((errors.build)(DataState::Populated).as_mut(), theme, (800.0, 600.0)).state;
    let manual_state = render_with_palette((manual.build)(DataState::Populated).as_mut(), theme, (800.0, 600.0)).state;

    // Each check must PASS on its own facet …
    (errors.check)(&errors_state, DataState::Populated, "self/Errors");
    (manual.check)(&manual_state, DataState::Populated, "self/Manual");

    // … and REJECT the other one's, plus an empty object (the "watching nothing"
    // shape). `catch_unwind` because a matrix check reports failure by panicking.
    let rejects = |check: Check, state: &Value, what: &str| {
        let s = state.clone();
        let r = std::panic::catch_unwind(move || check(&s, DataState::Populated, "substituted"));
        assert!(r.is_err(), "the check accepted {what} — it is not actually asserting anything specific");
    };
    // Silence the panic spam the deliberate failures print.
    let prev = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));
    rejects(errors.check, &manual_state, "the Manual pane's state as `Errors`");
    rejects(errors.check, &json!({}), "an empty object as `Errors`");
    rejects(manual.check, &errors_state, "the ErrCodeTab's state as `Manual`");
    rejects(manual.check, &json!({}), "an empty object as `Manual`");
    std::panic::set_hook(prev);
}

/// **Proves the gate bites** (like the MCP fake-tool test): inject a fake LEGEND
/// key and assert the gate's covering check would flag it. This is the RED proof —
/// a component added to the demo but missing from the matrix fails the gate above.
#[test]
fn coverage_gate_catches_a_fake() {
    force_devid_on();
    let matrix = matrix_keys();
    // Simulate a new demo component "newcomp" that nobody added to the matrix.
    let mut faked_legend = legend_keys();
    faked_legend.insert("newcomp");

    let missing: Vec<&&str> = faked_legend.difference(&matrix).collect();
    assert_eq!(missing, vec![&"newcomp"], "the gate must flag the uncovered fake component");
    assert_ne!(matrix, faked_legend, "a fake demo component makes the matrix != legend → the gate goes RED");
}

// ─────────────────────────────────────────────────────────────────────────────
// SCREENSHOT PROOF across every palette (LAW 4) — the gallery, visually proven.
//
// The single `snapshot.rs` golden proves *one* palette renders. This proves the
// representative populated layout renders to real pixels across **every**
// `Theme::ALL` palette, so the showcase gallery is verified themed, not just in
// one look. One golden per palette lives in `tests/snapshots/palette/` (git-lfs).
//
// Each shot is **compared** against its committed golden by
// `facett_core::golden::assert_golden_within(…, 2)` — it is not overwritten. Any pixel
// moved by more than 2 levels, a size change, or a missing golden fails the test, leaving
// `*.actual.png` / `*.diff.png` under `target/snapshot-failures/`. Bless an
// intended visual change with `UPDATE_SNAPSHOTS=1`.
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn screenshot_proof_populated_layout_across_every_palette() {
    force_devid_on();
    use facett_demo::DemoState;

    let out_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots/palette");

    let mut shots: Vec<(String, String)> = Vec::new();

    for (i, ctor) in Theme::ALL.iter().enumerate() {
        let theme = ctor();
        // A freshly populated demo per palette (every Facet component, real data).
        let mut demo = DemoState::new();
        demo.deck.set_palette(i);
        demo.deck.fx_mut().glow = true;
        assert_eq!(demo.fleet.len(), data::FLEET, "demo is populated before render");

        let theme_for_ui = theme;
        let mut harness = egui_kittest::Harness::builder()
            .with_size(egui::vec2(1280.0, 720.0))
            .build_ui(move |ui| {
                facett::set_theme(ui.ctx(), theme_for_ui);
                ui.heading(format!("facett-demo — palette: {}", theme_for_ui.name));
                demo.deck.ui(ui);
            });
        // Fixed frames so the virtualized grid/table, 3D spin and glow settle.
        harness.run_steps(4);

        let image = harness.render().expect("wgpu render produced an image");
        assert!(image.width() >= 1200 && image.height() >= 640, "[{}] rendered at requested size", theme.name);

        let slug = theme.name.replace('-', "_");
        let path = out_dir.join(format!("facett_demo_{slug}.png"));
        // THE GUARD: compare against the committed golden, never overwrite it.
        // Within 2 channel levels, per the golden module's rule for a host that jitters
        // (the bound and reasoning of facett-grid's snapshot.rs, 67a3dfb/8d13ba7).
        // MEASURED 2026-09-29 on oden's NVIDIA RTX 4090 (Vulkan, driver 595.91.07):
        // `palette/facett_demo_default` 15 565 of 921 600 pixels (1.69 %) differ with a max
        // channel delta of **2**, region x 2..1277 y 11..717; the render is byte-identical
        // on main 537ea35, 12264fd and this branch (actual PNG sha256 fc4101bc125f…). The
        // diff image is magenta only on glyph edges, graph edge strokes, node rings and
        // panel outlines — driver anti-aliasing rounding, no fill, layout or text change.
        // With the bound, every palette was reached (main stopped at the first): sci_fi
        // 14 858 (1.61 %), nordic_aurora 17 912 (1.94 %), cyberpunk_neon 14 906 (1.62 %),
        // amber_crt 15 703 (1.70 %), deep_space 18 463 (2.00 %), hugin_noir 17 512
        // (1.90 %) — each max delta 2, so the same AA class; 5/5 on the 4090.
        // The goldens stay the blessed ones; a structural regression moves channels by
        // tens to hundreds, far past 2.
        let verdict =
            facett::core::golden::assert_golden_within(&image, &path, &format!("palette/facett_demo_{slug}"), 2);
        shots.push((theme.name.to_string(), format!("{verdict:?}")));
    }

    // Every palette matched (or was explicitly blessed as) its committed golden.
    assert_eq!(shots.len(), Theme::ALL.len(), "one screenshot per palette");
    eprintln!("\n══ palette gallery ══");
    for (name, verdict) in &shots {
        eprintln!("  ✓ {name:<16} {verdict}");
    }
    eprintln!("── {} palette goldens COMPARED ──\n", shots.len());
    // Feed the matrix: ok iff every palette matched its committed golden (a
    // mismatch never reaches here — `assert_golden` panics first).
    #[cfg(feature = "testmatrix")]
    facett::core::testmatrix::emit(
        "facett_demo.palette_gallery",
        "every_palette_matches_golden",
        shots.len() == Theme::ALL.len(),
        &format!("{} palette goldens compared pixel-exactly", shots.len()),
    );
}