nornir 0.4.46

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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
//! 🏛 **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 std::time::Duration;

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

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

use super::facett_theme::Theme;

/// How often the **Live system** sub-view re-reads the warehouse (repaint-on-
/// change), mirroring `bench_live`/`coverage_live`.
const LIVE_RELOAD_EVERY: Duration = Duration::from_millis(2000);

/// The 🏛 Architecture tab is a CONTAINER: an internal sub-view selector picks
/// which architecture lens to draw. (Deps is rendered by the app — the tab only
/// owns which lens is active so the app routes the dep graph in; the other three
/// are owned + drawn here.)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArchSubView {
    /// 🔗 The dependency graph (cross-repo + intra-repo). Drawn by the app
    /// (`draw_dep_graph`) because it needs the timeline; consolidated under Arch.
    Deps,
    /// 📡 The wiring board, warehouse-driven + repaint-on-change.
    Live,
    /// 🏛 The EPIC ARCH wiring board (arch_graph/arch_svg), static.
    Wiring,
    /// 📍 Hållpunkter — the ui / gRPC / emitter LANDMARK functions as nodes.
    Boundaries,
}

impl ArchSubView {
    /// Every sub-view, in selector order — the strip the tab paints + the set the
    /// headless matrix enumerates.
    pub const ALL: [ArchSubView; 4] =
        [ArchSubView::Deps, ArchSubView::Live, ArchSubView::Wiring, ArchSubView::Boundaries];

    /// Stable id (the `state_json` / click contract name).
    pub fn id(self) -> &'static str {
        match self {
            ArchSubView::Deps => "Deps",
            ArchSubView::Live => "Live",
            ArchSubView::Wiring => "Wiring",
            ArchSubView::Boundaries => "Boundaries",
        }
    }

    /// The human label the selector chip paints.
    pub fn label(self) -> &'static str {
        match self {
            ArchSubView::Deps => "🔗 Deps",
            ArchSubView::Live => "📡 Live system",
            ArchSubView::Wiring => "🏛 Wiring",
            ArchSubView::Boundaries => "📍 Hållpunkter",
        }
    }

    fn from_id(s: &str) -> Option<ArchSubView> {
        ArchSubView::ALL.into_iter().find(|v| v.id() == s)
    }
}

/// 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>,
    /// node id → coverage verdict (`"covered"` | `"allowlisted"` | `"missing"`),
    /// cross-checked against the `surface_coverage` matrix: does a test exist for
    /// this marker? Empty when no coverage was recorded. Populated on BOTH the
    /// local (warehouse) and the remote (server) side so thin == fat — the
    /// green/red cross-check is the same warehouse data either way.
    #[serde(default)]
    pub coverage: std::collections::BTreeMap<String, 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,
    cli: usize,
    core_fns: usize,
    tables: usize,
    /// Markers with a covering test (`surface_coverage` verdict `covered`).
    tested: usize,
    /// Markers in the surface with no test (`missing`) — the red ones.
    untested: usize,
    /// Markers that are known-uncovered but allowlisted (tracked gaps).
    allowlisted: usize,
    /// Markers with no matching coverage row (not claimed either way).
    coverage_unknown: 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,
    /// node id → coverage verdict from the `surface_coverage` matrix
    /// (`"covered"`/`"allowlisted"`/`"missing"`). The cross-check that paints a
    /// marker green (a test exists) or red (none). Empty = no coverage recorded.
    coverage: std::collections::BTreeMap<String, String>,
    theme: Theme,
    // ── container: which sub-view (lens) is active ───────────────────────────
    /// The active sub-view (Deps / Live / Wiring / Hållpunkter).
    sub: ArchSubView,
    // ── click-to-code (the symbol → file:line bridge) ────────────────────────
    /// Local checkout root (`workspace_root/<member>`-ish) used to resolve a
    /// clicked node label to source via a fresh `symbol_facts` scan, and to read
    /// the inline preview window. Empty in remote mode (no checkout → no resolve).
    repo_root: PathBuf,
    /// The repo to scan for symbol resolution (the first configured member).
    resolve_repo: String,
    /// Scanned symbols, lazily loaded the first time a node is clicked (so the
    /// tab doesn't scan on open). `None` until attempted; `Some(vec)` after.
    symbols: Option<Vec<crate::knowledge::symbols::SymbolRow>>,
    /// The last click-to-code resolution: the queried symbol + its `file:line`
    /// candidates (best first). Drives the inline source-preview panel + the
    /// `state_json` last-clicked record + the `architecture.open` trace.
    last_open: Option<OpenResult>,
    /// `true` while the Live sub-view should repaint-on-change (the `live` toggle
    /// parity with bench_live/coverage_live). Reuses `reload()` on the timer.
    live: bool,
    last_live_reload: std::time::Instant,
}

