nornir 0.4.41

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! 🏛 **Architecture** tab — the EPIC ARCH wiring board, drawn **natively in
//! egui inside the running viz**.
//!
//! The wiring graph (UI-component ↔ gRPC ↔ core-fn ↔ warehouse-table) already
//! exists as the static circuit-board SVG `nornir arch svg` emits and as the
//! `arch_graph` MCP tool's JSON — but it could not be *viewed in the app*. This
//! pane closes that gap: it reads the persisted [`crate::arch::ArchGraph`] for the
//! active workspace and paints it with egui shapes — nodes coloured by
//! [`crate::arch::NodeKind`] via the active facett palette, edges showing the
//! wiring, navigable (pan/zoom, click a node → highlight its downstream wiring,
//! the same trace `nornir arch trace` computes). It is **egui-native** (no
//! usvg/resvg rasterisation), reusing the DepGraph / CallGraph rendering approach.
//!
//! Source split (mirrors every other pane):
//!   * **local / fat** — open the warehouse directly and
//!     [`merge`](crate::arch::warehouse::merged_arch_from_warehouse) every
//!     member's latest persisted board into one workspace-wide graph.
//!   * **thin / remote** — the server owns the redb lock, so the merge runs
//!     server-side and ships back over the `Viz.Architecture` RPC
//!     ([`crate::viz::remote::fetch_architecture`]).
//!
//! Empty state: if no member has a persisted board yet, the pane shows a clean
//! "run `nornir arch generate`" placeholder — never a hard error, never a TODO.

use std::collections::{BTreeSet, HashMap, VecDeque};
use std::path::PathBuf;

use eframe::egui::{self, Color32, FontId, Pos2, Sense, Stroke, Vec2};
use serde::{Deserialize, Serialize};

#[cfg(test)]
use crate::arch::ArchEdge;
use crate::arch::{ArchEdgeKind, ArchGraph, ArchNode, NodeKind};
use crate::viz::trace;

use super::facett_theme::Theme;

/// The decoded `Viz.Architecture` payload (the server's merged board + which
/// members contributed + any per-member load errors). Shared between the embedded
/// warehouse merge and the remote RPC decode, so a thin client renders the exact
/// same graph the fat path produces.
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct ArchPayload {
    pub graph: ArchGraph,
    #[serde(default)]
    pub members_with_data: Vec<String>,
    #[serde(default)]
    pub errors: Vec<String>,
}

/// Where the graph comes from — a local warehouse (fat) or the server (thin).
enum Src {
    Local(PathBuf),
    Remote { endpoint: String, token: String },
}

/// A laid-out node (graph node + its on-canvas position, before pan/zoom).
struct Laid {
    node: ArchNode,
    pos: Pos2,
}

/// INPUT of an architecture load — which source + workspace was asked for.
#[derive(Serialize)]
struct LoadIn {
    source: String,
    workspace: String,
}

/// OUTPUT of an architecture render — the exact board the user sees, as readable
/// data (LAW #6): counts per kind + edges + which node is selected.
#[derive(Serialize)]
struct RenderOut {
    node_count: usize,
    edge_count: usize,
    components: usize,
    grpc: usize,
    core_fns: usize,
    tables: usize,
    selected: Option<String>,
}

