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

nordisk/facett

facett-graphview/src/metro.rs

//! **Metro / subway-line view** — render a test-coverage **chain** as a transit
//! line. Each line runs from a UI button (the START), through the functions on
//! the chain that **emit** a `functional_status` (the STATIONS), past the
//! pass-through functions that carry no emitter (thin ticks, "ridden through"),
//! into the gRPC handler (END) and finally the warehouse table (TERMINUS).
//!
//! A **station is lit** when its emit actually fired while the start button was
//! driven; **unlit** when the emit never ran (a gap in coverage). A line is
//! **green** only when every gating station (Start / Emitter / Grpc / Terminus)
//! is lit — pass-throughs never gate, they are just ridden through.
//!
//! # Pure + UI-agnostic model
//! [`MetroStation`] / [`MetroLine`] / [`MetroMap`] are plain data with no egui or
//! backend dependency. nornir (or any host) builds a [`MetroMap`] from its
//! marker-matrix and hands it to [`MetroView`] — facett never learns what a
//! "warehouse" is, only how to draw the line.
//!
//! [`MetroView`] is the canonical [`facett_core::Facet`]: it drops into a
//! `FacetDeck` and exposes the whole drawn map (lines, per-station {label, kind,
//! lit}, per-line + overall `green`) through [`Facet::state_json`] (LAW 6) so a
//! headless test/robot asserts what was drawn without a single pixel.

use facett_core::{FacetCaps, Theme, theme};
use serde::{Deserialize, Serialize};

/// What a station is on the chain — drives its glyph and whether it **gates**
/// the line's green verdict.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum StationKind {
    /// The UI button atom whose `.clicked()` handler starts the chain.
    Start,
    /// A function on the chain that emits a `functional_status` — a real station.
    Emitter,
    /// A function on the chain with **no** emitter — ridden through, a thin tick.
    PassThrough,
    /// The gRPC handler at the server boundary.
    Grpc,
    /// The warehouse table the chain ultimately lands in.
    Terminus,
    /// A **caller arm** off the gRPC station: the request reaches the verb from
    /// the **UI** (the viz tab code paths). Drawn as a diverging branch with a
    /// distinct glyph/colour and a "UI" marker.
    UiClient,
    /// A **caller arm** off the gRPC station: the request reaches the verb from
    /// the **CLI** (the `nornir`/`nornir-mcp` binaries). Diverging branch, "CLI"
    /// marker.
    CliClient,
}

impl StationKind {
    /// Stable lowercase tag (matches `state_json`).
    pub fn as_str(self) -> &'static str {
        match self {
            StationKind::Start => "start",
            StationKind::Emitter => "emitter",
            StationKind::PassThrough => "passthrough",
            StationKind::Grpc => "grpc",
            StationKind::Terminus => "terminus",
            StationKind::UiClient => "ui_client",
            StationKind::CliClient => "cli_client",
        }
    }

    /// Parse a host tag; unknown ⇒ [`StationKind::PassThrough`] (the inert kind).
    pub fn parse(s: &str) -> Self {
        match s {
            "start" => StationKind::Start,
            "emitter" => StationKind::Emitter,
            "grpc" => StationKind::Grpc,
            "terminus" => StationKind::Terminus,
            "ui_client" => StationKind::UiClient,
            "cli_client" => StationKind::CliClient,
            _ => StationKind::PassThrough,
        }
    }

    /// The short caller **marker** for a client arm (`UI`/`CLI`), or `None` for the
    /// trunk station kinds. Drives the marker glyph drawn at the arm endpoint and
    /// the `marker` field in `state_json`.
    pub fn marker(self) -> Option<&'static str> {
        match self {
            StationKind::UiClient => Some("UI"),
            StationKind::CliClient => Some("CLI"),
            _ => None,
        }
    }

    /// Is this a **caller-arm** kind (a fork branch off the gRPC station) rather
    /// than a trunk station?
    pub fn is_client_arm(self) -> bool {
        matches!(self, StationKind::UiClient | StationKind::CliClient)
    }

    /// The glyph drawn for this kind: ▶ Start, ◆ Grpc, ■ Terminus; emitters are a
    /// plain circle (drawn by the painter, no glyph), pass-throughs a minor tick;
    /// caller arms get a distinct ▲ (UI) / ◇ (CLI) so the fork reads at a glance.
    pub fn glyph(self) -> &'static str {
        match self {
            StationKind::Start => "▶",
            StationKind::Emitter => "●",
            StationKind::PassThrough => "·",
            StationKind::Grpc => "◆",
            StationKind::Terminus => "■",
            StationKind::UiClient => "▲",
            StationKind::CliClient => "◇",
        }
    }

    /// Does this kind **gate** the line's green verdict? Every trunk kind but the
    /// inert pass-through must be lit for the line to be green. Caller arms
    /// (`UiClient`/`CliClient`) are **coverage forks**, not trunk gates — an
    /// unlit arm means "this verb wasn't exercised through that client", which is
    /// informational, never a trunk-red. They never gate.
    pub fn gates(self) -> bool {
        !matches!(self, StationKind::PassThrough | StationKind::UiClient | StationKind::CliClient)
    }

    /// Is this a full **station** (a filled circle / glyph stop) vs. a thin
    /// pass-through tick? Pass-throughs are the only non-stations; caller arms are
    /// drawn stops (on the diverging branch).
    pub fn is_station(self) -> bool {
        !matches!(self, StationKind::PassThrough)
    }
}

