Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/Skidbladnir

tests/gated_runs_are_declared_guard.rs

//! **A test behind a feature flag that nothing declares a run of is not a test.**
//!
//! `tests/silenced_tests_guard.rs` next door polices ONE shape of that: a
//! `tests/*.rs` whose crate-level `#![cfg(feature = …)]` is off by default compiles
//! to an empty binary and libtest prints `running 0 tests … ok`. Its remedy is a
//! *rescue arm* in `.nornir/testmatrix-arms.json` — and an arm is **prose a human
//! typed**. It records that somebody once ran the file and what they saw. Nothing
//! re-runs it, and nothing checks that anything ever will.
//!
//! ## The defect that forced this file (MEASURED 2026-08-25)
//!
//! `vmsuite::judge_active` graded systemd's transitional `deactivating` as
//! **stopped**. A suite case of `systemctl stop` → `Sleep(1500)` → collect therefore
//! passed on "it stopped" for any service that drains longer than 1.5 s; a real
//! service on this box sat in `deactivating` for 6.4 s. A false green inside the
//! harness whose whole job is catching false greens. Fixed in `4be0017`.
//!
//! It survived because of a gap NEITHER existing guard can see:
//!
//! * `src/vmsuite.rs` is `#[cfg(feature = "matrix")]` at its `pub mod` in
//!   `src/lib.rs:392`. Its **23 pure `#[test]` fns** — `Facts` parsing and the
//!   judges, none of which touch KVM — are unit tests inside the LIBRARY target, not
//!   a `tests/*.rs`, so `audit_repo`'s test-target walk never looks at them.
//! * arm 3 in `.nornir/testmatrix-arms.json` says those 20 (now 23) "RUN and PASS"
//!   — measured once, on 2026-08-03, by hand. The same arm already records the
//!   correction in its own words: *"those 20 do NOT run in a plain `cargo test`"*.
//! * Skidbladnir had **no `brokkr.toml`**, so the dwarves forge had no pipeline for
//!   this repo at all, and `.nornir/build-variants.toml` declared four variants,
//!   none of which enabled `matrix`. Verified 2026-08-25: `nornir/brokkr.toml` was
//!   the ONLY one in the whole constellation.
//!
//! So `--features matrix` was exercised by exactly one thing: a human remembering to
//! type it. It went three weeks without one.
//!
//! ## The contract, in one sentence
//!
//! **Every feature that gates a test in this repo is enabled by a declared
//! `[[build.variant]]`, and that variant is named by a step in `brokkr.toml`.**
//!
//! Three sources of "gates a test", because the defect class hides in all three:
//!
//! | source | shape | what missed it before |
//! |---|---|---|
//! | integration target | `tests/x.rs` with `#![cfg(feature = "f")]` | nothing — `audit_repo` sees these |
//! | cargo target | `[[test]]`/`[[bench]]` `required-features` | `cargo test` skips them silently, exit 0 |
//! | **library unit tests** | `#[cfg(feature = "f")] pub mod m;` where `m` holds `#[test]` | **everything — this is the `judge_active` hole** |
//!
//! ### Row 2 is not a hypothetical, and it is why this file is not a twin of
//! `silenced_tests_guard` (MEASURED 2026-08-25)
//!
//! `nornir_testmatrix::gatedtests::classify` opens with `extract_crate_cfg(src)?` and
//! returns `None` when a target has no crate-level `#![cfg]`. It parses
//! `required_features` (`gatedtests.rs:826`) and its own field doc says cargo
//! "silently skips" such a target — and then never consults it in the verdict. So the
//! second row of this table is invisible to the shared guard. Proven by putting the
//! SAME silence through both shapes, in a scratch worktree, one `#[test]` fn behind
//! `terraform`:
//!
//! * as `#![cfg(feature = "terraform")]` → `silenced_tests_guard` **RED**:
//!   `14 scanned · 6 feature-gated · 5 rescued · 1 SILENCED (1 hidden test fns)`
//! * as `[[test]] required-features = ["terraform"]`, cfg removed → the file is
//!   identical in effect (cargo builds and runs nothing) and `silenced_tests_guard`
//!   reports **`ok. 1 passed`**
//! * GATE 1 in THIS file goes red on the second shape and names it:
//!   ``· `terraform` gates: – `required-features` of test target `zz_blindness_probe```
//!
//! Consequence for this repo: moving a dark target's gate from `#![cfg]` to
//! `required-features` would look like tidying and would blind the shared guard, so
//! do not do it — the five silenced targets keep their `#![cfg]`. Consequence for the
//! fleet: 12 `[[test]] required-features` targets across dwarves, edda
//! (`gunnar-pack`, `korp-installer` ×3), facett ×4, gunnar ×3 and holger are in that
//! blind spot today. Fixing `classify` belongs in edda, next to the dependency-edge
//! work already in flight on `lane/darktest-holes`, not here.
//!
//! An `allow_unbuilt` excuse deliberately does NOT satisfy this guard the way it
//! satisfies `nornir_build_thing::feature_axis::FeatureAxis::gate`. "Nobody compiles
//! it, and here is why" is a reasonable answer about a capability. It is not a
//! reasonable answer about a *test*: a test nobody runs is the thing this repo keeps
//! paying for.
//!
//! ## What this guard proves, and what it does not
//!
//! It proves the DECLARATION loop is closed: a gated test surface is named by a
//! variant, and that variant is named by a pipeline step, so the forge compiles it
//! on every push. It does **not** prove the tests *execute* — a brokkr `variant`
//! step is `nornir_build_thing::build_variant`, a cargo BUILD (verified in
//! `dwarves/crates/dwarves/src/runner.rs:190`, `RealRunner::run`). Making the pure
//! judges execute on every plain `cargo test` needed them out from behind `matrix`
//! entirely — the split `.nornir/testmatrix-arms.json` arm 3 carried as an open
//! follow-up from 2026-08-03, and `94ca0f9` closed it. This guard is what stops the
//! NEXT one being declared nowhere at all.
//!
//! ## What is still dark, and in which of the two senses (MEASURED 2026-08-25)
//!
//! Counted by differencing the test ROSTER, not by reading source: `cargo test
//! --features F --lib -- --list` minus the same list with default features, for every
//! declared feature. Default run is **624** library tests; the union of every
//! single-feature arm is **763**, so **139** library tests are still behind a gate.
//! Of those, exactly **three** are heavy in the sense of needing something this box
//! cannot provide in-process, and all three say so with `#[ignore]`:
//! `archive::tests::znippy_delta_real_download_ships_only_changed_blob`,
//! `k8s_apply::tests::k8s_live_apply_scale_delete`,
//! `unfold::talos::tests::talos_live_apply`.
//!
//! The other **136** are hermetic — every one of them was RUN here and passed, in
//! 0.0x s, touching no root, no network and no hardware. They are not heavy; they are
//! **dependency-bound**: each reaches an item whose gate exists to keep an OPTIONAL
//! dependency out of the lean core (`promote` 34 → serde_yaml · `federation` 28 →
//! ureq · `sockets` 14 → base64 + app-heartbeat · `openbao` 13 → the reqwest-typed
//! `VaultHttp` field · `archive` 7 → znippy-core · `harvest` 7 + `download` 6 →
//! reqwest · `service_drive` 7 → draupnir · `machine` 6 → kvm's libc/draupnir-seed ·
//! `pki` 5 → vault · `unfold` 3 → redfish/terraform/talos · `k8s_apply` 3 → kube ·
//! `talos_apid` 2 → tonic · `watch` 1 → gix). Freeing those needs a dependency to
//! enter the build, which is the gate doing its job — so they stay, and "dark" is the
//! wrong word for them. Only a test hidden by a gate COARSER than its own dependency
//! is a defect, and that is what the pin below keeps closed.
//!
//! Five integration targets still compile to zero tests and are covered by arms:
//! `install_matrix_live`, `vm_systemd_suite`, `vm_korp_provision` (real KVM guests —
//! genuinely heavy), `service_kind_live` (real systemd), and `promote_contract`
//! (17 hermetic tests, dependency-bound on `Ladder::from_yaml`; a `tests/*.rs` cannot
//! be reached by an in-crate `cfg(test)`, so the split that freed the library half
//! does not reach it).
//!
//! ## Cost
//!
//! One `cargo metadata`, a `src/**` read and set arithmetic. Nothing is compiled, so
//! it is always on — like `silenced_tests_guard`, it carries no `#![cfg]` of its
//! own, because a guard hidden behind the mechanism it polices is the joke version
//! of itself.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use nornir_build_thing::variant::BuildVariantSet;
use nornir_testmatrix::gatedtests::{
    count_test_fns, default_features, extract_crate_cfg, feature_closure, parse_cfg_expr,
    workspace_crates,
};