pub struct ArchTabState {
    src: Src,
    workspace: String,
    /// `true` once a load has been attempted (so we don't reload every frame).
    loaded: bool,
    /// The merged board to render (empty until loaded / when no member has data).
    graph: ArchGraph,
    /// Members that contributed a board (for the placeholder / status line).
    members_with_data: Vec<String>,
    /// Configured members (for the "which members lack a board" placeholder).
    members: Vec<String>,
    /// Per-member load errors (surfaced; never blank the board).
    errors: Vec<String>,
    /// A human error string if the whole load failed (e.g. RPC down).
    load_error: Option<String>,
    /// Laid-out nodes + adjacency (index space), rebuilt when `graph` changes.
    laid: Vec<Laid>,
    /// id → index into `laid`.
    idx: HashMap<String, usize>,
    /// Forward adjacency over all edge kinds (for the downstream-trace highlight).
    adj: HashMap<usize, Vec<usize>>,
    /// Clicked node (index into `laid`) — highlights its downstream wiring.
    selected: Option<usize>,
    /// The downstream-reachable set from `selected` (BFS), recomputed on click.
    traced: BTreeSet<usize>,
    pan: Vec2,
    zoom: f32,
    /// Edge-trigger for the `architecture.render` trace event (once per data
    /// change / selection change, not once per frame).
    render_dirty: bool,
    theme: Theme,
}

impl ArchTabState {
    pub fn local(root: PathBuf) -> Self {
        Self::with(Src::Local(root), String::new())
    }
    pub fn remote(endpoint: String, token: String, workspace: String) -> Self {
        Self::with(Src::Remote { endpoint, token }, workspace)
    }
    fn with(src: Src, workspace: String) -> Self {
        Self {
            src,
            workspace,
            loaded: false,
            graph: ArchGraph::default(),
            members_with_data: Vec::new(),
            members: Vec::new(),
            errors: Vec::new(),
            load_error: None,
            laid: Vec::new(),
            idx: HashMap::new(),
            adj: HashMap::new(),
            selected: None,
            traced: BTreeSet::new(),
            pan: Vec2::ZERO,
            zoom: 1.0,
            render_dirty: false,
            theme: Theme::default(),
        }
    }

    /// Set the facett palette the pane paints with (C8).
    pub fn set_palette(&mut self, t: Theme) {
        self.theme = t;
    }

    /// The configured workspace members (for the placeholder that names which
    /// members still need `nornir arch generate`). Set by the app on build/switch.
    pub fn set_members(&mut self, members: Vec<String>) {
        self.members = members;
    }

    /// Re-scope to a different workspace (the picker switched): drop the cached
    /// board so the next draw reloads from the new workspace.
    pub fn set_workspace(&mut self, members: Vec<String>) {
        self.members = members;
        self.loaded = false;
        self.graph = ArchGraph::default();
        self.members_with_data.clear();
        self.errors.clear();
        self.load_error = None;
        self.laid.clear();
        self.idx.clear();
        self.adj.clear();
        self.selected = None;
        self.traced.clear();
        self.pan = Vec2::ZERO;
        self.zoom = 1.0;
    }

    /// Thin mode only: re-point the `Viz.Architecture` RPC at a new workspace.
    pub fn set_workspace_name(&mut self, workspace: String) {
        self.workspace = workspace;
    }

    /// Force a reload on the next draw (e.g. after a ⟳ Sync changed the warehouse).
    pub fn reload(&mut self) {
        self.loaded = false;
    }

    /// Load the merged board: local opens the warehouse + merges every member's
    /// latest board; remote reads the server's merge over `Viz.Architecture`.
    fn ensure_loaded(&mut self) {
        if self.loaded {
            return;
        }
        self.loaded = true;
        let source = match &self.src {
            Src::Local(p) => format!("local {}", p.display()),
            Src::Remote { endpoint, .. } => format!("remote {endpoint} (ws={})", self.workspace),
        };
        trace::emit_in(
            "architecture.load",
            &LoadIn { source, workspace: self.workspace.clone() },
        );
        let payload = match &self.src {
            Src::Local(root) => {
                match crate::warehouse::iceberg::IcebergWarehouse::open(root) {
                    Ok(wh) => {
                        let (graph, with_data, errors) =
                            crate::arch::warehouse::merged_arch_from_warehouse(&wh, &self.members);
                        Ok(ArchPayload { graph, members_with_data: with_data, errors })
                    }
                    Err(e) => Err(format!("open warehouse: {e:#}")),
                }
            }
            Src::Remote { endpoint, token } => {
                super::remote::fetch_architecture(endpoint, token, &self.workspace)
                    .map_err(|e| format!("{e:#}"))
            }
        };
        match payload {
            Ok(p) => {
                self.load_error = None;
                self.members_with_data = p.members_with_data;
                self.errors = p.errors;
                self.set_graph(p.graph);
            }
            Err(e) => {
                self.load_error = Some(e);
                self.set_graph(ArchGraph::default());
            }
        }
    }

