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/fixture.rs

//! The lens fixture: a hand-built workspace written through mimir-ingest's own
//! consumer (a scratch git repo + a scripted dumper emitting real mimir-schema
//! rows), plus the warehouse tables the lenses join — so a lens test reads
//! exactly what production reads.
//!
//! repo `shop`, crate shop@0.1.0 — units `lib` and `lib+test`, one artifact:
//!
//! ```text
//! shop                        src/lib.rs
//! ├─ checkout()        10–20  pub, no doc     CALLS Cart::total · charge ×3 · wrap
//! ├─ cart/                    src/cart.rs
//! │  ├─ Cart                  pub, documented
//! │  ├─ impl Cart
//! │  │  ├─ add()        9–14  pub, documented
//! │  │  └─ total()     16–22  pub, no doc     CALLS cart::open
//! │  ├─ open()         40–44  private
//! │  ├─ helper()       46–47  the dump repeats this key (two payloads)
//! │  └─ tests/ adds_up()      #[test]  CALLS add ×2 · total   TESTS add · total
//! ├─ pay/                     src/pay.rs
//! │  ├─ charge()        5–20  pub, no doc, cfg(feature = "stripe")
//! │  │                        CALLS stripe Client::send · audit ×2 · std process Command::new
//! │  ├─ audit()        22–30  private; holds `cfg!(feature = "trace")`   CALLS libc_write · shell
//! │  ├─ shell()        32–36  private         CALLS libc system (ffi)
//! │  ├─ bye()          38–39  pub(crate); holds `cfg!(feature = "trace")`   CALLS std process::exit   (nobody calls it)
//! │  ├─ refund()       56–58  pub, no doc, #[doc(hidden)]     (called from repo `web` only)
//! │  ├─ dead()         50–52  cfg(feature = "unused")                      (nobody calls it)
//! │  ├─ old_charge()   54     COMPILED OUT: cfg(feature = "legacy")
//! │  ├─ charges_once()        #[test]  CALLS charge   TESTS charge
//! │  └─ libc_write()   48     ffi
//! └─ util/ wrap<T>()          src/util.rs  `util` is #[doc(hidden)]; generic; linked twice: wrap<u32> 100 B, wrap<u64> 60 B
//! tables:   charge WRITES payment_tokens (pay.rs:9) · audit WRITES audit_log ×2 (pay.rs:25, 27)
//!           cart::open READS orders (cart.rs:42) · dead READS+WRITES orders (pay.rs:51)
//!           shell READS a table named at runtime ×2 (pay.rs:33, 35)
//! features: stripe (built) · trace (built) · unused (built) · legacy (declared, NEVER built)
//! binary only: shop::injected() 77 B (no source item) · drop glue of Cart 24 B
//! ```
//!
//! repo `web`, crate web@0.2.0: `render()` CALLS shop checkout · shop refund (stubs) · left_pad pad;
//! READS orders (lib.rs:5) — the same table node as shop's.
//!
//! [`Without::second_commit`]: shop's seq 2 removes `bye()` and `refund()` and adds `hello()` (pub).
//!
//! warehouse: `git_heat_facts` (src/pay.rs hot), `sbom_components` (shop: stripe
//! 2.0.0, left-pad 1.0.0, serde 1.0.0; web: left-pad 1.0.0), `vuln_findings` (stripe
//! 2.0.0, left-pad 1.0.0), three bench runs of shop with test outcomes.

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

use mimir_ingest::{BinaryDump, CommitDump, Consumer, CrateDump, Dumper, RepoSpec};
use mimir_schema::{EdgeKind, EdgeRow, Level, NodeRow, Origin, Provenance, SPAN_EDGE, SPAN_NODE, SpanRow, SymbolRow, edge_key, moniker, role};

use crate::code_room::CodeRoom;
use crate::warehouse::iceberg::{IcebergWarehouse, SbomComponentRow, VulnFinding};

/// Real source text + spans that point at it: the per-function vectors.
#[cfg(feature = "vector")]
pub mod vectors;
#[cfg(feature = "vector")]
pub mod clones;
/// Cosine-only look-alikes that are families, tests and one-liners: the embedding index's gates.
#[cfg(feature = "vector")]
pub mod trivial;
/// The compiled facts below a function: `group_twins` on the graph.
#[cfg(feature = "vector")]
pub mod groups;

pub const SHOP: &str = "shop";
pub const WEB: &str = "web";
const LIB: &str = "shop@0.1.0:lib";
const TEST: &str = "shop@0.1.0:lib+test";
const ARTIFACT: &str = "shop@x86_64-fixture:dev";

/// A shop moniker from its descriptors.
pub fn m(d: &str) -> String {
    moniker::moniker("shop", "0.1.0", d)
}

pub const CRATE: &str = "crate/";
pub const CHECKOUT: &str = "checkout().";
pub const CART: &str = "cart/";
pub const CART_T: &str = "cart/Cart#";
pub const IMPL: &str = "cart/impl#[Cart]";
pub const ADD: &str = "cart/impl#[Cart]add().";
pub const TOTAL: &str = "cart/impl#[Cart]total().";
pub const CART_OPEN: &str = "cart/open().";
pub const HELPER: &str = "cart/helper().";
pub const TESTS_MOD: &str = "cart/tests/";
pub const ADDS_UP: &str = "cart/tests/adds_up().";
pub const PAY: &str = "pay/";
pub const CHARGE: &str = "pay/charge().";
pub const AUDIT: &str = "pay/audit().";
pub const SHELL: &str = "pay/shell().";
pub const BYE: &str = "pay/bye().";
pub const DEAD: &str = "pay/dead().";
pub const REFUND: &str = "pay/refund().";
pub const CHARGES: &str = "pay/charges_once().";
pub const WRITE: &str = "pay/libc_write().";
pub const UTIL: &str = "util/";
pub const WRAP: &str = "util/wrap().";
pub const INJECTED: &str = "injected().";

fn feature(name: &str) -> String {
    moniker::feature("shop", "0.1.0", name)
}
fn old_charge() -> String {
    moniker::cfg_gated_out(&m(PAY), "old_charge().", "feature = \"legacy\"")
}
fn stripe_crate() -> String {
    moniker::crate_moniker("stripe", "2.0.0")
}
fn send() -> String {
    moniker::moniker("stripe", "2.0.0", "impl#[Client]send().")
}
fn std_m(d: &str) -> String {
    moniker::moniker("std", &moniker::lang_version("std"), d)
}
fn command_new() -> String {
    std_m("process/impl#[Command]new().")
}
fn exit() -> String {
    std_m("process/exit().")
}
fn system() -> String {
    moniker::moniker("libc", "0.2.190", "system().")
}
fn web_crate() -> String {
    moniker::crate_moniker("web", "0.2.0")
}
fn render() -> String {
    moniker::moniker("web", "0.2.0", "render().")
}
fn pad() -> String {
    moniker::moniker("left-pad", "1.0.0", "pad().")
}
fn wrap_u32() -> String {
    moniker::mono_instance(&m(WRAP), "shop::util::wrap::<u32>")
}
fn wrap_u64() -> String {
    moniker::mono_instance(&m(WRAP), "shop::util::wrap::<u64>")
}
pub const ORDERS: &str = "orders";
pub const PAYMENT_TOKENS: &str = "payment_tokens";
pub const AUDIT_LOG: &str = "audit_log";