fn repo_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf()
}

/// feature name → the human-readable evidence of what it gates.
type Gating = BTreeMap<String, Vec<String>>;

fn note(g: &mut Gating, feature: &str, evidence: String) {
    g.entry(feature.to_string()).or_default().push(evidence);
}

// ───────────────────────────── the crate's own feature table ─────────────────────────────

/// This crate's `[features]` table plus its `[[test]]` targets, read through
/// `cargo metadata` (the ONE reader — `nornir_testmatrix::gatedtests`).
fn crate_facts() -> (
    BTreeMap<String, Vec<String>>,
    Vec<nornir_testmatrix::gatedtests::TestTarget>,
) {
    let crates = workspace_crates(&repo_root()).expect("cargo metadata for this repo");
    let me = crates
        .iter()
        .find(|c| c.name == "skidbladnir")
        .expect("`skidbladnir` is a member of its own workspace");
    (me.features.clone(), me.tests.clone())
}

// ───────────────────────────── source 3: library unit tests ─────────────────────────────

/// Every `.rs` under `src/`.
fn rs_files(dir: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let Ok(rd) = std::fs::read_dir(dir) else {
        return out;
    };
    for e in rd.flatten() {
        let p = e.path();
        if p.is_dir() {
            out.extend(rs_files(&p));
        } else if p.extension().and_then(|s| s.to_str()) == Some("rs") {
            out.push(p);
        }
    }
    out.sort();
    out
}