    /// Swap in a new graph + rebuild the layout/adjacency + reset navigation.
    fn set_graph(&mut self, graph: ArchGraph) {
        self.graph = graph;
        self.selected = None;
        self.traced.clear();
        self.pan = Vec2::ZERO;
        self.zoom = 1.0;
        self.build_layout();
        self.render_dirty = true;
    }

    /// Layered layout (PCB-board style, reused from `arch::layers_of`'s model):
    /// columns by topological layer, tables pinned right; positions centred per
    /// column. Pure + deterministic, so the rendered board is stable.
    fn build_layout(&mut self) {
        self.laid.clear();
        self.idx.clear();
        self.adj.clear();
        let layers = layers_of(&self.graph);
        const COL_W: f32 = 230.0;
        const ROW_H: f32 = 64.0;
        let cols = layers.len().max(1) as f32;
        let rows = layers.iter().map(|l| l.len()).max().unwrap_or(1).max(1) as f32;
        let total_w = COL_W * (cols - 1.0).max(0.0);
        let total_h = ROW_H * (rows - 1.0).max(0.0);
        for (ci, layer) in layers.iter().enumerate() {
            let layer_h = ROW_H * (layer.len().saturating_sub(1)) as f32;
            let y0 = -total_h / 2.0 + (total_h - layer_h) / 2.0;
            for (ri, &node_i) in layer.iter().enumerate() {
                let x = -total_w / 2.0 + ci as f32 * COL_W;
                let y = y0 + ri as f32 * ROW_H;
                let node = self.graph.nodes[node_i].clone();
                self.idx.insert(node.id.clone(), self.laid.len());
                self.laid.push(Laid { node, pos: Pos2::new(x, y) });
            }
        }
        // Forward adjacency over all edge kinds, in index space.
        for e in &self.graph.edges {
            if let (Some(&f), Some(&t)) = (self.idx.get(&e.from), self.idx.get(&e.to)) {
                self.adj.entry(f).or_default().push(t);
            }
        }
    }

    /// BFS the downstream-reachable set from a clicked node (the visual twin of
    /// `nornir arch trace` lifted to the laid-out board).
    fn trace_from(&mut self, seed: usize) {
        self.traced.clear();
        let mut q = VecDeque::new();
        self.traced.insert(seed);
        q.push_back(seed);
        while let Some(cur) = q.pop_front() {
            if let Some(outs) = self.adj.get(&cur) {
                for &nxt in outs {
                    if self.traced.insert(nxt) {
                        q.push_back(nxt);
                    }
                }
            }
        }
    }