/// One **caller arm** diverging off a trunk station (in practice the gRPC stop):
/// a marked client (UI viz vs CLI) that invokes the verb. The renderer draws it
/// as a branch leaving the fork point at an angle, distinct from the linear trunk.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetroBranch {
    /// Stable id (e.g. `caller::ui::Ops.RunTestMatrix`). Selection identity.
    pub id: String,
    /// Short human label drawn on the arm (e.g. the client/binary name).
    pub label: String,
    /// The arm kind — `UiClient` or `CliClient` (carries the `UI`/`CLI` marker).
    pub kind: StationKind,
    /// `true` = the verb was exercised through THIS client in the latest coverage
    /// run (a LIT arm). `false` = not yet proven through this client (unlit) —
    /// honest, never a trunk-red (arms don't gate).
    pub lit: bool,
}

impl MetroBranch {
    /// Construct a caller arm. The `kind` should be a client-arm kind
    /// (`UiClient`/`CliClient`); the marker is derived from it.
    pub fn new(id: impl Into<String>, label: impl Into<String>, kind: StationKind, lit: bool) -> Self {
        Self { id: id.into(), label: label.into(), kind, lit }
    }

    /// The arm's caller marker (`UI`/`CLI`), or `None` if a non-client kind was
    /// (mis)used.
    pub fn marker(&self) -> Option<&'static str> {
        self.kind.marker()
    }
}

/// One stop on a metro line.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetroStation {
    /// Stable id (the fully-qualified fn / button atom). Selection identity.
    pub id: String,
    /// Short human label drawn under the stop.
    pub label: String,
    pub kind: StationKind,
    /// `true` = this emit fired when the start was driven (a LIT stop).
    /// Pass-throughs default to `true` (nothing to light) and never gate.
    pub lit: bool,
    /// **Caller-side FORKS** off this station (the small DAG branch list). Empty
    /// for an ordinary linear stop; on the gRPC station it carries the marked
    /// caller arms (UI viz / CLI) that invoke the verb. The renderer draws these
    /// as diverging arms at the fork point, NOT as duplicate trunk rows.
    pub branches: Vec<MetroBranch>,
}

impl MetroStation {
    /// Construct a stop with no caller forks (the common linear case).
    /// Pass-throughs are reported lit (they carry no emit).
    pub fn new(id: impl Into<String>, label: impl Into<String>, kind: StationKind, lit: bool) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            kind,
            lit: if kind == StationKind::PassThrough { true } else { lit },
            branches: Vec::new(),
        }
    }

    /// Construct a stop that **forks** to caller arms (the gRPC station with its
    /// UI/CLI callers). The arms render as diverging branches off this stop.
    pub fn with_branches(
        id: impl Into<String>,
        label: impl Into<String>,
        kind: StationKind,
        lit: bool,
        branches: Vec<MetroBranch>,
    ) -> Self {
        let mut s = Self::new(id, label, kind, lit);
        s.branches = branches;
        s
    }

    /// Does this station fork to one or more caller arms?
    pub fn has_branches(&self) -> bool {
        !self.branches.is_empty()
    }
}

/// One metro line — a single test chain, button → … → warehouse.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetroLine {
    /// Stable id (the chain id, e.g. `bench_run→Bench.Submit`).
    pub id: String,
    /// Human label drawn at the head of the line.
    pub label: String,
    /// Stops in chain order: START first, TERMINUS last (by convention).
    pub stations: Vec<MetroStation>,
}

impl MetroLine {
    pub fn new(id: impl Into<String>, label: impl Into<String>, stations: Vec<MetroStation>) -> Self {
        Self { id: id.into(), label: label.into(), stations }
    }

    /// **The green verdict.** A line is green only when every **gating** station
    /// (Start / Emitter / Grpc / Terminus) is lit. Pass-throughs are ignored —
    /// they are ridden through, not lit, and never make a line red. A line with
    /// no gating stations is vacuously green.
    pub fn is_green(&self) -> bool {
        self.stations.iter().filter(|s| s.kind.gates()).all(|s| s.lit)
    }

    /// The gating stations that are **unlit** — the reason a line is red. Empty
    /// when [`is_green`](Self::is_green).
    pub fn unlit(&self) -> Vec<&MetroStation> {
        self.stations.iter().filter(|s| s.kind.gates() && !s.lit).collect()
    }

    /// Count of full stations (everything but pass-through ticks).
    pub fn station_count(&self) -> usize {
        self.stations.iter().filter(|s| s.kind.is_station()).count()
    }
}

/// The whole map — every chain as a line.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct MetroMap {
    pub lines: Vec<MetroLine>,
}

impl MetroMap {
    pub fn new(lines: Vec<MetroLine>) -> Self {
        Self { lines }
    }

    /// Every line green ⇒ the whole map is green (the test-matrix is covered).
    /// An empty map is vacuously green.
    pub fn is_green(&self) -> bool {
        self.lines.iter().all(|l| l.is_green())
    }

    /// Count of green lines.
    pub fn green_count(&self) -> usize {
        self.lines.iter().filter(|l| l.is_green()).count()
    }
}

// ── the Facet component ──────────────────────────────────────────────────────