/// The file that holds `mod <name>;` declared inside `parent`.
fn module_file(parent: &Path, name: &str) -> Option<PathBuf> {
    let stem = parent.file_stem()?.to_str()?;
    let dir = if matches!(stem, "lib" | "mod" | "main") {
        parent.parent()?.to_path_buf()
    } else {
        parent.parent()?.join(stem)
    };
    let flat = dir.join(format!("{name}.rs"));
    if flat.is_file() {
        return Some(flat);
    }
    let nested = dir.join(name).join("mod.rs");
    nested.is_file().then_some(nested)
}

/// `mod x;` / `pub mod x;` / `pub(crate) mod x;` → `x`. Brace-bodied modules and
/// anything else return `None`.
fn file_mod_decl(line: &str) -> Option<&str> {
    let t = line.trim();
    let rest = ["pub(crate) mod ", "pub(super) mod ", "pub mod ", "mod "]
        .iter()
        .find_map(|p| t.strip_prefix(p))?;
    let name = rest.strip_suffix(';')?.trim();
    (!name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_')).then_some(name)
}

/// `#[test]` fns in the module rooted at `file`, following its `mod x;` children.
fn test_fns_in_subtree(file: &Path, depth: usize, seen: &mut BTreeSet<PathBuf>) -> usize {
    if depth > 8 || !seen.insert(file.to_path_buf()) {
        return 0;
    }
    let Ok(src) = std::fs::read_to_string(file) else {
        return 0;
    };
    let mut n = count_test_fns(&src);
    for line in src.lines() {
        if let Some(name) = file_mod_decl(line) {
            if let Some(child) = module_file(file, name) {
                n += test_fns_in_subtree(&child, depth + 1, seen);
            }
        }
    }
    n
}

/// The body of an OUTER `#[cfg(…)]` attribute — the text `parse_cfg_expr` wants.
///
/// Not a twin of `gatedtests::extract_crate_cfg`: that one walks a file's PROLOGUE
/// for INNER `#![cfg]` attributes and stops at the first item, which by construction
/// can never see a `#[cfg]` sitting on a `mod` declaration halfway down `lib.rs`.
fn outer_cfg_body(line: &str) -> Option<String> {
    let t = line.trim();
    let inner = t.strip_prefix("#[cfg(")?.strip_suffix(")]")?;
    (!inner.trim().is_empty()).then(|| inner.trim().to_string())
}

/// Features that gate library `#[test]` fns: a `#[cfg(feature = …)]` on a `mod x;`
/// whose file (or subtree) holds tests. **The `judge_active` hole.**
fn features_gating_unit_tests() -> Gating {
    let root = repo_root();
    let mut out: Gating = BTreeMap::new();
    for file in rs_files(&root.join("src")) {
        let Ok(src) = std::fs::read_to_string(&file) else {
            continue;
        };
        let lines: Vec<&str> = src.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            let Some(body) = outer_cfg_body(line) else {
                continue;
            };
            let Some(expr) = parse_cfg_expr(&body) else {
                continue;
            };
            let feats = expr.features();
            if feats.is_empty() {
                continue;
            }
            // The attribute applies to the next item line; skip further attributes
            // and doc comments so a stack of them still resolves.
            let Some(decl) = lines[i + 1..].iter().find(|l| {
                let t = l.trim();
                !t.is_empty() && !t.starts_with('#') && !t.starts_with("//")
            }) else {
                continue;
            };
            let Some(name) = file_mod_decl(decl) else {
                continue;
            };
            let Some(child) = module_file(&file, name) else {
                continue;
            };
            let n = test_fns_in_subtree(&child, 0, &mut BTreeSet::new());
            if n == 0 {
                continue;
            }
            let rel = child.strip_prefix(&root).unwrap_or(&child).display();
            for f in &feats {
                note(
                    &mut out,
                    f,
                    format!(
                        "{n} library `#[test]` fn(s) in {rel}, gated at {}:{}",
                        file.strip_prefix(&root).unwrap_or(&file).display(),
                        i + 1
                    ),
                );
            }
        }
    }
    out
}