/// One click-to-code resolution — the queried symbol, the resolved candidates,
/// whether the editor was launched, and the inline source-preview window.
#[derive(Clone, Default)]
struct OpenResult {
    query: String,
    hits: Vec<SymbolLoc>,
    /// `Some(true)` opened in editor, `Some(false)` `code` absent, `None` not tried.
    editor_opened: Option<bool>,
    /// The 1-based first line of `preview` + the source lines around the hit.
    preview_start: u32,
    preview: Vec<String>,
}

/// A marker's test-matrix status, derived from its `surface_coverage` verdict.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Cov {
    /// A covering test exists (`verdict = covered`).
    Tested,
    /// Known-uncovered but allowlisted (`verdict = allowlisted`) — a tracked gap.
    Allowlisted,
    /// In the surface, no test (`verdict = missing`) — RED.
    Untested,
    /// No coverage row matched this node — we don't claim either way.
    Unknown,
}

impl Cov {
    fn from_verdict(v: &str) -> Cov {
        match v {
            "covered" => Cov::Tested,
            "allowlisted" => Cov::Allowlisted,
            "missing" => Cov::Untested,
            _ => Cov::Unknown,
        }
    }
    fn label(self) -> &'static str {
        match self {
            Cov::Tested => "tested",
            Cov::Allowlisted => "allowlisted",
            Cov::Untested => "untested",
            Cov::Unknown => "unknown",
        }
    }
}

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,
            coverage: std::collections::BTreeMap::new(),
            theme: Theme::default(),
            sub: ArchSubView::Wiring,
            repo_root: PathBuf::new(),
            resolve_repo: String::new(),
            symbols: None,
            last_open: None,
            live: false,
            last_live_reload: std::time::Instant::now(),
        }
    }

    /// The active sub-view (lens). `pub` so the app routes the Deps lens to the
    /// dep graph + the headless matrix reads which lens is showing.
    pub fn sub_view(&self) -> ArchSubView {
        self.sub
    }

    /// Switch the active sub-view (selector click / robot drive). Emits the
    /// switch as a trace event so it's observable headlessly.
    pub fn set_sub_view(&mut self, sub: ArchSubView) {
        if self.sub != sub {
            self.sub = sub;
            trace::emit_event("architecture.subview", &serde_json::json!({ "sub": sub.id() }));
            self.render_dirty = true;
        }
    }

    /// Seed the local checkout root + the repo to scan for click-to-code symbol
    /// resolution (the inline source preview + `code --goto`). Set by the app on
    /// build/switch; empty in remote mode (no checkout, no resolve).
    pub fn set_resolve_source(&mut self, repo_root: PathBuf, repo: String) {
        if self.repo_root != repo_root || self.resolve_repo != repo {
            self.repo_root = repo_root;
            self.resolve_repo = repo;
            self.symbols = None; // re-scan lazily for the new source
        }
    }

    /// 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.coverage.clear();
        self.pan = Vec2::ZERO;
        self.zoom = 1.0;
        self.symbols = None;
        self.last_open = None;
    }

    /// 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);
                        // Cross-check every marker against the test matrix: read
                        // the workspace's latest surface_coverage and map verdicts
                        // onto the board's node ids — the SAME shared helper the
                        // server's thin path uses, so thin == fat. Same warehouse
                        // the fat board merge already opened.
                        let coverage = crate::arch::warehouse::coverage_for_graph(
                            &wh,
                            &self.workspace,
                            &graph,
                        );
                        Ok(ArchPayload { graph, members_with_data: with_data, errors, coverage })
                    }
                    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.coverage = p.coverage;
                self.set_graph(p.graph);
            }
            Err(e) => {
                self.load_error = Some(e);
                self.coverage.clear();
                self.set_graph(ArchGraph::default());
            }
        }
    }

    /// This node's test-matrix status (the green/red cross-check).
    fn cov_of(&self, node_id: &str) -> Cov {
        match self.coverage.get(node_id) {
            Some(v) => Cov::from_verdict(v),
            None => Cov::Unknown,
        }
    }

    /// 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);
                    }
                }
            }
        }
    }

    /// Lazily scan the configured repo's symbols (the click-to-code source of
    /// truth). Best-effort: in remote mode / with no checkout, leaves `symbols`
    /// an empty vec so resolution returns nothing (the printed `file:line` + the
    /// graph still work; only the inline preview is unavailable).
    fn ensure_symbols(&mut self) {
        if self.symbols.is_some() {
            return;
        }
        if self.repo_root.as_os_str().is_empty() || self.resolve_repo.is_empty() {
            self.symbols = Some(Vec::new());
            return;
        }
        let scan = crate::knowledge::scan_all(&self.repo_root, &self.resolve_repo);
        self.symbols = Some(match scan {
            Ok(s) => s.symbols.symbols,
            Err(_) => Vec::new(),
        });
    }

    /// Click-to-code: resolve a clicked node's `label` (or a typed symbol) to its
    /// source `file:line` via the SHARED [`crate::arch::resolve_symbol`] (the same
    /// bridge `nornir arch open` uses), then (i) open it in the editor
    /// (`code --goto`, best-effort), and (ii) load the inline source-preview
    /// window. The resolution is recorded in `last_open` for the preview panel +
    /// `state_json` + the `architecture.open` trace. Returns whether a hit was
    /// found. `pub` so the robot/CLI-parity drive + tests can fire it directly.
    pub fn open_symbol(&mut self, label: &str, launch_editor: bool) -> bool {
        self.ensure_symbols();
        let syms = self.symbols.as_deref().unwrap_or(&[]);
        let hits = crate::arch::resolve_symbol(syms, label);
        trace::emit_in(
            "architecture.open",
            &serde_json::json!({ "query": label, "candidates": hits.len() }),
        );
        let mut res = OpenResult { query: label.to_string(), hits: hits.clone(), ..Default::default() };
        if let Some(best) = hits.first() {
            // (ii) inline preview window (±6 lines), read from the checkout.
            let root = (!self.repo_root.as_os_str().is_empty()).then_some(self.repo_root.as_path());
            let (start, lines) = crate::arch::source_window(root, &best.file, best.line, 6);
            res.preview_start = start;
            res.preview = lines;
            // (i) best-effort editor launch.
            if launch_editor {
                res.editor_opened = Some(
                    crate::arch::open_in_editor(root, &best.file, best.line).unwrap_or(false),
                );
            }
        }
        let found = !res.hits.is_empty();
        trace::emit_end(
            "architecture.open",
            &serde_json::json!({
                "query": label,
                "resolved": res.hits.first().map(|h| format!("{}:{}", h.file, h.line)),
                "editor_opened": res.editor_opened,
            }),
        );
        self.last_open = Some(res);
        self.render_dirty = true;
        found
    }

    /// Build the **Hållpunkter** (boundary landmark) graph: the ui / gRPC /
    /// emitter functions as LANDMARK nodes, classified by the coverage feature's
    /// [`crate::coverage::classify`] (REUSED, not reinvented), from the scanned
    /// symbols. Each landmark is a node kind-mapped to the board's layers
    /// (ui→Component, grpc→Grpc, emitter→CoreFn) so it paints with the same
    /// legend; edges are omitted (landmarks are anchors, not a call graph).
    fn boundary_landmarks(&self) -> Vec<(Boundary, ArchNode)> {
        let syms = self.symbols.as_deref().unwrap_or(&[]);
        let mut out: Vec<(Boundary, ArchNode)> = Vec::new();
        let mut seen: BTreeSet<String> = BTreeSet::new();
        for s in syms {
            // Build the fully-qualified-ish name the classifier expects.
            let fq = if s.module_path.is_empty() {
                s.item_name.clone()
            } else {
                format!("{}::{}", s.module_path, s.item_name)
            };
            let b = classify(&fq, &s.file);
            if !b.is_boundary() {
                continue;
            }
            let kind = match b {
                Boundary::Ui => NodeKind::Component,
                Boundary::Grpc => NodeKind::Grpc,
                Boundary::Emitter | Boundary::Core => NodeKind::CoreFn,
            };
            let id = format!("{}:{}", b.as_str(), fq);
            if seen.insert(id.clone()) {
                out.push((b, ArchNode { id, label: s.item_name.clone(), kind }));
            }
        }
        out.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.label.cmp(&b.1.label)));
        out
    }

    /// (ui, grpc, emitter) landmark tally for the legend + `state_json`.
    fn boundary_tally(&self) -> (usize, usize, usize) {
        let (mut u, mut g, mut e) = (0, 0, 0);
        for (b, _) in self.boundary_landmarks() {
            match b {
                Boundary::Ui => u += 1,
                Boundary::Grpc => g += 1,
                Boundary::Emitter => e += 1,
                Boundary::Core => {}
            }
        }
        (u, g, e)
    }

    /// The 🏛 Architecture CONTAINER: paints the sub-view selector strip, then
    /// dispatches to the active lens. Deps is drawn by the app (it needs the
    /// timeline) — `draw` returns early for it after the strip, so the app's
    /// `draw_dep_graph` paints the central area; the other three lenses are drawn
    /// here. `draw_deps_for` is never called — the app routes by `sub_view()`.
    pub fn draw(&mut self, ui: &mut egui::Ui) {
        let theme = self.theme;
        // The sub-view selector strip — a chip per lens (Deps / Live / Wiring /
        // Hållpunkter), the active one highlighted. CONSOLIDATES deps under Arch.
        egui::TopBottomPanel::top("arch_subview").show_inside(ui, |ui| {
            ui.horizontal_wrapped(|ui| {
                ui.label(RichText::new("🏛 Architecture").strong().color(theme.text));
                ui.separator();
                for sv in ArchSubView::ALL {
                    if ui.selectable_label(self.sub == sv, sv.label()).clicked() {
                        self.set_sub_view(sv);
                    }
                }
            });
        });

        match self.sub {
            // The app paints the dep graph in the remaining central area after
            // this returns (it owns the timeline) — we leave the space free.
            ArchSubView::Deps => {}
            ArchSubView::Boundaries => self.draw_boundaries(ui),
            ArchSubView::Live | ArchSubView::Wiring => self.draw_board(ui),
        }
    }

    /// The 🏛 Wiring / 📡 Live system lens: the EPIC ARCH wiring board, drawn
    /// natively. Live additionally re-reads the warehouse on a timer + requests a
    /// repaint (repaint-on-change), mirroring bench_live/coverage_live.
    fn draw_board(&mut self, ui: &mut egui::Ui) {
        let theme = self.theme;
        // Live system: timer-driven reload + repaint (warehouse-driven).
        if self.sub == ArchSubView::Live {
            if self.live && self.last_live_reload.elapsed() >= LIVE_RELOAD_EVERY {
                self.loaded = false;
                self.last_live_reload = std::time::Instant::now();
            }
        }
        self.ensure_loaded();

        egui::TopBottomPanel::top("arch_controls").show_inside(ui, |ui| {
            ui.horizontal_wrapped(|ui| {
                ui.heading(if self.sub == ArchSubView::Live { "📡 Live system" } else { "🏛 Wiring" });
                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.sub == ArchSubView::Live {
                    ui.separator();
                    ui.checkbox(&mut self.live, "📡 live")
                        .on_hover_text("re-read the warehouse + repaint on change");
                }
                if !self.members_with_data.is_empty() {
                    ui.separator();
                    ui.label(format!("members: {}", self.members_with_data.join(", ")));
                }
            });
            // The kind legend (chip FILL = layer), coloured exactly as the chips paint.
            ui.horizontal_wrapped(|ui| {
                for (kind, name) in [
                    (NodeKind::Component, "UI component"),
                    (NodeKind::Grpc, "gRPC"),
                    (NodeKind::Cli, "CLI command"),
                    (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);
                }
            });
            // The coverage legend + summary (chip RING = test-matrix cross-check):
            // does a test exist for this marker? This is the keystone of the tab.
            let (tested, untested, allowlisted, unknown) = self.cov_counts();
            ui.horizontal_wrapped(|ui| {
                ui.label("tests:");
                for (col, name, n) in [
                    (super::facett_theme::GREEN, "tested", tested),
                    (super::facett_theme::RED, "untested", untested),
                    (super::facett_theme::AMBER, "allowlisted", allowlisted),
                ] {
                    let (rect, _) = ui.allocate_exact_size(Vec2::new(12.0, 12.0), Sense::hover());
                    ui.painter().rect_stroke(
                        rect,
                        2.0,
                        Stroke::new(2.0, col),
                        egui::epaint::StrokeKind::Outside,
                    );
                    ui.label(format!("{name} {n}"));
                    ui.add_space(8.0);
                }
                if unknown > 0 {
                    ui.label(format!("· {unknown} not in surface_coverage"));
                }
                if tested + untested + allowlisted + unknown == self.graph.nodes.len()
                    && self.coverage.is_empty()
                {
                    ui.label("· (no coverage recorded — run `nornir test coverage`)");
                }
            });
        });

        // 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;
        }

        // Click-to-code: the inline source-preview panel (sits below the board,
        // above the central canvas — egui needs side/bottom panels declared
        // before the CentralPanel). Shows the lines around the last-clicked
        // symbol's `file:line`, the editor-open result, and any extra candidates.
        self.draw_source_preview(ui);

        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);
                            // Click-to-code: resolve the clicked node → file:line,
                            // open in the editor (best-effort) + load the inline
                            // source preview. Tables have no symbol; skip them.
                            let node = &self.laid[i].node;
                            if node.kind != NodeKind::Table {
                                let label = node.label.clone();
                                self.open_symbol(&label, true);
                            }
                        }
                        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);
                // Ring = the test-matrix cross-check: green tested / red untested /
                // amber allowlisted; falls back to the kind stroke when unknown.
                // The selection ring still wins when this node is clicked.
                let ring = if self.selected == Some(i) {
                    Stroke::new(3.0, theme.selection())
                } else if let Some(cv) = cov_ring(self.cov_of(&l.node.id)) {
                    let cv = if highlighting && !on_trace { dim(cv) } else { cv };
                    Stroke::new(2.2, cv)
                } 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,
            );
        });

        // Live system: keep repainting so a warehouse change animates in.
        if self.sub == ArchSubView::Live && self.live {
            ui.ctx().request_repaint_after(Duration::from_millis(600));
        }
    }

    /// The inline source-preview panel for the last click-to-code resolution: the
    /// resolved `file:line`, the editor-open status, the source window, and any
    /// extra candidates. Hidden when nothing has been clicked. (ii) of the
    /// click-to-code contract.
    fn draw_source_preview(&mut self, ui: &mut egui::Ui) {
        let Some(open) = self.last_open.clone() else { return };
        let theme = self.theme;
        egui::TopBottomPanel::bottom("arch_source_preview")
            .resizable(true)
            .default_height(180.0)
            .show_inside(ui, |ui| {
                ui.horizontal(|ui| {
                    ui.label(RichText::new("📄 source").strong().color(theme.accent));
                    ui.label(RichText::new(&open.query).monospace().color(theme.text));
                    if let Some(best) = open.hits.first() {
                        ui.label(
                            RichText::new(format!("{}:{}", best.file, best.line))
                                .monospace()
                                .color(theme.text_dim),
                        );
                        match open.editor_opened {
                            Some(true) => { ui.colored_label(super::facett_theme::GREEN, "✓ opened in editor"); }
                            Some(false) => { ui.colored_label(super::facett_theme::AMBER, "code not found (preview only)"); }
                            None => {}
                        }
                    } else {
                        ui.colored_label(super::facett_theme::AMBER, "no symbol matched");
                    }
                    if ui.button("").on_hover_text("close preview").clicked() {
                        self.last_open = None;
                    }
                });
                if open.preview.is_empty() {
                    if !open.hits.is_empty() {
                        ui.weak("(source file not in this checkout — run locally to preview lines)");
                    }
                    return;
                }
                ui.separator();
                ScrollArea::vertical().id_salt("arch_src").auto_shrink([false, false]).show(ui, |ui| {
                    let target = open.hits.first().map(|h| h.line).unwrap_or(0);
                    for (off, line) in open.preview.iter().enumerate() {
                        let n = open.preview_start + off as u32;
                        let is_target = n == target;
                        let num = RichText::new(format!("{n:>5} ")).monospace().color(theme.text_dim);
                        let src = RichText::new(line).monospace().color(if is_target {
                            theme.accent
                        } else {
                            theme.text
                        });
                        ui.horizontal(|ui| {
                            ui.label(num);
                            if is_target {
                                ui.label(RichText::new("").color(theme.accent));
                            }
                            ui.label(src);
                        });
                    }
                });
            });
    }

    /// The 📍 **Hållpunkter** (boundaries) lens: the ui / gRPC / emitter LANDMARK
    /// functions drawn as distinct landmark nodes (chips), grouped by boundary,
    /// classified with the coverage feature's [`crate::coverage::classify`]
    /// (REUSED). Each landmark is clickable → click-to-code (same as the board).
    fn draw_boundaries(&mut self, ui: &mut egui::Ui) {
        let theme = self.theme;
        self.ensure_symbols();
        let landmarks = self.boundary_landmarks();
        let (u, g, e) = self.boundary_tally();

        egui::TopBottomPanel::top("arch_boundaries_head").show_inside(ui, |ui| {
            ui.horizontal_wrapped(|ui| {
                ui.heading("📍 Hållpunkter");
                ui.separator();
                ui.label("the hard-to-cover layer boundaries — the anchors a test matrix must reach");
            });
            ui.horizontal_wrapped(|ui| {
                ui.colored_label(theme.accent, format!("ui {u}"));
                ui.add_space(8.0);
                ui.colored_label(super::facett_theme::AMBER, format!("gRPC {g}"));
                ui.add_space(8.0);
                ui.colored_label(theme.point, format!("emitter {e}"));
                if self.repo_root.as_os_str().is_empty() {
                    ui.separator();
                    ui.weak("(remote: no checkout — run locally to classify landmarks)");
                }
            });
        });

        // The click-to-code preview panel works here too.
        self.draw_source_preview(ui);

        egui::CentralPanel::default().show_inside(ui, |ui| {
            if landmarks.is_empty() {
                ui.add_space(12.0);
                ui.weak(
                    "no boundary landmarks discovered yet — they are classified from the \
                     repo's scanned symbols (ui/draw/state_json under src/viz, gRPC handlers, \
                     emit*/trace points).",
                );
                return;
            }
            let mut to_open: Option<String> = None;
            ScrollArea::vertical().id_salt("arch_landmarks").auto_shrink([false, false]).show(ui, |ui| {
                for (bnd, group_color, group_name) in [
                    (Boundary::Ui, theme.accent, "ui (impl Facet)"),
                    (Boundary::Grpc, super::facett_theme::AMBER, "gRPC handlers"),
                    (Boundary::Emitter, theme.point, "emitter (state_json / emit* / $NORNIR_VIZ_TRACE)"),
                ] {
                    let group: Vec<&ArchNode> =
                        landmarks.iter().filter(|(b, _)| *b == bnd).map(|(_, n)| n).collect();
                    if group.is_empty() {
                        continue;
                    }
                    ui.add_space(6.0);
                    ui.label(RichText::new(group_name).strong().color(group_color));
                    ui.horizontal_wrapped(|ui| {
                        for n in group {
                            let chip = egui::Button::new(
                                RichText::new(&n.label).monospace().size(11.0).color(theme.text),
                            )
                            .fill(group_color.linear_multiply(0.22))
                            .stroke(Stroke::new(1.2, group_color));
                            if ui.add(chip).on_hover_text("open source (click-to-code)").clicked() {
                                to_open = Some(n.label.clone());
                            }
                        }
                    });
                }
            });
            if let Some(label) = to_open {
                self.open_symbol(&label, true);
            }
        });
    }

    /// 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(", ")
                ));
            }
        });
    }

    /// Per-marker test-matrix tally: (tested, untested, allowlisted, unknown).
    /// The keystone numbers — green ⟺ every marker has a covering test.
    fn cov_counts(&self) -> (usize, usize, usize, usize) {
        let (mut t, mut u, mut a, mut k) = (0, 0, 0, 0);
        for n in &self.graph.nodes {
            match self.cov_of(&n.id) {
                Cov::Tested => t += 1,
                Cov::Untested => u += 1,
                Cov::Allowlisted => a += 1,
                Cov::Unknown => k += 1,
            }
        }
        (t, u, a, k)
    }

    fn render_out(&self) -> RenderOut {
        let count = |k: NodeKind| self.graph.nodes.iter().filter(|n| n.kind == k).count();
        let (tested, untested, allowlisted, coverage_unknown) = self.cov_counts();
        RenderOut {
            node_count: self.graph.nodes.len(),
            edge_count: self.graph.edges.len(),
            components: count(NodeKind::Component),
            grpc: count(NodeKind::Grpc),
            cli: count(NodeKind::Cli),
            core_fns: count(NodeKind::CoreFn),
            tables: count(NodeKind::Table),
            tested,
            untested,
            allowlisted,
            coverage_unknown,
            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(),
                    // The canonical layer (ui/grpc/cli/core/table) — AUT8-GAP-LAYER,
                    // derived from kind so the matrix groups by the same strata.
                    "layer": n.kind.layer(),
                    // The per-marker cross-check: is there a test for it?
                    "cov": self.cov_of(&n.id).label(),
                })
            })
            .collect();
        let (tested, untested, allowlisted, coverage_unknown) = self.cov_counts();
        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();
        // 📍 Hållpunkter: the boundary landmark tally + the landmark labels by
        // boundary, classified with the coverage feature's `classify` (reused).
        let (bnd_ui, bnd_grpc, bnd_emitter) = self.boundary_tally();
        let landmark_list: Vec<serde_json::Value> = self
            .boundary_landmarks()
            .iter()
            .map(|(b, n)| serde_json::json!({ "boundary": b.as_str(), "label": n.label, "id": n.id }))
            .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),
            "cli": count(NodeKind::Cli),
            "core_fns": count(NodeKind::CoreFn),
            "tables": count(NodeKind::Table),
            // The keystone cross-check, as readable data: every marker tallied
            // against the test matrix. green ⟺ untested == 0.
            "coverage": {
                "tested": tested,
                "untested": untested,
                "allowlisted": allowlisted,
                "unknown": coverage_unknown,
                "has_data": !self.coverage.is_empty(),
            },
            "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,
            // ── CONTAINER: the active sub-view + the full sub-view list, so the
            // headless matrix mechanically enumerates every lens (LAW #6).
            "sub_view": self.sub.id(),
            "sub_views": ArchSubView::ALL.iter().map(|v| v.id()).collect::<Vec<_>>(),
            "live": self.live,
            // ── 📍 Hållpunkter: the ui/grpc/emitter LANDMARK tally (the boundary
            // anchors), classified by the coverage feature's `classify` (reused).
            "boundaries": {
                "ui": bnd_ui,
                "grpc": bnd_grpc,
                "emitter": bnd_emitter,
                "total": bnd_ui + bnd_grpc + bnd_emitter,
                "landmarks": landmark_list,
            },
            // ── click-to-code: the last-clicked symbol → file:line + candidates,
            // the editor-open result, and the inline preview line range — so a
            // robot test asserts the click-to-code WITHOUT pixels (task #3).
            "last_open": self.last_open.as_ref().map(|o| serde_json::json!({
                "query": o.query,
                "resolved": o.hits.first().map(|h| format!("{}:{}", h.file, h.line)),
                "file": o.hits.first().map(|h| h.file.clone()),
                "line": o.hits.first().map(|h| h.line),
                "symbol": o.hits.first().map(|h| h.symbol.clone()),
                "candidates": o.hits.len(),
                "editor_opened": o.editor_opened,
                "preview_lines": o.preview.len(),
                "preview_start": o.preview_start,
            })),
        })
    }

    // ── 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);
    }

    /// Inject coverage verdicts (node id → `covered`/`missing`/`allowlisted`) as
    /// the warehouse cross-check would deliver, so a test can assert the green/red
    /// tally via `state_json()` without a warehouse.
    #[doc(hidden)]
    pub fn inject_coverage_for_test(
        &mut self,
        coverage: std::collections::BTreeMap<String, String>,
    ) {
        self.coverage = coverage;
        self.render_dirty = true;
    }

    /// Inject scanned symbols directly (no warehouse / no checkout) so a test can
    /// drive click-to-code resolution + the boundary-landmark classifier via
    /// `state_json()` / `open_symbol`. Mirrors the other inject seams.
    #[doc(hidden)]
    pub fn inject_symbols_for_test(&mut self, symbols: Vec<crate::knowledge::symbols::SymbolRow>) {
        self.symbols = Some(symbols);
        self.render_dirty = true;
    }

    /// Set the active sub-view from a test (parity with a selector click).
    #[doc(hidden)]
    pub fn set_sub_view_by_id_for_test(&mut self, id: &str) -> bool {
        match ArchSubView::from_id(id) {
            Some(sv) => {
                self.set_sub_view(sv);
                true
            }
            None => false,
        }
    }

    /// 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,
        ),
        // CLI verbs on the palette edge colour — the third entrypoint marker
        // layer beside UI (accent) and gRPC (amber); kept off green/red so the
        // chip FILL never clashes with the coverage RING.
        NodeKind::Cli => (theme.edge.linear_multiply(0.30), theme.edge),
        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)
}