/// Layout metrics for the drawn lines (all in points).
const ROW_H: f32 = 64.0;
const LINE_LEFT: f32 = 150.0;
const STOP_GAP: f32 = 96.0;
const STATION_R: f32 = 9.0;
const TICK_R: f32 = 3.0;
const LINE_W: f32 = 6.0;

/// A robot-/CLI-addressable control message (FC-2) — the named boundary a headless
/// driver (or a host) drives the metro view through. Applied by
/// [`MetroView::update`]; the same [`Msg`] a host's drill-in gesture would produce.
#[derive(Clone, Debug, PartialEq)]
pub enum Msg {
    /// Drill into a line by its stable id (FC-5) — the host's line select.
    SelectLine(String),
    /// Clear the drill-in selection.
    ClearSelection,
}

/// Side work as data (FC-8). The metro view does no I/O — every [`Msg`] mutates only
/// the in-memory [`MetroState`] — so this is uninhabited on purpose: the type-checked
/// statement that [`MetroView::update`] never asks the host to do anything.
#[derive(Clone, Debug, PartialEq)]
pub enum Effect {}

/// **The complete observable state (FC-1 / FC-3)** of a [`MetroView`], in one
/// serializable, round-trippable struct: the whole drawn [`MetroMap`] plus the
/// drilled-in selection (keyed on the line **id**, FC-5). [`MetroView::state`] hands
/// back a `&MetroState`; a headless driver ([`facett_core::harness`]) snapshots it
/// after feeding a `Vec<Msg>`.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct MetroState {
    /// Every chain as a line — the whole drawn map.
    pub map: MetroMap,
    /// Selected line id (for a host's drill-in), if any.
    pub selected: Option<String>,
}

/// A subway-map view of test-coverage chains — a [`Facet`]. Renders each
/// [`MetroLine`] as a horizontal coloured line with circular stops; green tint
/// when the line is fully lit, red unlit stops when not.
pub struct MetroView {
    title: String,
    /// All observable state (FC-3).
    state: MetroState,
}

impl MetroView {
    /// An empty view with a title.
    pub fn new(title: impl Into<String>) -> Self {
        Self { title: title.into(), state: MetroState::default() }
    }

    /// Replace the map (the push model — call each refresh).
    pub fn set_map(&mut self, map: MetroMap) {
        self.state.map = map;
    }

    /// Re-title the view (the deck keys facets off [`Facet::title`], so a host that
    /// mounts the `local()`/`remote()` view under a specific tab key sets it here).
    pub fn set_title(&mut self, title: impl Into<String>) {
        self.title = title.into();
    }

    /// The current map.
    pub fn map(&self) -> &MetroMap {
        &self.state.map
    }

    /// **FC-3** — read the complete observable state at any frame boundary.
    pub fn state(&self) -> &MetroState {
        &self.state
    }

    /// **FC-2 / FC-8** — the single mutation path. Apply one [`Msg`]; returns the
    /// (always empty) [`Effect`]s the host should run. A host's line drill-in routes
    /// its [`Msg`] here too, so live == headless.
    pub fn update(&mut self, msg: Msg) -> Vec<Effect> {
        match msg {
            Msg::SelectLine(id) => self.state.selected = Some(id),
            Msg::ClearSelection => self.state.selected = None,
        }
        Vec::new()
    }

    /// Select a line by id (`None` clears). A thin wrapper over the FC-2
    /// [`update`](Self::update) mutation path.
    pub fn select(&mut self, id: Option<String>) {
        let _ = match id {
            Some(i) => self.update(Msg::SelectLine(i)),
            None => self.update(Msg::ClearSelection),
        };
    }

    /// **Discovery-contract `local()`** — the canonical no-arg ctor the test
    /// matrix calls to enumerate this facet. Builds a synthetic 2-line demo map
    /// (one fully-lit/green chain, one with an unlit emitter/red) so the view
    /// renders real lines with no fixture on disk. Mirrors the rest of the
    /// facett discovery law (`OsmView::local()` etc.).
    pub fn local() -> Self {
        let mut v = Self::new("Metro");
        v.set_map(demo_map());
        v
    }

    /// **Discovery-contract `remote()`** — same surface, the variant a host
    /// builds from a server-loaded marker matrix. No transport in facett, so the
    /// wiring is identical; kept so the matrix sees both ctors.
    pub fn remote() -> Self {
        let mut v = Self::local();
        v.title = "Metro (remote)".into();
        v
    }

    /// The fill colour for a stop, given the line's green verdict and the stop's
    /// lit state, derived from the active [`Theme`] so it follows the palette.
    fn stop_color(th: &Theme, line_green: bool, lit: bool) -> egui::Color32 {
        if !lit {
            // Unlit gating stop — the warm red used elsewhere in facett (no
            // semantic red in the base palette).
            facett_core::look::RED
        } else if line_green {
            th.point // the theme's green-ish "point" accent
        } else {
            th.accent // lit, but the line is red elsewhere — neutral accent
        }
    }

    /// The line's stroke colour: green when fully lit, else a dim neutral.
    fn line_color(th: &Theme, line_green: bool) -> egui::Color32 {
        if line_green { th.point } else { th.text_dim }
    }

