nornir 0.5.0

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
//! # autonom — the FEEDERS for the completeness gate (AUT2 / n-005)
//!
//! The pure enumerators + the gap/verdict model live in
//! [`nornir_testmatrix::discover`] + [`nornir_testmatrix::coverage`]. This module
//! is nornir's **iceberg-backed feeder layer**: it gathers the REAL inputs —
//! `symbol_facts` / `call_edges` from the warehouse, the viz tab enum, the clap
//! subcommands, the MCP `tools/list`, the facett-style registry — turns them
//! into the pure enumerators' row shapes, and assembles a [`Surface`] +
//! `covered` set so [`GateReport`] can be computed and persisted.
//!
//! ```text
//! gather_inputs (iceberg + clap + tab enum + tools/list)
//!   → discover::{viz_tabs, cli_commands, mcp_tools, facett_components, unreached_functions}
//!   → Surface  +  covered set (test-reachable closure over call_edges)
//!   → GateReport::compute(Surface, covered, allowlist)            (the verdict)
//!   → rows_for(...) → surface_coverage iceberg table              (persisted)
//! ```
//!
//! The allowlist (`autonom-allow.toml`, checked in) is SEEDED (`--seed-allowlist`)
//! with every currently-uncovered surface so the gate is GREEN now and burns
//! down by deletion. The gate FAILS if any surface is uncovered + un-allowlisted
//! OR an allowlist entry is stale (HARD zero, not a ratchet).

pub mod megagate;

use std::collections::BTreeSet;
use std::path::Path;

use anyhow::{Context, Result};

use crate::knowledge::query::{load_latest, KnowledgeView};
use crate::knowledge::symbols::{CallEdgeRow, SymbolRow as KSymbolRow};
use crate::warehouse::iceberg::IcebergWarehouse;
use std::collections::BTreeMap;

use crate::warehouse::surface_coverage::{
    append_surface_coverage, covered_with_utfallsrum, latest_surface_coverage,
    query_surface_coverage, rows_for_with_utfallsrum, seed_allowlist, Allowlist, CoverageRow,
    CoverageSelector, CoverageSummary, GateReport, Verdict,
};
use nornir_testmatrix::discover::{
    cli_commands, covered_atoms, facett_components, grpc_handlers, mcp_tools, ui_atoms,
    unreached_functions, viz_tabs, CallEdge, DiscoveredAtom, FacetRow, Surface, SymbolRow,
};
use nornir_testmatrix::utfallsrum::UtfallsrumSummary;

/// The discrete-surface inputs the binary feeds in (it does the clap / tab-enum
/// / tools-list / registry introspection — the lib stays binary-free). Functions
/// are NOT in here: they're read from the warehouse knowledge map.
#[derive(Debug, Clone, Default)]
pub struct SurfaceInputs {
    /// Viz tab names (the `Tab` enum's debug names) — each yields a fat + thin node.
    pub viz_tabs: Vec<String>,
    /// CLI subcommand names (clap `Command::get_subcommands`).
    pub cli_commands: Vec<String>,
    /// MCP tool names (the registered `tools/list`).
    pub mcp_tools: Vec<String>,
    /// facett-style components (registry ∩ impl Facet). For nornir the viz tabs
    /// ARE the components; a leaf repo plugs its own. Often empty for nornir
    /// (the viz_tabs axis already covers the renderable surface).
    pub facett: Vec<FacetRow>,
    /// gRPC handler labels (`Service.verb`), derived from the knowledge map via
    /// [`crate::arch::grpc_handlers_from_symbols`] — each becomes a `Thin`-mode
    /// [`SurfaceKind::Grpc`](nornir_testmatrix::discover::SurfaceKind::Grpc) node so
    /// every RPC backend is a must-be-covered surface (not an invisible handler).
    pub grpc: Vec<String>,
    /// UI atoms discovered by the live atom-walk (`nornir_robotui::all_atoms`),
    /// one [`DiscoveredAtom`] per `(tab, label)`. The binary/test feeds these from
    /// the running viz; each becomes a `ui_atom` surface node (covered ⟺ its tab
    /// ran AND its state was clean). Empty for a gate run without a live walk.
    pub atoms: Vec<DiscoveredAtom>,
}

/// nornir's canonical viz tab names (the `viz::app::Tab` enum debug names).
/// The viz crate is feature-gated, so the gate references this stable list; the
/// `tabs_match_enum` test in the viz crate keeps it honest against `Tab::ALL`.
pub const VIZ_TABS: &[&str] = &[
    "Nornir",
    "Timeline",
    "DepGraph",
    "CallGraph",
    "Architecture",
    "Metro",
    "Funnel",
    "TimeTravel",
    "LiveRun",
    "Release",
    "Knowledge",
    "Warehouse",
    "Mcp",
    "Search",
    "Gates",
    "Bench",
    "Test",
    "Leaderboard",
    "Security",
    "Holger",
    "Manual",
];

/// nornir's canonical MCP tool names (the registered `tools/list`). The MCP
/// matrix harness (`tests/mcp_matrix`) enforces tools/list completeness against
/// the LIVE server, so this list is the gate's join key, kept in step there.
pub const MCP_TOOLS: &[&str] = &[
    "affected_by_change", "bench_history", "build_order", "callees_of", "callers_of",
    "changed_since_last_release", "crate_published", "defined_in", "dep_graph_svg", "dep_path",
    "dependents_of", "deps_of", "docs_book", "docs_check", "docs_export", "docs_history",
    "docs_init", "docs_render", "dwarf_call_path", "dwarf_callees", "dwarf_callers",
    "dwarf_defined_in", "dwarf_symbol_lookup", "external_dep_users", "funnel_add_node",
    "funnel_create_plan", "funnel_link", "funnel_next", "funnel_show", "funnel_status",
    "funnel_submit_idea", "guard_apply", "guard_status", "guard_verify", "index_status",
    "knowledge_call_path", "knowledge_callees", "knowledge_callers", "knowledge_defined_in",
    "knowledge_symbol_lookup", "path_between", "regression_trace", "release_gate_all",
    "release_gate_coverage", "release_gate_docs_fresh", "release_gate_nexus_floor",
    "release_gate_no_regression", "release_gate_path_patches", "repo_overview", "repos_list",
    "search", "symbol_lookup", "sync_now", "test_coverage", "vector_search", "viz.click",
    "viz.state", "workspace_register", "workspace_use", "workspaces_list",
];