    pub fn draw(&mut self, ui: &mut egui::Ui) {
        let theme = self.theme;
        self.ensure_loaded();

        egui::TopBottomPanel::top("arch_controls").show_inside(ui, |ui| {
            ui.horizontal_wrapped(|ui| {
                ui.heading("🏛 Architecture");
                ui.separator();
                ui.label(format!(
                    "{} nodes · {} edges",
                    self.graph.nodes.len(),
                    self.graph.edges.len()
                ));
                ui.separator();
                if ui.button("↻ reload").clicked() {
                    self.loaded = false;
                }
                if ui.button("⊙ fit").clicked() {
                    self.pan = Vec2::ZERO;
                    self.zoom = 1.0;
                }
                if self.selected.is_some() && ui.button("✖ clear selection").clicked() {
                    self.selected = None;
                    self.traced.clear();
                    self.render_dirty = true;
                }
                if !self.members_with_data.is_empty() {
                    ui.separator();
                    ui.label(format!("members: {}", self.members_with_data.join(", ")));
                }
            });
            // The kind legend, coloured exactly as the chips paint.
            ui.horizontal_wrapped(|ui| {
                for (kind, name) in [
                    (NodeKind::Component, "UI component"),
                    (NodeKind::Grpc, "gRPC"),
                    (NodeKind::CoreFn, "core fn"),
                    (NodeKind::Table, "warehouse table"),
                ] {
                    let (fill, _stroke) = kind_color(&theme, kind);
                    let (rect, _) = ui.allocate_exact_size(Vec2::new(12.0, 12.0), Sense::hover());
                    ui.painter().rect_filled(rect, 2.0, fill);
                    ui.label(name);
                    ui.add_space(8.0);
                }
            });
        });

        // Edge-triggered render trace (LAW #6): emit what the board shows once per
        // data/selection change, not every frame.
        if self.render_dirty {
            trace::emit_end("architecture.render", &self.render_out());
            self.render_dirty = false;
        }

        egui::CentralPanel::default().show_inside(ui, |ui| {
            if let Some(err) = &self.load_error {
                ui.colored_label(super::facett_theme::RED, format!("architecture load failed: {err}"));
                return;
            }
            for e in &self.errors {
                ui.colored_label(super::facett_theme::AMBER, format!("{e}"));
            }
            if self.graph.nodes.is_empty() {
                self.draw_placeholder(ui);
                return;
            }

            let (resp, painter) = ui.allocate_painter(ui.available_size(), Sense::click_and_drag());
            painter.rect_filled(resp.rect, 4.0, theme.bg);
            if resp.dragged() {
                self.pan += resp.drag_delta();
            }
            if resp.hovered() {
                let scroll = ui.input(|i| i.raw_scroll_delta.y);
                if scroll != 0.0 {
                    self.zoom = (self.zoom * (1.0 + scroll * 0.001)).clamp(0.25, 4.0);
                }
            }
            let origin = resp.rect.center() + self.pan;
            let zoom = self.zoom;
            let project = |p: Pos2| origin + p.to_vec2() * zoom;

            // Click-to-select: nearest node within its box; clicking empty clears.
            if resp.clicked() {
                if let Some(click) = resp.interact_pointer_pos() {
                    let hit = self.laid.iter().enumerate().find_map(|(i, l)| {
                        let c = project(l.pos);
                        let half = Vec2::new(BOX_W, BOX_H) * 0.5 * zoom;
                        let rect = egui::Rect::from_center_size(c, half * 2.0);
                        rect.contains(click).then_some(i)
                    });
                    match hit {
                        Some(i) => {
                            self.selected = Some(i);
                            self.trace_from(i);
                        }
                        None => {
                            self.selected = None;
                            self.traced.clear();
                        }
                    }
                    self.render_dirty = true;
                }
            }

            let highlighting = self.selected.is_some();
            // Edges first (so chips sit on top).
            for e in &self.graph.edges {
                let (Some(&fi), Some(&ti)) = (self.idx.get(&e.from), self.idx.get(&e.to)) else {
                    continue;
                };
                let on_trace =
                    highlighting && self.traced.contains(&fi) && self.traced.contains(&ti);
                let (pa, pb) = (project(self.laid[fi].pos), project(self.laid[ti].pos));
                // Start at the source chip's right edge, end at the target's left.
                let a = pa + Vec2::new(BOX_W * 0.5 * zoom, 0.0);
                let b = pb - Vec2::new(BOX_W * 0.5 * zoom, 0.0);
                let base = edge_color(&theme, e.kind);
                let color = if highlighting && !on_trace {
                    dim(base)
                } else {
                    base
                };
                let w = if on_trace { 2.4 } else { 1.4 };
                // PCB-ish cubic with a mid breakpoint.
                let mid = Pos2::new((a.x + b.x) * 0.5, a.y);
                let mid2 = Pos2::new((a.x + b.x) * 0.5, b.y);
                painter.add(egui::Shape::CubicBezier(egui::epaint::CubicBezierShape::from_points_stroke(
                    [a, mid, mid2, b],
                    false,
                    Color32::TRANSPARENT,
                    Stroke::new(w, color),
                )));
                // Arrowhead at the callee.
                let dir = (b - mid2).normalized();
                let perp = Vec2::new(-dir.y, dir.x);
                let head = 6.0 * zoom.clamp(0.6, 1.6);
                painter.line_segment([b, b - dir * head + perp * head * 0.5], Stroke::new(w, color));
                painter.line_segment([b, b - dir * head - perp * head * 0.5], Stroke::new(w, color));
            }

            // Chips (nodes).
            for (i, l) in self.laid.iter().enumerate() {
                let c = project(l.pos);
                let (fill, stroke) = kind_color(&theme, l.node.kind);
                let on_trace = highlighting && self.traced.contains(&i);
                let (fill, stroke) = if highlighting && !on_trace {
                    (dim(fill), dim(stroke))
                } else {
                    (fill, stroke)
                };
                let size = Vec2::new(BOX_W, BOX_H) * zoom;
                let rect = egui::Rect::from_center_size(c, size);
                painter.rect_filled(rect, 5.0 * zoom, fill);
                let ring = if self.selected == Some(i) {
                    Stroke::new(3.0, theme.selection())
                } else {
                    Stroke::new(1.4, stroke)
                };
                painter.rect_stroke(rect, 5.0 * zoom, ring, egui::epaint::StrokeKind::Outside);
                if zoom > 0.45 {
                    painter.text(
                        c,
                        egui::Align2::CENTER_CENTER,
                        &l.node.label,
                        FontId::proportional(11.0 * zoom.clamp(0.7, 1.4)),
                        theme.text,
                    );
                }
            }

            // Hint footer.
            let hint = match self.selected {
                Some(i) => format!(
                    "{}{} downstream node(s) lit · click empty to clear · drag to pan, scroll to zoom",
                    self.laid[i].node.label,
                    self.traced.len().saturating_sub(1),
                ),
                None => "click a node to highlight its downstream wiring · drag to pan, scroll to zoom".to_string(),
            };
            painter.text(
                resp.rect.left_top() + Vec2::new(8.0, 8.0),
                egui::Align2::LEFT_TOP,
                hint,
                FontId::proportional(12.0),
                theme.text_dim,
            );
        });
    }