/// The node every dump writes for a table it touches.
fn table_node(name: &str) -> N {
    N(NodeRow::new(moniker::table(name), mimir_schema::kind::TABLE, Level::Item, name, moniker::TABLE_PACKAGE, moniker::TABLE_VERSION, Origin::Local))
}

fn touch(from: &str, table: &str, access: mimir_schema::Access, count: u32) -> EdgeRow {
    EdgeRow { access: Some(access), count, ..EdgeRow::new(from, moniker::table(table), EdgeKind::TouchesTable) }
}

fn touch_site(from: &str, table: &str, file: &str, line: u32) -> SpanRow {
    site(from, &moniker::table(table), EdgeKind::TouchesTable, file, line)
}

fn drop_cart() -> String {
    moniker::moniker("shop", "0.1.0", "`drop_in_place<shop::cart::Cart>`().")
}

struct N(NodeRow);

fn n(id: String, kind: &str, level: Level, name: &str, parent: Option<String>) -> N {
    let (krate, version) = moniker::parse(&id).map(|(p, v, _)| (p.to_string(), v.to_string())).unwrap_or(("extern".into(), "0".into()));
    let mut row = NodeRow::new(id, kind, level, name, krate, version, Origin::Local);
    row.parent = parent;
    N(row)
}

impl N {
    fn cfg(mut self, c: &str) -> Self {
        self.0.cfg = Some(c.into());
        self
    }
    fn test(mut self) -> Self {
        self.0.is_test = true;
        self
    }
    fn ty(mut self, t: &str) -> Self {
        self.0.ty = Some(t.into());
        self
    }
    /// A reference stub of a dependency / std item.
    fn stub(mut self, origin: Origin) -> Self {
        self.0.defined_here = false;
        self.0.origin = origin;
        self
    }
    /// Nominal visibility, rustc's effective visibility, and whether it has a doc comment.
    fn vis(mut self, nominal: &str, effective: mimir_schema::EffectiveVisibility, doc: bool) -> Self {
        self.0.visibility = Some(nominal.into());
        self.0.effective_visibility = Some(effective);
        self.0.has_doc = Some(doc);
        self.0.doc = doc.then(|| "A documented item.".to_string());
        self.0.doc_hidden = Some(false);
        self
    }
    /// `#[doc(hidden)]` on the item.
    fn hidden(mut self) -> Self {
        self.0.doc_hidden = Some(true);
        self
    }
    fn declared(mut self, yes: bool) -> Self {
        self.0.defined_here = yes;
        self
    }
}

fn item(d: &str, kind: &str, name: &str, parent: &str) -> N {
    n(m(d), kind, Level::Item, name, Some(m(parent)))
}

fn e(from: &str, to: &str, kind: EdgeKind, count: u32) -> EdgeRow {
    EdgeRow { count, ..EdgeRow::new(from, to, kind) }
}

fn gated(from: &str, feature_name: &str, partial: bool, negated: bool) -> EdgeRow {
    EdgeRow { partial: Some(partial), negated: Some(negated), ..EdgeRow::new(from, feature(feature_name), EdgeKind::GatedBy) }
}

fn span(id: &str, file: &str, start: u32, end: u32) -> SpanRow {
    SpanRow { target: SPAN_NODE, key: id.into(), file: file.into(), start_line: start, end_line: end }
}

fn site(from: &str, to: &str, kind: EdgeKind, file: &str, line: u32) -> SpanRow {
    SpanRow { target: SPAN_EDGE, key: edge_key(from, to, kind), file: file.into(), start_line: line, end_line: line }
}

fn unit(owner: &str, nodes: Vec<N>, edges: Vec<EdgeRow>, spans: Vec<SpanRow>) -> CrateDump {
    let rows: Vec<NodeRow> = nodes.into_iter().map(|n| n.0).collect();
    CrateDump {
        krate: owner.into(),
        universe: false,
        nodes: vec![mimir_schema::nodes_batch(&rows).unwrap()],
        edges: vec![mimir_schema::edges_batch(&edges).unwrap()],
        spans: vec![mimir_schema::spans_batch(&spans).unwrap()],
    }
}

/// What a test can switch off in the dump, to prove a lens reads its feed.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Without {
    /// No CALLS edge into the impure std / libc items.
    pub impure_calls: bool,
    /// No ENABLES edge from the crate node (nothing says what was built).
    pub enables: bool,
    /// No binary stream at all.
    pub binary: bool,
    /// Shop gets a second commit: `pay::bye` and `pay::refund` go, `pay::hello` comes.
    pub second_commit: bool,
    /// No TOUCHES_TABLE edge and no table node (no fn touches a table).
    pub touches: bool,
}

/// One MORE consumed shop commit ([`advance_shop`]), twisting exactly one
/// thing the trust walk reads (or, for [`Twist::Unrelated`], nothing it reads).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Twist {
    /// `checkout()`'s span grows a line: the room moves, the trust graph does not.
    Unrelated,
    /// `audit()` gains a raw `libc::system` call: its local trust FALLS (1.0 → 0.2).
    ImpurityRises,
    /// A new `pay::hello2()` appears, called by `checkout()`: a node and an
    /// edge are ADDED, reachable from the entry surface, untested.
    NewReachable,
    /// [`Twist::NewReachable`], and `hello2()` also calls `cart::open()` (it
    /// reads `orders`): the table gains a reacher.
    NewTableReacher,
    /// `total()` no longer calls `cart::open()`: `orders` loses reachers.
    CallDropped,
}

pub const HELLO2: &str = "pay/hello2().";

fn lib(w: Without, second: bool) -> CrateDump {
    lib_t(w, second, None)
}