    /// The fill/stroke colour for a **caller arm** (a fork branch): UI arms use the
    /// theme accent, CLI arms a warm amber, both dimmed when the arm is unlit (the
    /// verb wasn't exercised through that client). Distinct from the trunk green so
    /// the fork reads as "who calls this", not "is the chain covered".
    fn arm_color(th: &Theme, kind: StationKind, lit: bool) -> egui::Color32 {
        let base = match kind {
            StationKind::CliClient => egui::Color32::from_rgb(214, 160, 70), // amber CLI
            _ => th.accent,                                                  // UI viz
        };
        if lit {
            base
        } else {
            // Dim an unlit arm toward the neutral dim text — present but unproven.
            egui::Color32::from_rgba_unmultiplied(base.r(), base.g(), base.b(), 120)
        }
    }
}

/// Per-row vertical span (points) reserved ABOVE the trunk for the diverging
/// caller arms, so a forked row doesn't overlap its neighbour.
const ARM_RISE: f32 = 30.0;
/// Horizontal offset (points) of an arm's endpoint from the fork station.
const ARM_RUN: f32 = 34.0;
/// Radius of a caller-arm endpoint stop.
const ARM_R: f32 = 7.0;

/// The synthetic demo map used by [`MetroView::local`] — also the shape a host
/// produces. Line A is all-lit (green) and its gRPC verb **forks to BOTH** caller
/// arms (UI viz + CLI, both lit); line B has one unlit emitter (red) and its verb
/// is **called only by the CLI** (one CLI arm).
pub fn demo_map() -> MetroMap {
    let line_a = MetroLine::new(
        "bench_run→Bench.Submit",
        "Bench Run",
        vec![
            MetroStation::new("ui::bench_button", "Run", StationKind::Start, true),
            MetroStation::new("bench::collect", "collect", StationKind::Emitter, true),
            MetroStation::new("bench::normalize", "normalize", StationKind::PassThrough, true),
            MetroStation::new("bench::submit", "submit", StationKind::Emitter, true),
            // The gRPC verb FORKS back to its two callers — UI viz + CLI, both lit.
            MetroStation::with_branches(
                "grpc::Bench.Submit",
                "Bench.Submit",
                StationKind::Grpc,
                true,
                vec![
                    MetroBranch::new("caller::ui::Bench.Submit", "viz", StationKind::UiClient, true),
                    MetroBranch::new("caller::cli::Bench.Submit", "nornir", StationKind::CliClient, true),
                ],
            ),
            MetroStation::new("warehouse::bench_runs", "bench_runs", StationKind::Terminus, true),
        ],
    );
    let line_b = MetroLine::new(
        "docs_export→Docs.Render",
        "Docs Export",
        vec![
            MetroStation::new("ui::docs_button", "Export", StationKind::Start, true),
            MetroStation::new("docs::gather", "gather", StationKind::Emitter, true),
            MetroStation::new("docs::render_svg", "render_svg", StationKind::Emitter, false), // unlit!
            // This verb is called ONLY by the CLI — a single CLI arm.
            MetroStation::with_branches(
                "grpc::Docs.Render",
                "Docs.Render",
                StationKind::Grpc,
                true,
                vec![MetroBranch::new("caller::cli::Docs.Render", "nornir-mcp", StationKind::CliClient, true)],
            ),
            MetroStation::new("warehouse::doc_exports", "doc_exports", StationKind::Terminus, true),
        ],
    );
    MetroMap::new(vec![line_a, line_b])
}

impl MetroView {
    /// The copyable text: the selected line's `label` when one is selected, else
    /// every line label, one per line.
    pub fn copy_text(&self) -> Option<String> {
        if self.state.map.lines.is_empty() {
            return None;
        }
        if let Some(id) = self.state.selected.as_deref()
            && let Some(l) = self.state.map.lines.iter().find(|l| l.id == id)
        {
            return Some(l.label.clone());
        }
        Some(self.state.map.lines.iter().map(|l| l.label.clone()).collect::<Vec<_>>().join("\n"))
    }
}

// ── typed copy (§16) — read-only: selected line label or the label list ───────
impl facett_core::clip::CopySource for MetroView {
    fn copy_kinds(&self) -> &[facett_core::clip::ClipKind] {
        use facett_core::clip::ClipKind;
        &[ClipKind::Text]
    }
    fn copy_payload(&self) -> Option<facett_core::clip::ClipPayload> {
        self.copy_text().map(facett_core::clip::ClipPayload::Text)
    }
}

