nornir 0.4.42

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
//! # 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).

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 crate::warehouse::surface_coverage::{
    append_surface_coverage, latest_surface_coverage, query_surface_coverage, rows_for,
    seed_allowlist, Allowlist, CoverageRow, CoverageSelector, CoverageSummary, GateReport,
};
use nornir_testmatrix::discover::{
    cli_commands, facett_components, mcp_tools, unreached_functions, viz_tabs, CallEdge, FacetRow,
    Surface, SymbolRow,
};

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

/// 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",
    "Funnel",
    "TimeTravel",
    "LiveRun",
    "Release",
    "Knowledge",
    "Warehouse",
    "Mcp",
    "Search",
    "Gates",
    "Bench",
    "Test",
    "Leaderboard",
    "Security",
];

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

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

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(facett_components(&inputs.facett))
        .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,
            // Discrete surfaces: covered iff a same-named test-reachable handler.
            VizTab | CliCommand | McpTool | FacettComponent => {
                reachable_idents.contains(&node.id.to_lowercase())
            }
        };
        if is_covered {
            covered.insert(node.key_str());
        }
    }
    // 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 inputs = nornir_surface_inputs(cli_commands);
    let (symbols, edges) = knowledge_to_rows(view);
    let (surface, _covered) = build_surface_and_covered(&inputs, &symbols, &edges);
    surface
}

// ─── 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> {
    let view = load_latest(wh, repo)
        .with_context(|| format!("load knowledge map for repo `{repo}`"))?;
    let (symbols, edges) = knowledge_to_rows(&view);
    let (surface, covered) = build_surface_and_covered(inputs, &symbols, &edges);
    let report = GateReport::compute(run_id, workspace, &surface, &covered, &allowlist);
    Ok(GateState { surface, covered, allowlist, report })
}

/// 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(
        run_id,
        workspace,
        &state.surface,
        &state.covered,
        &state.allowlist,
        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");
    }

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

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