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

nordisk/nornir

src/mimir_lens/room_feed/room_tests.rs

//! Every wired lens, asked the way a front door asks it
//! ([`crate::mimir_lens::answer`]), over the fixture workspace
//! ([`super::fixture`]). Each test names the room feed it would go red
//! without; the `*_goes_blind_without_*` tests switch that feed off in the
//! dump and assert the answer changes — and says why.

use serde_json::{Value, json};

use super::fixture::{self, SHOP, WEB, Without};

fn worst(v: &Value) -> &Vec<Value> {
    v["worst"].as_array().unwrap_or_else(|| panic!("no worst: {v}"))
}

fn state(v: &Value) -> &str {
    v["lens_meta"]["state"].as_str().unwrap_or_else(|| panic!("no lens_meta.state: {v}"))
}

fn note(v: &Value) -> &str {
    v["evidence_note"].as_str().unwrap_or("")
}

fn feed<'a>(v: &'a Value, table: &str) -> &'a Value {
    v["feeds"].as_array().and_then(|f| f.iter().find(|x| x["table"] == table)).unwrap_or_else(|| panic!("no feed `{table}` in {}", v["feeds"]))
}

// ── the envelope ────────────────────────────────────────────────────────────

#[test]
fn a_repo_that_is_not_consumed_refuses_by_state_and_names_the_consumed_ones() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    let v = ws.ask("villa", json!({ "repo": "nobody" }));
    assert_eq!(state(&v), "not_consumed", "{v}");
    assert!(note(&v).contains("nobody") && note(&v).contains(SHOP) && note(&v).contains(WEB), "{}", note(&v));
    assert!(worst(&v).is_empty());
}

#[test]
fn a_workspace_with_nothing_consumed_refuses_instead_of_answering_empty() {
    let _g = fixture::serial();
    let tmp = tempfile::tempdir().unwrap();
    let room = crate::code_room::CodeRoom::new("empty", tmp.path());
    let v = crate::mimir_lens::answer("villa", &crate::code_room::Reach::room_only(&room), &json!({}));
    assert_eq!(state(&v), "not_consumed", "{v}");
    assert!(note(&v).contains("no repo has been consumed"), "{}", note(&v));
}

#[test]
fn a_door_that_holds_no_warehouse_reads_the_one_beside_the_code_room() {
    let _g = fixture::serial();
    let ws = fixture::workspace();
    // the MCP / CLI doors hand over the code room only
    let v = crate::mimir_lens::answer("anomaly", &crate::code_room::Reach::room_only(&ws.room), &json!({ "repo": SHOP }));
    assert_eq!(feed(&v, "git_heat_facts")["missing"], false, "{v}");
    assert!(feed(&v, "git_heat_facts")["rows"].as_u64().unwrap() >= 4);
}

// ── anomaly: git_heat_facts ─────────────────────────────────────────────────

#[test]
fn anomaly_flags_the_file_that_suddenly_churns_and_reads_every_generation() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    // six flat scans of src/cart.rs, then a burst
    for (i, total) in [5, 5, 5, 5, 5, 5, 25].into_iter().enumerate() {
        fixture::heat(&ws, SHOP, 1_000_000 * (i as i64 + 1), &[("src/cart.rs", total, 0, 0, 1)]);
    }
    let v = ws.ask("anomaly", json!({ "repo": SHOP }));
    assert_eq!(state(&v), "complete", "{v}");
    assert_eq!(feed(&v, "git_heat_facts")["rows"], 7);
    let hit = worst(&v).iter().find(|a| a["subject"] == "shop/src/cart.rs").unwrap_or_else(|| panic!("{v}"));
    assert_eq!(hit["kind"], "stable-node-churn");
    // another repo's filter sees none of it, and says the table has no row of that repo
    let other = ws.ask("anomaly", json!({ "repo": WEB }));
    assert_eq!(state(&other), "empty_gap", "{other}");
    assert!(note(&other).contains("no row of repo `web`"), "{}", note(&other));
}

/// Four scans are not a baseline: the answer says "not enough history" and
/// judges nothing — the z = 4.0 alarms loki raised on ≈2 generations per file.
#[test]
fn anomaly_with_too_few_scans_says_not_enough_history() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    for (i, total) in [5, 5, 5, 25].into_iter().enumerate() {
        fixture::heat(&ws, SHOP, 1_000_000 * (i as i64 + 1), &[("src/cart.rs", total, 0, 0, 1)]);
    }
    let v = ws.ask("anomaly", json!({ "repo": SHOP }));
    assert!(worst(&v).is_empty(), "{v}");
    assert_eq!(state(&v), "empty_gap", "not judged is not \"nothing found\": {v}");
    assert!(note(&v).contains("not enough history"), "{}", note(&v));
}

// ── villa: CALLS into the impure std / libc items ───────────────────────────

#[test]
fn villa_finds_the_three_impure_sites_at_their_lines() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    let v = ws.ask("villa", json!({ "repo": SHOP }));
    assert_eq!(state(&v), "complete", "{v}");
    assert_eq!(v["kind"], "villa");
    assert_eq!(v["heresies"], 3, "{v}");
    let got: Vec<(String, String, String)> = v["findings"]
        .as_array()
        .unwrap()
        .iter()
        .map(|h| (h["kind"].as_str().unwrap().to_string(), h["symbol"].as_str().unwrap().to_string(), h["loc"].as_str().unwrap().to_string()))
        .collect();
    assert_eq!(
        got,
        vec![
            ("shell".to_string(), "shop::pay::shell".to_string(), "src/pay.rs:34".to_string()),
            ("process".to_string(), "shop::pay::charge".to_string(), "src/pay.rs:12".to_string()),
            ("process-control".to_string(), "shop::pay::bye".to_string(), "src/pay.rs:39".to_string()),
        ]
    );
    assert_eq!(v["findings"][1]["callee"], "std::process::Command::new");
    assert_eq!(v["findings"][0]["callee"], "libc::system");
    // the answer says what it cannot see
    assert!(note(&v).contains("LOWER BOUND") && note(&v).contains("closures"), "{}", note(&v));
    assert!(feed(&v, "code_edges:CALLS")["rows"].as_u64().unwrap() > 0);
    // web has no impure call: an empty FACT, not a gap
    let web = ws.ask("villa", json!({ "repo": WEB }));
    assert_eq!((state(&web), web["heresies"].as_u64()), ("empty_fact", Some(0)), "{web}");
}