impl MetroView {
    /// **FC-9 render** — a **pure** function of `&self`: it paints the header + the
    /// subway lines and *returns* the [`Msg`]s the interactions produced (none today —
    /// the trunk is `Sense::hover`, selection is host-driven via [`select`](Self::select)).
    /// It MUST NOT mutate the [`MetroState`]; the
    /// [`impl_facet_via_elm!`](facett_core::impl_facet_via_elm) bridge applies any
    /// returned messages through [`update`](Self::update).
    pub fn view(&self, ui: &mut egui::Ui) -> Vec<Msg> {
        let msgs: Vec<Msg> = Vec::new();
        let th = theme(ui);

        // ── header: line + green counts ────────────────────────────────────
        ui.horizontal_wrapped(|ui| {
            let total = self.state.map.lines.len();
            let green = self.state.map.green_count();
            ui.label(egui::RichText::new(format!("{total} line(s)")).color(th.text).strong());
            ui.separator();
            ui.label(
                egui::RichText::new(format!("✓ {green} green"))
                    .color(if green == total && total > 0 { th.point } else { th.text_dim }),
            );
            ui.label(
                egui::RichText::new(format!("✗ {} red", total - green))
                    .color(if green < total { facett_core::look::RED } else { th.text_dim }),
            );
        });
        ui.separator();

        if self.state.map.lines.is_empty() {
            // The empty-scene state carries the stable UI error code facet-graphview-1
            // (facett_core::errcode) on its a11y atom so tests + consumers react to the
            // CODE, not a matched string.
            let resp = ui.label(egui::RichText::new("no lines").color(th.text_dim));
            resp.widget_info(|| {
                facett_core::a11y::Semantics::error("no lines").error_code("facet-graphview-1").widget_info()
            });
            #[cfg(feature = "testmatrix")]
            facett_core::testmatrix::emit(
                "facett-graphview::MetroView::view",
                "ui_render",
                true,
                "lines=0 drew=empty_hint",
            );
            return msgs;
        }

        // ── each line gets a row, painted as a horizontal track ────────────
        let n = self.state.map.lines.len();
        let (rect, _resp) = ui.allocate_exact_size(
            // Reserve ARM_RISE of headroom so the diverging caller arms (which rise
            // ABOVE the trunk on a forked row) never overlap the row above.
            egui::vec2(ui.available_width().max(640.0), (ROW_H + ARM_RISE) * n as f32 + 16.0),
            egui::Sense::hover(),
        );
        let painter = ui.painter_at(rect);

        for (li, line) in self.state.map.lines.iter().enumerate() {
            let green = line.is_green();
            // Bias the trunk toward the lower part of the row band so the arms have
            // room to rise above it.
            let y = rect.top() + (ROW_H + ARM_RISE) * li as f32 + ARM_RISE + ROW_H * 0.5;
            let line_col = MetroView::line_color(&th, green);

            // Line label at the head.
            painter.text(
                egui::pos2(rect.left() + 8.0, y),
                egui::Align2::LEFT_CENTER,
                &line.label,
                egui::FontId::proportional(14.0),
                if green { th.point } else { th.text },
            );

            // The track: a thick stroke from the first to the last stop.
            let x0 = rect.left() + LINE_LEFT;
            let stops = &line.stations;
            if !stops.is_empty() {
                let x_last = x0 + STOP_GAP * (stops.len() as f32 - 1.0);
                painter.line_segment(
                    [egui::pos2(x0, y), egui::pos2(x_last.max(x0), y)],
                    egui::Stroke::new(LINE_W, line_col),
                );
            }

            // Each stop.
            for (si, st) in stops.iter().enumerate() {
                let x = x0 + STOP_GAP * si as f32;
                let center = egui::pos2(x, y);
                if st.kind == StationKind::PassThrough {
                    // Thin minor tick — ridden through, not a station.
                    painter.circle_filled(center, TICK_R, th.text_dim);
                } else {
                    let fill = MetroView::stop_color(&th, green, st.lit);
                    if st.lit {
                        painter.circle_filled(center, STATION_R, fill);
                    } else {
                        // Hollow red ring for an unlit gating stop.
                        painter.circle_stroke(center, STATION_R, egui::Stroke::new(2.5_f32, fill));
                    }
                    // Distinct glyph for the chain endpoints.
                    let glyph = st.kind.glyph();
                    if matches!(st.kind, StationKind::Start | StationKind::Grpc | StationKind::Terminus) {
                        painter.text(
                            egui::pos2(x, y - STATION_R - 11.0),
                            egui::Align2::CENTER_CENTER,
                            glyph,
                            egui::FontId::proportional(12.0),
                            th.text,
                        );
                    }
                }
                // Station label under the stop.
                painter.text(
                    egui::pos2(x, y + STATION_R + 9.0),
                    egui::Align2::CENTER_CENTER,
                    &st.label,
                    egui::FontId::proportional(10.0),
                    th.text_dim,
                );

                // ── CALLER-SIDE FORKS: diverging arms off this station ───────
                // Each caller arm (UI viz / CLI) rises as a short diagonal branch
                // from the fork point, fanned left→right, marked UI/CLI. NOT a
                // duplicate trunk row — a real divergence at the gRPC stop.
                if st.has_branches() {
                    let m = st.branches.len();
                    for (bi, br) in st.branches.iter().enumerate() {
                        // Fan the arms across a small horizontal spread above the stop.
                        let frac = if m > 1 { bi as f32 / (m as f32 - 1.0) - 0.5 } else { 0.0 };
                        let ex = x + frac * (ARM_RUN * (m as f32).min(2.0));
                        let ey = y - ARM_RISE;
                        let col = MetroView::arm_color(&th, br.kind, br.lit);
                        // The arm stroke from the fork point up to the endpoint.
                        painter.line_segment(
                            [center, egui::pos2(ex, ey)],
                            egui::Stroke::new(3.0_f32, col),
                        );
                        // Endpoint stop: filled when lit, hollow ring when unlit.
                        let ep = egui::pos2(ex, ey);
                        if br.lit {
                            painter.circle_filled(ep, ARM_R, col);
                        } else {
                            painter.circle_stroke(ep, ARM_R, egui::Stroke::new(2.0_f32, col));
                        }
                        // The arm's UI/CLI marker glyph + tag above the endpoint.
                        painter.text(
                            egui::pos2(ex, ey - ARM_R - 8.0),
                            egui::Align2::CENTER_CENTER,
                            format!("{} {}", br.kind.glyph(), br.marker().unwrap_or("")),
                            egui::FontId::proportional(10.0),
                            col,
                        );
                    }
                }
            }
        }

        #[cfg(feature = "testmatrix")]
        facett_core::testmatrix::emit(
            "facett-graphview::MetroView::view",
            "ui_render",
            !self.state.map.lines.is_empty(),
            &format!("lines={} green={}", self.state.map.lines.len(), self.state.map.green_count()),
        );

        msgs
    }
}

