facett-graphview 0.1.8

facett — a vello-backed, domain-agnostic scalable 2D graph render engine. Runtime-selects vello (GPU/wgpu) when a usable GPU exists, vello_cpu (multithreaded SIMD) as the no-GPU fallback. The eventual home for every graph surface (dep/arch/release dashboards, korp, graph-DB browsing).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
//! **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::{Facet, FacetCaps, Theme, theme};

/// 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)]
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)]
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)]
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)]
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)]
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 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,
    map: MetroMap,
    /// Selected line id (for a host's drill-in). Headless-settable.
    selected: Option<String>,
}

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

    /// Replace the map (the push model — call each refresh).
    pub fn set_map(&mut self, map: MetroMap) {
        self.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.map
    }

    /// Select a line by id (`None` clears).
    pub fn select(&mut self, id: Option<String>) {
        self.selected = id;
    }

    /// **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).
            egui::Color32::from_rgb(224, 90, 90)
        } 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 Facet for MetroView {
    fn title(&self) -> &str {
        &self.title
    }

    fn ui(&mut self, ui: &mut egui::Ui) {
        let th = theme(ui);

        // ── header: line + green counts ────────────────────────────────────
        ui.horizontal_wrapped(|ui| {
            let total = self.map.lines.len();
            let green = self.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 { egui::Color32::from_rgb(224, 90, 90) } else { th.text_dim }),
            );
        });
        ui.separator();

        if self.map.lines.is_empty() {
            ui.label(egui::RichText::new("no lines").color(th.text_dim));
            #[cfg(feature = "testmatrix")]
            facett_core::testmatrix::emit(
                "facett-graphview::MetroView::ui",
                "ui_render",
                true,
                "lines=0 drew=empty_hint",
            );
            return;
        }

        // ── each line gets a row, painted as a horizontal track ────────────
        let n = self.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.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, 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, 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, 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::ui",
            "ui_render",
            !self.map.lines.is_empty(),
            &format!("lines={} green={}", self.map.lines.len(), self.map.green_count()),
        );
    }

    fn state_json(&self) -> serde_json::Value {
        serde_json::json!({
            "title": self.title,
            "lines": self.map.lines.len(),
            "green_lines": self.map.green_count(),
            "green": self.map.is_green(),
            "selected": self.selected,
            "line": self.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<_>>(),
        })
    }

    fn selection_json(&self) -> serde_json::Value {
        match &self.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()
    }

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

#[cfg(test)]
mod tests {
    use super::*;

    #[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());
    }
}