/// **The tool a shell-out runs is read from its call, never guessed per repo.**
/// Measured 2026-10-16: a `runuser` and a `cargo` call in dwarves both read
/// "git", from a static per-repo list. The binary is the string literal at the
/// call site: read from the consumed checkout, or the label is left out.
#[test]
fn villa_names_the_tool_from_the_call_site_or_not_at_all() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    let pay = ws.room.layout().clone_of(SHOP).join("src/pay.rs");
    let mut lines: Vec<String> = (1..=40).map(|i| format!("// line {i}")).collect();
    lines[11] = r#"    let out = std::process::Command::new("curl").arg("-s").output();"#.to_string();
    std::fs::create_dir_all(pay.parent().unwrap()).unwrap();
    std::fs::write(&pay, lines.join("\n")).unwrap();
    let v = ws.ask("villa", json!({ "repo": SHOP }));
    let charge = v["findings"].as_array().unwrap().iter().find(|h| h["symbol"] == "shop::pay::charge").unwrap_or_else(|| panic!("{v}"));
    assert_eq!((charge["kind"].as_str(), charge["known_tool"].as_str()), (Some("external-tool"), Some("curl")), "{charge}");
    // no literal at the site: no tool named
    std::fs::write(&pay, "// moved\n").unwrap();
    let v = ws.ask("villa", json!({ "repo": SHOP, "limit": 9 }));
    let charge = v["findings"].as_array().unwrap().iter().find(|h| h["symbol"] == "shop::pay::charge").unwrap_or_else(|| panic!("{v}"));
    assert_eq!((charge["kind"].as_str(), charge["known_tool"].as_str()), (Some("process"), None), "{charge}");
}

/// **A per-repo lens asked for one repo opens that repo's room only** — not the
/// whole workspace's (`Scope::current()` folded all 21 repos for a `repo=nornir`
/// ask, 2026-10-16). The lenses that count what arrives from other repos keep
/// the workspace room, and say so in their scope.
#[test]
fn a_per_repo_lens_opens_the_room_of_its_repo_only() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    for lens in crate::mimir_lens::REPO_SCOPED {
        let v = ws.ask(lens, json!({ "repo": SHOP }));
        let scope = v["lens_meta"]["room_scope"].as_str().unwrap_or_else(|| panic!("{lens}: {v}"));
        assert!(scope.contains(SHOP) && !scope.contains(WEB), "{lens}: room scope {scope}");
    }
    assert!(ws.room.peek(&mimir_room::Scope::current()).unwrap().is_none(), "no per-repo ask built the workspace room");
    for lens in ["change_risk", "zombie_features", "world_impact"] {
        let v = ws.ask(lens, json!({ "repo": SHOP }));
        let scope = v["lens_meta"]["room_scope"].as_str().unwrap_or_else(|| panic!("{lens}: {v}"));
        assert!(scope.contains(WEB), "{lens} counts what arrives from the other repos: {scope}");
    }
}

#[test]
fn villa_goes_blind_without_the_calls_into_the_impure_items() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without { impure_calls: true, ..Default::default() });
    let v = ws.ask("villa", json!({ "repo": SHOP }));
    // only process::exit is left (its edge is still in the dump)
    assert_eq!(v["heresies"], 1, "{v}");
    assert_eq!(v["findings"][0]["kind"], "process-control");
}

// ── zombie_features: feature nodes · ENABLES from crate nodes · GATED_BY ────

fn zombies(v: &Value) -> Vec<(String, String)> {
    worst(v).iter().map(|f| (f["feature"].as_str().unwrap().to_string(), f["direction"].as_str().unwrap().to_string())).collect()
}

#[test]
fn zombie_features_splits_never_built_from_unreached() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    let v = ws.ask("zombie_features", json!({ "repo": SHOP }));
    assert_eq!(state(&v), "complete", "{v}");
    assert_eq!(v["features_seen"], 4, "{v}");
    // legacy: declared, no crate was compiled with it — its one item is a compiled-out stub
    // unused: built, `dead()` exists only under it, nothing calls it
    // stripe: built and called (4 sites) · trace: only a cfg!(…) inside audit() and inside bye(),
    // which NOBODY calls — the item is there either way (`partial`), so it is not judged
    assert_eq!(zombies(&v), vec![("shop/legacy".to_string(), "never-built".to_string()), ("shop/unused".to_string(), "unreached".to_string())]);
    let legacy = &worst(&v)[0];
    assert_eq!((legacy["gated_items"].as_u64(), legacy["compiled_out_items"].as_u64()), (Some(1), Some(1)), "{legacy}");
    assert!(legacy["sites"][0].as_str().unwrap().starts_with("src/pay.rs:54"), "{legacy}");
    let unused = &worst(&v)[1];
    // the room links an artifact, but no Build Thing run filed one: the bytes are unknown, and said
    assert_eq!((unused["inbound_calls"].as_u64(), unused["bytes_in_binary"].as_u64()), (Some(0), None), "{unused}");
    assert!(note(&v).contains("bytes_in_binary: no Build Thing run has filed an analysed artifact built from shop yet: ⚒ Build it"), "{}", note(&v));
    assert_eq!(feed(&v, "code_edges:GATED_BY")["rows"], 5);
    assert!(note(&v).contains("cfg_attr") && note(&v).contains("KEPT items only"), "the lower bounds are said: {}", note(&v));
    // a repo with no feature at all: a fact
    let web = ws.ask("zombie_features", json!({ "repo": WEB }));
    assert_eq!((state(&web), web["features_seen"].as_u64()), ("empty_fact", Some(0)), "{web}");
}

#[test]
fn zombie_features_reads_what_was_built_from_enables() {
    let _g = fixture::serial();
    // no ENABLES edge from the crate node: nothing was compiled with any feature
    let ws = fixture::graph_only(Without { enables: true, ..Default::default() });
    let v = ws.ask("zombie_features", json!({ "repo": SHOP }));
    let mut got = zombies(&v);
    got.sort();
    assert_eq!(
        got,
        vec![
            ("shop/legacy".to_string(), "never-built".to_string()),
            ("shop/stripe".to_string(), "never-built".to_string()),
            ("shop/trace".to_string(), "never-built".to_string()),
            ("shop/unused".to_string(), "never-built+unreached".to_string()),
        ]
    );
}

// ── change_risk: call sites per file · the test-reachable set · git heat ────

#[test]
fn change_risk_is_callers_times_churn_times_uncovered_per_file() {
    let _g = fixture::serial();
    let ws = fixture::workspace();
    let v = ws.ask("change_risk", json!({ "repo": SHOP }));
    assert_eq!(v["files_scored"], 4, "{v}");
    let got: Vec<(String, u64, u64, f64)> = worst(&v)
        .iter()
        .map(|u| (u["file"].as_str().unwrap().to_string(), u["downstream_callers"].as_u64().unwrap(), u["churn_90d"].as_u64().unwrap(), u["coverage_frac"].as_f64().unwrap()))
        .collect();
    // pay.rs: charge 4 + audit 2 + shell 1 + refund 1 (from repo `web`) sites; charge / audit / shell of 6 fns are test-reached
    // lib.rs: checkout is called once (from repo `web`) and no test reaches it
    // cart.rs: add 2 + total 2 + open 1; helper is the one fn no test reaches
    assert_eq!(got, vec![("src/pay.rs".to_string(), 8, 12, 0.5), ("src/lib.rs".to_string(), 1, 5, 0.0), ("src/cart.rs".to_string(), 5, 2, 0.75)]);
    assert_eq!(worst(&v)[0]["risk"].as_f64(), Some(48.0));
    assert!(note(&v).contains("coverage_fn"), "the empty line-coverage table is named: {}", note(&v));
    assert_eq!(state(&v), "partial", "coverage_fn is missing: {v}");
    // without heat the answer is an empty gap, never "no risk"
    let cold = fixture::graph_only(Without::default());
    let c = cold.ask("change_risk", json!({ "repo": SHOP }));
    assert_eq!(state(&c), "empty_gap", "{c}");
    assert_eq!(feed(&c, "git_heat_facts")["missing"], true);
}