// ── FC-2 / FC-3 / FC-8 / FC-9: the canonical Elm split ────────────────────────
impl facett_core::Elm for MetroView {
    type Model = MetroState;
    type Msg = Msg;
    type Effect = Effect;

    fn title(&self) -> &str {
        &self.title
    }
    fn state(&self) -> &MetroState {
        &self.state
    }
    fn update(&mut self, msg: Msg) -> Vec<Effect> {
        MetroView::update(self, msg)
    }
    fn view(&self, ui: &mut egui::Ui) -> Vec<Msg> {
        MetroView::view(self, ui)
    }
}

// The bridge macro writes `impl Facet for MetroView` from the `Elm` impl: `title`,
// the FC-9 `ui` loop (`for m in view(ui) { update(m) }`), plus the extra overrides
// below. **Form 3** (`custom_state_json`) because the view publishes a RICHER
// `state_json` than a plain `serde(state())`: the derived green verdict + per-line
// station/unlit/branch topology (the keys facett-demo's mega_matrix + the metro_view
// test read) come from the [`MetroMap`] verdict helpers, not the raw serde dump — so
// the default `state_json` is suppressed and this byte-for-byte one supplied.
facett_core::impl_facet_via_elm!(MetroView, custom_state_json, {
    fn state_json(&self) -> serde_json::Value {
        serde_json::json!({
            "title": self.title,
            "lines": self.state.map.lines.len(),
            "green_lines": self.state.map.green_count(),
            "green": self.state.map.is_green(),
            "selected": self.state.selected,
            "line": self.state.map.lines.iter().map(|l| serde_json::json!({
                "id": l.id,
                "label": l.label,
                "green": l.is_green(),
                "station_count": l.station_count(),
                "unlit": l.unlit().iter().map(|s| s.label.clone()).collect::<Vec<_>>(),
                "stations": l.stations.iter().map(|s| serde_json::json!({
                    "id": s.id,
                    "label": s.label,
                    "kind": s.kind.as_str(),
                    "lit": s.lit,
                    // Caller-side FORKS (LAW 6): the marked UI/CLI arms off this
                    // station. Empty array for an ordinary linear stop.
                    "branches": s.branches.iter().map(|b| serde_json::json!({
                        "id": b.id,
                        "label": b.label,
                        "kind": b.kind.as_str(),
                        "marker": b.marker(),
                        "lit": b.lit,
                    })).collect::<Vec<_>>(),
                })).collect::<Vec<_>>(),
            })).collect::<Vec<_>>(),
            // The stable UI ERROR CODE for the empty-scene state (facett_core::errcode):
            // present so tests + consumers react to the CODE, not a matched string.
            "error_code": if self.state.map.lines.is_empty() {
                serde_json::json!("facet-graphview-1")
            } else {
                serde_json::Value::Null
            },
        })
    }

    /// STRUCTURAL severity (the Robot-UI gate signal): RED when the metro map has no
    /// lines to lay out (the facet-graphview-1 empty state), the Info floor otherwise.
    fn severity(&self) -> facett_core::Severity {
        if self.state.map.lines.is_empty() {
            facett_core::Severity::Error
        } else {
            facett_core::Severity::Info
        }
    }

    fn copy(&mut self) -> Option<String> {
        use facett_core::clip::CopySource as _;
        self.copy_payload().map(|p| p.as_text())
    }

    fn selection_json(&self) -> serde_json::Value {
        match &self.state.selected {
            Some(id) => serde_json::json!({ "line": id }),
            None => serde_json::Value::Null,
        }
    }

    /// Reads the active [`Theme`] (stops/line colours follow the palette) and
    /// refits to any host size; a line is selectable for drill-in.
    fn caps(&self) -> FacetCaps {
        FacetCaps::NONE.themeable().resizable().selectable().copyable()
    }

    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
        Some(self)
    }
});

#[cfg(test)]
mod tests {
    use super::*;
    // `Facet` for `state_json`/`selection_json`/`title`/`caps`; `state()`/`select()`
    // are inherent.
    use facett_core::Facet;

    #[test]
    fn typed_copy_is_selected_line_or_the_line_list() {
        use facett_core::clip::{ClipKind, CopySource};
        let mut v = MetroView::new("metro");
        v.set_map(demo_map());
        let p = v.copy_payload().expect("populated map copies");
        assert_eq!(p.kind(), ClipKind::Text);
        assert_eq!(p.as_text(), "Bench Run\nDocs Export");
        // Select a line -> the copy narrows to that line's label.
        v.select(Some("bench_run\u{2192}Bench.Submit".into()));
        assert_eq!(v.copy_payload().unwrap().as_text(), "Bench Run");
    }

