nornir 0.4.34

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
//! EPIC ARCH — the **architecture-wiring auto-generator** (n-006).
//!
//! Coarsen the fn-level knowledge facts (`symbol_facts` + `call_edges`) and the
//! `fn → warehouse-table` access fact (`warehouse_access_edges`,
//! [`crate::warehouse::access_scan`]) into ONE component/gRPC/core/table wiring
//! graph — the picture `.nornir/architecture-wiring.md` §2 hand-derives, but
//! produced *by code*.
//!
//! The model is a **quotient** of the fn-level call graph by an *owner-fn*
//! classifier ([`classify`]):
//!
//! | owner-fn shape                                   | node kind            |
//! |--------------------------------------------------|----------------------|
//! | `impl Facet for T` (a viz pane / UI component)   | [`NodeKind::Component`] (`T`) |
//! | a gRPC service handler (`Svc::verb`)             | [`NodeKind::Grpc`] (`Svc.verb`) |
//! | `query_<table>` / `append_<table>` (an accessor) | [`NodeKind::Table`] (the table) |
//! | anything else                                    | [`NodeKind::CoreFn`] (`crate::module`) |
//!
//! Collapsing every fn-level call edge `caller → callee` to
//! `class(caller) → class(callee)` turns the dense fn graph into the
//! component↔gRPC↔core↔table board. The `fn → table` access fact supplies the
//! `* → Table` edges directly (a call graph never yields "this fn writes that
//! table"). Self-edges and duplicate edges are dropped, so e.g. the Test tab's
//! `fetch_test_results → test_results` collapses to `TestTab → test_results`.
//!
//! The graph renders [`to_svg`] in the **skade circuit-board** house style — a
//! direct-emit SVG (no mermaid, no typst layout engine), so it is available in
//! every feature set. It historizes to the warehouse keyed by git sha
//! ([`warehouse`]) and is generated/exported by `nornir arch [svg]`.

pub mod warehouse;

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use crate::knowledge::symbols::{CallEdgeRow, SymbolRow};
use crate::warehouse::access_scan::{Access, AccessEdge};

/// A node kind in the coarsened architecture graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum NodeKind {
    /// An entrypoint / UI component — a `T` with `impl Facet for T` (a viz pane).
    Component,
    /// A gRPC service handler — `Service.verb`.
    Grpc,
    /// A core function / module (the catch-all bucket, labelled `crate::module`).
    CoreFn,
    /// A warehouse table.
    Table,
}

impl NodeKind {
    pub fn as_str(self) -> &'static str {
        match self {
            NodeKind::Component => "component",
            NodeKind::Grpc => "grpc",
            NodeKind::CoreFn => "corefn",
            NodeKind::Table => "table",
        }
    }
    pub fn parse(s: &str) -> Self {
        match s {
            "component" => NodeKind::Component,
            "grpc" => NodeKind::Grpc,
            "table" => NodeKind::Table,
            _ => NodeKind::CoreFn,
        }
    }
}

/// One coarsened node. `id` is unique + stable; `label` is the displayed text.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ArchNode {
    pub id: String,
    pub label: String,
    pub kind: NodeKind,
}

/// A relation between coarsened nodes. `reads`/`writes` are the only kinds the
/// access fact yields (`* → Table`); plain calls are `Calls`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum ArchEdgeKind {
    Calls,
    Reads,
    Writes,
}

impl ArchEdgeKind {
    pub fn as_str(self) -> &'static str {
        match self {
            ArchEdgeKind::Calls => "calls",
            ArchEdgeKind::Reads => "reads",
            ArchEdgeKind::Writes => "writes",
        }
    }
    pub fn parse(s: &str) -> Self {
        match s {
            "reads" => ArchEdgeKind::Reads,
            "writes" => ArchEdgeKind::Writes,
            _ => ArchEdgeKind::Calls,
        }
    }
}

/// A coarsened edge `from → to`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ArchEdge {
    pub from: String,
    pub to: String,
    pub kind: ArchEdgeKind,
}

/// The coarsened architecture graph: nodes + edges, deterministically ordered.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArchGraph {
    pub nodes: Vec<ArchNode>,
    pub edges: Vec<ArchEdge>,
}

/// The owner-fn classifier — the heart of the quotient. Maps a fn's
/// fully-qualified caller/callee path (as recorded in `symbol_facts` /
/// `call_edges`, e.g. `nornir::TestTab::fetch_test_results`) to the node it
/// collapses into.
///
/// `facet_impls` is the set of `T` types that have an `impl Facet for T`
/// (derived from `symbol_facts`); a fn whose owning type is one of them is a
/// **Component**. `grpc_handlers` maps a fully-qualified handler fn path to its
/// `Service.verb` label. `accessors` maps an accessor fn ident (last segment)
/// to the table it touches. Anything unmatched is a **CoreFn** bucketed by
/// `crate::module`.
pub struct Classifier<'a> {
    /// Type names (last segment) with an `impl Facet for T`.
    pub facet_impls: &'a BTreeSet<String>,
    /// Map: fully-qualified handler fn path → `Service.verb` label.
    pub grpc_handlers: &'a BTreeMap<String, String>,
}