// ── churn: git heat × functions per file ────────────────────────────────────

#[test]
fn churn_ranks_hotspots_by_frequency_times_the_rooms_function_count() {
    let _g = fixture::serial();
    let ws = fixture::workspace();
    let v = ws.ask("churn", json!({ "repo": SHOP }));
    let got: Vec<(String, i64, i64)> = worst(&v).iter().map(|n| (n["file"].as_str().unwrap().to_string(), n["complexity"].as_i64().unwrap(), n["hotspot"].as_i64().unwrap())).collect();
    // pay.rs holds 7 fns (6 + its test), cart.rs 5 (4 + its test), lib.rs 1, util.rs 1
    assert_eq!(got, vec![("src/pay.rs".to_string(), 7, 84), ("src/cart.rs".to_string(), 5, 10), ("src/lib.rs".to_string(), 1, 5), ("src/util.rs".to_string(), 1, 0)]);
    assert_eq!(state(&v), "complete", "{v}");
    // the band is the request's
    let low = ws.ask("churn", json!({ "repo": SHOP, "band": "low", "cutoff_low": 2 }));
    let files: Vec<&str> = worst(&low).iter().map(|n| n["file"].as_str().unwrap()).collect();
    assert_eq!(files.len(), 2, "{low}");
    assert!(files.contains(&"src/cart.rs") && files.contains(&"src/util.rs"));
}

// ── bench_gaps: call sites / files / coverage per module ────────────────────

#[test]
fn bench_gaps_ranks_the_modules_and_says_the_repo_was_never_benched() {
    let _g = fixture::serial();
    let ws = fixture::workspace();
    let v = ws.ask("bench_gaps", json!({ "repo": SHOP }));
    let repo = &v["per_repo"][0];
    assert_eq!((repo["repo"].as_str(), repo["hot_paths"].as_u64()), (Some(SHOP), Some(4)), "{v}");
    let got: Vec<(String, u64, u64)> = repo["worst"].as_array().unwrap().iter().map(|h| (h["module"].as_str().unwrap().to_string(), h["fan_in"].as_u64().unwrap(), h["commits_90d"].as_u64().unwrap())).collect();
    // the test module `shop::cart::tests` is no bench surface
    assert_eq!(got, vec![("shop::pay".to_string(), 8, 12), ("shop::cart".to_string(), 5, 2), ("shop".to_string(), 1, 5), ("shop::util".to_string(), 1, 0)]);
    assert_eq!(repo["worst"][0]["test_coverage"], 0.5);
    // the fixture's runs carry test outcomes and no bench arm
    assert_eq!((repo["bench_runs"].as_u64(), repo["bench_arms"].as_u64(), repo["unbenched"].as_u64()), (Some(3), Some(0), Some(4)), "{v}");
    assert_eq!(state(&v), "partial", "{v}");
    assert_eq!(feed(&v, "bench_results")["missing"], true);
    assert!(note(&v).contains("bench_results"), "{}", note(&v));
}

// ── undoc_api: effective visibility + has_doc ───────────────────────────────

#[test]
fn undoc_api_ranks_the_undocumented_public_fns_by_their_files_churn() {
    let _g = fixture::serial();
    let ws = fixture::workspace();
    let v = ws.ask("undoc_api", json!({ "repo": SHOP }));
    assert_eq!(state(&v), "complete", "{v}");
    // public = checkout, Cart::add, Cart::total, charge; `dead` is `pub` but no crate can name it;
    // `refund` is `#[doc(hidden)]` and `wrap` sits in the `#[doc(hidden)]` module `util`: public, not documented API
    assert_eq!((v["pub_fns"].as_u64(), v["undocumented_pub_fns"].as_u64(), v["churny_undocumented"].as_u64()), (Some(4), Some(3), Some(3)), "{v}");
    let got: Vec<(String, String, i64)> = worst(&v).iter().map(|u| (u["func"].as_str().unwrap().to_string(), format!("{}:{}", u["file"].as_str().unwrap(), u["line"]), u["commits_90d"].as_i64().unwrap())).collect();
    assert_eq!(
        got,
        vec![
            ("shop::pay::charge".to_string(), "src/pay.rs:5".to_string(), 12),
            ("shop::checkout".to_string(), "src/lib.rs:10".to_string(), 5),
            ("shop::cart::Cart::total".to_string(), "src/cart.rs:16".to_string(), 2),
        ]
    );
    assert!(note(&v).contains("1 `pub` function(s) no other crate can name"), "{}", note(&v));
    assert!(note(&v).contains("nor 2 `#[doc(hidden)]` function(s)"), "{}", note(&v));
}

// ── weak_tests: the test node's reach → files → churn ───────────────────────

#[test]
fn weak_tests_joins_the_outcome_history_to_the_test_nodes_reach() {
    let _g = fixture::serial();
    let ws = fixture::workspace();
    let v = ws.ask("weak_tests", json!({ "repo": SHOP }));
    assert_eq!((v["tests_seen"].as_u64(), v["judgeable"].as_u64(), v["placebos"].as_u64(), v["churn_joined"].as_u64()), (Some(3), Some(3), Some(1), Some(2)), "{v}");
    let got: Vec<(String, String, u64, u64)> = worst(&v)
        .iter()
        .map(|t| (t["test_name"].as_str().unwrap().to_string(), t["verdict"].as_str().unwrap().to_string(), t["churn_commits_90d"].as_u64().unwrap(), t["reachable_symbols"].as_u64().unwrap()))
        .collect();
    // charges_once reaches charge → audit → shell + libc_write, all in src/pay.rs (12 commits / 90 d): never red
    // while the code under it churned. adds_up reaches add, total, open in src/cart.rs (2 commits).
    assert_eq!(got[0], ("pay::charges_once".to_string(), "PLACEBO".to_string(), 12, 4));
    assert!(got.contains(&("cart::tests::adds_up".to_string(), "CANNOT-GO-RED".to_string(), 2, 3)), "{got:?}");
    // the name no `#[test]` node answers to is said, and its verdict rests on run history alone
    assert!(got.contains(&("ghost::never_compiled".to_string(), "CANNOT-GO-RED".to_string(), 0, 0)), "{got:?}");
    assert!(note(&v).contains("1 of 3 test name(s)"), "{}", note(&v));
    assert_eq!(state(&v), "partial");
}

// ── reachable_vuln: what the repo's own code uses of each crate@version ─────

#[test]
fn reachable_vuln_refuses_the_crate_the_code_calls_and_holds_the_one_it_does_not() {
    let _g = fixture::serial();
    let ws = fixture::workspace();
    let v = ws.ask("reachable_vuln", json!({}));
    let got: Vec<(String, String, String, u64)> = worst(&v)
        .iter()
        .map(|f| (f["repo"].as_str().unwrap().to_string(), f["crate"].as_str().unwrap().to_string(), f["verdict"].as_str().unwrap().to_string(), f["call_sites"].as_u64().unwrap()))
        .collect();
    // web calls left-pad twice; shop calls stripe once; shop resolves left-pad and never calls it
    assert_eq!(
        got,
        vec![
            (WEB.to_string(), "left_pad".to_string(), "refuse".to_string(), 2),
            (SHOP.to_string(), "stripe".to_string(), "refuse".to_string(), 1),
            (SHOP.to_string(), "left_pad".to_string(), "hold".to_string(), 0),
        ]
    );
    assert_eq!(state(&v), "complete", "{v}");
    assert!(note(&v).contains("OWN code"), "the direct-use bound is said: {}", note(&v));
    // the svg rides the same answer when a door asks for it
    let svg = ws.ask("reachable_vuln", json!({ "repo": SHOP, "svg": true }));
    assert!(svg["svg"].as_str().is_some_and(|s| s.contains("<svg") && s.contains("stripe")), "{svg}");
}