// ───────────────────────────── sources 1 + 2: cargo targets ─────────────────────────────

/// Features that gate an integration test target or a `[[bench]]`.
fn features_gating_targets(
    features: &BTreeMap<String, Vec<String>>,
    tests: &[nornir_testmatrix::gatedtests::TestTarget],
) -> Gating {
    let root = repo_root();
    let on_by_default = default_features(features);
    let mut out: Gating = BTreeMap::new();

    for t in tests {
        for f in &t.required_features {
            if !on_by_default.contains(f) && features.contains_key(f) {
                note(
                    &mut out,
                    f,
                    format!("`required-features` of test target `{}`", t.name),
                );
            }
        }
        let Ok(src) = std::fs::read_to_string(&t.src_path) else {
            continue;
        };
        let Some(body) = extract_crate_cfg(&src) else {
            continue;
        };
        let Some(expr) = parse_cfg_expr(&body) else {
            continue;
        };
        if expr.compiles_with(&on_by_default) {
            continue;
        }
        let n = count_test_fns(&src);
        let rel = t
            .src_path
            .strip_prefix(&root)
            .unwrap_or(&t.src_path)
            .display();
        for f in expr.features() {
            if features.contains_key(&f) {
                note(
                    &mut out,
                    &f,
                    format!("{n} `#[test]` fn(s) in {rel}, `#![cfg({body})]`"),
                );
            }
        }
    }

    // `[[bench]] required-features` — cargo metadata's `tests` list does not carry
    // bench targets, and this repo's bencher law makes a bench a gate like any other.
    let doc: toml::Value =
        toml::from_str(&std::fs::read_to_string(root.join("Cargo.toml")).expect("read Cargo.toml"))
            .expect("parse Cargo.toml");
    if let Some(benches) = doc.get("bench").and_then(|b| b.as_array()) {
        for b in benches {
            let name = b.get("name").and_then(|n| n.as_str()).unwrap_or("?");
            let Some(req) = b.get("required-features").and_then(|r| r.as_array()) else {
                continue;
            };
            for f in req.iter().filter_map(|f| f.as_str()) {
                if !on_by_default.contains(f) && features.contains_key(f) {
                    note(
                        &mut out,
                        f,
                        format!("`required-features` of bench `{name}`"),
                    );
                }
            }
        }
    }
    out
}