impl<'a> Classifier<'a> {
    /// Classify one fully-qualified fn path into its coarsened node.
    pub fn classify(&self, fq: &str) -> ArchNode {
        // gRPC handler — exact match on the recorded handler path.
        if let Some(label) = self.grpc_handlers.get(fq) {
            return ArchNode {
                id: format!("grpc:{label}"),
                label: label.clone(),
                kind: NodeKind::Grpc,
            };
        }
        // Component — the owning type (`crate::Mod::Type::method` → `Type`) has
        // an `impl Facet for Type`. We look at the *penultimate* path segment
        // (the type the method is defined on).
        let segs: Vec<&str> = fq.split("::").collect();
        if segs.len() >= 2 {
            let owner_ty = segs[segs.len() - 2];
            if self.facet_impls.contains(owner_ty) {
                return ArchNode {
                    id: format!("component:{owner_ty}"),
                    label: owner_ty.to_string(),
                    kind: NodeKind::Component,
                };
            }
        }
        // CoreFn — bucket by `crate::module` (drop the fn name + any type/impl
        // tail so a whole module collapses to one chip).
        let bucket = core_bucket(fq);
        ArchNode {
            id: format!("corefn:{bucket}"),
            label: bucket,
            kind: NodeKind::CoreFn,
        }
    }
}

/// Bucket a fq fn path to `crate::module` — keep the crate + the first module
/// segment, drop deeper module/type/fn tails so a module collapses to one node.
/// `nornir::viz::live::Loader::hydrate` → `nornir::viz`. A bare `crate::fn`
/// (`nornir::main`) → `nornir`.
fn core_bucket(fq: &str) -> String {
    let segs: Vec<&str> = fq.split("::").collect();
    match segs.len() {
        0 => "unknown".to_string(),
        1 => segs[0].to_string(),
        2 => segs[0].to_string(), // crate::fn → crate
        _ => format!("{}::{}", segs[0], segs[1]),
    }
}

/// Derive the set of `T` with `impl Facet for T` from `symbol_facts` rows.
/// A facet impl is recorded as an `impl`-kind symbol with item_name
/// `impl Facet for T` (the [`crate::knowledge::symbols`] convention).
pub fn facet_impls_from_symbols(symbols: &[SymbolRow]) -> BTreeSet<String> {
    let mut out = BTreeSet::new();
    for s in symbols {
        if s.item_kind == "impl" {
            if let Some(t) = parse_facet_impl(&s.item_name) {
                out.insert(t);
            }
        }
    }
    out
}

/// Derive the gRPC handler map from `symbol_facts`: every method defined on a
/// `XxxSvc`-style service struct whose impl block is `impl XxxSvcTrait for
/// XxxSvc` (the tonic-generated handler trait convention used by
/// `src/bin/nornir-server.rs`) maps `fq_fn_path → "Service.Verb"`.
///
/// The service name is the `Svc` struct minus its `Svc` suffix (`VizSvc` →
/// `Viz`), and the verb is the method name in CamelCase (`timeline` →
/// `Timeline`), so `VizSvc::timeline` → `Viz.Timeline` — matching the
/// `proto/nornir.proto` service.verb naming the acceptance fixture uses.
pub fn grpc_handlers_from_symbols(symbols: &[SymbolRow]) -> BTreeMap<String, String> {
    // Service struct types that have a tonic handler impl (`impl *Trait for *Svc`).
    let mut svc_types: BTreeSet<String> = BTreeSet::new();
    for s in symbols {
        if s.item_kind == "impl" {
            if let Some(ty) = parse_grpc_impl(&s.item_name) {
                svc_types.insert(ty);
            }
        }
    }
    let mut out = BTreeMap::new();
    for s in symbols {
        if s.item_kind != "fn" {
            continue;
        }
        // The method's owning type is the last segment of its module_path.
        let owner_ty = s.module_path.rsplit("::").next().unwrap_or("");
        if !svc_types.contains(owner_ty) {
            continue;
        }
        let service = owner_ty.strip_suffix("Svc").unwrap_or(owner_ty);
        let verb = to_camel(&s.item_name);
        let label = format!("{service}.{verb}");
        let fq = format!("{}::{}", s.module_path, s.item_name);
        out.insert(fq, label);
    }
    out
}

/// `impl VizSvcTrait for VizSvc` → `Some("VizSvc")`. Matches a trait whose name
/// ends in `Trait` (the tonic handler-trait convention) implemented for a type
/// whose name ends in `Svc`.
fn parse_grpc_impl(label: &str) -> Option<String> {
    let rest = label.strip_prefix("impl ")?;
    let (trait_part, ty_part) = rest.split_once(" for ")?;
    let trait_last = trait_part.rsplit("::").next().unwrap_or(trait_part).trim();
    let ty = ty_part.trim();
    let bare = ty.split(['<', ' ']).next().unwrap_or(ty);
    let last = bare.rsplit("::").next().unwrap_or(bare).trim();
    if trait_last.ends_with("Trait") && last.ends_with("Svc") && !last.is_empty() {
        Some(last.to_string())
    } else {
        None
    }
}