// ── generic_cost / binary_drift: Build Thing's filings, never the room's links ─

/// The fixture room LINKS an artifact (its binary stream: mono instances,
/// sizes, an injected symbol), and no Build Thing run filed one: the binary
/// lenses read what builder 2 filed and nothing else, so they say no build
/// filed one — the room's linked artifact (`<builds>/mimir_v2/artifacts`) is
/// not read at all. Their answers from filed builds: `built_tests`.
#[test]
fn the_binary_lenses_read_no_linked_room_artifact_only_what_build_thing_filed() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    for lens in ["generic_cost", "binary_drift"] {
        let v = ws.ask(lens, json!({ "repo": SHOP }));
        assert_eq!(state(&v), "empty_gap", "{v}");
        assert!(worst(&v).is_empty(), "{v}");
        assert!(note(&v).contains("no Build Thing run has filed an artifact for `shop` yet: ⚒ Build it"), "{}", note(&v));
        assert!(!note(&v).contains("binary stream ["), "the room's binary stream is not read: {}", note(&v));
        assert_eq!(v["lens_meta"]["room_scope"], Value::Null, "no room was opened: {v}");
    }
    let d = ws.ask("binary_drift", json!({ "repo": SHOP }));
    assert!(d["attestation"].as_str().unwrap().contains("UNKNOWN"), "{d}");
    assert_eq!(ws.ask("generic_cost", json!({}))["report_kind"], "bloat");
}

// ── name_collision / symbol_identity: the ids the fold merged ───────────────

#[test]
fn name_collision_counts_the_edges_into_a_merged_id_beside_the_leaf_baseline() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    let v = ws.ask("name_collision", json!({}));
    // `open` does not collide here; the fixture's one repeated key is cart::helper, which nobody calls
    let w = worst(&v);
    assert_eq!(w.len(), 1, "{v}");
    assert_eq!((w[0]["name"].as_str(), w[0]["distinct_defs"].as_u64(), w[0]["conflated_edges"].as_u64()), (Some("shop::cart::helper"), Some(2), Some(0)), "{v}");
    assert_eq!((v["conflated_edges"].as_u64(), v["unresolved_edges"].as_u64()), (Some(0), Some(0)));
    assert_eq!(v["conflation_pct"], 0.0);
    // every CALLS edge out of the workspace's own code was seen
    assert_eq!(v["edges_seen"].as_u64(), feed(&v, "code_edges:CALLS")["rows"].as_u64());
    assert_eq!(state(&v), "complete");
}

#[test]
fn symbol_identity_names_the_id_one_unit_wrote_twice() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    let v = ws.ask("symbol_identity", json!({ "repo": SHOP }));
    assert_eq!(v["verdict"], "unsound", "{v}");
    assert_eq!(v["ambiguous_symbols"], 1);
    let w = &worst(&v)[0];
    assert_eq!((w["cause"].as_str(), w["kind"].as_str(), w["definitions"].as_u64()), (Some("repeated_key_in_unit"), Some("fn"), Some(2)), "{w}");
    assert!(w["symbol"].as_str().unwrap().ends_with("cart/helper()."), "{w}");
    assert!(w["sites"].as_array().unwrap().iter().any(|s| s == "src/cart.rs:46"), "{w}");
    assert_eq!(v["repos_with_repeated_keys"], json!([SHOP]));
    // web repeats nothing
    let web = ws.ask("symbol_identity", json!({ "repo": WEB }));
    assert_eq!((web["verdict"].as_str(), state(&web)), (Some("sound"), "empty_fact"), "{web}");
}

// ── trust: the room's (max, min) walk over local trust ──────────────────────

/// A trust value, to the thousandth (local trust is `1.0 − penalties` in floats).
fn milli(v: &Value) -> i64 {
    (v.as_f64().unwrap_or(f64::NAN) * 1000.0).round() as i64
}

fn trust_row<'a>(v: &'a Value, func: &str) -> &'a Value {
    worst(v).iter().find(|t| t["func"] == func).unwrap_or_else(|| panic!("`{func}` is not in the refuse/hold tail: {}", v["worst"]))
}

#[test]
fn trust_bottlenecks_every_chain_at_its_weakest_hop_and_names_it() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    let v = ws.ask("trust", json!({ "repo": SHOP }));
    assert_eq!(v["coverage_fed"], true, "{v}");
    // shell() calls libc system: 1.0 − 0.8 = 0.2, and a test reaches it
    let shell = trust_row(&v, "shop::pay::shell");
    assert_eq!((shell["decision"].as_str(), milli(&shell["local_trust"]), milli(&shell["inherited_trust"])), (Some("refuse"), 200, 200), "{shell}");
    assert_eq!(shell["weakest_hop"], "shop::pay::shell");
    assert!(shell["reason"].as_str().unwrap().contains("libc::system"), "{shell}");
    // charge() spawns a process: 0.5 → hold; audit() is clean but every chain to it passes charge()
    let charge = trust_row(&v, "shop::pay::charge");
    assert_eq!((charge["decision"].as_str(), milli(&charge["local_trust"])), (Some("hold"), 500), "{charge}");
    let audit = trust_row(&v, "shop::pay::audit");
    assert_eq!((audit["decision"].as_str(), milli(&audit["local_trust"]), milli(&audit["inherited_trust"])), (Some("hold"), 1000, 500), "{audit}");
    assert_eq!(audit["weakest_hop"], "shop::pay::charge", "names the hop that caps the chain: {audit}");
    assert!(audit["reason"].as_str().unwrap().contains("std::process::Command::new"), "{audit}");
    // bye() exits the process and no test reaches it: 1.0 − 0.3 − 0.2 = 0.5
    assert_eq!(milli(&trust_row(&v, "shop::pay::bye")["local_trust"]), 500);
    // the two tests are no nodes: add() — only a test calls it — is an entry of its own, clean and tested
    assert_eq!(v["nodes_seen"], 12, "{v}");
    assert!(!worst(&v).iter().any(|t| t["func"].as_str().unwrap().contains("adds_up") || t["func"].as_str().unwrap().contains("charges_once")), "{}", v["worst"]);
    // total() is clean, tested, and called by checkout(): act — not in the tail
    assert!(!worst(&v).iter().any(|t| t["func"] == "shop::cart::Cart::total"), "{}", v["worst"]);
    // this lens does not read the table edges yet, and the answer says so
    assert_eq!(state(&v), "partial");
    assert!(note(&v).contains("the sensitive-data term of local trust is NOT applied"), "{}", note(&v));
}