fn lib_t(w: Without, second: bool, twist: Option<Twist>) -> CrateDump {
    use EdgeKind::*;
    use mimir_schema::EffectiveVisibility as Eff;
    let mut nodes = vec![
        n(m(CRATE), "crate", Level::Crate, "shop", None),
        item(CHECKOUT, "fn", "checkout", CRATE).vis("pub", Eff::Direct, false),
        n(m(CART), "mod", Level::Module, "cart", Some(m(CRATE))),
        item(CART_T, "struct", "Cart", CART).vis("pub", Eff::Direct, true),
        item(IMPL, "impl", "_", CART),
        item(ADD, "method", "add", IMPL).vis("pub", Eff::Direct, true),
        item(TOTAL, "method", "total", IMPL).vis("pub", Eff::Direct, false),
        item(CART_OPEN, "fn", "open", CART).vis("private", Eff::Internal, false),
        // the SAME key twice with two payloads: a producer collision
        item(HELPER, "fn", "helper", CART).vis("private", Eff::Internal, false),
        item(HELPER, "fn", "helper", CART).vis("private", Eff::Internal, false).ty("fn() -> u8"),
        n(m(PAY), "mod", Level::Module, "pay", Some(m(CRATE))),
        item(CHARGE, "fn", "charge", PAY).cfg("feature = \"stripe\"").vis("pub", Eff::Direct, false),
        item(AUDIT, "fn", "audit", PAY).vis("private", Eff::Internal, false),
        item(SHELL, "fn", "shell", PAY).vis("private", Eff::Internal, false),
        item(DEAD, "fn", "dead", PAY).cfg("feature = \"unused\"").vis("pub", Eff::Internal, false),
        item(WRITE, "ffi", "libc_write", PAY),
        n(old_charge(), "cfg_gated_out", Level::Item, "old_charge", Some(m(PAY))).cfg("feature = \"legacy\"").ty("fn"),
        n(m(UTIL), "mod", Level::Module, "util", Some(m(CRATE))).hidden(),
        item(WRAP, "fn", "wrap", UTIL).vis("pub", Eff::Direct, true),
        n(feature("stripe"), "feature", Level::Item, "stripe", Some(m(CRATE))),
        n(feature("trace"), "feature", Level::Item, "trace", Some(m(CRATE))),
        n(feature("unused"), "feature", Level::Item, "unused", Some(m(CRATE))),
        n(feature("legacy"), "feature", Level::Item, "legacy", Some(m(CRATE))),
        n(stripe_crate(), "crate", Level::Crate, "stripe", None).stub(Origin::Library),
        n(send(), "method", Level::Item, "send", None).stub(Origin::Library),
        n(command_new(), "method", Level::Item, "new", None).stub(Origin::Lang),
        n(exit(), "fn", Level::Item, "exit", None).stub(Origin::Lang),
        n(system(), "ffi", Level::Item, "system", None).stub(Origin::Library),
    ];
    if second {
        nodes.push(item("pay/hello().", "fn", "hello", PAY).vis("pub", Eff::Direct, false));
    } else {
        nodes.push(item(BYE, "fn", "bye", PAY).vis("pub(crate)", Eff::Internal, false));
        nodes.push(item(REFUND, "fn", "refund", PAY).vis("pub", Eff::Direct, false).hidden());
    }
    let c = |f: &str, t: &str| e(&m(f), &m(t), Contains, 1);
    let mut edges = vec![
        c(CRATE, CART),
        c(CRATE, PAY),
        c(CRATE, UTIL),
        c(CRATE, CHECKOUT),
        c(CART, CART_T),
        c(CART, IMPL),
        c(IMPL, ADD),
        c(IMPL, TOTAL),
        c(CART, CART_OPEN),
        c(CART, HELPER),
        c(PAY, CHARGE),
        c(PAY, AUDIT),
        c(PAY, SHELL),
        c(PAY, DEAD),
        c(PAY, WRITE),
        e(&m(PAY), &old_charge(), Contains, 1),
        c(UTIL, WRAP),
        e(&m(CHECKOUT), &m(TOTAL), Calls, 1),
        e(&m(CHECKOUT), &m(CHARGE), Calls, 3),
        e(&m(CHECKOUT), &m(WRAP), Calls, 1),
        e(&m(CHARGE), &send(), Calls, 1),
        e(&m(CHARGE), &m(AUDIT), Calls, 2),
        e(&m(AUDIT), &m(WRITE), Calls, 1),
        e(&m(AUDIT), &m(SHELL), Calls, 1),
        e(&m(TOTAL), &m(CART_OPEN), Calls, 1),
        e(&m(CHECKOUT), &m(CART_T), UsesType, 1),
        e(&m(IMPL), &m(CART_T), ForType, 1),
        e(&m(CRATE), &stripe_crate(), DependsOn, 1),
        gated(&m(CHARGE), "stripe", false, false),
        gated(&m(AUDIT), "trace", true, false),
        gated(&m(DEAD), "unused", false, false),
        gated(&old_charge(), "legacy", false, false),
    ];
    if second {
        edges.push(c(PAY, "pay/hello()."));
    } else {
        edges.push(c(PAY, BYE));
        edges.push(c(PAY, REFUND));
        edges.push(e(&m(BYE), &exit(), Calls, 1));
        // a `cfg!(feature = "trace")` inside bye(): the item is there either way
        edges.push(gated(&m(BYE), "trace", true, false));
    }
    if !w.impure_calls {
        edges.push(e(&m(CHARGE), &command_new(), Calls, 1));
        edges.push(e(&m(SHELL), &system(), Calls, 1));
    }
    if !w.enables {
        for f in ["stripe", "trace", "unused"] {
            edges.push(e(&m(CRATE), &feature(f), Enables, 1));
        }
    }
    if !w.touches {
        use mimir_schema::Access;
        nodes.extend([ORDERS, PAYMENT_TOKENS, AUDIT_LOG, mimir_schema::TABLE_UNRESOLVED].map(table_node));
        edges.push(touch(&m(CHARGE), PAYMENT_TOKENS, Access::Write, 1));
        edges.push(touch(&m(AUDIT), AUDIT_LOG, Access::Write, 2));
        edges.push(touch(&m(CART_OPEN), ORDERS, Access::Read, 1));
        edges.push(touch(&m(DEAD), ORDERS, Access::Both, 1));
        edges.push(touch(&m(SHELL), mimir_schema::TABLE_UNRESOLVED, Access::Read, 2));
    }
    let mut spans = vec![
        span(&m(CRATE), "src/lib.rs", 1, 40),
        span(&m(CHECKOUT), "src/lib.rs", 10, 20),
        span(&m(CART), "src/cart.rs", 1, 60),
        span(&m(CART_T), "src/cart.rs", 3, 6),
        span(&m(IMPL), "src/cart.rs", 8, 30),
        span(&m(ADD), "src/cart.rs", 9, 14),
        span(&m(TOTAL), "src/cart.rs", 16, 22),
        span(&m(CART_OPEN), "src/cart.rs", 40, 44),
        span(&m(HELPER), "src/cart.rs", 46, 47),
        span(&m(PAY), "src/pay.rs", 1, 60),
        span(&m(CHARGE), "src/pay.rs", 5, 20),
        span(&m(AUDIT), "src/pay.rs", 22, 30),
        span(&m(SHELL), "src/pay.rs", 32, 36),
        span(&m(WRITE), "src/pay.rs", 48, 48),
        span(&m(DEAD), "src/pay.rs", 50, 52),
        span(&old_charge(), "src/pay.rs", 54, 54),
        span(&m(UTIL), "src/util.rs", 1, 9),
        span(&m(WRAP), "src/util.rs", 3, 8),
        site(&m(CHECKOUT), &m(CHARGE), Calls, "src/lib.rs", 14),
        site(&m(CHECKOUT), &m(CHARGE), Calls, "src/lib.rs", 15),
        site(&m(CHECKOUT), &m(CHARGE), Calls, "src/lib.rs", 18),
        site(&m(CHARGE), &command_new(), Calls, "src/pay.rs", 12),
        site(&m(SHELL), &system(), Calls, "src/pay.rs", 34),
    ];
    if !w.touches {
        spans.push(touch_site(&m(CHARGE), PAYMENT_TOKENS, "src/pay.rs", 9));
        spans.push(touch_site(&m(AUDIT), AUDIT_LOG, "src/pay.rs", 25));
        spans.push(touch_site(&m(AUDIT), AUDIT_LOG, "src/pay.rs", 27));
        spans.push(touch_site(&m(CART_OPEN), ORDERS, "src/cart.rs", 42));
        spans.push(touch_site(&m(DEAD), ORDERS, "src/pay.rs", 51));
        spans.push(touch_site(&m(SHELL), mimir_schema::TABLE_UNRESOLVED, "src/pay.rs", 33));
        spans.push(touch_site(&m(SHELL), mimir_schema::TABLE_UNRESOLVED, "src/pay.rs", 35));
    }
    if !second {
        spans.push(span(&m(REFUND), "src/pay.rs", 56, 58));
        spans.push(span(&m(BYE), "src/pay.rs", 38, 39));
        spans.push(site(&m(BYE), &exit(), Calls, "src/pay.rs", 39));
    }
    match twist {
        None => {}
        Some(Twist::Unrelated) => {
            for s in &mut spans {
                if s.target == SPAN_NODE && s.key == m(CHECKOUT) {
                    s.end_line = 21;
                }
            }
        }
        Some(Twist::ImpurityRises) => {
            edges.push(e(&m(AUDIT), &system(), Calls, 1));
            spans.push(site(&m(AUDIT), &system(), Calls, "src/pay.rs", 29));
        }
        Some(Twist::NewReachable) | Some(Twist::NewTableReacher) => {
            nodes.push(item(HELLO2, "fn", "hello2", PAY).vis("pub", Eff::Direct, false));
            edges.push(c(PAY, HELLO2));
            edges.push(e(&m(CHECKOUT), &m(HELLO2), Calls, 1));
            spans.push(span(&m(HELLO2), "src/pay.rs", 61, 62));
            if twist == Some(Twist::NewTableReacher) {
                edges.push(e(&m(HELLO2), &m(CART_OPEN), Calls, 1));
            }
        }
        Some(Twist::CallDropped) => {
            edges.retain(|x| !(x.from == m(TOTAL) && x.to == m(CART_OPEN) && x.kind == Calls));
        }
    }
    // declared features: all four, also when nothing says which were built
    let nodes = nodes
        .into_iter()
        .map(|mut x| {
            if x.0.kind == "feature" {
                x = x.declared(true);
            }
            x
        })
        .collect();
    unit(LIB, nodes, edges, spans)
}