/// nornir's canonical CLI subcommand names (clap kebab-case of the `Cmd` enum).
/// The `nornir` binary OVERRIDES this with live `Cli::command()` introspection
/// (the true anti-drift source); this const is the fallback for callers without
/// the clap tree (e.g. the MCP server), and is asserted against the binary by a
/// functest.
pub const CLI_COMMANDS: &[&str] = &[
    "guard", "bench", "release", "test", "docs", "introspect", "warehouse", "index", "robot",
    "vector", "knowledge", "map", "funnel", "repos", "root", "serve", "viz", "install", "key",
    "workspace", "security", "mimir", "diagram", "bakeoff",
];

/// nornir's discrete-surface inputs from the canonical lists. The binary may
/// override `cli_commands` with live clap introspection (the lib stays
/// binary-free); an EMPTY `cli_commands` falls back to [`CLI_COMMANDS`]. The tab
/// + tool lists are the canonical nornir surface.
pub fn nornir_surface_inputs(cli_commands: Vec<String>) -> SurfaceInputs {
    let cli_commands = if cli_commands.is_empty() {
        CLI_COMMANDS.iter().map(|s| s.to_string()).collect()
    } else {
        cli_commands
    };
    SurfaceInputs {
        viz_tabs: VIZ_TABS.iter().map(|s| s.to_string()).collect(),
        cli_commands,
        mcp_tools: MCP_TOOLS.iter().map(|s| s.to_string()).collect(),
        facett: Vec::new(),
        // gRPC handlers are repo-specific (read from the knowledge map) — filled
        // by `enumerate_surface`/`gather` from `grpc_labels_from_view`, not here.
        grpc: Vec::new(),
        // UI atoms come from a LIVE atom-walk (the viz crate / a test), not the
        // static lists — a gate run without a walk has none.
        atoms: Vec::new(),
    }
}

/// The gathered, fully-differenced gate state for one workspace.
pub struct GateState {
    pub surface: Surface,
    pub covered: BTreeSet<String>,
    pub allowlist: Allowlist,
    pub report: GateReport,
    /// Per-surface **outcome-space coverage** (`surface_key → utfallsrum
    /// summary`) measured this run. Empty when no outcome-space rows were
    /// recorded (the threshold-off / legacy path). Drives the utfallsrum gate:
    /// a surface only counts as covered when it ran end-to-end AND its
    /// function(s) swept ≥`utfallsrum_threshold` outcome classes.
    pub utfallsrum: BTreeMap<String, UtfallsrumSummary>,
    /// The minimum outcome classes a surface must sweep to count as covered
    /// ([`DEFAULT_UTFALLSRUM_THRESHOLD`]); `0` disables the rule (legacy: ran ⟺
    /// covered).
    pub utfallsrum_threshold: usize,
}

impl GateState {
    pub fn summary(&self) -> String {
        self.report.summary()
    }
}

// ─── building the surface ────────────────────────────────────────────────

/// Map the warehouse knowledge view into the pure discover row shapes.
///
/// Reachability over the persisted `call_edges` is at **identifier
/// granularity** (the syn scan records callees as the last path segment, e.g.
/// `Arc::new` → `new`), so both the caller path and the symbol fqn are reduced
/// to their last segment for matching. A function is a **test root** iff it
/// lives in a test module (`module_path` contains `tests`) or its name is a
/// conventional test name (`test_*` / `it_*` / `prop_*`). This is intentionally
/// approximate — the pure reachability is exhaustively unit-tested; here we feed
/// it the best available facts.
pub fn knowledge_to_rows(view: &KnowledgeView) -> (Vec<SymbolRow>, Vec<CallEdge>) {
    let symbols: Vec<SymbolRow> = view
        .symbols
        .iter()
        .filter(|s| s.item_kind == "fn")
        .map(|s| {
            let fqn = last_seg(&s.item_name).to_string();
            SymbolRow {
                fqn,
                is_test: is_test_symbol(s),
                label: Some(format!("{}::{}", s.module_path, s.item_name)),
            }
        })
        .collect();
    let edges: Vec<CallEdge> = view
        .calls
        .iter()
        .map(|c: &CallEdgeRow| CallEdge {
            caller: last_seg(&c.caller_path).to_string(),
            callee: last_seg(&c.callee_ident).to_string(),
        })
        .collect();
    (symbols, edges)
}

fn last_seg(s: &str) -> &str {
    s.rsplit("::").next().unwrap_or(s)
}

/// A symbol is a test root iff it sits in a test module or has a test-y name.
fn is_test_symbol(s: &KSymbolRow) -> bool {
    let m = s.module_path.to_lowercase();
    let n = s.item_name.as_str();
    m.split("::").any(|seg| seg == "tests" || seg == "test")
        || n.starts_with("test_")
        || n.starts_with("it_")
        || n.starts_with("prop_")
}