/// The room's bottleneck walk and the reference Dijkstra in `trust.rs` are the
/// same function: every node, same inherited trust.
#[test]
fn trust_the_rooms_walk_equals_the_reference_walk() {
    use std::collections::{BTreeMap, BTreeSet};

    use crate::mimir_lens::trust::{Trust, reference};
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    let room = ws.room.room(&mimir_room::Scope::current()).unwrap();
    let callables: Vec<u64> = ["fn", "method"]
        .iter()
        .flat_map(|k| room.mask(&mimir_room::MaskSpec { node_kinds: vec![k.to_string()], defined_only: true, origins: vec![mimir_schema::Origin::Local], ..Default::default() }).unwrap().value.ordinals().to_vec())
        .collect::<BTreeSet<u64>>()
        .into_iter()
        .collect();
    let at: BTreeMap<u64, usize> = callables.iter().enumerate().map(|(i, o)| (*o, i)).collect();
    // an arbitrary but varied local trust per node
    let local: Vec<Trust> = (0..callables.len()).map(|i| Trust([1.0, 0.2, 0.5, 0.8, 0.0][i % 5])).collect();
    let mask = room.mask_of(&callables);
    let edges = room.edges(&mimir_room::EdgeSel { kinds: vec![mimir_schema::EdgeKind::Calls], from: Some(&mask), to: Some(&mask), cap: None, heaviest_first: false }).unwrap().value.edges;
    let mut forward: BTreeMap<usize, BTreeSet<usize>> = BTreeMap::new();
    for e in &edges {
        forward.entry(at[&e.from]).or_default().insert(at[&e.to]);
    }
    let (want, _) = reference::widest_paths(&local, &forward);
    let has_caller: BTreeSet<u64> = edges.iter().filter(|e| e.from != e.to).map(|e| e.to).collect();
    let entries: Vec<u64> = callables.iter().copied().filter(|o| !has_caller.contains(o)).collect();
    let weights = mimir_room::Weights { default: Trust::ONE.weight(), set: callables.iter().zip(&local).map(|(o, t)| (*o, t.weight())).collect() };
    let got: BTreeMap<u64, u64> = room.bottleneck(&entries, &[mimir_schema::EdgeKind::Calls], &weights, Some(&mask)).unwrap().value.into_iter().collect();
    assert!(callables.len() >= 15 && edges.len() >= 10, "the fixture graph is not trivial");
    for (o, i) in &at {
        assert_eq!(got.get(o).map(|w| Trust::from_weight(*w).0), want.get(i).map(|w| w.0.0), "{}", room.display_path(*o));
    }
}

// ── trust, incremental: the kept walk advanced by the room's delta ──────────

/// The whole answer, minus the one field that may differ between two equal
/// computations (`lens_meta.ms`): what ZERO-LOSS compares.
fn sans_ms(v: &Value) -> Value {
    let mut v = v.clone();
    if let Some(meta) = v["lens_meta"].as_object_mut() {
        meta.remove("ms");
    }
    v
}

/// ZERO-LOSS: the incremental answer must EQUAL the full recompute — forget
/// the kept walk, ask again (the full path), diff everything but the timing.
fn assert_equals_full(ws: &fixture::Workspace, incremental: &Value, params: Value) {
    use crate::mimir_lens::trust::incremental as inc;
    inc::forget();
    let (f0, ..) = inc::stats();
    let full = ws.ask("trust", params);
    let (f1, ..) = inc::stats();
    assert_eq!(f1 - f0, 1, "forgetting the kept walk forces the full path");
    assert_eq!(sans_ms(incremental), sans_ms(&full), "ZERO-LOSS: the incremental answer IS the full answer");
}

/// (i) An unrelated commit (a span moves) leaves every trust input unchanged:
/// the kept walk is CARRIED forward — no bottleneck walk — and the answer
/// equals both the full recompute and the pre-commit answer.
#[test]
fn trust_carries_the_kept_walk_over_an_unrelated_commit() {
    use crate::mimir_lens::trust::incremental as inc;
    let _g = fixture::serial();
    inc::forget();
    let ws = fixture::graph_only(Without::default());
    let before = ws.ask("trust", json!({ "repo": SHOP }));
    fixture::advance_shop(&ws, fixture::Twist::Unrelated);
    let (f0, c0, a0) = inc::stats();
    let carried = ws.ask("trust", json!({ "repo": SHOP }));
    let (f1, c1, a1) = inc::stats();
    assert_eq!((f1 - f0, c1 - c0, a1 - a0), (0, 1, 0), "nothing the walk reads changed: carried, not recomputed");
    // the carried answer IS the previous answer (the room scope string moved
    // with the commit, so the envelope's scope lines differ — the reading not)
    for k in ["worst", "nodes_seen", "entry_points", "act", "hold", "refuse", "unreachable"] {
        assert_eq!(carried[k], before[k], "{k} of the carried answer is the previous answer's");
    }
    eprintln!("trust on the shop fixture ({} nodes): full {} ms · carried {} ms", before["nodes_seen"], before["lens_meta"]["ms"], carried["lens_meta"]["ms"]);
    assert_equals_full(&ws, &carried, json!({ "repo": SHOP }));
}

/// (ii) `audit()`'s impurity rises (its local trust FALLS): the decrease path
/// re-walks the forward cone only, and the new verdicts equal the full walk —
/// audit and everything downstream of it refuse at 0.2.
#[test]
fn trust_rewalks_the_cone_when_an_impurity_rises() {
    use crate::mimir_lens::trust::incremental as inc;
    let _g = fixture::serial();
    inc::forget();
    let ws = fixture::graph_only(Without::default());
    let before = ws.ask("trust", json!({ "repo": SHOP }));
    assert_eq!((milli(&trust_row(&before, "shop::pay::audit")["local_trust"])), 1000, "audit starts clean");
    fixture::advance_shop(&ws, fixture::Twist::ImpurityRises);
    let (f0, c0, a0) = inc::stats();
    let after = ws.ask("trust", json!({ "repo": SHOP }));
    let (f1, c1, a1) = inc::stats();
    assert_eq!((f1 - f0, c1 - c0, a1 - a0), (0, 0, 1), "a fallen local is ADVANCED (the cone pass), not a full walk");
    let audit = trust_row(&after, "shop::pay::audit");
    assert_eq!((audit["decision"].as_str(), milli(&audit["local_trust"]), milli(&audit["inherited_trust"])), (Some("refuse"), 200, 200), "{audit}");
    assert!(audit["reason"].as_str().unwrap().contains("libc::system"), "{audit}");
    // downstream of audit, shell keeps its 0.2 (its own shell-out already caps it)
    let shell = trust_row(&after, "shop::pay::shell");
    assert_eq!(milli(&shell["inherited_trust"]), 200, "{shell}");
    assert_equals_full(&ws, &after, json!({ "repo": SHOP }));
}