/// The test harness unit: the tests, and what it compiles again.
fn harness() -> CrateDump {
    use EdgeKind::*;
    let nodes = vec![
        n(m(TESTS_MOD), "mod", Level::Module, "tests", Some(m(CART))).cfg("test"),
        item(ADDS_UP, "fn", "adds_up", TESTS_MOD).test(),
        item(CHARGES, "fn", "charges_once", PAY).test(),
    ];
    let edges = vec![
        e(&m(CART), &m(TESTS_MOD), Contains, 1),
        e(&m(TESTS_MOD), &m(ADDS_UP), Contains, 1),
        e(&m(PAY), &m(CHARGES), Contains, 1),
        e(&m(ADDS_UP), &m(ADD), Calls, 2),
        e(&m(ADDS_UP), &m(TOTAL), Calls, 1),
        e(&m(CHARGES), &m(CHARGE), Calls, 1),
        e(&m(ADDS_UP), &m(ADD), Tests, 1),
        e(&m(ADDS_UP), &m(TOTAL), Tests, 1),
        e(&m(CHARGES), &m(CHARGE), Tests, 1),
    ];
    let spans = vec![span(&m(TESTS_MOD), "src/cart.rs", 49, 59), span(&m(ADDS_UP), "src/cart.rs", 50, 58), span(&m(CHARGES), "src/pay.rs", 40, 46)];
    unit(TEST, nodes, edges, spans)
}

fn sym(id: &str, symbol: &str, demangled: Option<&str>, r: &str, size: Option<u64>) -> SymbolRow {
    SymbolRow {
        id: id.into(),
        symbol: symbol.into(),
        demangled: demangled.map(str::to_string),
        role: r.into(),
        krate: "shop".into(),
        version: "0.1.0".into(),
        binary: Some("shop".into()),
        section: size.map(|_| ".text".to_string()),
        addr: size.map(|_| 0x1000),
        size,
        provenance: Provenance::BinaryOnly,
        valid_from_sha: None,
        valid_to_sha: None,
    }
}

fn artifact() -> BinaryDump {
    let bin_only = |id: String, kind: &str, name: &str, parent: Option<String>| {
        let mut row = n(id, kind, Level::Item, name, parent).0;
        row.provenance = Provenance::BinaryOnly;
        row
    };
    let nodes = vec![
        bin_only(wrap_u32(), "mono_instance", "shop::util::wrap::<u32>", Some(m(WRAP))),
        bin_only(wrap_u64(), "mono_instance", "shop::util::wrap::<u64>", Some(m(WRAP))),
        bin_only(m(INJECTED), "fn", "injected", None),
        bin_only(drop_cart(), "fn", "drop_in_place<shop::cart::Cart>", None),
    ];
    let inst = |from: String| EdgeRow { provenance: Provenance::BinaryOnly, ..EdgeRow::new(from, m(WRAP), EdgeKind::InstanceOf) };
    BinaryDump {
        artifact: ARTIFACT.into(),
        nodes: vec![mimir_schema::nodes_batch(&nodes).unwrap()],
        edges: vec![mimir_schema::edges_batch(&[inst(wrap_u32()), inst(wrap_u64())]).unwrap()],
        symbols: vec![
            mimir_schema::symbols_batch(&[
                sym(&m(CHECKOUT), "_Rcheckout", Some("shop::checkout"), role::ITEM, Some(120)),
                sym(&m(CHARGE), "_Rcharge", Some("shop::pay::charge"), role::ITEM, Some(300)),
                sym(&wrap_u32(), "_Rwrap_u32", Some("shop::util::wrap::<u32>"), role::MONO, Some(100)),
                sym(&wrap_u64(), "_Rwrap_u64", Some("shop::util::wrap::<u64>"), role::MONO, Some(60)),
                sym(&m(INJECTED), "_Rinjected", Some("shop::injected"), role::ITEM, Some(77)),
                sym(&drop_cart(), "_Rdrop_cart", Some("core::ptr::drop_in_place::<shop::cart::Cart>"), role::ITEM, Some(24)),
            ])
            .unwrap(),
        ],
        ledger: None,
        ms: 0,
    }
}

fn shop_commit(w: Without, second: bool) -> CommitDump {
    shop_commit_t(w, second, None)
}

fn shop_commit_t(w: Without, second: bool, twist: Option<Twist>) -> CommitDump {
    CommitDump {
        toolchain: "nightly-fixture".into(),
        workspace_crates: [LIB.to_string(), TEST.to_string()].into(),
        workspace_targets: ["shop:lib".to_string(), "shop:bin:shop".to_string()].into(),
        failed_units: BTreeSet::new(),
        owner_disambiguations: 0,
        crates: vec![lib_t(w, second, twist), harness()],
        binary: !w.binary,
        binaries: if w.binary { vec![] } else { vec![artifact()] },
    }
}