// ───────────────────────────── the declared side ─────────────────────────────

fn build_space() -> BuildVariantSet {
    BuildVariantSet::discover(&repo_root())
        .expect("read .nornir/build-variants.toml")
        .expect("Skidbladnir declares a .nornir/build-variants.toml")
}

/// feature → the variants that enable it, transitively (a variant declaring
/// `matrix` covers `kvm` too, because `matrix = ["kvm"]`).
fn covered_by(
    set: &BuildVariantSet,
    features: &BTreeMap<String, Vec<String>>,
) -> BTreeMap<String, Vec<String>> {
    let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for v in &set.variants {
        for f in feature_closure(features, &v.features) {
            out.entry(f).or_default().push(v.name.clone());
        }
    }
    out
}

/// Every variant named by a `run = { variant = "…" }` step in `brokkr.toml`.
/// `None` ⇒ the repo declares no pipeline at all.
fn brokkr_step_variants() -> Option<BTreeSet<String>> {
    let path = repo_root().join("brokkr.toml");
    let text = std::fs::read_to_string(&path).ok()?;
    let doc: toml::Value = toml::from_str(&text).expect("parse brokkr.toml");
    let mut out = BTreeSet::new();
    let stages = doc
        .get("pipeline")
        .and_then(|p| p.get("stage"))
        .and_then(|s| s.as_array());
    for stage in stages.into_iter().flatten() {
        let steps = stage.get("step").and_then(|s| s.as_array());
        for step in steps.into_iter().flatten() {
            if let Some(v) = step
                .get("run")
                .and_then(|r| r.get("variant"))
                .and_then(|v| v.as_str())
            {
                out.insert(v.to_string());
            }
        }
    }
    Some(out)
}

/// Union of the three sources.
fn all_gating() -> Gating {
    let (features, tests) = crate_facts();
    let mut g = features_gating_targets(&features, &tests);
    for (f, ev) in features_gating_unit_tests() {
        g.entry(f).or_default().extend(ev);
    }
    g
}

// ───────────────────────────── the gates ─────────────────────────────

/// **GATE 1** — a feature that gates a test is enabled by a declared variant.
#[test]
fn every_feature_that_gates_a_test_is_enabled_by_a_declared_variant() {
    let (features, _) = crate_facts();
    let gating = all_gating();
    let on_by_default = default_features(&features);
    let covered = covered_by(&build_space(), &features);

    let uncovered: Vec<&String> = gating
        .keys()
        .filter(|f| !on_by_default.contains(*f) && !covered.contains_key(*f))
        .collect();

    assert!(
        uncovered.is_empty(),
        "{} feature(s) gate tests that NO declared `[[build.variant]]` enables — \
         nothing but a human typing `--features` ever compiles them, and nothing at \
         all runs them:\n{}\n\nFix: declare a `[[build.variant]]` in \
         `.nornir/build-variants.toml` that enables the feature (adding it to \
         `[build] offers` first — `BuildVariantSet::validate` refuses a variant \
         reaching for a capability the repo has not offered), and name that variant \
         from a `brokkr.toml` step. A `[build.allow_unbuilt]` excuse does NOT count \
         here: \"nobody compiles it, and here is why\" is not an answer about a TEST.",
        uncovered.len(),
        uncovered
            .iter()
            .map(|f| format!(
                "  · `{f}` gates:\n{}",
                gating[*f]
                    .iter()
                    .map(|e| format!("      – {e}"))
                    .collect::<Vec<_>>()
                    .join("\n")
            ))
            .collect::<Vec<_>>()
            .join("\n")
    );
}