/// (iii) A new `pay::hello2()` appears, called by `checkout()`: the increase
/// path seeds the frontier at the added node and propagates — no full walk —
/// and the new node's verdict equals the full walk's (0.8: untested).
#[test]
fn trust_advances_the_frontier_when_a_new_fn_appears() {
    use crate::mimir_lens::trust::incremental as inc;
    let _g = fixture::serial();
    inc::forget();
    let ws = fixture::graph_only(Without::default());
    let before = ws.ask("trust", json!({ "repo": SHOP, "act_at": 0.9 }));
    assert!(!worst(&before).iter().any(|t| t["func"] == "shop::pay::hello2"), "{before}");
    fixture::advance_shop(&ws, fixture::Twist::NewReachable);
    let (f0, c0, a0) = inc::stats();
    let after = ws.ask("trust", json!({ "repo": SHOP, "act_at": 0.9 }));
    let (f1, c1, a1) = inc::stats();
    assert_eq!((f1 - f0, c1 - c0, a1 - a0), (0, 0, 1), "an added node is ADVANCED (the raise pass), not a full walk");
    let hello = trust_row(&after, "shop::pay::hello2");
    assert_eq!((hello["decision"].as_str(), milli(&hello["local_trust"]), milli(&hello["inherited_trust"])), (Some("hold"), 800, 800), "untested, reached through the clean checkout(): {hello}");
    assert_eq!(after["nodes_seen"].as_u64(), Some(before["nodes_seen"].as_u64().unwrap() + 1), "{after}");
    assert_equals_full(&ws, &after, json!({ "repo": SHOP, "act_at": 0.9 }));
}

// ── world_impact: Room::diff between two consumer ordinals · dependents ─────

#[test]
fn world_impact_reads_the_last_commits_change_and_who_depends_on_it() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without { second_commit: true, ..Default::default() });
    let v = ws.ask("world_impact", json!({}));
    let w = worst(&v);
    assert_eq!(w.len(), 1, "{v}");
    // shop seq 2: + hello (pub) · − bye (pub(crate)) · − refund (pub, called by web)
    assert_eq!((w[0]["world_repo"].as_str(), w[0]["crate_name"].as_str()), (Some("shop@1→2"), Some("shop")), "{v}");
    assert_eq!((w[0]["added_items"].as_i64(), w[0]["removed_items"].as_i64(), w[0]["changed_items"].as_i64()), (Some(1), Some(2), Some(0)), "{v}");
    assert_eq!((w[0]["breaking"].as_bool(), w[0]["suggested_bump"].as_str()), (Some(true), Some("major")), "a removed PUBLIC item: {v}");
    assert_eq!(w[0]["world_callers"], json!([WEB]), "web still calls the removed refund(): {v}");
    // web has one commit: said; the ring and the dep graph are missing: said
    assert!(note(&v).contains("repo `web` has ONE consumed commit"), "{}", note(&v));
    assert!(note(&v).contains("P5") && note(&v).contains("dep_graph_edges"), "{}", note(&v));
    assert_eq!(state(&v), "partial");
    // one commit everywhere: no window, an empty gap
    let one = fixture::graph_only(Without::default());
    let o = one.ask("world_impact", json!({}));
    assert_eq!(state(&o), "empty_gap", "{o}");
    assert!(note(&o).contains("no repo of the request has two consumed commits"), "{}", note(&o));
}

/// **A repo's commit window is folded once per (repo, seq).** Two as-of rooms
/// per repo per ask made `world_impact` 39.4 s on every call on dwarf (15
/// windows, 30 uncached rooms); the change between seq N−1 and N never changes
/// once computed, so the second ask folds no as-of room at all.
#[test]
fn world_impact_folds_a_window_once_per_repo_and_seq() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without { second_commit: true, ..Default::default() });
    let before = super::graph::uncached_builds();
    let a = ws.ask("world_impact", json!({}));
    assert_eq!(super::graph::uncached_builds() - before, 2, "one window (shop 1→2): two as-of rooms");
    let b = ws.ask("world_impact", json!({ "limit": 7 }));
    assert_eq!(super::graph::uncached_builds() - before, 2, "asked again: the window (shop, 2) is kept");
    assert_eq!(a["worst"], b["worst"], "the kept window answers the same");
    assert_eq!(b["worst"][0]["world_callers"], json!([WEB]), "who depends on it is read from the current room: {b}");
}

/// **The window from the READ-FAST zone: no as-of room.** With the zone
/// materialized, world_impact reads the commit window from the interval rows
/// and folds no room — and answers exactly what the two folded rooms answer
/// (the shop without a binary stream; with one, the rooms are folded).
#[test]
fn world_impact_reads_the_window_from_the_read_fast_zone_without_a_fold() {
    let _g = fixture::serial();
    let folded = fixture::graph_only(Without { second_commit: true, binary: true, ..Default::default() });
    let before = super::graph::uncached_builds();
    let a = folded.ask("world_impact", json!({}));
    assert_eq!(super::graph::uncached_builds() - before, 2, "no zone: two as-of rooms");
    let ws = fixture::graph_only(Without { second_commit: true, binary: true, ..Default::default() });
    let log = ws.room.log().unwrap();
    for repo in [SHOP, WEB] {
        log.block_on(log.materialize(repo)).unwrap();
    }
    let before = super::graph::uncached_builds();
    let b = ws.ask("world_impact", json!({}));
    assert_eq!(super::graph::uncached_builds() - before, 0, "the zone answers the window: no as-of room");
    assert_eq!(a["worst"], b["worst"], "the same changes, callers and rank");
    assert_eq!((a["changes_seen"].as_u64(), a["breaking_changes"].as_u64()), (b["changes_seen"].as_u64(), b["breaking_changes"].as_u64()));
    // a binary stream joins a node's rows: the zone declines and the rooms are folded
    let linked = fixture::graph_only(Without { second_commit: true, ..Default::default() });
    let log = linked.room.log().unwrap();
    for repo in [SHOP, WEB] {
        log.block_on(log.materialize(repo)).unwrap();
    }
    let before = super::graph::uncached_builds();
    let c = linked.ask("world_impact", json!({}));
    assert_eq!(super::graph::uncached_builds() - before, 2, "binary stream: two as-of rooms");
    assert!(!worst(&c).is_empty(), "{c}");
}

// ── subclone: source text + the room's item spans ───────────────────────────

#[cfg(feature = "vector")]
#[test]
fn subclone_gets_its_item_spans_from_the_room() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    // the checkout beside the warehouse root: two files with one shared 24-line run each inside a fn
    let body: String = (0..24).map(|i| format!("    let v{i} = input.iter().map(|x| x * {i} + offset_{i}(x)).filter(|y| *y > {i}).count();\n")).collect();
    let src = |name: &str, lead: &str| format!("{lead}pub fn {name}(input: &[u64]) -> usize {{\n{body}    v0 + v23\n}}\n");
    let root = ws.builds().parent().unwrap().join("git").join(SHOP).join("src");
    std::fs::create_dir_all(&root).unwrap();
    // the fixture room places `charge` at src/pay.rs 5–20 and `checkout` at src/lib.rs 10–20
    std::fs::write(root.join("pay.rs"), src("charge", "\n\n\n\n")).unwrap();
    std::fs::write(root.join("lib.rs"), src("checkout", "\n\n\n\n\n\n\n\n\n")).unwrap();
    std::fs::write(root.join("notes.rs"), "// a file the consumed configuration never compiled\npub fn stray() {}\n").unwrap();

    let v = ws.ask("subclone", json!({ "repo": SHOP }));
    assert_eq!((v["scanned"].as_bool(), v["files_scanned"].as_u64()), (Some(true), Some(3)), "{v}");
    // the two files the room has spans for are judged; the third is counted span-less, with the reason
    assert_eq!(v["files_without_spans"], 1, "{v}");
    assert!(note(&v).contains("the code room holds no span in them"), "{}", note(&v));
    assert_eq!(v["findings_total"], 1, "{v}");
    assert_eq!(v["groups_r6_unjudged"], 0, "both sites lie in a callable body the room names: {v}");
    assert_eq!(state(&v), "partial");

    // without a room the lens still scans — span-less, and says why
    let no_room = crate::mimir_lens::answer("subclone", &crate::code_room::Reach { room: None, warehouse: Some(&ws.warehouse) }, &json!({ "repo": SHOP }));
    assert_eq!((no_room["scanned"].as_bool(), no_room["files_without_spans"].as_u64()), (Some(true), Some(3)), "{no_room}");
    assert!(note(&no_room).contains("no_room"), "{}", note(&no_room));
    // and without a repo it refuses, naming the ones it can scan
    let refused = ws.ask("subclone", json!({}));
    assert_eq!((refused["scanned"].as_bool(), state(&refused)), (Some(false), "invalid_argument"), "{refused}");
    assert_eq!(refused["repos_available"], json!([SHOP]));
}