fn web_commit(w: Without) -> CommitDump {
    let mut nodes = vec![
        n(web_crate(), "crate", Level::Crate, "web", None),
        n(render(), "fn", Level::Item, "render", Some(web_crate())),
        item(CHECKOUT, "fn", "checkout", CRATE).stub(Origin::Library),
        item(REFUND, "fn", "refund", PAY).stub(Origin::Library),
        n(pad(), "fn", Level::Item, "pad", None).stub(Origin::Library),
    ];
    let mut edges = vec![
        e(&web_crate(), &render(), EdgeKind::Contains, 1),
        e(&render(), &m(CHECKOUT), EdgeKind::Calls, 1),
        e(&render(), &m(REFUND), EdgeKind::Calls, 1),
        e(&render(), &pad(), EdgeKind::Calls, 2),
    ];
    let mut spans = vec![span(&web_crate(), "src/lib.rs", 1, 9), span(&render(), "src/lib.rs", 3, 8)];
    if !w.touches {
        nodes.push(table_node(ORDERS));
        edges.push(touch(&render(), ORDERS, mimir_schema::Access::Read, 1));
        spans.push(touch_site(&render(), ORDERS, "src/lib.rs", 5));
    }
    CommitDump {
        toolchain: "nightly-fixture".into(),
        workspace_crates: ["web@0.2.0:lib".to_string()].into(),
        workspace_targets: ["web:lib".to_string()].into(),
        failed_units: BTreeSet::new(),
        owner_disambiguations: 0,
        crates: vec![unit("web@0.2.0:lib", nodes, edges, spans)],
        binary: false,
        binaries: vec![],
    }
}

struct Scripted(Vec<CommitDump>);

impl Dumper for Scripted {
    fn dump(&mut self, _: &Path, _: &str) -> anyhow::Result<CommitDump> {
        Ok(self.0.remove(0))
    }
}

/// A scratch repo with `n` commits that each touch a `.rs` file.
fn scratch(dir: &Path, n: usize) {
    nornir_git::gitio::init(dir).unwrap();
    for i in 0..n {
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/lib.rs"), format!("// commit {i}\n")).unwrap();
        nornir_git::gitio::commit_all(dir, &format!("c{i}")).unwrap();
    }
}

/// One workspace on disk: its code room, its warehouse, and the temp dir that holds both.
pub struct Workspace {
    pub room: CodeRoom,
    pub warehouse: IcebergWarehouse,
    _tmp: tempfile::TempDir,
    builds: PathBuf,
}

impl Workspace {
    pub fn reach(&self) -> crate::code_room::Reach<'_> {
        crate::code_room::Reach::new(&self.room, &self.warehouse)
    }

    pub fn builds(&self) -> &Path {
        &self.builds
    }

    /// Ask a lens the way a front door does.
    pub fn ask(&self, lens: &str, params: serde_json::Value) -> serde_json::Value {
        crate::mimir_lens::answer(lens, &self.reach(), &params)
    }
}

/// The room cache is per process and keyed by lake identity; fixtures in one
/// test binary still build one at a time so a slow box does not thrash it.
static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());

pub fn serial() -> std::sync::MutexGuard<'static, ()> {
    SERIAL.lock().unwrap_or_else(|e| e.into_inner())
}

fn consume(room: &CodeRoom, tmp: &Path, name: &str, commits: Vec<CommitDump>) {
    scratch(&tmp.join(format!("src-{name}")), commits.len());
    let spec = RepoSpec {
        name: name.into(),
        source: tmp.join(format!("src-{name}")).to_string_lossy().into_owned(),
        branch: "main".into(),
        worktree: room.layout().clone_of(name),
        initial_offset: None,
    };
    let log = room.log().expect("the lake opens");
    let reports = log.block_on(async {
        let mut c = Consumer::boot(log.clone(), Scripted(commits)).await.unwrap();
        c.run(&spec).await.unwrap()
    });
    assert!(reports.iter().all(|r| r.status == "ok"), "{reports:?}");
}

/// Consume one MORE shop commit into an existing workspace (built by
/// [`graph_only`] without `second_commit`), twisted for the trust lens's
/// incremental walk: the scratch repo gains a commit and the consumer resumes
/// from its offset, so the room ADVANCES exactly as production's does.
pub fn advance_shop(ws: &Workspace, twist: Twist) {
    let dir = ws._tmp.path().join(format!("src-{SHOP}"));
    std::fs::write(dir.join("src/lib.rs"), format!("// {twist:?}\n")).unwrap();
    nornir_git::gitio::commit_all(&dir, &format!("{twist:?}")).unwrap();
    let spec = RepoSpec {
        name: SHOP.into(),
        source: dir.to_string_lossy().into_owned(),
        branch: "main".into(),
        worktree: ws.room.layout().clone_of(SHOP),
        initial_offset: None,
    };
    let log = ws.room.log().expect("the lake opens");
    let reports = log.block_on(async {
        let mut c = Consumer::boot(log.clone(), Scripted(vec![shop_commit_t(Without::default(), false, Some(twist))])).await.unwrap();
        c.run(&spec).await.unwrap()
    });
    assert!(reports.iter().all(|r| r.status == "ok"), "{reports:?}");
}

/// The fixture with the room only (no warehouse rows).
pub fn graph_only(w: Without) -> Workspace {
    let tmp = tempfile::tempdir().unwrap();
    let builds = tmp.path().join("builds");
    std::fs::create_dir_all(&builds).unwrap();
    let warehouse = IcebergWarehouse::open(&builds).unwrap();
    let room = CodeRoom::new("fixture", &builds);
    let mut shop = vec![shop_commit(w, false)];
    if w.second_commit {
        shop.push(shop_commit(w, true));
    }
    consume(&room, tmp.path(), SHOP, shop);
    consume(&room, tmp.path(), WEB, vec![web_commit(w)]);
    Workspace { room, warehouse, builds, _tmp: tmp }
}

/// One generation of `git_heat_facts` for a repo: `(file, commits_total, commits_30d, commits_90d, authors)`.
pub fn heat(ws: &Workspace, repo: &str, at_micros: i64, files: &[(&str, i64, i64, i64, i64)]) {
    use crate::knowledge::git_heat::{GitHeatRow, GitHeatScan};
    let ts = chrono::DateTime::from_timestamp_micros(at_micros).unwrap();
    let scan = GitHeatScan {
        snapshot_id: uuid::Uuid::new_v4(),
        ts,
        repo: repo.into(),
        files: files
            .iter()
            .map(|(f, total, d30, d90, authors)| GitHeatRow { file: (*f).into(), commits_total: *total, commits_30d: *d30, commits_90d: *d90, authors_total: *authors, last_commit_ts: ts })
            .collect(),
    };
    ws.warehouse.append_git_heat_scan(&scan).unwrap();
}

/// One bench run of `repo` at `version` with these test outcomes `(name, passed)`.
pub fn bench_run(ws: &Workspace, repo: &str, version: &str, tests: &[(&str, bool)]) {
    let run: crate::bench::BenchRun = serde_json::from_value(serde_json::json!({
        "id": uuid::Uuid::new_v4(),
        "date": "2026-10-13",
        "version": version,
        "machine": "fixture",
        "cores": 4,
        "results": [],
        "tests": tests.iter().map(|(name, passed)| serde_json::json!({ "name": name, "passed": passed })).collect::<Vec<_>>(),
    }))
    .unwrap();
    ws.warehouse.block_on(ws.warehouse.append_bench_run_async(repo, &run)).unwrap();
}

/// The whole fixture: the room, and the warehouse tables the lenses join.
pub fn workspace() -> Workspace {
    let ws = workspace_without_runs();
    // three runs over two code versions; no test ever failed
    for version in ["0.1.0", "0.1.0", "0.1.1"] {
        bench_run(&ws, SHOP, version, &[("cart::tests::adds_up", true), ("pay::charges_once", true), ("ghost::never_compiled", true)]);
    }
    ws
}