    /// The clean "nothing generated yet" placeholder — never a hard error.
    fn draw_placeholder(&self, ui: &mut egui::Ui) {
        ui.add_space(24.0);
        ui.vertical_centered(|ui| {
            ui.heading("No architecture wiring recorded yet");
            ui.add_space(8.0);
            ui.label(
                "The EPIC ARCH board is generated per repo and historized in the \
                 warehouse. Generate it, then reload this tab:",
            );
            ui.add_space(6.0);
            let cmd = if self.members.is_empty() {
                "nornir arch generate --repo <member>".to_string()
            } else {
                format!("nornir arch generate --repo {}", self.members[0])
            };
            ui.code(&cmd);
            if !self.members.is_empty() {
                ui.add_space(8.0);
                ui.label(format!(
                    "members in this workspace with no board yet: {}",
                    self.members
                        .iter()
                        .filter(|m| !self.members_with_data.contains(m))
                        .cloned()
                        .collect::<Vec<_>>()
                        .join(", ")
                ));
            }
        });
    }

    fn render_out(&self) -> RenderOut {
        let count = |k: NodeKind| self.graph.nodes.iter().filter(|n| n.kind == k).count();
        RenderOut {
            node_count: self.graph.nodes.len(),
            edge_count: self.graph.edges.len(),
            components: count(NodeKind::Component),
            grpc: count(NodeKind::Grpc),
            core_fns: count(NodeKind::CoreFn),
            tables: count(NodeKind::Table),
            selected: self.selected.map(|i| self.laid[i].node.label.clone()),
        }
    }