// ── data_reach: TOUCHES_TABLE + CALLS backwards ─────────────────────────────

fn reach_row<'a>(v: &'a Value, table: &str, accessor: &str) -> &'a Value {
    worst(v).iter().find(|r| r["table"] == table && r["accessor_fn"] == accessor).unwrap_or_else(|| panic!("no row {table} / {accessor} in {}", v["worst"]))
}

#[test]
fn data_reach_says_which_code_reaches_which_table_and_how() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    let v = ws.ask("data_reach", json!({ "repo": SHOP }));
    assert_eq!(state(&v), "complete", "{v}");
    assert!(feed(&v, "code_edges:TOUCHES_TABLE")["rows"].as_u64().unwrap() >= 5, "{}", v["feeds"]);
    // four (table, fn) edges with a known table, three tables, two of them sensitive by name
    assert_eq!((v["access_edges_seen"].as_u64(), v["tables_seen"].as_u64(), v["leak_paths_seen"].as_u64()), (Some(4), Some(3), Some(2)), "{v}");
    assert_eq!(v["sensitive_tables"], json!(["audit_log", "payment_tokens"]));

    // the direct touch: access, sites, and the fn by its path
    let audit = reach_row(&v, "audit_log", "shop::pay::audit");
    assert_eq!((audit["access"].as_str(), audit["sensitivity"].as_str(), audit["site_count"].as_u64()), (Some("write"), Some("audit-pii"), Some(2)), "{audit}");
    assert_eq!(audit["sites"], json!(["src/pay.rs:25", "src/pay.rs:27"]));
    // reachability over CALLS, backwards: charge calls audit, checkout and the test call charge
    assert_eq!(audit["reachers"], json!(["shop::checkout", "shop::pay::charge", "shop::pay::charges_once"]), "{audit}");
    assert_eq!((audit["reach_breadth"].as_u64(), audit["public_entry"].as_bool()), (Some(3), Some(true)));
    let charge = reach_row(&v, "payment_tokens", "shop::pay::charge");
    assert_eq!((charge["access"].as_str(), charge["sensitivity"].as_str(), charge["reach_breadth"].as_u64()), (Some("write"), Some("credential"), Some(2)), "{charge}");
    let open = reach_row(&v, "orders", "shop::cart::open");
    assert_eq!((open["access"].as_str(), open["sensitivity"].as_str()), (Some("read"), Some("")), "{open}");
    assert_eq!(open["reachers"], json!(["shop::cart::Cart::total", "shop::cart::tests::adds_up", "shop::checkout"]), "{open}");
    // a fn nobody calls and nobody outside the crate can name: no reacher, no public entry
    let dead = reach_row(&v, "orders", "shop::pay::dead");
    assert_eq!((dead["access"].as_str(), dead["reach_breadth"].as_u64(), dead["public_entry"].as_bool()), (Some("both"), Some(0), Some(false)), "{dead}");

    // the ranking: sensitive first (the wider reach of the two writes), then a write before a read
    let order: Vec<(&str, &str)> = worst(&v).iter().map(|r| (r["table"].as_str().unwrap(), r["accessor_fn"].as_str().unwrap())).collect();
    assert_eq!(order, [("audit_log", "shop::pay::audit"), ("payment_tokens", "shop::pay::charge"), ("orders", "shop::pay::dead"), ("orders", "shop::cart::open")]);

    // per table: who reads, who writes, how far it reaches
    let orders = v["tables"].as_array().unwrap().iter().find(|t| t["table"] == "orders").unwrap();
    assert_eq!((orders["readers"].as_u64(), orders["writers"].as_u64(), orders["sites"].as_u64(), orders["reach"].as_u64()), (Some(2), Some(1), Some(2), Some(5)), "{orders}");

    // the runtime-named table: counted and named, never a row of a table
    assert_eq!((v["unresolved_edges"].as_u64(), v["unresolved_sites"].as_u64()), (Some(1), Some(2)), "{v}");
    assert_eq!(v["unresolved"][0]["accessor_fn"], "shop::pay::shell");
    assert_eq!(v["unresolved"][0]["sites"], json!(["src/pay.rs:33", "src/pay.rs:35"]));
    assert!(worst(&v).iter().all(|r| r["table"] != "<unresolved>"));
    assert!(note(&v).contains("2 site(s) in 1 fn(s) touch a table whose name is not known at compile time"), "{}", note(&v));
    assert!(v["lens_meta"]["lower_bounds"].as_array().unwrap().iter().any(|b| b.as_str().unwrap().contains("closure parameter")), "{v}");
}

#[test]
fn data_reach_scope_is_the_requests_repos() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without::default());
    // every repo: web's own touch of the SAME table is a row, and web's
    // render() — which calls shop's checkout — is a reacher of shop's touches
    let all = ws.ask("data_reach", json!({}));
    assert_eq!(all["access_edges_seen"], 5, "{all}");
    assert_eq!(all["tables_seen"], 3, "two repos meet at one `orders` node: {}", all["tables"]);
    let render = reach_row(&all, "orders", "web::render");
    assert_eq!((render["repo"].as_str(), render["access"].as_str()), (Some(WEB), Some("read")), "{render}");
    let audit = reach_row(&all, "audit_log", "shop::pay::audit");
    assert!(audit["reachers"].as_array().unwrap().contains(&json!("web::render")), "{audit}");
    assert_eq!(audit["reach_breadth"], 4);
    // one repo: only its code touches, and the walk does not leave it
    let web = ws.ask("data_reach", json!({ "repo": WEB }));
    assert_eq!((web["access_edges_seen"].as_u64(), web["unresolved_sites"].as_u64()), (Some(1), Some(0)), "{web}");
    assert_eq!(worst(&web)[0]["accessor_fn"], "web::render");
    let shop = ws.ask("data_reach", json!({ "repo": SHOP }));
    assert_eq!(reach_row(&shop, "audit_log", "shop::pay::audit")["reach_breadth"], 3, "web::render is outside the scope");
}