/// **GATE 2** — the covering variant is actually RUN by the forge.
///
/// A variant declared and never named by a pipeline step is the same silence one
/// level up: the declaration exists, and still nothing builds it on a push.
#[test]
fn every_variant_that_covers_a_gated_test_is_run_by_a_brokkr_step() {
    let (features, _) = crate_facts();
    let gating = all_gating();
    let on_by_default = default_features(&features);
    let covered = covered_by(&build_space(), &features);

    let run = brokkr_step_variants().unwrap_or_else(|| {
        panic!(
            "this repo declares NO `brokkr.toml`, so the dwarves forge has no pipeline \
             for it and NOTHING is built automatically — every declared variant is a \
             file somebody has to remember to build by hand. Measured across the \
             constellation on 2026-08-25: `nornir/brokkr.toml` was the only one. \
             Declare one (copy the shape from `nornir/brokkr.toml`; the schema is \
             `dwarves/crates/dwarves/src/brokkr/model.rs`)."
        )
    });
    assert!(
        !run.is_empty(),
        "`brokkr.toml` declares no `run = {{ variant = … }}` step at all"
    );

    let unrun: Vec<String> = gating
        .keys()
        .filter(|f| !on_by_default.contains(*f))
        .filter_map(|f| {
            let by = covered.get(f)?;
            by.iter().all(|v| !run.contains(v)).then(|| {
                format!(
                    "  · `{f}` is enabled only by variant(s) {by:?}, which no pipeline step runs"
                )
            })
        })
        .collect();

    assert!(
        unrun.is_empty(),
        "{} gated test surface(s) are declared but never RUN — a variant no \
         `brokkr.toml` step names is built by nobody:\n{}",
        unrun.len(),
        unrun.join("\n")
    );
}

/// **NON-VACUOUS** — both sides of the subtraction are real.
///
/// A scan that found no gated tests, or a build space with no variants, makes the
/// gates above pass over an empty world. Both numbers are asserted, and the scanner
/// is anchored to a library-unit-test gate that really exists today.
///
/// **The anchor moved on 2026-08-25, and that is the point.** It used to be
/// `src/vmsuite.rs`'s 23 tests behind `matrix` — the exact hole `judge_active` hid
/// in. Those tests are no longer gated at all (the pure judges were lifted out of
/// the `matrix` module in `94ca0f9`), so anchoring on them would now assert the
/// defect is still there. It anchors on `service-drive` instead, which is a real
/// remaining library-unit-test gate, and the vmsuite case became the REGRESSION pin
/// below.
#[test]
fn the_scan_sees_a_real_library_unit_test_gate() {
    let unit = features_gating_unit_tests();
    let anchor = unit.get("service-drive").unwrap_or_else(|| {
        panic!(
            "the library-unit-test scan did not find `service-drive` gating anything. \
             `src/lib.rs` gates `pub mod service_drive;` on it and \
             `src/service_drive.rs` holds 7 `#[test]` fns — if that is invisible here, \
             so is the next `judge_active`. Found: {:?}",
            unit.keys().collect::<Vec<_>>()
        )
    });
    assert!(
        anchor.iter().any(|e| e.contains("src/service_drive.rs")),
        "`service-drive` was found gating something, but not `src/service_drive.rs` — \
         the scanner is resolving modules to the wrong files: {anchor:?}"
    );

    let gating = all_gating();
    assert!(
        gating.len() >= 3,
        "only {} feature(s) found gating tests in a repo with {} declared features — \
         the scan is seeing almost nothing: {:?}",
        gating.len(),
        crate_facts().0.len(),
        gating.keys().collect::<Vec<_>>()
    );
    // Still true after the split: these three gate a `tests/*.rs` target, which is a
    // different question from gating a library unit test.
    for known in ["matrix", "promote", "service-drive"] {
        assert!(
            gating.contains_key(known),
            "`{known}` has a rescue arm in `.nornir/testmatrix-arms.json` (it gates a \
             test file) and the scan did not find it: {:?}",
            gating.keys().collect::<Vec<_>>()
        );
    }
}