    /// The 🏛 Architecture tab's slice of `state_json` (LAW #6) — the exact board
    /// it renders: counts per kind, edges, which members contributed, the selected
    /// node + its downstream-traced labels, and the active palette.
    pub fn state_json(&self) -> serde_json::Value {
        let count = |k: NodeKind| self.graph.nodes.iter().filter(|n| n.kind == k).count();
        let kinds: Vec<serde_json::Value> = self
            .graph
            .nodes
            .iter()
            .map(|n| serde_json::json!({ "id": n.id, "label": n.label, "kind": n.kind.as_str() }))
            .collect();
        let edges: Vec<serde_json::Value> = self
            .graph
            .edges
            .iter()
            .map(|e| serde_json::json!({ "from": e.from, "to": e.to, "kind": e.kind.as_str() }))
            .collect();
        let traced: Vec<String> =
            self.traced.iter().map(|&i| self.laid[i].node.label.clone()).collect();
        serde_json::json!({
            "source": match &self.src { Src::Local(_) => "local", Src::Remote { .. } => "remote" },
            "workspace": self.workspace,
            "node_count": self.graph.nodes.len(),
            "edge_count": self.graph.edges.len(),
            "components": count(NodeKind::Component),
            "grpc": count(NodeKind::Grpc),
            "core_fns": count(NodeKind::CoreFn),
            "tables": count(NodeKind::Table),
            "nodes": kinds,
            "edges": edges,
            "members_with_data": self.members_with_data,
            "members": self.members,
            "errors": self.errors,
            "load_error": self.load_error,
            "selected": self.selected.map(|i| self.laid[i].node.label.clone()),
            "traced_downstream": traced,
            "empty": self.graph.nodes.is_empty(),
            "palette": self.theme.name,
        })
    }

    // ── test-only injectors (no warehouse / no server) ───────────────────────

    /// Inject a merged board directly (as the warehouse merge / RPC would deliver)
    /// + the configured members, so the inject-assert harness can read
    /// `state_json()` back without a warehouse or server. Returns nothing; after
    /// this the board renders the injected graph.
    #[doc(hidden)]
    pub fn inject_for_test(&mut self, graph: ArchGraph, members_with_data: Vec<String>) {
        self.loaded = true;
        self.load_error = None;
        self.members_with_data = members_with_data;
        self.errors = Vec::new();
        self.set_graph(graph);
    }

    /// Drive a click on the node with `label` (parity with a pointer click), so a
    /// test can assert the downstream-trace highlight via `state_json()`.
    #[doc(hidden)]
    pub fn select_by_label_for_test(&mut self, label: &str) -> bool {
        if let Some(i) = self.laid.iter().position(|l| l.node.label == label) {
            self.selected = Some(i);
            self.trace_from(i);
            self.render_dirty = true;
            true
        } else {
            false
        }
    }
}

const BOX_W: f32 = 184.0;
const BOX_H: f32 = 34.0;

/// Chip (fill, stroke) per node kind, on the active facett palette. Each kind
/// gets a distinct semantic tint so the four layers read apart at a glance: UI
/// components on the palette accent, gRPC on amber, core-fns on the neutral
/// node-fill, warehouse tables on the palette point colour (the warehouse rail).
fn kind_color(theme: &Theme, kind: NodeKind) -> (Color32, Color32) {
    match kind {
        NodeKind::Component => (theme.accent.linear_multiply(0.30), theme.accent),
        NodeKind::Grpc => (
            super::facett_theme::AMBER.linear_multiply(0.30),
            super::facett_theme::AMBER,
        ),
        NodeKind::CoreFn => (theme.node_fill, theme.node_stroke),
        NodeKind::Table => (theme.point.linear_multiply(0.30), theme.point),
    }
}