#[test]
fn data_reach_goes_blind_without_touches_table_and_does_not_invent_a_row() {
    let _g = fixture::serial();
    let ws = fixture::graph_only(Without { touches: true, ..Default::default() });
    let v = ws.ask("data_reach", json!({ "repo": SHOP }));
    assert!(worst(&v).is_empty(), "{v}");
    assert_eq!((v["access_edges_seen"].as_u64(), v["tables_seen"].as_u64(), v["unresolved_sites"].as_u64()), (Some(0), Some(0), Some(0)), "{v}");
    // this lake was created with the `access` column: every edge row was
    // written by a producer that writes TOUCHES_TABLE, so none is a FACT
    assert_eq!(state(&v), "empty_fact", "{v}");
    assert_eq!(feed(&v, "code_edges:TOUCHES_TABLE")["rows"], 0);
    assert_eq!(feed(&v, "code_edges:TOUCHES_TABLE")["missing"], false);
}

// ── the lenses that wait for a producer ─────────────────────────────────────

#[test]
fn no_lens_waits_for_a_producer_any_more() {
    // data_reach reads the driver's TOUCHES_TABLE edges, the two vector lenses
    // read one vector per function node: the `not_wired` list is empty, and
    // `every_lens_answers_the_envelope…` below holds every lens to that
    assert!(crate::mimir_lens::WAITING.is_empty(), "a lens waits for a producer again: {:?}", crate::mimir_lens::WAITING);
}

#[test]
fn every_lens_answers_the_envelope_and_none_is_left_on_the_generic_stub() {
    let _g = fixture::serial();
    let ws = fixture::workspace();
    for lens in crate::mimir_lens::LENSES {
        let v = ws.ask(lens, json!({ "repo": SHOP }));
        assert_eq!(v["kind"], *lens);
        assert!(v["worst"].is_array() && v["feeds"].is_array(), "{lens}: {v}");
        assert!(!note(&v).is_empty(), "{lens}");
        let waiting = crate::mimir_lens::WAITING.iter().any(|(l, _)| l == lens);
        assert_eq!(state(&v) == "not_wired", waiting, "{lens}: {}", state(&v));
        // the vector lenses are wired; nobody embedded this fixture — graph
        // first, they answer from the graph and say the embedding index added nothing
        if ["similar_code", "same_intent", "semantic_twins"].contains(lens) {
            if !cfg!(feature = "vector") {
                assert_eq!(state(&v), "not_linked", "{lens}: {v}");
            } else {
                // (`semantic_twins` reads the bodies' shapes too: this fixture has none — a gap of its own)
                assert!(["complete", "empty_fact", "empty_gap"].contains(&state(&v)), "{lens}: {v}");
                assert!(state(&v) != "empty_gap" || !v["lens_meta"]["gaps"].to_string().contains("vector"), "{lens}: no vector is no gap: {v}");
                assert!(note(&v).contains("the embedding index added nothing"), "{lens}: {}", note(&v));
            }
            continue;
        }
        if !waiting {
            assert!(["complete", "partial", "empty_fact", "empty_gap"].contains(&state(&v)), "{lens}: {}", state(&v));
            // the lenses that read no room (`git_heat_facts`, Build Thing's filings) carry no room scope
            assert!(v["lens_meta"]["room_scope"].as_str().is_some() || crate::mimir_lens::ROOMLESS.contains(lens), "{lens}: no room scope");
        }
    }
}

// ── a real lake ─────────────────────────────────────────────────────────────

/// **The real-repo instrument.** Ask every lens against a lake a consumer
/// wrote for a real repo, and print per lens: state, rows, time, the top three
/// findings and the evidence note. `#[ignore]`d — it reads a lake outside the
/// tree:
///
/// ```text
/// MIMIR_PROOF_BUILDS=<builds dir holding mimir_v2/lake> [MIMIR_PROOF_REPO=<repo>] [MIMIR_PROOF_CHECKOUT=<git checkout>] \
///   cargo test --lib real_lake_every_lens -- --ignored --nocapture
/// ```
///
/// With `MIMIR_PROOF_CHECKOUT` set and no `git_heat_facts` in the warehouse
/// yet, the checkout's git history is scanned into it first (the P7 trigger,
/// run by hand).
#[test]
#[ignore = "reads a real lake: set MIMIR_PROOF_BUILDS"]
fn real_lake_every_lens() {
    let builds = std::path::PathBuf::from(std::env::var("MIMIR_PROOF_BUILDS").expect("MIMIR_PROOF_BUILDS"));
    let repo = std::env::var("MIMIR_PROOF_REPO").unwrap_or_default();
    let warehouse = crate::warehouse::iceberg::IcebergWarehouse::open(&builds).unwrap();
    if let Ok(checkout) = std::env::var("MIMIR_PROOF_CHECKOUT")
        && warehouse.scan_preview("git_heat_facts", 1).map(|p| p.rows.is_empty()).unwrap_or(true)
    {
        let scan = crate::knowledge::git_heat::scan_repo(std::path::Path::new(&checkout), &repo, uuid::Uuid::new_v4(), chrono::Utc::now()).unwrap();
        println!("git heat: {} files of {checkout} scanned into {}", scan.files.len(), builds.display());
        warehouse.append_git_heat_scan(&scan).unwrap();
    }
    let room = crate::code_room::CodeRoom::new("proof", &builds);
    let reach = crate::code_room::Reach::new(&room, &warehouse);
    let t = std::time::Instant::now();
    let opened = room.room(&mimir_room::Scope::current()).unwrap();
    let stats = opened.stats();
    println!("room: {} — {} nodes, {} symbols, opened in {} ms (build {:?})", stats.scope, stats.nodes, stats.symbols, t.elapsed().as_millis(), stats.build);
    println!("edges: {:?}", stats.edges);
    let mut names: Vec<&str> = crate::mimir_lens::LENSES.to_vec();
    names.extend(crate::mimir_lens::SOURCE_LENSES);
    let mut out = serde_json::Map::new();
    for lens in names {
        let t = std::time::Instant::now();
        let v = crate::mimir_lens::answer(lens, &reach, &json!({ "repo": repo, "limit": 10 }));
        let ms = t.elapsed().as_millis();
        let rows = v["worst"].as_array().map_or(0, Vec::len);
        println!("\n=== {lens}: state {} · {rows} row(s) shown · {ms} ms", state(&v));
        let head: serde_json::Map<String, Value> = v.as_object().unwrap().iter().filter(|(k, x)| !x.is_array() && !x.is_object() && !["evidence_note", "model_attribution", "kind", "report_kind", "svg"].contains(&k.as_str())).map(|(k, x)| (k.clone(), x.clone())).collect();
        println!("    {}", serde_json::to_string(&head).unwrap());
        for row in v["worst"].as_array().into_iter().flatten().take(3) {
            let mut row = row.clone();
            if let Some(o) = row.as_object_mut() {
                o.remove("evidence_note");
                o.remove("explain");
            }
            println!("    · {row}");
        }
        println!("    note: {}", note(&v));
        out.insert(lens.to_string(), v);
    }
    if let Ok(path) = std::env::var("MIMIR_PROOF_OUT") {
        std::fs::write(&path, serde_json::to_string_pretty(&Value::Object(out)).unwrap()).unwrap();
        println!("\nfull answers: {path}");
    }
}