/// [`workspace`] before any test, bench or coverage run was filed: the room, git
/// heat, the sbom and the advisories — what a real step then files into.
pub fn workspace_without_runs() -> Workspace {
    let ws = graph_only(Without::default());
    heat(&ws, SHOP, 1_000_000, &[("src/pay.rs", 40, 6, 12, 3), ("src/cart.rs", 9, 0, 2, 1), ("src/lib.rs", 20, 1, 5, 2), ("src/util.rs", 3, 0, 0, 1)]);
    heat(&ws, WEB, 1_000_000, &[("src/lib.rs", 4, 1, 3, 1)]);
    let comp = |name: &str, version: &str| SbomComponentRow { name: name.into(), version: version.into(), license: "MIT".into(), derived_from: "source".into() };
    ws.warehouse.append_sbom_components(SHOP, uuid::Uuid::new_v4(), &[comp("stripe", "2.0.0"), comp("left-pad", "1.0.0"), comp("serde", "1.0.0")]).unwrap();
    ws.warehouse.append_sbom_components(WEB, uuid::Uuid::new_v4(), &[comp("left-pad", "1.0.0")]).unwrap();
    let vuln = |name: &str, version: &str, id: &str| VulnFinding { crate_name: name.into(), version: version.into(), ids: vec![id.into()], summary: format!("{id}: upgrade"), checked_at_micros: 1 };
    ws.warehouse.append_vuln_findings(&[vuln("stripe", "2.0.0", "RUSTSEC-2026-0001"), vuln("left-pad", "1.0.0", "RUSTSEC-2026-0002")]).unwrap();
    ws
}

// ── the calibration tree ────────────────────────────────────────────────────

/// A generated source tree and the rows a driver would write for it: 24
/// modules of one crate (`plant@0.1.0`, repo `plant`), five functions each,
/// written to `<tmp>/git/plant/src/<topic>.rs`.
///
/// The text is generated so its extents are known by construction — the room
/// fixture carries exactly those spans — and shaped like code a calibration
/// can be measured on: what a function IS lives in the calls it makes, the
/// fields it reads and the types it names (kept by a rename), with few locals
/// and literals (changed by one). The three functions `settle_*`, `prune_*`,
/// `merge_*` of a topic share a parameter list, as do `audit_*` and `rank_*`:
/// same signature, different body — the hard negatives.
pub mod calibration_tree {
    use super::*;

    pub const REPO: &str = "plant";
    const TOPICS: [&str; 24] = [
        "ledger", "parcel", "sensor", "tariff", "voyage", "kernel", "lattice", "harbor", "meadow", "quarry", "beacon", "cipher", "glacier", "orchard", "turbine", "satchel", "lantern",
        "compass", "furnace", "anchor", "canyon", "ribbon", "saddle", "thicket",
    ];
    const VERBS: [&str; 5] = ["settle", "prune", "merge", "audit", "rank"];
    const STEPS: [&str; 12] = ["gate", "step", "seal", "probe", "fold", "trim", "lift", "bind", "scan", "pack", "weld", "sift"];

    fn pm(d: &str) -> String {
        moniker::moniker("plant", "0.1.0", d)
    }
    fn kit(name: &str) -> String {
        moniker::moniker("kit", "1.0.0", &format!("{name}()."))
    }
    fn cap(s: &str) -> String {
        let mut c = s.chars();
        c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default()
    }

    /// One generated function: its lines, the callees it names, its parameters.
    pub struct Generated {
        pub topic: &'static str,
        pub name: String,
        pub lines: Vec<String>,
        pub callees: Vec<String>,
        pub params: Vec<(&'static str, String)>,
    }