/// **REGRESSION PIN** — the pure halves stay out from behind their gates.
///
/// On 2026-08-25 five features stopped gating library unit tests: their modules were
/// ungated and only the dependency-bound items kept an individual `#[cfg]`. That
/// moved 176 tests into every default `cargo test`. The cheapest way to lose all of
/// it is one `#[cfg(feature = …)]` put back on a `pub mod` line by somebody tidying
/// up, and nothing else in the repo would notice: the tests would go back to
/// reporting nothing, exactly as they did for the three weeks `judge_active` was
/// wrong.
///
/// So each one is pinned by name. This is not a duplicate of the gate above — that
/// one asks "is every gating feature declared", which a re-gated module would still
/// satisfy, because the variant declaring it is still there.
///
/// # RED, RECOVERED (2026-08-25)
///
/// `aec8680` shipped this pin saying *"the lane's red proof went down with its
/// transcript; what I can vouch for is that it runs green"*. A pin nobody has seen
/// fail is a pin, not a guard, so the red was reconstructed rather than argued —
/// against the tree as it stood BEFORE the six lifts, `e4e00d3` (the commit before
/// `2d012bb`), with this file copied in unchanged:
///
/// ```text
/// $ git worktree add --detach ../wt-skid-before e4e00d3
/// $ cp tests/gated_runs_are_declared_guard.rs ../wt-skid-before/tests/
/// $ cargo test --test gated_runs_are_declared_guard      # in that worktree
///
/// test result: FAILED. 5 passed; 1 failed
/// ---- the_features_whose_pure_halves_were_lifted_out_stay_out ----
/// 6 pure test surface(s) went back behind a feature gate:
///   · `matrix`     is gating src/vmsuite.rs   again — 23 library `#[test]` fn(s), gated at src/lib.rs:374
///   · `promote`    is gating src/promote      again — 99 library `#[test]` fn(s), gated at src/lib.rs:422
///   · `sockets`    is gating src/socket.rs    again — 61 library `#[test]` fn(s), gated at src/lib.rs:411
///   · `machine`    is gating src/machine.rs   again — 19 library `#[test]` fn(s), gated at src/lib.rs:351
///   · `federation` is gating src/federation   again — 36 library `#[test]` fn(s), gated at src/lib.rs:446
///   · `kubernetes` is gating src/provision.rs again —  3 library `#[test]` fn(s), gated at src/lib.rs:186
/// ```
///
/// 241 library tests, each named with the file and the `lib.rs` line that hid it —
/// applied output, not a round trip. The other five tests in this file pass on that
/// same tree, which is the discrimination: this pin is the only one of the six that
/// can tell the two trees apart, so a green here is a green about something.
///
/// Also recorded because `aec8680`'s message overstates it: that commit contains no
/// dependency-edge logic. It renamed the non-vacuity anchor from
/// `matrix`/`src/vmsuite.rs` to `service-drive`/`src/service_drive.rs` (the old
/// anchor would have asserted the defect was still present after `94ca0f9`), added
/// this pin, and split out `the_declared_side_is_real_and_validates`. The third
/// source *this* file answers is the library-unit-test one in the table above, and it
/// had that before `aec8680`. The dependency-EDGE source lives entirely in edda
/// `bbde6c9` (`nornir-testmatrix`'s `src_roots`/`deps`/`manifest_path`), and this
/// file references none of those three fields. Skidbladnir is a single-crate
/// workspace: its four `dep/feature` entries (`draupnir/backend-oci`,
/// `draupnir/seed`, `draupnir/backend-tunnr`, `nornir-testmatrix/testmatrix`) light
/// features in OTHER crates' test gates, never its own, so that source has nothing to
/// find here.
#[test]
fn the_features_whose_pure_halves_were_lifted_out_stay_out() {
    let unit = features_gating_unit_tests();
    // feature → the file whose library tests it must NOT be hiding any more.
    let lifted = [
        (
            "matrix",
            "src/vmsuite.rs",
            "the 23 judges that grade a real init",
        ),
        (
            "promote",
            "src/promote",
            "the slot registry, prod guard and app seam",
        ),
        (
            "sockets",
            "src/socket.rs",
            "the socket registry and evidence classifier",
        ),
        (
            "machine",
            "src/machine.rs",
            "MachineSpec and the content-addressed ImageCache",
        ),
        (
            "federation",
            "src/federation",
            "coordinate and upstream-URL building",
        ),
        (
            "kubernetes",
            "src/provision.rs",
            "the rendered postgres manifests",
        ),
    ];
    let mut regressed = Vec::new();
    for (feature, file, what) in lifted {
        if let Some(ev) = unit.get(feature) {
            if let Some(hit) = ev.iter().find(|e| e.contains(file)) {
                regressed.push(format!(
                    "  · `{feature}` is gating {file} again ({what}) — {hit}"
                ));
            }
        }
    }
    assert!(
        regressed.is_empty(),
        "{} pure test surface(s) went back behind a feature gate:\n{}\n\nThese were \
         lifted out deliberately: the module is dependency-free and only the items \
         that touch the feature's dependency should carry `#[cfg]`. Re-gating the \
         whole module hides its tests from every default run again. If a NEW \
         dependency really did land in one of these modules, gate that item — not \
         the `pub mod` line.",
        regressed.len(),
        regressed.join("\n")
    );
}