/// Assemble the full [`Surface`] from the discrete inputs + the warehouse
/// knowledge map, and compute the `covered` set.
///
/// COVERED:
/// - **functions**: a fn is covered iff it's in the test-reachable closure over
///   `call_edges` (so the surface gap is exactly `unreached_functions`).
/// - **viz tabs / CLI / MCP / facett**: covered iff a test-reachable function's
///   identifier matches a wiring marker for that surface — pragmatically, we
///   treat these discrete surfaces as covered when a same-named handler fn is
///   test-reachable, else they fall to the allowlist (seeded). This keeps the
///   gate honest (a never-tested tab outs itself) while letting the allowlist
///   burn down as real interaction tests land.
pub fn build_surface_and_covered(
    inputs: &SurfaceInputs,
    symbols: &[SymbolRow],
    edges: &[CallEdge],
) -> (Surface, BTreeSet<String>) {
    let reachable = nornir_testmatrix::discover::test_reachable(symbols, edges);

    let mut surface = Surface::new();
    surface
        .extend(viz_tabs(inputs.viz_tabs.iter().cloned()))
        .extend(cli_commands(inputs.cli_commands.iter().cloned()))
        .extend(mcp_tools(inputs.mcp_tools.iter().cloned()))
        .extend(grpc_handlers(inputs.grpc.iter().cloned()))
        .extend(facett_components(&inputs.facett))
        .extend(ui_atoms(&inputs.atoms))
        .extend(unreached_functions(symbols, edges));

    // Covered set:
    //  - every function NOT in `unreached_functions` is covered → its key.
    //  - a discrete surface (tab/cli/mcp/facett) is covered iff a test-reachable
    //    fn's identifier matches its id (case-insensitive last-segment match).
    let reachable_idents: BTreeSet<String> =
        reachable.iter().map(|s| s.to_lowercase()).collect();

    let mut covered: BTreeSet<String> = BTreeSet::new();
    for node in &surface.nodes {
        use nornir_testmatrix::discover::SurfaceKind::*;
        let is_covered = match node.kind {
            // A Function node only EXISTS when unreached → never covered here.
            Function => false,
            // gRPC: covered iff its VERB (the handler fn name, the `Service.verb`
            // last segment) is test-reachable — the RPC handler has a test.
            Grpc => {
                let verb = node.id.rsplit('.').next().unwrap_or(&node.id).to_lowercase();
                reachable_idents.contains(&verb)
            }
            // Discrete surfaces: covered iff a same-named test-reachable handler.
            VizTab | CliCommand | McpTool | FacettComponent => {
                reachable_idents.contains(&node.id.to_lowercase())
            }
            // UI atoms have their OWN verdict (the live atom-walk's ran-and-clean
            // rule), added below via `covered_atoms` — not the handler-name rule.
            UiAtom => false,
        };
        if is_covered {
            covered.insert(node.key_str());
        }
    }
    // UI atoms: covered ⟺ the atom\'s tab RAN and its state was CLEAN (no error
    // atom). This is the live atom-walk\'s verdict, computed by the pure
    // `covered_atoms` over the fed `DiscoveredAtom`s — so a `ui_atom` surface node
    // the gate counts is only green when the viz actually rendered it error-free.
    covered.extend(covered_atoms(&inputs.atoms));
    // Functions: the gap is exactly `unreached_functions`, so covered fns are the
    // reachable ones — but they aren't surface nodes (only unreached fns are), so
    // they don't need a covered key. The `total` is over surface nodes only.
    (surface, covered)
}

/// Enumerate the FULL nornir surface in one call (plan node n-000's unified
/// entry point). Assembles the discrete-surface [`SurfaceInputs`] from the
/// canonical [`VIZ_TABS`] / [`MCP_TOOLS`] / [`CLI_COMMANDS`] lists (via
/// [`nornir_surface_inputs`]), maps the warehouse `view` into discover rows
/// (via [`knowledge_to_rows`]), and runs [`build_surface_and_covered`] —
/// returning the discovered [`Surface`]. The caller no longer hand-assembles
/// `SurfaceInputs`.
///
/// `cli_commands` lets the binary inject live clap introspection; pass an EMPTY
/// vec to fall back to the canonical [`CLI_COMMANDS`]. `view` is the warehouse
/// knowledge map — function nodes are read from it (the lib stays binary-free,
/// so the warehouse read itself stays at the caller, e.g. [`gather`]'s
/// `load_latest`). For just the surface without coverage, this is the one call.
pub fn enumerate_surface(view: &KnowledgeView, cli_commands: Vec<String>) -> Surface {
    let mut inputs = nornir_surface_inputs(cli_commands);
    inputs.grpc = grpc_labels_from_view(view);
    let (symbols, edges) = knowledge_to_rows(view);
    let (surface, _covered) = build_surface_and_covered(&inputs, &symbols, &edges);
    surface
}

/// Like [`enumerate_surface`] but ALSO folds in the live atom-walk's discovered
/// [`DiscoveredAtom`]s, so the returned [`Surface`] carries one `ui_atom` node per
/// rendered atom alongside the tabs/CLI/MCP/gRPC/function surface. This is the
/// entry the S3 atom-coverage path uses: the binary/test runs the walk, hands the
/// atoms here, and the completeness gate then counts atoms as surface nodes.
pub fn enumerate_surface_with_atoms(
    view: &KnowledgeView,
    cli_commands: Vec<String>,
    atoms: Vec<DiscoveredAtom>,
) -> Surface {
    let mut inputs = nornir_surface_inputs(cli_commands);
    inputs.grpc = grpc_labels_from_view(view);
    inputs.atoms = atoms;
    let (symbols, edges) = knowledge_to_rows(view);
    let (surface, _covered) = build_surface_and_covered(&inputs, &symbols, &edges);
    surface
}

/// **S3 atom-coverage PRODUCER** — turn a batch of live atom-walk results into
/// `surface_coverage` [`CoverageRow`]s the gate reads, WITHOUT needing the
/// warehouse knowledge map. One row per discovered atom: `kind = "ui_atom"`,
/// `id = "<tab>/<label>"`, `surface_key = "ui_atom:<tab>/<label>@na"` (the
/// [`SurfaceNode::key_str`](nornir_testmatrix::discover::SurfaceNode) convention),
/// `verdict = covered` iff the atom\'s tab ran AND its state was clean (no error
/// atom), else `missing`. Append these via
/// [`append_surface_coverage`](crate::warehouse::surface_coverage::append_surface_coverage)
/// and `autonom`/the gate counts them like any other surface node (same table,
/// same `CoverageSummary::from_rows` roll-up).
///
/// Deduped by `(tab, label)` so a label that maps to several galley nodes is one
/// row. The role is recorded in the row\'s `reason` (`"role:Button"`) since a
/// `ui_atom` carries no allowlist reason — keeping the warehouse row self-describing.
pub fn atom_coverage_rows(
    run_id: &str,
    workspace: &str,
    atoms: &[DiscoveredAtom],
    ts_micros: i64,
) -> Vec<CoverageRow> {
    let mut surface = Surface::new();
    surface.extend(ui_atoms(atoms));
    let covered = covered_atoms(atoms);
    // Map role onto each node so we can stamp it into the row reason.
    let role_for = |id: &str| -> String {
        atoms
            .iter()
            .find(|a| format!("{}/{}", a.tab, a.label) == id)
            .map(|a| if a.role.is_empty() { String::new() } else { format!("role:{}", a.role) })
            .unwrap_or_default()
    };
    let mut rows: Vec<CoverageRow> = surface
        .nodes
        .iter()
        .map(|node| {
            let key = node.key_str();
            let (verdict, reason) = if covered.contains(&key) {
                (Verdict::Covered, role_for(&node.id))
            } else {
                (Verdict::Missing, role_for(&node.id))
            };
            CoverageRow::from_node(run_id, workspace, node, verdict, &reason, ts_micros)
        })
        .collect();
    rows.sort_by(|a, b| a.surface_key.cmp(&b.surface_key));
    rows
}