/// The coverage ring colour for a marker's test-matrix status: green = a test
/// exists, red = none, amber = allowlisted gap, `None` = unknown (keep the kind
/// stroke). Uses the facett status palette — no ad-hoc chrome.
fn cov_ring(cov: Cov) -> Option<Color32> {
    match cov {
        Cov::Tested => Some(super::facett_theme::GREEN),
        Cov::Untested => Some(super::facett_theme::RED),
        Cov::Allowlisted => Some(super::facett_theme::AMBER),
        Cov::Unknown => None,
    }
}

/// 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 coverage_cross_check_tallies_tested_vs_untested() {
        let mut st = ArchTabState::local(PathBuf::from("/nonexistent"));
        st.inject_for_test(board(), vec!["nornir".into()]);
        // TestTab has a test; Viz.Architecture has none; test_results is allowlisted.
        let mut cov = std::collections::BTreeMap::new();
        cov.insert("component:TestTab".to_string(), "covered".to_string());
        cov.insert("grpc:Viz.Architecture".to_string(), "missing".to_string());
        cov.insert("table:test_results".to_string(), "allowlisted".to_string());
        st.inject_coverage_for_test(cov);
        let js = st.state_json();
        // The keystone tally: green ⟺ untested == 0.
        assert_eq!(js["coverage"]["tested"], 1);
        assert_eq!(js["coverage"]["untested"], 1);
        assert_eq!(js["coverage"]["allowlisted"], 1);
        // 5 nodes, 3 carry a verdict → 2 unmatched (never a false green).
        assert_eq!(js["coverage"]["unknown"], 2);
        assert_eq!(js["coverage"]["has_data"], true);
        // The per-marker verdict surfaces in the nodes array.
        let nodes = js["nodes"].as_array().unwrap();
        let find = |id: &str| {
            nodes.iter().find(|n| n["id"] == id).unwrap()["cov"].as_str().unwrap().to_string()
        };
        assert_eq!(find("component:TestTab"), "tested");
        assert_eq!(find("grpc:Viz.Architecture"), "untested");
        assert_eq!(find("table:test_results"), "allowlisted");
        assert_eq!(find("corefn:nornir::viz"), "unknown");
    }

    #[test]
    fn no_coverage_data_is_all_unknown_not_false_green() {
        let mut st = ArchTabState::local(PathBuf::from("/nonexistent"));
        st.inject_for_test(board(), vec!["nornir".into()]);
        let js = st.state_json();
        assert_eq!(js["coverage"]["has_data"], false);
        assert_eq!(js["coverage"]["tested"], 0);
        assert_eq!(js["coverage"]["unknown"], 5, "no data → all unknown, none green");
    }

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