    #[test]
    fn green_only_when_every_gating_station_lit() {
        let line = MetroLine::new(
            "l",
            "L",
            vec![
                MetroStation::new("s", "start", StationKind::Start, true),
                MetroStation::new("e", "emit", StationKind::Emitter, true),
                MetroStation::new("p", "pass", StationKind::PassThrough, false), // pass-through "unlit" ignored
                MetroStation::new("g", "grpc", StationKind::Grpc, true),
                MetroStation::new("t", "wh", StationKind::Terminus, true),
            ],
        );
        assert!(line.is_green(), "all gating stops lit + a pass-through doesn't gate");
        assert!(line.unlit().is_empty());
    }

    #[test]
    fn one_unlit_emitter_makes_line_red() {
        let line = MetroLine::new(
            "l",
            "L",
            vec![
                MetroStation::new("s", "start", StationKind::Start, true),
                MetroStation::new("e", "emit", StationKind::Emitter, false),
            ],
        );
        assert!(!line.is_green());
        assert_eq!(line.unlit().len(), 1);
        assert_eq!(line.unlit()[0].label, "emit");
    }

    #[test]
    fn passthrough_constructed_lit_and_never_gates() {
        let p = MetroStation::new("p", "p", StationKind::PassThrough, false);
        assert!(p.lit, "pass-through is forced lit (nothing to light)");
        assert!(!p.kind.gates());
        assert!(!p.kind.is_station());
    }

    #[test]
    fn kind_parse_roundtrip() {
        for k in [
            StationKind::UiClient,
            StationKind::CliClient,
            StationKind::Start,
            StationKind::Emitter,
            StationKind::PassThrough,
            StationKind::Grpc,
            StationKind::Terminus,
        ] {
            assert_eq!(StationKind::parse(k.as_str()), k);
        }
        assert_eq!(StationKind::parse("bogus"), StationKind::PassThrough);
    }

    #[test]
    fn map_green_iff_all_lines_green() {
        let m = demo_map();
        assert_eq!(m.lines.len(), 2);
        assert!(!m.is_green(), "line B has an unlit emitter");
        assert_eq!(m.green_count(), 1);
    }

    #[test]
    fn local_builds_two_line_demo() {
        let v = MetroView::local();
        assert_eq!(v.map().lines.len(), 2);
        assert!(v.map().lines[0].is_green());
        assert!(!v.map().lines[1].is_green());
    }

    /// `set_title` re-keys the view (the deck addresses facets by `title()`) while
    /// leaving the map intact — the seam a host (facett-demo) mounts `local()` under
    /// a specific tab key with. Inject a title, assert it lands in `title()` AND the
    /// folded `state_json["title"]`, and the two-line map still renders.
    #[test]
    fn set_title_rekeys_view_and_keeps_the_map() {
        let mut v = MetroView::local();
        v.set_title("metro");
        assert_eq!(Facet::title(&v), "metro", "title() reflects the new key");
        let sj = v.state_json();
        assert_eq!(sj["title"], "metro", "state_json carries the new title");
        assert_eq!(sj["lines"].as_u64(), Some(2), "the demo map survived the re-title");
        assert_eq!(sj["green_lines"].as_u64(), Some(1), "one green / one red line still");
    }

    // ── caller-side FORKS ───────────────────────────────────────────────────

    /// Caller arms are NON-gating coverage forks: an UNLIT arm must NOT turn the
    /// trunk red. A line that's green on its trunk stays green regardless of arm
    /// state — the fork is "who calls it", not "is the chain covered".
    #[test]
    fn caller_arms_never_gate_the_trunk() {
        assert!(!StationKind::UiClient.gates());
        assert!(!StationKind::CliClient.gates());
        assert!(StationKind::UiClient.is_client_arm() && StationKind::CliClient.is_client_arm());

        let line = MetroLine::new(
            "l",
            "L",
            vec![
                MetroStation::new("s", "start", StationKind::Start, true),
                MetroStation::with_branches(
                    "g",
                    "grpc",
                    StationKind::Grpc,
                    true,
                    vec![
                        MetroBranch::new("ui", "viz", StationKind::UiClient, false), // UNLIT arm
                        MetroBranch::new("cli", "nornir", StationKind::CliClient, true),
                    ],
                ),
                MetroStation::new("t", "wh", StationKind::Terminus, true),
            ],
        );
        assert!(line.is_green(), "an unlit caller arm does not gate the green trunk");
        assert!(line.unlit().is_empty(), "arms are not counted as unlit gating stops");
    }

    /// The markers: `UiClient` → "UI", `CliClient` → "CLI", trunk kinds → None.
    #[test]
    fn client_kinds_carry_the_right_marker() {
        assert_eq!(StationKind::UiClient.marker(), Some("UI"));
        assert_eq!(StationKind::CliClient.marker(), Some("CLI"));
        assert_eq!(StationKind::Grpc.marker(), None);
        let b = MetroBranch::new("x", "viz", StationKind::UiClient, true);
        assert_eq!(b.marker(), Some("UI"));
    }