/// snake_case / single ident → CamelCase verb (`bakeoff_results` → `BakeoffResults`).
fn to_camel(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut upper = true;
    for c in s.chars() {
        if c == '_' {
            upper = true;
        } else if upper {
            out.extend(c.to_uppercase());
            upper = false;
        } else {
            out.push(c);
        }
    }
    out
}

/// Build the full architecture graph from raw knowledge + access facts,
/// deriving the Facet-component set and the gRPC-handler map from `symbols`.
/// This is the one-call entrypoint `nornir arch` uses.
pub fn generate(
    symbols: &[SymbolRow],
    calls: &[CallEdgeRow],
    access: &[AccessEdge],
) -> ArchGraph {
    let facets = facet_impls_from_symbols(symbols);
    let handlers = grpc_handlers_from_symbols(symbols);
    let cls = Classifier { facet_impls: &facets, grpc_handlers: &handlers };
    build_graph(symbols, calls, access, &cls)
}

/// `impl Facet for TestTab` → `Some("TestTab")`; `impl Foo for Bar` → `None`.
/// The trait match is on the *bare* `Facet` trait name (last path segment of
/// the trait), so `impl crate::facett::Facet for T` also matches.
fn parse_facet_impl(label: &str) -> Option<String> {
    let rest = label.strip_prefix("impl ")?;
    let (trait_part, ty_part) = rest.split_once(" for ")?;
    let trait_last = trait_part.rsplit("::").next().unwrap_or(trait_part).trim();
    if trait_last != "Facet" {
        return None;
    }
    // The self-type may carry generics (`Grid<T>`) — take the bare type ident.
    let ty = ty_part.trim();
    let bare = ty.split(['<', ' ']).next().unwrap_or(ty);
    let last = bare.rsplit("::").next().unwrap_or(bare).trim();
    if last.is_empty() {
        None
    } else {
        Some(last.to_string())
    }
}

/// Build the coarsened [`ArchGraph`] — the quotient of `calls` by `classify`,
/// plus the `* → Table` edges from `access`.
///
/// - Each `caller → callee` call edge becomes `class(caller) → class(callee)`
///   with kind [`ArchEdgeKind::Calls`]. Self-edges (a node calling itself) and
///   duplicates collapse away.
/// - Each access edge `caller_fn → (table, read|write)` becomes
///   `class(caller_fn) → Table(table)` with kind `Reads`/`Writes`. The
///   `<dynamic>` sentinel table is skipped (no concrete node).
/// - A callee that is not itself a defined symbol (an external/library call) is
///   still classified by its identifier shape; bare idents with no `::` are
///   dropped (they can't be meaningfully bucketed and would be noise).
pub fn build_graph(
    symbols: &[SymbolRow],
    calls: &[CallEdgeRow],
    access: &[AccessEdge],
    cls: &Classifier<'_>,
) -> ArchGraph {
    let mut nodes: BTreeMap<String, ArchNode> = BTreeMap::new();
    let mut edges: BTreeSet<ArchEdge> = BTreeSet::new();

    let add_node = |nodes: &mut BTreeMap<String, ArchNode>, n: ArchNode| {
        nodes.entry(n.id.clone()).or_insert(n);
    };

    // Seed: every defined symbol that is a fn → its classified node (so a pane
    // with no outgoing call still appears as a chip). Cheap + makes the board
    // reflect the surface, not just the edges.
    for s in symbols {
        if s.item_kind != "fn" {
            continue;
        }
        let fq = format!("{}::{}", s.module_path, s.item_name);
        add_node(&mut nodes, cls.classify(&fq));
    }

    // Call edges → coarsened Calls edges.
    for c in calls {
        let from = cls.classify(&c.caller_path);
        // The callee is recorded as an identifier (`Foo::bar` or bare `bar`).
        // Classify it the same way; skip bare idents (no `::`) — unbucketable
        // noise (`new`, `unwrap`, `push`, …).
        if !c.callee_ident.contains("::") {
            // Still record the caller node so it is on the board.
            add_node(&mut nodes, from);
            continue;
        }
        let to = cls.classify(&c.callee_ident);
        let (from_id, to_id) = (from.id.clone(), to.id.clone());
        add_node(&mut nodes, from);
        add_node(&mut nodes, to);
        if from_id != to_id {
            edges.insert(ArchEdge { from: from_id, to: to_id, kind: ArchEdgeKind::Calls });
        }
    }

    // Access edges → `* → Table` Reads/Writes edges (the edge no call graph has).
    for a in access {
        if a.table == crate::warehouse::access_scan::DYNAMIC_TABLE {
            continue;
        }
        let from = cls.classify(&a.caller_fn);
        let from_id = from.id.clone();
        let table_id = format!("table:{}", a.table);
        add_node(&mut nodes, from);
        add_node(
            &mut nodes,
            ArchNode {
                id: table_id.clone(),
                label: a.table.clone(),
                kind: NodeKind::Table,
            },
        );
        let kind = match a.access {
            Access::Read => ArchEdgeKind::Reads,
            Access::Write => ArchEdgeKind::Writes,
        };
        if from_id != table_id {
            edges.insert(ArchEdge { from: from_id, to: table_id, kind });
        }
    }

    let mut nodes: Vec<ArchNode> = nodes.into_values().collect();
    nodes.sort();
    let edges: Vec<ArchEdge> = edges.into_iter().collect();
    ArchGraph { nodes, edges }
}