    /// The function `verb_topic`, deterministic in (topic, verb): five
    /// statements, each a chain of four of its OWN ten steps (calls nobody
    /// else makes), two of the topic's three shared methods and one of the
    /// topic's constants; a local per statement, a comment on the first and
    /// the last.
    pub fn function(t: usize, v: usize) -> Generated {
        const LOCALS: [&str; 12] = ["acc", "cur", "tmp", "head", "tail", "sum", "mid", "low", "high", "buf", "out", "rest"];
        const STATEMENTS: usize = 5;
        let (topic, verb) = (TOPICS[t], VERBS[v]);
        let name = format!("{verb}_{topic}");
        let ty = cap(topic);
        let mut rng = crate::mimir_calibrate::Lcg((t as u64 + 1) * 7919 + (v as u64 + 1) * 104_729);
        let mut steps: Vec<&str> = STEPS.to_vec();
        let words: Vec<&str> = (0..10).map(|_| steps.remove(rng.below(steps.len()))).collect();
        let own: Vec<String> = words.iter().map(|w| format!("{name}_{w}")).collect();
        let shared = [format!("{topic}_weight"), format!("{topic}_floor"), format!("{topic}_ratio")];
        let field = format!("{topic}_{}", ["count", "total", "limit", "span"][v % 4]);
        let mut pool: Vec<&str> = LOCALS.to_vec();
        let locals: Vec<&str> = (0..STATEMENTS).map(|_| pool.remove(rng.below(pool.len()))).collect();
        let wide = v < 3;
        let (params, head, bound): (Vec<(&'static str, String)>, String, &str) = if wide {
            (vec![("batch", format!("&{ty}")), ("limit", "usize".into())], format!("pub fn {name}(batch: &{ty}, limit: usize) -> u64 {{"), "limit as u64")
        } else {
            (vec![("batch", format!("&mut {ty}")), ("floor", "u64".into())], format!("pub fn {name}(batch: &mut {ty}, floor: u64) -> bool {{"), "floor")
        };
        let mut lines = vec![format!("/// {} the {topic} against its {field}.", cap(verb)), head];
        let mut at = 0usize;
        let mut step = || {
            at += 1;
            own[(at - 1) % own.len()].clone()
        };
        for i in 0..STATEMENTS {
            if i == 0 || i == STATEMENTS - 1 {
                lines.push(format!("    // {} {}", words[i], if i == 0 { "first" } else { "last" }));
            }
            let prev = if i == 0 { format!("batch.{field}") } else { locals[i - 1].to_string() };
            let mut expr = if i == 0 { format!("{}({prev}, {bound})", step()) } else { format!("{}({prev})", step()) };
            for _ in 1..4 {
                expr.push_str(&match rng.below(2) {
                    0 => format!(".{}()", step()),
                    _ => format!(".{}({}({prev}))", step(), step()),
                });
            }
            for j in 0..2 {
                expr.push_str(&format!(".{}()", shared[(i + j + v) % 3]));
            }
            expr.push_str(&format!(".max({ty}::{})", ["COUNT", "TOTAL", "LIMIT", "SPAN"][(i + v) % 4]));
            lines.push(format!("    let {} = {expr};", locals[i]));
        }
        let last = locals[STATEMENTS - 1];
        lines.push(if wide { format!("    {last}.{}()", shared[v % 3]) } else { format!("    {last}.{}() > floor", shared[v % 3]) });
        lines.push("}".into());
        let mut callees: Vec<String> = own.iter().chain(shared.iter()).cloned().collect();
        callees.push("max".into());
        callees.sort();
        Generated { topic, name, lines, callees, params }
    }

    /// The tree on disk, the workspace over it, and every generated function
    /// with the extent it was written at: `(file, start_line, end_line, function)`.
    pub struct Tree {
        pub ws: Workspace,
        pub checkout: std::path::PathBuf,
        pub written: Vec<(String, usize, usize, Generated)>,
    }

    pub fn build() -> Tree {
        let tmp = tempfile::tempdir().unwrap();
        let builds = tmp.path().join("builds");
        let checkout = tmp.path().join("git").join(REPO);
        std::fs::create_dir_all(checkout.join("src")).unwrap();
        std::fs::create_dir_all(&builds).unwrap();
        let mut nodes = vec![n(pm(CRATE), "crate", Level::Crate, "plant", None)];
        let mut edges: Vec<EdgeRow> = Vec::new();
        let mut spans = vec![span(&pm(CRATE), "src/lib.rs", 1, 1)];
        let mut stubs: BTreeSet<String> = BTreeSet::new();
        let mut written = Vec::new();
        for (t, topic) in TOPICS.iter().enumerate() {
            let file = format!("src/{topic}.rs");
            let module = pm(&format!("{topic}/"));
            let mut text: Vec<String> = vec![format!("//! The {topic} module."), String::new()];
            nodes.push(n(module.clone(), "mod", Level::Module, topic, Some(pm(CRATE))));
            edges.push(e(&pm(CRATE), &module, EdgeKind::Contains, 1));
            for v in 0..VERBS.len() {
                let f = function(t, v);
                let id = pm(&format!("{topic}/{}().", f.name));
                let (start, end) = (text.len() + 1, text.len() + f.lines.len());
                text.extend(f.lines.iter().cloned());
                text.push(String::new());
                nodes.push(n(id.clone(), "fn", Level::Item, &f.name, Some(module.clone())));
                edges.push(e(&module, &id, EdgeKind::Contains, 1));
                spans.push(span(&id, &file, start as u32, end as u32));
                for (p, ty) in &f.params {
                    let pid = pm(&format!("{topic}/{}().({p})", f.name));
                    nodes.push(n(pid.clone(), "param", Level::Part, p, Some(id.clone())).ty(ty));
                    edges.push(e(&id, &pid, EdgeKind::Contains, 1));
                }
                for c in &f.callees {
                    stubs.insert(c.clone());
                    edges.push(e(&id, &kit(c), EdgeKind::Calls, 1));
                }
                written.push((file.clone(), start, end, f));
            }
            spans.push(span(&module, &file, 1, text.len() as u32));
            std::fs::write(checkout.join(&file), text.join("\n") + "\n").unwrap();
        }
        for c in &stubs {
            nodes.push(n(kit(c), "fn", Level::Item, c, None).stub(Origin::Library));
        }
        let commit = CommitDump {
            toolchain: "nightly-fixture".into(),
            workspace_crates: ["plant@0.1.0:lib".to_string()].into(),
            workspace_targets: ["plant:lib".to_string()].into(),
            failed_units: BTreeSet::new(),
            owner_disambiguations: 0,
            crates: vec![unit("plant@0.1.0:lib", nodes, edges, spans)],
            binary: false,
            binaries: vec![],
        };
        let warehouse = IcebergWarehouse::open(&builds).unwrap();
        let room = CodeRoom::new("calibration", &builds);
        consume(&room, tmp.path(), REPO, vec![commit]);
        Tree { ws: Workspace { room, warehouse, builds, _tmp: tmp }, checkout, written }
    }
}

/// The system-boundary fixture: repo `net` (crate net@0.1.0) whose code
/// reaches std and a dependency, with the dependency universe dumped and
/// the boundary written (`mimir_ingest::boundary::ensure`, the generated
/// sample kernel BTF):
///
/// ```text
/// net::start()  → net::fetch()                                      (own → own)
/// net::fetch()  → hyperish::get() → std TcpStream::connect → std sys connect → libc connect ⇒ connect (network)
/// net::save()   → std fs::write → std sys open_c → libc open64      ⇒ openat (file)
/// net::sum()    → nothing                                           (pure)
/// ```
/// warehouse: `sbom_components` net: hyperish 1.0.0; `vuln_findings` hyperish 1.0.0.
pub mod boundary_ws {
    use super::*;
    use mimir_ingest::boundary;

    pub const NET: &str = "net";

    pub fn net(d: &str) -> String {
        moniker::moniker("net", "0.1.0", d)
    }
    pub fn hyper(d: &str) -> String {
        moniker::moniker("hyperish", "1.0.0", d)
    }
    pub fn libc(d: &str) -> String {
        moniker::moniker("libc", "0.2.177", d)
    }
    fn std(d: &str) -> String {
        std_m(d)
    }

    fn ring(owner: &str, nodes: Vec<N>, edges: Vec<EdgeRow>) -> CrateDump {
        let rows: Vec<NodeRow> = nodes.into_iter().map(|n| n.0).collect();
        CrateDump { krate: owner.into(), universe: true, nodes: vec![mimir_schema::nodes_batch(&rows).unwrap()], edges: vec![mimir_schema::edges_batch(&edges).unwrap()], spans: vec![] }
    }

    fn def(id: String, kind: &str, level: Level, name: &str, origin: Origin) -> N {
        let mut x = n(id, kind, level, name, None);
        x.0.origin = origin;
        x
    }

    fn ffi(sym: &str) -> N {
        let mut x = def(libc(&format!("unix/{sym}().")), "ffi", Level::Item, sym, Origin::Library);
        x.0.link_name = Some(sym.into());
        x
    }

    /// What a second `net` commit changes, for the reach lenses' kept walks.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum NetTwist {
        /// `sum()`'s span grows a line: the room moves, no edge does.
        Unrelated,
        /// `sum()` now calls `fetch()`: one function's calls change, and it
        /// reaches the network.
        SumCallsFetch,
        /// `start()` no longer calls `fetch()`: it reaches nothing.
        StartDropsFetch,
        /// `sum()` calls an `extern "C" fn getpid` of our own: the C map
        /// makes it a target (the boundary's targets move).
        OwnFfi,
        /// A dependency crate nobody had is dumped: a ring write moves the
        /// `universe_manifest`.
        NewRingCrate,
    }

    fn commit() -> CommitDump {
        commit_t(None)
    }