/// The declaration side is real, and the build space it is read from validates.
#[test]
fn the_declared_side_is_real_and_validates() {
    let set = build_space();
    assert!(
        !set.variants.is_empty(),
        "the build space declares no variants at all"
    );
    // A row reaching for a feature the repo does not `offers` is rejected by
    // build-thing itself, so a variant added to satisfy GATE 1 that the forge would
    // refuse to load is not coverage. Asserted here rather than trusted.
    for v in &set.variants {
        set.validate(v)
            .unwrap_or_else(|e| panic!("`.nornir/build-variants.toml` does not validate: {e:#}"));
    }
    let covered = covered_by(&set, &crate_facts().0);
    assert!(
        !covered.is_empty(),
        "no declared variant enables ANY feature — GATE 1 would then be judging \
         everything against an empty set"
    );
}

/// **RED PROBE** — GATE 1 can say no.
///
/// Strip every variant's features (the state this repo was actually in on
/// 2026-08-25) and assert the gate names the gated features as uncovered. Without
/// this, a green above could equally mean the gate is unreachable.
#[test]
fn the_gate_reports_red_when_no_variant_enables_the_gated_features() {
    let (features, _) = crate_facts();
    let gating = all_gating();
    let on_by_default = default_features(&features);

    let mut set = build_space();
    for v in &mut set.variants {
        v.features.clear();
    }
    let covered = covered_by(&set, &features);

    let uncovered: Vec<&String> = gating
        .keys()
        .filter(|f| !on_by_default.contains(*f) && !covered.contains_key(*f))
        .collect();

    assert_eq!(
        uncovered.len(),
        gating
            .keys()
            .filter(|f| !on_by_default.contains(*f))
            .count(),
        "with every variant's features cleared, EVERY non-default gating feature must \
         be reported uncovered; the gate saw only {uncovered:?}"
    );
    assert!(
        uncovered.iter().any(|f| *f == "matrix"),
        "the red probe did not name `matrix` — the gate cannot report the very defect \
         it was written for: {uncovered:?}"
    );
}