/// gRPC handler labels (`Service.verb`) discovered in the knowledge map — the
/// values of [`crate::arch::grpc_handlers_from_symbols`], sorted + deduped. This
/// is autonom FINDING the already-marked gRPC handlers (a tonic handler impl IS
/// the mark); it never assigns the mark.
fn grpc_labels_from_view(view: &KnowledgeView) -> Vec<String> {
    let mut labels: Vec<String> =
        crate::arch::grpc_handlers_from_symbols(&view.symbols).into_values().collect();
    labels.sort();
    labels.dedup();
    labels
}

// ─── the gate (gather → compute → persist) ─────────────────────────────────

/// Gather the gate state for `workspace` from the warehouse + discrete inputs,
/// against the checked-in `allowlist`. Reads the LATEST knowledge scan for
/// `repo` (the workspace's primary repo, usually the workspace name).
pub fn gather(
    wh: &IcebergWarehouse,
    workspace: &str,
    repo: &str,
    inputs: &SurfaceInputs,
    allowlist: Allowlist,
    run_id: &str,
) -> Result<GateState> {
    gather_with_utfallsrum(
        wh,
        workspace,
        repo,
        inputs,
        allowlist,
        run_id,
        BTreeMap::new(),
        0,
    )
}

/// Like [`gather`] but applies the **utfallsrum threshold**: a surface that ran
/// end-to-end is only counted as covered when its function(s) swept at least
/// `utfallsrum_threshold` outcome classes (`utfallsrum` maps `surface_key → the
/// measured outcome-space summary`). A one-value smoke test no longer flips a
/// surface green. `utfallsrum_threshold == 0` is the legacy behaviour (ran ⟺
/// covered) and `utfallsrum` may be empty.
#[allow(clippy::too_many_arguments)]
pub fn gather_with_utfallsrum(
    wh: &IcebergWarehouse,
    workspace: &str,
    repo: &str,
    inputs: &SurfaceInputs,
    allowlist: Allowlist,
    run_id: &str,
    utfallsrum: BTreeMap<String, UtfallsrumSummary>,
    utfallsrum_threshold: usize,
) -> Result<GateState> {
    let view = load_latest(wh, repo)
        .with_context(|| format!("load knowledge map for repo `{repo}`"))?;
    // Enrich the discrete inputs with the gRPC handlers FOUND in this repo's
    // knowledge map, so every RPC is a counted surface (autonom finds the marks).
    let mut inputs = inputs.clone();
    inputs.grpc = grpc_labels_from_view(&view);
    let (symbols, edges) = knowledge_to_rows(&view);
    let (surface, ran) = build_surface_and_covered(&inputs, &symbols, &edges);
    // The covered set requires BOTH ran AND the utfallsrum threshold (≥K classes
    // swept). With threshold 0 / empty map this is exactly `ran` (legacy).
    let covered = covered_with_utfallsrum(&ran, &utfallsrum, utfallsrum_threshold);
    let report = GateReport::compute(run_id, workspace, &surface, &covered, &allowlist);
    Ok(GateState {
        surface,
        covered,
        allowlist,
        report,
        utfallsrum,
        utfallsrum_threshold,
    })
}

/// Persist a gate run's full per-node coverage rows to `surface_coverage`.
pub fn persist(wh: &IcebergWarehouse, state: &GateState, run_id: &str, workspace: &str) -> Result<()> {
    let ts = chrono::Utc::now().timestamp_micros();
    let rows = rows_for_with_utfallsrum(
        run_id,
        workspace,
        &state.surface,
        &state.covered,
        &state.allowlist,
        &state.utfallsrum,
        ts,
    );
    wh.block_on(append_surface_coverage(wh, &rows))
}

/// Re-seed the allowlist with every currently-uncovered surface node (the
/// `--seed-allowlist` mode). Preserves existing reasons. Returns the new
/// allowlist for the caller to serialize to `autonom-allow.toml`.
pub fn reseed(state: &GateState) -> Allowlist {
    seed_allowlist(&state.surface, &state.covered, &state.allowlist)
}

/// Read the latest persisted gate verdict for `workspace` and roll it into a
/// [`CoverageSummary`] — what the viz Test pane + `test_coverage` tool show.
pub fn read_latest_summary(wh: &IcebergWarehouse, workspace: &str) -> Result<CoverageSummary> {
    let rows = wh.block_on(latest_surface_coverage(wh, workspace))?;
    Ok(CoverageSummary::from_rows(&rows))
}

/// Read all persisted rows for a run (for the CLI `--json` dump).
pub fn read_run(wh: &IcebergWarehouse, run_id: &str) -> Result<Vec<CoverageRow>> {
    wh.block_on(query_surface_coverage(wh, &CoverageSelector::Run(run_id.to_string())))
}

/// AUT5 release-blocking gate helper: gather the surface vs covered verdict for
/// `repo` (canonical nornir surface inputs + the repo's checked-in allowlist),
/// PERSIST the run to `surface_coverage`, and return the [`GateState`]. The
/// release pipeline (`release gate-all` / the server `gate_all` RPC) calls this
/// and then applies [`crate::release::gate::coverage_gate`] to the returned
/// `report` — RED iff `Surface − Covered ≠ ∅` (any uncovered+un-allowlisted
/// surface) OR a stale allowlist entry. One call so the CLI, the server RPC, and
/// the `release_gate_coverage` MCP tool share identical behaviour (CLI parity).
///
/// `cli_commands` lets the binary inject live clap introspection; pass EMPTY to
/// fall back to the canonical [`CLI_COMMANDS`]. `run_id` stamps the persisted run.
pub fn gate_coverage_for_repo(
    wh: &IcebergWarehouse,
    workspace: &str,
    repo: &str,
    repo_root: &Path,
    cli_commands: Vec<String>,
    run_id: &str,
) -> Result<GateState> {
    let inputs = nornir_surface_inputs(cli_commands);
    let allowlist = load_allowlist(&allowlist_path(repo_root))?;
    let state = gather(wh, workspace, repo, &inputs, allowlist, run_id)?;
    persist(wh, &state, run_id, workspace)?;
    Ok(state)
}

// ─── allowlist file I/O (TOML; nornir has the toml dep) ─────────────────────