    fn commit_t(twist: Option<NetTwist>) -> CommitDump {
        let c = EdgeKind::Calls;
        let own_nodes = vec![
            n(net("crate/"), "crate", Level::Crate, "net", None),
            n(net("start()."), "fn", Level::Item, "start", Some(net("crate/"))),
            n(net("fetch()."), "fn", Level::Item, "fetch", Some(net("crate/"))),
            n(net("save()."), "fn", Level::Item, "save", Some(net("crate/"))),
            n(net("sum()."), "fn", Level::Item, "sum", Some(net("crate/"))),
            def(hyper("crate/"), "crate", Level::Crate, "hyperish", Origin::Library).declared(false),
            def(hyper("get()."), "fn", Level::Item, "get", Origin::Library).declared(false),
            def(std("crate/"), "crate", Level::Crate, "std", Origin::Lang).declared(false),
            def(std("fs/write()."), "fn", Level::Item, "write", Origin::Lang).declared(false),
        ];
        let mut own_edges = vec![
            e(&net("crate/"), &hyper("crate/"), EdgeKind::DependsOn, 1),
            e(&net("crate/"), &std("crate/"), EdgeKind::DependsOn, 1),
            e(&net("start()."), &net("fetch()."), c, 1),
            e(&net("fetch()."), &hyper("get()."), c, 1),
            e(&net("save()."), &std("fs/write()."), c, 1),
        ];
        let mut spans = vec![
            span(&net("start()."), "src/lib.rs", 1, 2),
            span(&net("fetch()."), "src/lib.rs", 3, 8),
            span(&net("save()."), "src/lib.rs", 10, 14),
            span(&net("sum()."), "src/lib.rs", 16, 18),
        ];
        match twist {
            None => {}
            Some(NetTwist::Unrelated) => spans[3].end_line = 19,
            Some(NetTwist::SumCallsFetch) => own_edges.push(e(&net("sum()."), &net("fetch()."), c, 1)),
            Some(NetTwist::StartDropsFetch) => own_edges.retain(|x| x.from != net("start().")),
            Some(NetTwist::OwnFfi) | Some(NetTwist::NewRingCrate) => {}
        }
        let mut own_nodes = own_nodes;
        if twist == Some(NetTwist::OwnFfi) {
            let mut x = n(net("sys/getpid()."), "ffi", Level::Item, "getpid", Some(net("crate/")));
            x.0.link_name = Some("getpid".into());
            own_nodes.push(x);
            own_edges.push(e(&net("sum()."), &net("sys/getpid()."), c, 1));
        }
        let hyperish = ring(
            "hyperish@1.0.0:lib",
            vec![def(hyper("crate/"), "crate", Level::Crate, "hyperish", Origin::Library), def(hyper("get()."), "fn", Level::Item, "get", Origin::Library), def(std("crate/"), "crate", Level::Crate, "std", Origin::Lang).declared(false)],
            vec![e(&hyper("crate/"), &std("crate/"), EdgeKind::DependsOn, 1), e(&hyper("get()."), &std("net/tcp/impl#[TcpStream]connect()."), c, 1)],
        );
        let stdc = ring(
            "std@lang:lib",
            vec![
                def(std("crate/"), "crate", Level::Crate, "std", Origin::Lang),
                def(std("fs/write()."), "fn", Level::Item, "write", Origin::Lang),
                def(std("sys/fs/impl#[File]open_c()."), "method", Level::Item, "open_c", Origin::Lang),
                def(std("net/tcp/impl#[TcpStream]connect()."), "method", Level::Item, "connect", Origin::Lang),
                def(std("sys/net/impl#[Socket]connect()."), "method", Level::Item, "connect", Origin::Lang),
                def(libc("crate/"), "crate", Level::Crate, "libc", Origin::Library).declared(false),
            ],
            vec![
                e(&std("crate/"), &libc("crate/"), EdgeKind::DependsOn, 1),
                e(&std("fs/write()."), &std("sys/fs/impl#[File]open_c()."), c, 1),
                e(&std("sys/fs/impl#[File]open_c()."), &libc("unix/open64()."), c, 1),
                e(&std("net/tcp/impl#[TcpStream]connect()."), &std("sys/net/impl#[Socket]connect()."), c, 1),
                e(&std("sys/net/impl#[Socket]connect()."), &libc("unix/connect()."), c, 1),
            ],
        );
        let libcc = ring("libc@0.2.177:lib", vec![def(libc("crate/"), "crate", Level::Crate, "libc", Origin::Library), ffi("open64"), ffi("connect"), ffi("write")], vec![]);
        CommitDump {
            toolchain: "nightly-fixture".into(),
            workspace_crates: ["net@0.1.0:lib".to_string()].into(),
            workspace_targets: ["net:lib".to_string()].into(),
            failed_units: BTreeSet::new(),
            owner_disambiguations: 0,
            crates: {
                let mut v = vec![unit("net@0.1.0:lib", own_nodes, own_edges, spans), hyperish, stdc, libcc];
                if twist == Some(NetTwist::NewRingCrate) {
                    let x = moniker::moniker("extra", "1.0.0", "crate/");
                    v.push(ring("extra@1.0.0:lib", vec![def(x, "crate", Level::Crate, "extra", Origin::Library)], vec![]));
                }
                v
            },
            binary: false,
            binaries: vec![],
        }
    }

    /// The `net` workspace; `with_boundary = false` = the universe is there,
    /// the boundary was never written.
    pub fn workspace(with_boundary: bool) -> Workspace {
        let tmp = tempfile::tempdir().unwrap();
        let builds = tmp.path().join("builds");
        std::fs::create_dir_all(&builds).unwrap();
        let warehouse = IcebergWarehouse::open(&builds).unwrap();
        let room = CodeRoom::new("fixture", &builds);
        consume(&room, tmp.path(), NET, vec![commit()]);
        if with_boundary {
            let btf = tmp.path().join("vmlinux.btf");
            std::fs::write(&btf, boundary::btf::sample_kernel()).unwrap();
            let kernel = boundary::KernelSource { path: btf, release: "6.99.0-test".into(), chosen: "configured" };
            let target = boundary::Target::parse("x86_64-unknown-linux-gnu").unwrap();
            let log = room.log().expect("the lake opens");
            let w = log.writer().unwrap();
            log.block_on(boundary::ensure(&w, &target, "nightly-fixture", Some(&kernel))).unwrap();
        }
        let comp = SbomComponentRow { name: "hyperish".into(), version: "1.0.0".into(), license: "MIT".into(), derived_from: "source".into() };
        warehouse.append_sbom_components(NET, uuid::Uuid::new_v4(), &[comp]).unwrap();
        warehouse
            .append_vuln_findings(&[VulnFinding { crate_name: "hyperish".into(), version: "1.0.0".into(), ids: vec!["RUSTSEC-2026-0099".into()], summary: "RUSTSEC-2026-0099: upgrade".into(), checked_at_micros: 1 }])
            .unwrap();
        Workspace { room, warehouse, builds, _tmp: tmp }
    }

    /// A ring write after the first asks: a commit that dumps one more
    /// dependency crate (the `universe_manifest` moves).
    pub fn write_ring_crate(ws: &Workspace) {
        advance(ws, NetTwist::NewRingCrate);
    }

    /// Consume one MORE `net` commit, twisted: the scratch repo gains a
    /// commit and the consumer resumes from its offset, so the rooms
    /// ADVANCE as production's do.
    pub fn advance(ws: &Workspace, twist: NetTwist) {
        let dir = ws._tmp.path().join(format!("src-{NET}"));
        std::fs::write(dir.join("src/lib.rs"), format!("// {twist:?}\n")).unwrap();
        nornir_git::gitio::commit_all(&dir, &format!("{twist:?}")).unwrap();
        let spec = RepoSpec {
            name: NET.into(),
            source: dir.to_string_lossy().into_owned(),
            branch: "main".into(),
            worktree: ws.room.layout().clone_of(NET),
            initial_offset: None,
        };
        let log = ws.room.log().expect("the lake opens");
        let reports = log.block_on(async {
            let mut c = Consumer::boot(log.clone(), Scripted(vec![commit_t(Some(twist))])).await.unwrap();
            c.run(&spec).await.unwrap()
        });
        assert!(reports.iter().all(|r| r.status == "ok"), "{reports:?}");
    }
}