/// Trace mode (ARCH5 `nornir arch trace <entrypoint>` / AUT7 `flow <entrypoint>`):
/// the focused sub-board of everything **reachable downstream** from the
/// coarsened node an `entrypoint` ident collapses into. The entrypoint is
/// matched by node label or id substring (case-insensitive) against the full
/// [`ArchGraph`] `graph` — so `TestTab`, `Viz.Timeline`, or a `crate::module`
/// bucket all resolve. From each matched seed we BFS the `Calls`/`Reads`/`Writes`
/// edges forward, keeping only the reached nodes + the edges among them. The
/// result is itself an [`ArchGraph`], so it renders with the same circuit-board
/// [`to_svg`]. Returns an empty graph when no node matches the entrypoint.
///
/// This is the visual twin of `knowledge_call_path` lifted to the coarsened
/// board: instead of an fn-level chain it answers "open this surface — which
/// gRPC verbs / core modules / warehouse tables does it reach?".
pub fn trace_from(graph: &ArchGraph, entrypoint: &str) -> ArchGraph {
    use std::collections::{HashMap, VecDeque};
    let needle = entrypoint.to_lowercase();
    // Seeds: any node whose label or id contains the entrypoint substring.
    let seeds: BTreeSet<&str> = graph
        .nodes
        .iter()
        .filter(|n| {
            n.label.to_lowercase().contains(&needle) || n.id.to_lowercase().contains(&needle)
        })
        .map(|n| n.id.as_str())
        .collect();
    if seeds.is_empty() {
        return ArchGraph::default();
    }
    // Forward adjacency over all edge kinds.
    let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
    for e in &graph.edges {
        adj.entry(e.from.as_str()).or_default().push(e.to.as_str());
    }
    // BFS reachability from every seed.
    let mut reached: BTreeSet<&str> = BTreeSet::new();
    let mut queue: VecDeque<&str> = VecDeque::new();
    for &s in &seeds {
        if reached.insert(s) {
            queue.push_back(s);
        }
    }
    while let Some(cur) = queue.pop_front() {
        if let Some(outs) = adj.get(cur) {
            for &nxt in outs {
                if reached.insert(nxt) {
                    queue.push_back(nxt);
                }
            }
        }
    }
    let by_id: BTreeMap<&str, &ArchNode> =
        graph.nodes.iter().map(|n| (n.id.as_str(), n)).collect();
    let mut nodes: Vec<ArchNode> = reached
        .iter()
        .filter_map(|id| by_id.get(id).map(|n| (*n).clone()))
        .collect();
    nodes.sort();
    let edges: Vec<ArchEdge> = graph
        .edges
        .iter()
        .filter(|e| reached.contains(e.from.as_str()) && reached.contains(e.to.as_str()))
        .cloned()
        .collect();
    ArchGraph { nodes, edges }
}

// ───────────────────────────────────────────────────────────────────────────
// SVG render — skade circuit-board style, direct-emit (no mermaid, no typst).
// ───────────────────────────────────────────────────────────────────────────

impl ArchGraph {
    /// Render the graph as a **self-contained, static SVG** in the skade
    /// circuit-board house style: a dark PCB substrate, layered chips coloured
    /// by [`NodeKind`], cyan call traces and amber read/write traces. No
    /// mermaid, no JavaScript, no diagram engine, no typst — the markup is
    /// emitted directly so it renders verbatim in any viewer and is available
    /// in every feature set.
    pub fn to_svg(&self) -> String {
        render_pcb_svg(self)
    }

    /// A plain-text adjacency dump — the no-pixels fallback (terminal output).
    pub fn to_text(&self) -> String {
        let mut s = String::new();
        s.push_str("nodes:\n");
        for n in &self.nodes {
            s.push_str(&format!("  [{}] {}\n", n.kind.as_str(), n.label));
        }
        if self.edges.is_empty() {
            s.push_str("edges: (none)\n");
        } else {
            s.push_str("edges:\n");
            for e in &self.edges {
                s.push_str(&format!("  {}{} ({})\n", e.from, e.to, e.kind.as_str()));
            }
        }
        s
    }
}

fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// Layered BFS columns. Layer 0 = sources (no incoming edge). Cycles broken
/// deterministically (idempotent output for a given input). Tables are pinned
/// to the **last** layer so they ground on the right (the warehouse rail).
fn layers_of(graph: &ArchGraph) -> Vec<Vec<usize>> {
    use std::collections::HashMap;
    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(|n| n.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
}

/// Chip gradient/stroke per node kind (the skade PCB palette).
fn kind_style(kind: NodeKind) -> (&'static str, &'static str) {
    // (fill, stroke)
    match kind {
        NodeKind::Component => ("#14384f", "#3aa0d0"), // UI chip — glacier blue
        NodeKind::Grpc => ("#3a2a14", "#d0962a"),      // RPC chip — amber
        NodeKind::CoreFn => ("#173d57", "#5a8fb0"),    // core chip — steel
        NodeKind::Table => ("#0c2438", "#2db6e0"),     // warehouse rail — cyan
    }
}

fn render_pcb_svg(graph: &ArchGraph) -> String {
    use std::collections::HashMap;
    if graph.nodes.is_empty() {
        return String::from(
            "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 320 80\" \
             font-family=\"'DejaVu Sans', sans-serif\">\
             <rect x=\"0\" y=\"0\" width=\"320\" height=\"80\" fill=\"#06111d\"/>\
             <text x=\"16\" y=\"44\" fill=\"#5a8fb0\" font-size=\"14\">(empty architecture graph)</text>\
             </svg>\n",
        );
    }
    let layers = layers_of(graph);
    let col_w = 240.0f64;
    let row_h = 56.0f64;
    let box_w = 188.0f64;
    let box_h = 34.0f64;
    let margin = 28.0f64;

    let cols = layers.len().max(1);
    let rows = layers.iter().map(|l| l.len()).max().unwrap_or(1).max(1);
    let width = margin * 2.0 + col_w * cols as f64;
    let height = margin * 2.0 + row_h * rows as f64;

    let mut pos: HashMap<usize, (f64, f64)> = HashMap::new();
    for (ci, layer) in layers.iter().enumerate() {
        let total_h = layer.len() as f64 * row_h;
        let start_y = margin + (height - margin * 2.0 - total_h) / 2.0;
        for (ri, &node_i) in layer.iter().enumerate() {
            let x = margin + ci as f64 * col_w;
            let y = start_y + ri as f64 * row_h;
            pos.insert(node_i, (x, y));
        }
    }
    let id_to_idx: HashMap<&str, usize> =
        graph.nodes.iter().enumerate().map(|(i, nd)| (nd.id.as_str(), i)).collect();

    let mut s = String::new();
    s.push_str(&format!(
        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {width:.0} {height:.0}\" \
         font-family=\"'DejaVu Sans', 'Segoe UI', sans-serif\" font-size=\"12\">\n"
    ));
    s.push_str(
        "<defs>\
         <linearGradient id=\"arch-board\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\
         <stop offset=\"0\" stop-color=\"#0b1c2e\"/><stop offset=\"1\" stop-color=\"#06111d\"/>\
         </linearGradient>\
         <marker id=\"arch-arrow\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"3\" \
         orient=\"auto\"><path d=\"M0,0 L7,3 L0,6 Z\" fill=\"#3aa0d0\"/></marker>\
         <marker id=\"arch-arrow-rw\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"3\" \
         orient=\"auto\"><path d=\"M0,0 L7,3 L0,6 Z\" fill=\"#d0962a\"/></marker>\
         </defs>\n",
    );
    // PCB substrate.
    s.push_str(&format!(
        "<rect x=\"0\" y=\"0\" width=\"{width:.0}\" height=\"{height:.0}\" fill=\"url(#arch-board)\"/>\n"
    ));

    // Traces (edges) first, so chips sit on top.
    for e in &graph.edges {
        let (Some(&fi), Some(&ti)) =
            (id_to_idx.get(e.from.as_str()), id_to_idx.get(e.to.as_str()))
        else {
            continue;
        };
        let (Some(&(fx, fy)), Some(&(tx, ty))) = (pos.get(&fi), pos.get(&ti)) else {
            continue;
        };
        let x1 = fx + box_w;
        let y1 = fy + box_h / 2.0;
        let x2 = tx;
        let y2 = ty + box_h / 2.0;
        // Right-angled-ish PCB trace via a cubic with a mid breakpoint.
        let mid = (x1 + x2) / 2.0;
        let (color, marker, dash) = match e.kind {
            ArchEdgeKind::Calls => ("#3aa0d0", "url(#arch-arrow)", ""),
            ArchEdgeKind::Reads => ("#d0962a", "url(#arch-arrow-rw)", " stroke-dasharray=\"6 4\""),
            ArchEdgeKind::Writes => ("#e0b050", "url(#arch-arrow-rw)", ""),
        };
        s.push_str(&format!(
            "<path d=\"M{x1:.0},{y1:.0} C{mid:.0},{y1:.0} {mid:.0},{y2:.0} {x2:.0},{y2:.0}\" \
             fill=\"none\" stroke=\"{color}\" stroke-width=\"1.6\"{dash} \
             marker-end=\"{marker}\" opacity=\"0.85\"/>\n"
        ));
    }

    // Chips (nodes).
    for (i, nd) in graph.nodes.iter().enumerate() {
        let Some(&(x, y)) = pos.get(&i) else { continue };
        let (fill, stroke) = kind_style(nd.kind);
        let label = xml_escape(&nd.label);
        s.push_str(&format!(
            "<rect x=\"{x:.0}\" y=\"{y:.0}\" width=\"{box_w:.0}\" height=\"{box_h:.0}\" rx=\"5\" \
             fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.4\"/>\n"
        ));
        // Solder-pad dot on the chip's left edge (PCB flavour).
        s.push_str(&format!(
            "<circle cx=\"{:.0}\" cy=\"{:.0}\" r=\"2.4\" fill=\"{stroke}\"/>\n",
            x + 6.0,
            y + box_h / 2.0,
        ));
        s.push_str(&format!(
            "<text x=\"{:.0}\" y=\"{:.0}\" text-anchor=\"middle\" fill=\"#dbeaf4\">{label}</text>\n",
            x + box_w / 2.0 + 4.0,
            y + box_h / 2.0 + 4.0,
        ));
    }
    s.push_str("</svg>\n");
    s
}

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

    fn sym_fn(module_path: &str, name: &str) -> SymbolRow {
        SymbolRow {
            crate_name: "nornir".into(),
            module_path: module_path.into(),
            item_kind: "fn".into(),
            item_name: name.into(),
            visibility: "pub".into(),
            file: "src/x.rs".into(),
            line: 1,
            doc_lines: 0,
            signature: None,
        }
    }
    fn sym_impl(module_path: &str, label: &str) -> SymbolRow {
        SymbolRow {
            crate_name: "nornir".into(),
            module_path: module_path.into(),
            item_kind: "impl".into(),
            item_name: label.into(),
            visibility: "pub".into(),
            file: "src/x.rs".into(),
            line: 1,
            doc_lines: 0,
            signature: None,
        }
    }
    fn call(caller: &str, callee: &str) -> CallEdgeRow {
        CallEdgeRow {
            crate_name: "nornir".into(),
            caller_path: caller.into(),
            callee_ident: callee.into(),
            call_kind: "call".into(),
            file: "src/x.rs".into(),
            line: 1,
        }
    }
    fn access(caller: &str, table: &str, a: Access) -> AccessEdge {
        AccessEdge {
            caller_fn: caller.into(),
            crate_name: "nornir".into(),
            table: table.into(),
            access: a,
            file: "src/x.rs".into(),
            line: 1,
        }
    }

    #[test]
    fn parse_facet_impl_only_facet_trait() {
        assert_eq!(parse_facet_impl("impl Facet for TestTab").as_deref(), Some("TestTab"));
        assert_eq!(
            parse_facet_impl("impl crate::facett::Facet for Grid<T>").as_deref(),
            Some("Grid")
        );
        assert_eq!(parse_facet_impl("impl Clone for Foo"), None);
        assert_eq!(parse_facet_impl("impl Foo"), None);
    }

    #[test]
    fn core_bucket_collapses_to_crate_module() {
        assert_eq!(core_bucket("nornir::viz::live::Loader::hydrate"), "nornir::viz");
        assert_eq!(core_bucket("nornir::viz::build_timeline"), "nornir::viz");
        assert_eq!(core_bucket("nornir::main"), "nornir");
        assert_eq!(core_bucket("nornir"), "nornir");
    }

    /// THE acceptance fixture from the task: the Test tab's
    /// `fetch_test_results → test_results` collapses to `TestTab → test_results`.
    #[test]
    fn test_tab_fetch_collapses_to_component_and_table() {
        // TestTab is a Facet component; its fetch fn reads test_results.
        let symbols = vec![
            sym_impl("nornir::viz::test_tab", "impl Facet for TestTab"),
            sym_fn("nornir::viz::test_tab::TestTab", "fetch_test_results"),
        ];
        // fetch calls a per-table accessor (recorded only as a call edge here)…
        let calls = vec![call(
            "nornir::viz::test_tab::TestTab::fetch_test_results",
            "query_test_results",
        )];
        // …and the access fact says that fn reads test_results.
        let acc = vec![access(
            "nornir::viz::test_tab::TestTab::fetch_test_results",
            "test_results",
            Access::Read,
        )];

        let facets = facet_impls_from_symbols(&symbols);
        assert!(facets.contains("TestTab"));
        let cls = Classifier { facet_impls: &facets, grpc_handlers: &BTreeMap::new() };
        let g = build_graph(&symbols, &calls, &acc, &cls);

        // The component node TestTab exists.
        let comp = g
            .nodes
            .iter()
            .find(|n| n.kind == NodeKind::Component && n.label == "TestTab")
            .expect("TestTab component node");
        // The table node test_results exists.
        let tbl = g
            .nodes
            .iter()
            .find(|n| n.kind == NodeKind::Table && n.label == "test_results")
            .expect("test_results table node");

        // The collapsed edge is exactly TestTab --reads--> test_results.
        assert!(
            g.edges.iter().any(|e| e.from == comp.id
                && e.to == tbl.id
                && e.kind == ArchEdgeKind::Reads),
            "expected TestTab -reads-> test_results; got {:?}",
            g.edges
        );
        // The bare `query_test_results` callee (no `::`) produced no spurious
        // node beyond the component + table (plus the impl-derived seed).
        assert!(
            g.nodes.iter().all(|n| n.label != "query_test_results"),
            "accessor ident should not be a standalone node: {:?}",
            g.nodes
        );
    }

    #[test]
    fn grpc_handler_classifies_and_collapses() {
        let symbols = vec![sym_fn("nornir::server::Viz", "timeline")];
        let mut handlers = BTreeMap::new();
        handlers.insert("nornir::server::Viz::timeline".to_string(), "Viz.Timeline".to_string());
        // The handler calls build_timeline (a core fn) which writes release_lineage.
        let calls = vec![call("nornir::server::Viz::timeline", "build_timeline::foo")];
        let acc = vec![access("nornir::server::Viz::timeline", "release_lineage", Access::Write)];

        let facets = BTreeSet::new();
        let cls = Classifier { facet_impls: &facets, grpc_handlers: &handlers };
        let g = build_graph(&symbols, &calls, &acc, &cls);

        let grpc = g
            .nodes
            .iter()
            .find(|n| n.kind == NodeKind::Grpc && n.label == "Viz.Timeline")
            .expect("Viz.Timeline gRPC node");
        let tbl = g
            .nodes
            .iter()
            .find(|n| n.kind == NodeKind::Table && n.label == "release_lineage")
            .unwrap();
        assert!(g.edges.iter().any(|e| e.from == grpc.id
            && e.to == tbl.id
            && e.kind == ArchEdgeKind::Writes));
    }

    #[test]
    fn self_edges_and_dupes_collapse_away() {
        // Two fns in the SAME module calling each other → a self-edge on the
        // module's CoreFn node → must NOT appear.
        let symbols = vec![sym_fn("nornir::mimir", "a"), sym_fn("nornir::mimir", "b")];
        let calls = vec![
            call("nornir::mimir::a", "nornir::mimir::b"),
            call("nornir::mimir::b", "nornir::mimir::a"),
        ];
        let facets = BTreeSet::new();
        let cls = Classifier { facet_impls: &facets, grpc_handlers: &BTreeMap::new() };
        let g = build_graph(&symbols, &calls, &[], &cls);
        assert!(g.edges.is_empty(), "intra-module self-edge must collapse: {:?}", g.edges);
        // One CoreFn node nornir::mimir.
        assert_eq!(g.nodes.len(), 1);
        assert_eq!(g.nodes[0].kind, NodeKind::CoreFn);
        assert_eq!(g.nodes[0].label, "nornir::mimir");
    }

    #[test]
    fn dynamic_table_access_is_skipped() {
        let acc = vec![access("nornir::viz::warehouse_tab::run", "<dynamic>", Access::Read)];
        let facets = BTreeSet::new();
        let cls = Classifier { facet_impls: &facets, grpc_handlers: &BTreeMap::new() };
        let g = build_graph(&[], &[], &acc, &cls);
        assert!(g.nodes.iter().all(|n| n.kind != NodeKind::Table), "no <dynamic> table node");
    }

    #[test]
    fn svg_is_circuit_board_with_expected_labels() {
        let symbols = vec![
            sym_impl("nornir::viz::test_tab", "impl Facet for TestTab"),
            sym_fn("nornir::viz::test_tab::TestTab", "fetch_test_results"),
        ];
        let acc = vec![access(
            "nornir::viz::test_tab::TestTab::fetch_test_results",
            "test_results",
            Access::Read,
        )];
        let facets = facet_impls_from_symbols(&symbols);
        let cls = Classifier { facet_impls: &facets, grpc_handlers: &BTreeMap::new() };
        let g = build_graph(&symbols, &[], &acc, &cls);
        let svg = g.to_svg();
        assert!(svg.starts_with("<svg"), "{svg}");
        assert!(svg.contains("</svg>"));
        assert!(!svg.contains("mermaid"));
        // Circuit-board flavour: dark substrate + the traces.
        assert!(svg.contains("arch-board"), "PCB substrate gradient: {svg}");
        assert!(svg.contains("<path "), "edge traces: {svg}");
        // Expected node labels are present.
        assert!(svg.contains(">TestTab<"), "TestTab chip label: {svg}");
        assert!(svg.contains(">test_results<"), "table chip label: {svg}");
        assert!(svg.len() > 400);
    }

    #[test]
    fn grpc_handlers_derived_from_symbols() {
        let symbols = vec![
            sym_impl("nornir::server", "impl VizSvcTrait for VizSvc"),
            sym_fn("nornir::server::VizSvc", "timeline"),
            sym_fn("nornir::server::VizSvc", "bakeoff_results"),
            // a non-svc impl method must not be picked up
            sym_impl("nornir::server", "impl Clone for VizSvc"),
        ];
        let handlers = grpc_handlers_from_symbols(&symbols);
        assert_eq!(
            handlers.get("nornir::server::VizSvc::timeline").map(String::as_str),
            Some("Viz.Timeline")
        );
        assert_eq!(
            handlers.get("nornir::server::VizSvc::bakeoff_results").map(String::as_str),
            Some("Viz.BakeoffResults")
        );
    }

    #[test]
    fn generate_end_to_end_derives_both_maps() {
        // A pane + a server handler + a table, end-to-end through `generate`.
        let symbols = vec![
            sym_impl("nornir::viz::test_tab", "impl Facet for TestTab"),
            sym_fn("nornir::viz::test_tab::TestTab", "fetch_test_results"),
            sym_impl("nornir::server", "impl VizSvcTrait for VizSvc"),
            sym_fn("nornir::server::VizSvc", "test_results"),
        ];
        let calls = vec![];
        let acc = vec![
            access("nornir::viz::test_tab::TestTab::fetch_test_results", "test_results", Access::Read),
            access("nornir::server::VizSvc::test_results", "test_results", Access::Read),
        ];
        let g = generate(&symbols, &calls, &acc);
        assert!(g.nodes.iter().any(|n| n.kind == NodeKind::Component && n.label == "TestTab"));
        assert!(g.nodes.iter().any(|n| n.kind == NodeKind::Grpc && n.label == "Viz.TestResults"));
        assert!(g.nodes.iter().any(|n| n.kind == NodeKind::Table && n.label == "test_results"));
        // Both the component AND the gRPC verb read test_results.
        let tbl = g.nodes.iter().find(|n| n.kind == NodeKind::Table).unwrap();
        let reads: Vec<&str> = g
            .edges
            .iter()
            .filter(|e| e.to == tbl.id && e.kind == ArchEdgeKind::Reads)
            .map(|e| e.from.as_str())
            .collect();
        assert!(reads.contains(&"component:TestTab"), "{reads:?}");
        assert!(reads.contains(&"grpc:Viz.TestResults"), "{reads:?}");
    }

    /// ARCH5/AUT7 trace mode: from the `TestTab` entrypoint we reach exactly the
    /// downstream table it reads, and an unrelated component is pruned.
    #[test]
    fn trace_from_entrypoint_keeps_only_reachable() {
        // TestTab -reads-> test_results; an unrelated MapTab -reads-> map_tiles.
        let g = ArchGraph {
            nodes: vec![
                ArchNode { id: "component:TestTab".into(), label: "TestTab".into(), kind: NodeKind::Component },
                ArchNode { id: "component:MapTab".into(), label: "MapTab".into(), kind: NodeKind::Component },
                ArchNode { id: "table:test_results".into(), label: "test_results".into(), kind: NodeKind::Table },
                ArchNode { id: "table:map_tiles".into(), label: "map_tiles".into(), kind: NodeKind::Table },
            ],
            edges: vec![
                ArchEdge { from: "component:TestTab".into(), to: "table:test_results".into(), kind: ArchEdgeKind::Reads },
                ArchEdge { from: "component:MapTab".into(), to: "table:map_tiles".into(), kind: ArchEdgeKind::Reads },
            ],
        };
        let sub = trace_from(&g, "TestTab");
        // Exactly the seed + its reachable table — MapTab/map_tiles pruned.
        let labels: BTreeSet<&str> = sub.nodes.iter().map(|n| n.label.as_str()).collect();
        assert!(labels.contains("TestTab"), "{labels:?}");
        assert!(labels.contains("test_results"), "{labels:?}");
        assert!(!labels.contains("MapTab"), "unreachable pruned: {labels:?}");
        assert!(!labels.contains("map_tiles"), "unreachable pruned: {labels:?}");
        // The one kept edge is TestTab -reads-> test_results.
        assert_eq!(sub.edges.len(), 1);
        assert_eq!(sub.edges[0].from, "component:TestTab");
        assert_eq!(sub.edges[0].to, "table:test_results");
        assert_eq!(sub.edges[0].kind, ArchEdgeKind::Reads);
        // It renders the same circuit-board SVG.
        let svg = sub.to_svg();
        assert!(svg.contains(">TestTab<") && svg.contains(">test_results<"));
        // An entrypoint that matches nothing yields the empty graph.
        assert!(trace_from(&g, "no_such_surface").nodes.is_empty());
    }

    #[test]
    fn empty_graph_renders_placeholder_svg() {
        let svg = ArchGraph::default().to_svg();
        assert!(svg.starts_with("<svg"));
        assert!(svg.contains("empty architecture graph"));
    }
}