    /// LAW 6: a verb called by BOTH ui+cli serialises TWO marked arms; a verb
    /// called by only the CLI serialises ONE CLI arm — asserted on `state_json`
    /// DATA (the branch topology + per-arm marker), no pixels.
    #[test]
    fn state_json_carries_the_branch_topology_and_markers() {
        let v = MetroView::local(); // demo: line A forks UI+CLI, line B forks CLI-only
        let sj = v.state_json();
        let lines = sj["line"].as_array().unwrap();

        // Line A's gRPC stop → two arms, marked UI + CLI, both lit.
        let line_a = &lines[0];
        let grpc_a = line_a["stations"]
            .as_array()
            .unwrap()
            .iter()
            .find(|s| s["kind"] == "grpc")
            .expect("line A has a grpc station");
        let arms_a = grpc_a["branches"].as_array().unwrap();
        assert_eq!(arms_a.len(), 2, "the verb called by BOTH renders two arms");
        let markers_a: Vec<&str> = arms_a.iter().map(|b| b["marker"].as_str().unwrap()).collect();
        assert!(markers_a.contains(&"UI") && markers_a.contains(&"CLI"), "UI+CLI markers: {markers_a:?}");
        assert!(arms_a.iter().all(|b| b["lit"].as_bool().unwrap()), "both arms lit");
        assert_eq!(arms_a.iter().find(|b| b["marker"] == "UI").unwrap()["kind"], "ui_client");
        assert_eq!(arms_a.iter().find(|b| b["marker"] == "CLI").unwrap()["kind"], "cli_client");

        // Line B's gRPC stop → exactly ONE CLI arm.
        let line_b = &lines[1];
        let grpc_b = line_b["stations"]
            .as_array()
            .unwrap()
            .iter()
            .find(|s| s["kind"] == "grpc")
            .expect("line B has a grpc station");
        let arms_b = grpc_b["branches"].as_array().unwrap();
        assert_eq!(arms_b.len(), 1, "the CLI-only verb renders a single arm");
        assert_eq!(arms_b[0]["marker"], "CLI");
        assert_eq!(arms_b[0]["kind"], "cli_client");

        // A non-forking stop (the Start) carries an empty branch array.
        let start_a = line_a["stations"].as_array().unwrap().iter().find(|s| s["kind"] == "start").unwrap();
        assert_eq!(start_a["branches"].as_array().unwrap().len(), 0, "linear stop has no forks");
    }

    /// RAGNARÖK (LAW 2): an EMPTY map carries no lines — the empty-state, never a
    /// vacuous green-with-data. (the host paints the red empty hint.)
    #[test]
    fn empty_map_is_the_empty_state() {
        let v = MetroView::new("Metro");
        let sj = v.state_json();
        assert_eq!(sj["lines"].as_u64(), Some(0), "no lines on an empty map");
        assert_eq!(sj["line"].as_array().unwrap().len(), 0);
        assert!(v.map().lines.is_empty());
    }

    // ── FC-2 → FC-3 as a *headless* property: feed a `Vec<Msg>` through the core
    //    harness and assert the resulting `MetroState` — no egui, no GPU. ─────────
    #[test]
    fn harness_snapshot_drives_select_and_clear() {
        use facett_core::harness;
        let mut v = MetroView::local();
        // Selecting an existing line id is observable in the snapshot.
        let snap = harness::snapshot(&mut v, [Msg::SelectLine("bench_run\u{2192}Bench.Submit".into())]);
        assert_eq!(snap.selected.as_deref(), Some("bench_run\u{2192}Bench.Submit"), "selection is observable headlessly");
        assert_eq!(&snap, v.state(), "the snapshot is a clone of the live state");
        // Clearing wipes it.
        let snap = harness::snapshot(&mut v, [Msg::SelectLine("docs_export\u{2192}Docs.Render".into()), Msg::ClearSelection]);
        assert_eq!(snap.selected, None, "ClearSelection empties the selection");
    }

    #[test]
    fn drive_reports_no_effects_and_state_round_trips() {
        use facett_core::harness;
        let mut v = MetroView::local();
        // FC-8: the metro view does no I/O, so the effect stream is always empty.
        let effects = harness::drive(&mut v, [Msg::SelectLine("bench_run\u{2192}Bench.Submit".into())]);
        assert!(effects.is_empty(), "FC-8: metro emits no Effects");
        // FC-3: the observable Model (map + selection) round-trips through serde.
        let json = serde_json::to_value(v.state()).unwrap();
        assert_eq!(json["selected"], "bench_run\u{2192}Bench.Submit");
        let back: MetroState = serde_json::from_value(json).unwrap();
        assert_eq!(&back, v.state(), "serde(state) -> state round-trips (the whole map survives)");
    }

    /// FC-5: the selection is keyed on the **stable line id**, so it survives a full
    /// map replacement that reorders the lines (a "re-layout" of the trunk). The
    /// selected id still resolves to its line even though its index changed.
    #[test]
    fn selection_survives_line_reorder_on_stable_id() {
        use facett_core::harness;
        let mut v = MetroView::local();
        let _ = harness::drive(&mut v, [Msg::SelectLine("docs_export\u{2192}Docs.Render".into())]);
        // Rebuild the map with the two lines in the OPPOSITE order (same stable ids).
        let mut reordered = demo_map();
        reordered.lines.reverse();
        v.set_map(reordered);
        // The selection is unchanged (keyed on id, not position) and still resolves.
        assert_eq!(v.state().selected.as_deref(), Some("docs_export\u{2192}Docs.Render"));
        assert!(
            v.map().lines.iter().any(|l| Some(l.id.as_str()) == v.state().selected.as_deref()),
            "the selected id still names a real line after the reorder",
        );
        // And the drill-in copy still narrows to that line's label.
        assert_eq!(v.copy_text().as_deref(), Some("Docs Export"));
    }
}