/// The canonical allowlist path for a repo: `<repo_root>/.nornir/autonom-allow.toml`.
pub fn allowlist_path(repo_root: &Path) -> std::path::PathBuf {
    repo_root.join(".nornir").join("autonom-allow.toml")
}

/// Load the checked-in allowlist (empty if the file is absent).
pub fn load_allowlist(path: &Path) -> Result<Allowlist> {
    if !path.exists() {
        return Ok(Allowlist::new());
    }
    let text = std::fs::read_to_string(path)
        .with_context(|| format!("read allowlist {}", path.display()))?;
    let al: Allowlist =
        toml::from_str(&text).with_context(|| format!("parse allowlist {}", path.display()))?;
    Ok(al)
}

/// Write the allowlist as a checked-in `autonom-allow.toml` (the `--seed`/burn-down
/// file). Creates the `.nornir/` dir if needed.
pub fn save_allowlist(path: &Path, allowlist: &Allowlist) -> Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)
            .with_context(|| format!("create dir {}", dir.display()))?;
    }
    let header = "# autonom-allow.toml — the completeness-gate allowlist.\n\
        # SEEDED by `nornir test coverage --seed-allowlist` with every currently-\n\
        # uncovered surface node. BURN IT DOWN: delete an entry once a real\n\
        # inject-assert test covers that surface. A STALE entry (now-covered or\n\
        # surface-gone) FAILS the gate — the excuse must not outlive its surface.\n\n";
    let body = toml::to_string_pretty(allowlist)
        .with_context(|| format!("serialize allowlist {}", path.display()))?;
    std::fs::write(path, format!("{header}{body}"))
        .with_context(|| format!("write allowlist {}", path.display()))?;
    Ok(())
}

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

    fn sym(name: &str, module: &str, is_test_mod: bool) -> SymbolRow {
        // Build via the knowledge mapping so is_test detection is exercised.
        let krow = KSymbolRow {
            crate_name: "nornir".into(),
            module_path: if is_test_mod { format!("{module}::tests") } else { module.into() },
            item_kind: "fn".into(),
            item_name: name.into(),
            visibility: "pub".into(),
            file: "src/x.rs".into(),
            line: 1,
            doc_lines: 0,
            signature: None,
        };
        let view = KnowledgeView { symbols: vec![krow], calls: vec![] };
        knowledge_to_rows(&view).0.pop().unwrap()
    }

    #[test]
    fn knowledge_mapping_detects_test_roots_and_idents() {
        let view = KnowledgeView {
            symbols: vec![
                KSymbolRow {
                    crate_name: "nornir".into(), module_path: "nornir::foo::tests".into(),
                    item_kind: "fn".into(), item_name: "test_it".into(), visibility: "".into(),
                    file: "f.rs".into(), line: 1, doc_lines: 0, signature: None,
                },
                KSymbolRow {
                    crate_name: "nornir".into(), module_path: "nornir::foo".into(),
                    item_kind: "fn".into(), item_name: "render".into(), visibility: "pub".into(),
                    file: "f.rs".into(), line: 2, doc_lines: 0, signature: None,
                },
                // a non-fn item is dropped.
                KSymbolRow {
                    crate_name: "nornir".into(), module_path: "nornir::foo".into(),
                    item_kind: "struct".into(), item_name: "Thing".into(), visibility: "pub".into(),
                    file: "f.rs".into(), line: 3, doc_lines: 0, signature: None,
                },
            ],
            calls: vec![CallEdgeRow {
                crate_name: "nornir".into(), caller_path: "nornir::foo::tests::test_it".into(),
                callee_ident: "render".into(), call_kind: "call".into(), file: "f.rs".into(), line: 1,
            }],
        };
        let (symbols, edges) = knowledge_to_rows(&view);
        assert_eq!(symbols.len(), 2, "only fn items, struct dropped");
        let test_it = symbols.iter().find(|s| s.fqn == "test_it").unwrap();
        assert!(test_it.is_test, "test_ name in tests module is a root");
        let render = symbols.iter().find(|s| s.fqn == "render").unwrap();
        assert!(!render.is_test);
        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].caller, "test_it");
        assert_eq!(edges[0].callee, "render", "callee reduced to last segment");
    }

    #[test]
    fn unreached_fn_is_a_gap_reached_fn_is_not() {
        // test_it → render (reached) ; orphan (unreached).
        let symbols = vec![
            sym("test_it", "nornir::foo", true),
            sym("render", "nornir::foo", false),
            sym("orphan", "nornir::foo", false),
        ];
        let edges = vec![CallEdge { caller: "test_it".into(), callee: "render".into() }];
        let inputs = SurfaceInputs::default();
        let (surface, covered) = build_surface_and_covered(&inputs, &symbols, &edges);

        // Only the orphan fn is a surface node (unreached); render is reached.
        let fn_nodes: Vec<_> =
            surface.nodes.iter().filter(|n| n.kind == SurfaceKind::Function).collect();
        assert_eq!(fn_nodes.len(), 1, "only the unreached fn is surface");
        assert_eq!(fn_nodes[0].id, "orphan");
        // The orphan is NOT in covered → it's the gap.
        assert!(!covered.contains(&fn_nodes[0].key_str()));

        let report = GateReport::compute("r", "ws", &surface, &covered, &Allowlist::new());
        assert!(!report.is_green(), "an unreached fn makes the gate RED");
        assert_eq!(report.gap.missing.len(), 1);
        assert_eq!(report.gap.missing[0].id, "orphan");
    }

    /// S3: the atom-walk's discovered atoms become `ui_atom` surface nodes that
    /// the completeness gate COUNTS, and the producer's verdict (covered <=> a
    /// clean tab, missing <=> a dirty tab) round-trips into the rows. Proves
    /// `build_surface_and_covered` + `atom_coverage_rows` agree.
    #[test]
    fn ui_atoms_become_counted_surface_nodes_with_clean_dirty_verdicts() {
        let atoms = vec![
            DiscoveredAtom {
                tab: "test".into(),
                label: "Run full matrix".into(),
                role: "Button".into(),
                ran: true,
                clean: true, // clean tab -> covered
            },
            DiscoveredAtom {
                tab: "nornir".into(),
                label: "is not served".into(),
                role: "Label".into(),
                ran: true,
                clean: false, // dirty tab -> missing
            },
        ];
        let inputs = SurfaceInputs {
            viz_tabs: vec![],
            cli_commands: vec![],
            mcp_tools: vec![],
            facett: vec![],
            grpc: vec![],
            atoms: atoms.clone(),
        };
        let (surface, covered) =
            build_surface_and_covered(&inputs, &[], &[]);
        // Two ui_atom nodes are in the discovered surface (the gate counts them).
        let ui_nodes: Vec<_> = surface
            .nodes
            .iter()
            .filter(|n| n.kind == SurfaceKind::UiAtom)
            .collect();
        assert_eq!(ui_nodes.len(), 2, "both atoms are counted surface nodes");
        // The clean-tab atom is covered; the dirty-tab atom is NOT.
        assert!(covered.contains("ui_atom:test/Run full matrix@na"), "clean atom covered");
        assert!(
            !covered.contains("ui_atom:nornir/is not served@na"),
            "dirty (error) tab atom is not covered",
        );

        // The producer agrees: a covered + a missing row, with the role in reason.
        let rows = atom_coverage_rows("r-atom", "nornir", &atoms, 7);
        assert_eq!(rows.len(), 2);
        let run = rows.iter().find(|r| r.id == "test/Run full matrix").unwrap();
        assert_eq!(run.verdict(), Verdict::Covered);
        assert_eq!(run.reason, "role:Button", "role recorded in the row reason");
        let dirty = rows.iter().find(|r| r.id == "nornir/is not served").unwrap();
        assert_eq!(dirty.verdict(), Verdict::Missing);
    }

    #[test]
    fn discrete_surface_covered_when_handler_reachable_else_seed_to_green() {
        // A test reaches `test_tab` (the Test viz tab handler) but nothing reaches
        // the `bench_tab` handler. The Test tab is covered; Bench is a gap until
        // seeded.
        let symbols = vec![
            sym("test_root", "nornir::viz", true),
            sym("Test", "nornir::viz", false),
        ];
        let edges = vec![CallEdge { caller: "test_root".into(), callee: "Test".into() }];
        let inputs = SurfaceInputs {
            viz_tabs: vec!["Test".into(), "Bench".into()],
            cli_commands: vec!["coverage".into()],
            mcp_tools: vec!["test_coverage".into()],
            facett: vec![],
            grpc: vec![],
            atoms: vec![],
        };
        let (surface, covered) = build_surface_and_covered(&inputs, &symbols, &edges);

        // Test@fat + Test@thin are covered (handler `Test` is reachable).
        assert!(covered.contains("viz_tab:Test@fat"));
        assert!(covered.contains("viz_tab:Test@thin"));
        // Bench is NOT covered (no reachable handler).
        assert!(!covered.contains("viz_tab:Bench@fat"));

        let report = GateReport::compute("r", "ws", &surface, &covered, &Allowlist::new());
        assert!(!report.is_green(), "Bench/cli/mcp are uncovered → RED before seeding");

        // SEED the allowlist → every uncovered surface excused → GREEN now.
        let seeded = seed_allowlist(&surface, &covered, &Allowlist::new());
        let report2 = GateReport::compute("r", "ws", &surface, &covered, &seeded);
        assert!(report2.is_green(), "seeded allowlist makes the gate green now");
        // The covered Test tab is NOT seeded (no excuse needed).
        assert!(!seeded.entries.iter().any(|e| e.key == "viz_tab:Test@fat"));
        // Bench/cli/mcp ARE seeded.
        assert!(seeded.entries.iter().any(|e| e.key == "viz_tab:Bench@fat"));
        assert!(seeded.entries.iter().any(|e| e.key == "cli_command:coverage@na"));
        assert!(seeded.entries.iter().any(|e| e.key == "mcp_tool:test_coverage@na"));
    }

    /// The utfallsrum gate end-to-end through the warehouse: a viz tab whose
    /// handler is test-reachable RAN, but its function swept only ONE outcome
    /// class — under the ≥2 threshold it does NOT count as covered, and the
    /// persisted row carries the low score. Sweeping a second class flips it.
    #[test]
    fn utfallsrum_threshold_unflips_a_single_value_smoke_then_reflips_on_second_class() {
        use nornir_testmatrix::utfallsrum::Outcome;
        use crate::knowledge::symbols::SymbolScan;

        let dir = tempfile::tempdir().unwrap();
        let wh = IcebergWarehouse::open(dir.path()).unwrap();

        // A test reaches the `Bench` viz handler → the Bench tab RAN end-to-end.
        let scan = SymbolScan {
            snapshot_id: uuid::Uuid::new_v4(),
            ts: chrono::Utc::now(),
            repo: "myrepo".into(),
            symbols: vec![
                KSymbolRow {
                    crate_name: "myrepo".into(), module_path: "myrepo::viz::tests".into(),
                    item_kind: "fn".into(), item_name: "test_bench".into(), visibility: "".into(),
                    file: "f.rs".into(), line: 1, doc_lines: 0, signature: None,
                },
                KSymbolRow {
                    crate_name: "myrepo".into(), module_path: "myrepo::viz".into(),
                    item_kind: "fn".into(), item_name: "Bench".into(), visibility: "pub".into(),
                    file: "f.rs".into(), line: 2, doc_lines: 0, signature: None,
                },
            ],
            calls: vec![CallEdgeRow {
                crate_name: "myrepo".into(), caller_path: "myrepo::viz::tests::test_bench".into(),
                callee_ident: "Bench".into(), call_kind: "call".into(), file: "f.rs".into(), line: 1,
            }],
            features: Vec::new(),
            tests: Vec::new(),
        };
        wh.append_symbol_scan(&scan).unwrap();

        let inputs = SurfaceInputs {
            viz_tabs: vec!["Bench".into()],
            ..Default::default()
        };

        // ONE outcome class swept → below threshold 2.
        let mut o = Outcome::for_fn("Bench")
            .class("empty", "no runs ⇒ empty board")
            .class("many", "N runs ⇒ N rows");
        o.hit("empty", "Bench([]) == empty");
        let mut util = BTreeMap::new();
        util.insert("viz_tab:Bench@fat".to_string(), o.summary());

        let state = gather_with_utfallsrum(
            &wh, "ws", "myrepo", &inputs, Allowlist::new(), "run-smoke",
            util.clone(), 2,
        )
        .unwrap();
        assert!(
            !state.covered.contains("viz_tab:Bench@fat"),
            "ran end-to-end but only 1 class swept → NOT covered under threshold 2",
        );
        // The persisted row still carries the measured score (0.5 of 2 classes).
        persist(&wh, &state, "run-smoke", "ws").unwrap();
        let rows = read_run(&wh, "run-smoke").unwrap();
        let fat = rows.iter().find(|r| r.surface_key == "viz_tab:Bench@fat").unwrap();
        assert!((fat.utfallsrum_covered - 0.5).abs() < 1e-9, "0.5 score persisted");

        // Sweep the SECOND class → now ≥2 → covered.
        o.hit("many", "Bench(3) == 3 rows");
        util.insert("viz_tab:Bench@fat".to_string(), o.summary());
        let state2 = gather_with_utfallsrum(
            &wh, "ws", "myrepo", &inputs, Allowlist::new(), "run-full",
            util, 2,
        )
        .unwrap();
        assert!(
            state2.covered.contains("viz_tab:Bench@fat"),
            "2 classes swept → meets threshold → now covered",
        );

        // And legacy (threshold 0): the single-value run WAS covered (ran ⟺ covered).
        let legacy = gather_with_utfallsrum(
            &wh, "ws", "myrepo", &inputs, Allowlist::new(), "run-legacy",
            BTreeMap::new(), 0,
        )
        .unwrap();
        assert!(
            legacy.covered.contains("viz_tab:Bench@fat"),
            "threshold 0 is the legacy ran ⟺ covered behaviour",
        );
    }

    #[test]
    fn grpc_handler_is_a_thin_surface_covered_when_verb_reachable() {
        use nornir_testmatrix::discover::{Mode, SurfaceKind};
        // A test reaches `submit` (the Bench.Submit handler verb); nothing reaches
        // `architecture`. So Bench.Submit is covered, Viz.Architecture is a gap —
        // an RPC with no test now OUTS itself as a red surface.
        let symbols = vec![
            sym("test_root", "nornir::server", true),
            sym("submit", "nornir::server", false),
        ];
        let edges = vec![CallEdge { caller: "test_root".into(), callee: "submit".into() }];
        let inputs = SurfaceInputs {
            viz_tabs: vec![],
            cli_commands: vec![],
            mcp_tools: vec![],
            facett: vec![],
            grpc: vec!["Bench.Submit".into(), "Viz.Architecture".into()],
            atoms: vec![],
        };
        let (surface, covered) = build_surface_and_covered(&inputs, &symbols, &edges);
        // Both handlers are Thin-mode gRPC surface nodes (the UI/gRPC layer mark).
        let grpc: Vec<_> =
            surface.nodes.iter().filter(|n| n.kind == SurfaceKind::Grpc).collect();
        assert_eq!(grpc.len(), 2);
        assert!(grpc.iter().all(|n| n.mode == Mode::Thin));
        // Covered iff the verb (handler fn) is test-reachable.
        assert!(covered.contains("grpc:Bench.Submit@thin"), "verb `submit` is reached");
        assert!(!covered.contains("grpc:Viz.Architecture@thin"), "verb `architecture` is not");
    }

    #[test]
    fn enumerate_surface_yields_canonical_nornir_surface_in_one_call() {
        // Feed a real warehouse-shaped knowledge view (one test root reaching the
        // `Funnel` viz handler, plus an unreached `orphan` fn) and assert the
        // single-call entry point returns the FULL canonical surface.
        let view = KnowledgeView {
            symbols: vec![
                KSymbolRow {
                    crate_name: "nornir".into(), module_path: "nornir::viz::tests".into(),
                    item_kind: "fn".into(), item_name: "test_funnel".into(), visibility: "".into(),
                    file: "f.rs".into(), line: 1, doc_lines: 0, signature: None,
                },
                KSymbolRow {
                    crate_name: "nornir".into(), module_path: "nornir::viz".into(),
                    item_kind: "fn".into(), item_name: "Funnel".into(), visibility: "pub".into(),
                    file: "f.rs".into(), line: 2, doc_lines: 0, signature: None,
                },
                KSymbolRow {
                    crate_name: "nornir".into(), module_path: "nornir::misc".into(),
                    item_kind: "fn".into(), item_name: "orphan".into(), visibility: "pub".into(),
                    file: "f.rs".into(), line: 3, doc_lines: 0, signature: None,
                },
            ],
            calls: vec![CallEdgeRow {
                crate_name: "nornir".into(), caller_path: "nornir::viz::tests::test_funnel".into(),
                callee_ident: "Funnel".into(), call_kind: "call".into(), file: "f.rs".into(), line: 1,
            }],
        };

        // ONE call — no hand-assembled SurfaceInputs; empty cli → canonical fallback.
        let surface = enumerate_surface(&view, Vec::new());

        // The canonical viz tabs are all present (assert known names explicitly).
        let viz_ids: BTreeSet<&str> = surface
            .nodes
            .iter()
            .filter(|n| n.kind == SurfaceKind::VizTab)
            .map(|n| n.id.as_str())
            .collect();
        assert!(viz_ids.contains("Funnel"), "Funnel tab must be enumerated");
        assert!(viz_ids.contains("Warehouse"), "Warehouse tab must be enumerated");
        // Every canonical tab made it into the surface.
        for tab in VIZ_TABS {
            assert!(viz_ids.contains(tab), "canonical viz tab `{tab}` missing from surface");
        }

        // MCP tools: count > 0 and equal to the canonical list size.
        let mcp_count = surface
            .nodes
            .iter()
            .filter(|n| n.kind == SurfaceKind::McpTool)
            .count();
        assert!(mcp_count > 0, "MCP tools must be enumerated");
        assert_eq!(mcp_count, MCP_TOOLS.len(), "all canonical MCP tools enumerated");
        assert!(
            surface.nodes.iter().any(|n| n.kind == SurfaceKind::McpTool && n.id == "funnel_show"),
            "a known MCP tool (funnel_show) must be present",
        );

        // CLI commands: non-empty, fell back to the canonical list.
        let cli_count = surface
            .nodes
            .iter()
            .filter(|n| n.kind == SurfaceKind::CliCommand)
            .count();
        assert!(cli_count > 0, "CLI commands must be enumerated");
        assert_eq!(cli_count, CLI_COMMANDS.len(), "canonical CLI fallback used");

        // The unreached `orphan` fn surfaced as a Function node; the reached
        // `Funnel` handler did NOT (only gaps are function nodes).
        let fn_ids: BTreeSet<&str> = surface
            .nodes
            .iter()
            .filter(|n| n.kind == SurfaceKind::Function)
            .map(|n| n.id.as_str())
            .collect();
        assert!(fn_ids.contains("orphan"), "unreached fn must surface");
        assert!(!fn_ids.contains("Funnel"), "test-reached handler is not a gap");
    }

    /// AUT5 release-blocking GATE, end-to-end through a REAL warehouse: seed a
    /// knowledge scan whose surface has one element with NO covering row (an
    /// unreached fn), run the wiring helper [`gate_coverage_for_repo`] + the
    /// release verdict [`crate::release::gate::coverage_gate`], and assert the
    /// gate FAILS and NAMES that element. Then allowlist it and assert the gate
    /// PASSES. Inject real input (a persisted scan), assert real output (the
    /// red verdict text + the green pass).
    #[test]
    fn aut5_gate_red_when_surface_uncovered_green_when_allowlisted() {
        use crate::knowledge::symbols::SymbolScan;
        use crate::release::gate::coverage_gate;

        let dir = tempfile::tempdir().unwrap();
        let wh = IcebergWarehouse::open(dir.path()).unwrap();

        // A real knowledge scan: one test root reaches `wired`, but `orphan` is
        // unreached → `orphan` is the lone surface gap (drive the gate, not a
        // hand-built Surface). No discrete-surface inputs in this test (empty
        // viz/cli/mcp via a custom gather path below) — we feed canonical inputs
        // and the gap is the unreached fn, which we then excuse.
        let scan = SymbolScan {
            snapshot_id: uuid::Uuid::new_v4(),
            ts: chrono::Utc::now(),
            repo: "myrepo".into(),
            symbols: vec![
                KSymbolRow {
                    crate_name: "myrepo".into(), module_path: "myrepo::t::tests".into(),
                    item_kind: "fn".into(), item_name: "test_root".into(), visibility: "".into(),
                    file: "f.rs".into(), line: 1, doc_lines: 0, signature: None,
                },
                KSymbolRow {
                    crate_name: "myrepo".into(), module_path: "myrepo::x".into(),
                    item_kind: "fn".into(), item_name: "wired".into(), visibility: "pub".into(),
                    file: "f.rs".into(), line: 2, doc_lines: 0, signature: None,
                },
                KSymbolRow {
                    crate_name: "myrepo".into(), module_path: "myrepo::x".into(),
                    item_kind: "fn".into(), item_name: "orphan_fn".into(), visibility: "pub".into(),
                    file: "f.rs".into(), line: 3, doc_lines: 0, signature: None,
                },
            ],
            calls: vec![CallEdgeRow {
                crate_name: "myrepo".into(), caller_path: "myrepo::t::tests::test_root".into(),
                callee_ident: "wired".into(), call_kind: "call".into(), file: "f.rs".into(), line: 1,
            }],
            features: Vec::new(),
            tests: Vec::new(),
        };
        wh.append_symbol_scan(&scan).unwrap();

        // The repo root (for the allowlist file) — empty dir, no allowlist yet.
        let repo_root = dir.path().join("myrepo");
        std::fs::create_dir_all(&repo_root).unwrap();

        // RED: `orphan_fn` is uncovered + un-allowlisted → the gate must fail and
        // name it. Use EMPTY cli (canonical fallback), and discrete surfaces are
        // also uncovered — but they too are gaps, so the gate is red regardless;
        // we assert specifically that the unreached fn is named.
        let state = gate_coverage_for_repo(
            &wh, "ws", "myrepo", &repo_root, Vec::new(), "run-red",
        )
        .unwrap();
        let err = coverage_gate(&state.report).unwrap_err().to_string();
        assert!(err.contains("RED"), "gate must be RED: {err}");
        assert!(err.contains("orphan_fn"), "gate must name the uncovered fn: {err}");

        // GREEN: seed the allowlist with EVERY currently-uncovered surface (the
        // burn-down excuse) → the gate now passes. This proves adding the covering
        // (allowlist) row flips the verdict.
        let seeded = reseed(&state);
        save_allowlist(&allowlist_path(&repo_root), &seeded).unwrap();
        assert!(
            seeded.entries.iter().any(|e| e.key.contains("orphan_fn")),
            "orphan_fn must be in the seeded allowlist: {:?}",
            seeded.entries.iter().map(|e| &e.key).collect::<Vec<_>>(),
        );
        let state2 = gate_coverage_for_repo(
            &wh, "ws", "myrepo", &repo_root, Vec::new(), "run-green",
        )
        .unwrap();
        assert!(
            coverage_gate(&state2.report).is_ok(),
            "with every gap allowlisted the gate must be GREEN: {}",
            state2.report.summary(),
        );

        // And a STALE allowlist entry (an excuse with no matching surface) must
        // re-RED the gate — the excuse cannot outlive its surface.
        let mut stale = seeded.clone();
        stale.entries.push(crate::warehouse::surface_coverage::AllowEntry {
            key: "viz_tab:GhostTabThatDoesNotExist@fat".into(),
            reason: "lingering excuse".into(),
        });
        save_allowlist(&allowlist_path(&repo_root), &stale).unwrap();
        let state3 = gate_coverage_for_repo(
            &wh, "ws", "myrepo", &repo_root, Vec::new(), "run-stale",
        )
        .unwrap();
        let err3 = coverage_gate(&state3.report).unwrap_err().to_string();
        assert!(err3.contains("stale"), "a stale allowlist entry re-reds the gate: {err3}");
    }

    #[test]
    fn allowlist_toml_round_trips_through_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".nornir").join("autonom-allow.toml");
        let al = Allowlist {
            entries: vec![
                super::super::warehouse::surface_coverage::AllowEntry {
                    key: "viz_tab:Bench@thin".into(),
                    reason: "TODO(autonom): wire thin RPC test".into(),
                },
            ],
        };
        save_allowlist(&path, &al).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.contains("BURN IT DOWN"), "header carries the burn-down rule");
        assert!(text.contains("viz_tab:Bench@thin"));

        let back = load_allowlist(&path).unwrap();
        assert_eq!(back, al, "allowlist round-trips through TOML");

        // A missing file loads as empty (not an error).
        let empty = load_allowlist(&dir.path().join("nope.toml")).unwrap();
        assert!(empty.entries.is_empty());
    }
}