/// Edge colour per relation kind: calls on the palette accent, reads/writes on
/// amber (the warehouse access traces).
fn edge_color(theme: &Theme, kind: ArchEdgeKind) -> Color32 {
    match kind {
        ArchEdgeKind::Calls => theme.edge,
        ArchEdgeKind::Reads | ArchEdgeKind::Writes => super::facett_theme::AMBER,
    }
}

/// Dim a colour toward transparency for the un-traced background when a node is
/// selected (so the lit downstream path pops).
fn dim(c: Color32) -> Color32 {
    c.linear_multiply(0.22)
}

/// Layered BFS columns (verbatim model of `arch::layers_of`, reimplemented here
/// against the laid graph so the native render columns match the SVG's): layer 0
/// = sources (no incoming edge), tables pinned to the rightmost column (the
/// warehouse ground rail). Deterministic, cycle-safe.
fn layers_of(graph: &ArchGraph) -> Vec<Vec<usize>> {
    let n = graph.nodes.len();
    let idx: HashMap<&str, usize> =
        graph.nodes.iter().enumerate().map(|(i, nd)| (nd.id.as_str(), i)).collect();
    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
    let mut indeg: Vec<usize> = vec![0; n];
    for e in &graph.edges {
        if let (Some(&f), Some(&t)) = (idx.get(e.from.as_str()), idx.get(e.to.as_str())) {
            if f != t {
                adj[f].push(t);
                indeg[t] += 1;
            }
        }
    }
    let mut layer_of = vec![0usize; n];
    let mut remaining: BTreeSet<usize> = (0..n).collect();
    let mut level = 0usize;
    while !remaining.is_empty() {
        let ready: Vec<usize> = remaining.iter().copied().filter(|&i| indeg[i] == 0).collect();
        if ready.is_empty() {
            for &i in &remaining {
                layer_of[i] = level;
            }
            break;
        }
        for &i in &ready {
            layer_of[i] = level;
            remaining.remove(&i);
        }
        for &i in &ready {
            for &j in &adj[i] {
                if indeg[j] > 0 {
                    indeg[j] -= 1;
                }
            }
        }
        level += 1;
    }
    // Pin tables to the rightmost column (the warehouse ground rail).
    let mut max_level = *layer_of.iter().max().unwrap_or(&0);
    let has_table = graph.nodes.iter().any(|nd| nd.kind == NodeKind::Table);
    if has_table {
        max_level = max_level.max(1);
        for (i, nd) in graph.nodes.iter().enumerate() {
            if nd.kind == NodeKind::Table {
                layer_of[i] = max_level;
            }
        }
    }
    let mut layers: Vec<Vec<usize>> = vec![Vec::new(); max_level + 1];
    let mut order: Vec<usize> = (0..n).collect();
    order.sort_by(|&a, &b| graph.nodes[a].label.cmp(&graph.nodes[b].label));
    for i in order {
        layers[layer_of[i]].push(i);
    }
    layers
}

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

    fn board() -> ArchGraph {
        // TestTab -reads-> test_results ; Viz.Architecture -writes-> release_lineage
        // ; TestTab -calls-> nornir::viz (a core fn).
        ArchGraph {
            nodes: vec![
                ArchNode { id: "component:TestTab".into(), label: "TestTab".into(), kind: NodeKind::Component },
                ArchNode { id: "grpc:Viz.Architecture".into(), label: "Viz.Architecture".into(), kind: NodeKind::Grpc },
                ArchNode { id: "corefn:nornir::viz".into(), label: "nornir::viz".into(), kind: NodeKind::CoreFn },
                ArchNode { id: "table:test_results".into(), label: "test_results".into(), kind: NodeKind::Table },
                ArchNode { id: "table:release_lineage".into(), label: "release_lineage".into(), kind: NodeKind::Table },
            ],
            edges: vec![
                ArchEdge { from: "component:TestTab".into(), to: "table:test_results".into(), kind: ArchEdgeKind::Reads },
                ArchEdge { from: "component:TestTab".into(), to: "corefn:nornir::viz".into(), kind: ArchEdgeKind::Calls },
                ArchEdge { from: "grpc:Viz.Architecture".into(), to: "table:release_lineage".into(), kind: ArchEdgeKind::Writes },
            ],
        }
    }

    #[test]
    fn injected_board_renders_counts_in_state_json() {
        let mut st = ArchTabState::local(PathBuf::from("/nonexistent"));
        st.set_members(vec!["nornir".into()]);
        st.inject_for_test(board(), vec!["nornir".into()]);
        let js = st.state_json();
        assert_eq!(js["node_count"], 5);
        assert_eq!(js["edge_count"], 3);
        assert_eq!(js["components"], 1);
        assert_eq!(js["grpc"], 1);
        assert_eq!(js["core_fns"], 1);
        assert_eq!(js["tables"], 2);
        assert_eq!(js["empty"], false);
        assert_eq!(js["members_with_data"][0], "nornir");
        assert_eq!(js["source"], "local");
    }

    #[test]
    fn empty_board_shows_placeholder_not_error() {
        let mut st = ArchTabState::local(PathBuf::from("/nonexistent"));
        st.set_members(vec!["nornir".into()]);
        st.inject_for_test(ArchGraph::default(), vec![]);
        let js = st.state_json();
        assert_eq!(js["empty"], true);
        assert_eq!(js["node_count"], 0);
        assert!(js["load_error"].is_null(), "empty board is not an error");
    }

    #[test]
    fn click_lights_downstream_trace() {
        let mut st = ArchTabState::local(PathBuf::from("/nonexistent"));
        st.inject_for_test(board(), vec!["nornir".into()]);
        // Click TestTab: downstream = {TestTab, test_results, nornir::viz}.
        assert!(st.select_by_label_for_test("TestTab"));
        let js = st.state_json();
        assert_eq!(js["selected"], "TestTab");
        let traced: BTreeSet<String> = js["traced_downstream"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap().to_string())
            .collect();
        assert!(traced.contains("TestTab"));
        assert!(traced.contains("test_results"));
        assert!(traced.contains("nornir::viz"));
        // release_lineage is NOT reachable from TestTab (it's Viz.Architecture's).
        assert!(!traced.contains("release_lineage"), "unreachable node not lit: {traced:?}");
    }

    #[test]
    fn layers_pin_tables_right_and_sources_left() {
        let g = board();
        let layers = layers_of(&g);
        // Sources (TestTab, Viz.Architecture — no incoming edge) in layer 0.
        let l0: BTreeSet<&str> =
            layers[0].iter().map(|&i| g.nodes[i].label.as_str()).collect();
        assert!(l0.contains("TestTab"));
        assert!(l0.contains("Viz.Architecture"));
        // Every table is pinned to the LAST layer (the warehouse ground rail), and
        // no table appears in any earlier column.
        let last = layers.len() - 1;
        for (li, layer) in layers.iter().enumerate() {
            for &i in layer {
                if g.nodes[i].kind == NodeKind::Table {
                    assert_eq!(li, last, "table `{}` not on the right rail", g.nodes[i].label);
                }
            }
        }
        // The last layer actually carries the tables.
        assert!(
            layers[last].iter().any(|&i| g.nodes[i].kind == NodeKind::Table),
            "the rightmost column carries the warehouse tables"
        );
    }

    #[test]
    fn palette_switch_reaches_pane() {
        let mut st = ArchTabState::local(PathBuf::from("/nonexistent"));
        st.inject_for_test(board(), vec!["nornir".into()]);
        assert_eq!(st.state_json()["palette"], "default");
        st.set_palette(Theme::cyberpunk_neon());
        assert_eq!(st.state_json()["palette"], "cyberpunk-neon");
    }
}