codelore-lib 0.27.3

CodeLore — Behavioral Code Analyzer library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! End-to-end coverage for the Martin/Lakos structural metrics
//! (`instability` + `architecture-metrics`) over a fixture with a known
//! shape: `a ↔ b` form a 2-cycle, `c` imports `a`. The graph algorithms
//! are unit-tested in `analyses::import_graph`; this drives the full
//! ingest → metric path and pins the exact numbers.
//!
//! Also covers `architecture-metrics`' corpus-relative percentile rows: the
//! additivity contract (no active `repo_metrics` pool ⇒ byte-identical to
//! the seven base rows), the three extra rows once a synthetic calibration
//! artifact with a `repo_metrics` section is passed via `--calibration`, and
//! the default path where the embedded world artifact's pools activate the
//! rows with no configuration.

use codelore_lib::analyses::architecture_metrics::run_architecture_metrics;
use codelore_lib::analyses::instability::run_instability;
use codelore_lib::calibration::{
    CALIBRATION_FORMAT_VERSION, CalibrationArtifact, RepoMetrics, attach_repo_metrics,
};
use codelore_lib::facts::FactsDb;
use codelore_lib::repo::GixRepo;
use codelore_lib::test_support::permissive_coupling_opts;
use std::collections::{BTreeMap, HashMap};
use std::io::Write;
use std::path::Path;
use std::process::Command;

fn git(dir: &Path, args: &[&str]) {
    let status = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .status()
        .expect("spawn git");
    assert!(status.success(), "git {args:?} failed");
}

fn write(root: &Path, rel: &str, content: &str) {
    let p = root.join(rel);
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
    std::fs::write(p, content).unwrap();
}

/// Build the `a ↔ b` cycle + `c → a` fixture and ingest it.
fn ingested_cycle_repo() -> (tempfile::TempDir, FactsDb, codelore_lib::Options) {
    let dir = tempfile::tempdir().expect("tempdir");
    let p = dir.path();
    git(p, &["init", "-b", "main", "--quiet"]);
    git(p, &["config", "user.email", "m@example.com"]);
    git(p, &["config", "user.name", "M"]);
    write(
        p,
        "Cargo.toml",
        "[package]\nname=\"m\"\nversion=\"0.1.0\"\nedition=\"2021\"\n",
    );
    write(p, "src/lib.rs", "pub mod a;\npub mod b;\npub mod c;\n");
    write(p, "src/a.rs", "use crate::b;\npub fn a() { b::b(); }\n");
    write(p, "src/b.rs", "use crate::a;\npub fn b() { a::a(); }\n");
    write(p, "src/c.rs", "use crate::a;\npub fn c() { a::a(); }\n");
    git(p, &["add", "."]);
    let status = Command::new("git")
        .arg("-C")
        .arg(p)
        .args(["commit", "-m", "init", "--quiet"])
        .env("GIT_AUTHOR_DATE", "2026-01-01T10:00:00Z")
        .env("GIT_COMMITTER_DATE", "2026-01-01T10:00:00Z")
        .status()
        .expect("spawn git commit");
    assert!(status.success(), "git commit failed");

    let repo = GixRepo::open(p).expect("open repo");
    let db = FactsDb::new_in_memory().expect("in-memory db");
    let opts = permissive_coupling_opts(p.to_path_buf());
    db.ingest(&repo, &opts).expect("ingest repo");
    (dir, db, opts)
}

/// Build a fixture whose four imports separate all three disclosure signals:
/// two `use crate::…` edges that resolve to tracked files, one `use
/// crate::missing` edge that is repo-relative but points at a module with no
/// tracked file (a *first-party candidate the resolver missed*), and one `use
/// std::…` edge that legitimately points outside the repo. So:
/// resolved = 2, first-party candidates = 3 (the two resolved + the missed
/// relative one), total = 4.
fn ingested_first_party_mix_repo() -> (tempfile::TempDir, FactsDb, codelore_lib::Options) {
    let dir = tempfile::tempdir().expect("tempdir");
    let p = dir.path();
    git(p, &["init", "-b", "main", "--quiet"]);
    git(p, &["config", "user.email", "m@example.com"]);
    git(p, &["config", "user.name", "M"]);
    write(
        p,
        "Cargo.toml",
        "[package]\nname=\"m\"\nversion=\"0.1.0\"\nedition=\"2021\"\n",
    );
    write(p, "src/lib.rs", "pub mod a;\npub mod b;\n");
    write(
        p,
        "src/a.rs",
        // crate::b resolves; crate::missing is repo-relative but has no
        // tracked file (resolver miss); std::fmt is genuinely external.
        "use crate::b;\nuse crate::missing;\nuse std::fmt;\npub fn a() { b::b(); }\n",
    );
    write(p, "src/b.rs", "use crate::a;\npub fn b() { a::a(); }\n");
    git(p, &["add", "."]);
    let status = Command::new("git")
        .arg("-C")
        .arg(p)
        .args(["commit", "-m", "init", "--quiet"])
        .env("GIT_AUTHOR_DATE", "2026-01-01T10:00:00Z")
        .env("GIT_COMMITTER_DATE", "2026-01-01T10:00:00Z")
        .status()
        .expect("spawn git commit");
    assert!(status.success(), "git commit failed");

    let repo = GixRepo::open(p).expect("open repo");
    let db = FactsDb::new_in_memory().expect("in-memory db");
    let opts = permissive_coupling_opts(p.to_path_buf());
    db.ingest(&repo, &opts).expect("ingest repo");
    (dir, db, opts)
}

#[test]
fn instability_matches_martin_metrics() {
    let (_dir, db, opts) = ingested_cycle_repo();
    let rows = run_instability(&db, &opts).expect("run instability");
    let by: HashMap<&str, &_> = rows.iter().map(|r| (r.path.as_str(), r)).collect();

    // a: imported by b and c (Ca=2); imports b (Ce=1) → I = 1/3.
    let a = by.get("src/a.rs").expect("a present");
    assert_eq!((a.ca, a.ce), (2, 1), "a: {a:?}");
    assert!((a.instability - 1.0 / 3.0).abs() < 1e-9, "a I=1/3: {a:?}");

    // b: imported by a (Ca=1); imports a (Ce=1) → I = 1/2.
    let b = by.get("src/b.rs").expect("b present");
    assert_eq!((b.ca, b.ce), (1, 1), "b: {b:?}");
    assert!((b.instability - 0.5).abs() < 1e-9, "b I=1/2: {b:?}");

    // c: imported by nothing (Ca=0); imports a (Ce=1) → I = 1 (unstable).
    let c = by.get("src/c.rs").expect("c present");
    assert_eq!((c.ca, c.ce), (0, 1), "c: {c:?}");
    assert!((c.instability - 1.0).abs() < 1e-9, "c I=1: {c:?}");
}

/// An isolated Tier-1 source file — one that imports nothing and is
/// imported by nothing — is still a counted node. `src/lib.rs`
/// (`pub mod a; pub mod b; pub mod c;`) declares modules but carries no
/// `use` edges, so it never appears in the resolved `imports` table in
/// either direction. The graph is seeded from every live source file, so
/// it is a singleton (empty-adjacency) node with `ca == ce == 0` and
/// `instability == 0.0`, rather than being absent from the graph.
#[test]
fn isolated_source_file_is_a_counted_node() {
    let (_dir, db, opts) = ingested_cycle_repo();
    let rows = run_instability(&db, &opts).expect("run instability");
    let lib = rows
        .iter()
        .find(|r| r.path == "src/lib.rs")
        .expect("isolated src/lib.rs is a counted node");
    assert_eq!(
        (lib.ca, lib.ce),
        (0, 0),
        "isolated file imports nothing and is imported by nothing: {lib:?}"
    );
    assert!(
        lib.instability.abs() < 1e-9,
        "no coupling either way → instability 0.0: {lib:?}"
    );
}

#[test]
fn architecture_metrics_report_the_cycle_and_type() {
    let (_dir, db, opts) = ingested_cycle_repo();
    let rows = run_architecture_metrics(&db, &opts).expect("run architecture-metrics");
    let m: HashMap<&str, &str> = rows
        .iter()
        .map(|r| (r.metric.as_str(), r.value.as_str()))
        .collect();

    assert_eq!(
        m.get("files"),
        Some(&"4"),
        "4 source files in the graph (a, b, c + the isolated lib.rs): {m:?}"
    );
    assert_eq!(m.get("dependency_cycles"), Some(&"1"), "one cycle: {m:?}");
    assert_eq!(
        m.get("largest_cycle"),
        Some(&"2"),
        "the a↔b tangle is size 2: {m:?}"
    );
    assert_eq!(
        m.get("architecture_type"),
        Some(&"core-periphery"),
        "one dominant cycle → core-periphery: {m:?}"
    );
    // propagation_cost is present and a parseable ratio in [0, 1].
    let pc: f64 = m
        .get("propagation_cost")
        .expect("propagation_cost present")
        .parse()
        .expect("propagation_cost parses");
    assert!((0.0..=1.0).contains(&pc), "propagation cost in [0,1]: {pc}");
}

/// The two companion disclosure rows split the headline rate so a low
/// `import_resolution_rate` can't be misread as a weak resolver. Over the
/// first-party-mix fixture (resolved 2, first-party candidates 3, total 4):
/// `import_resolution_rate` = 2/4 = 0.5, `first_party_import_share` = 3/4 =
/// 0.75, and `resolution_rate_first_party` = 2/3 ≈ 0.6667 — the resolver
/// covered two of the three imports that actually aim at the repo, a far
/// higher number than the 0.5 headline the third-party `std::fmt` drags down.
#[test]
fn architecture_metrics_splits_resolution_into_first_party_signals() {
    let (_dir, db, opts) = ingested_first_party_mix_repo();
    let rows = run_architecture_metrics(&db, &opts).expect("run architecture-metrics");
    let m: HashMap<&str, &str> = rows
        .iter()
        .map(|r| (r.metric.as_str(), r.value.as_str()))
        .collect();

    assert_eq!(
        m.get("import_resolution_rate"),
        Some(&"0.5000"),
        "resolved 2 / total 4: {m:?}"
    );
    assert_eq!(
        m.get("first_party_import_share"),
        Some(&"0.7500"),
        "first-party candidates 3 / total 4: {m:?}"
    );
    assert_eq!(
        m.get("resolution_rate_first_party"),
        Some(&"0.6667"),
        "resolved 2 / first-party candidates 3: {m:?}"
    );
}

/// Fixture isolating the first-party-wildcard undercount fix: a resolved
/// relative import, an unresolved first-party GLOB (`use crate::missing::*;`
/// — `classify` tags this `Wildcard`, not `Relative`, since the trailing-glob
/// test runs before the relative-root test), and a genuinely external import.
/// So: resolved = 1 (`crate::b`), first-party candidates = 2 (the resolved
/// `crate::b` + the unresolved-but-unambiguously-in-repo `crate::missing::*`
/// glob), total = 3, of which 1 is a wildcard.
fn ingested_first_party_wildcard_repo() -> (tempfile::TempDir, FactsDb, codelore_lib::Options) {
    let dir = tempfile::tempdir().expect("tempdir");
    let p = dir.path();
    git(p, &["init", "-b", "main", "--quiet"]);
    git(p, &["config", "user.email", "m@example.com"]);
    git(p, &["config", "user.name", "M"]);
    write(
        p,
        "Cargo.toml",
        "[package]\nname=\"m\"\nversion=\"0.1.0\"\nedition=\"2021\"\n",
    );
    write(p, "src/lib.rs", "pub mod a;\npub mod b;\n");
    write(
        p,
        "src/a.rs",
        // crate::b resolves (relative); crate::missing::* is a first-party
        // GLOB the resolver can't map to a single tracked file (kind =
        // 'wildcard', not 'relative'); std::fmt is genuinely external.
        "use crate::b;\nuse crate::missing::*;\nuse std::fmt;\npub fn a() { b::b(); }\n",
    );
    write(p, "src/b.rs", "pub fn b() {}\n");
    git(p, &["add", "."]);
    let status = Command::new("git")
        .arg("-C")
        .arg(p)
        .args(["commit", "-m", "init", "--quiet"])
        .env("GIT_AUTHOR_DATE", "2026-01-01T10:00:00Z")
        .env("GIT_COMMITTER_DATE", "2026-01-01T10:00:00Z")
        .status()
        .expect("spawn git commit");
    assert!(status.success(), "git commit failed");

    let repo = GixRepo::open(p).expect("open repo");
    let db = FactsDb::new_in_memory().expect("in-memory db");
    let opts = permissive_coupling_opts(p.to_path_buf());
    db.ingest(&repo, &opts).expect("ingest repo");
    (dir, db, opts)
}

/// `first_party_import_share` must count an unresolved first-party glob
/// (`use crate::missing::*;`) — pre-fix it fell entirely out of the
/// numerator because `classify` tags it `Wildcard`, not `Relative`, and the
/// old predicate only recognised `kind = 'relative'`. Also pins the new
/// `wildcard_import_share` disclosure row.
#[test]
fn architecture_metrics_counts_first_party_wildcard_and_reports_wildcard_share() {
    let (_dir, db, opts) = ingested_first_party_wildcard_repo();
    let rows = run_architecture_metrics(&db, &opts).expect("run architecture-metrics");
    let m: HashMap<&str, &str> = rows
        .iter()
        .map(|r| (r.metric.as_str(), r.value.as_str()))
        .collect();

    assert_eq!(
        m.get("import_resolution_rate"),
        Some(&"0.3333"),
        "resolved 1 / total 3: {m:?}"
    );
    // Fixed value: 2/3 = 0.6667 (crate::b resolved + the crate::missing::*
    // glob counted as first-party despite kind='wildcard'). Pre-fix this
    // read 0.3333 — the glob silently fell out of the numerator.
    assert_eq!(
        m.get("first_party_import_share"),
        Some(&"0.6667"),
        "first-party candidates 2 / total 3, including the unresolved glob: {m:?}"
    );
    assert_eq!(
        m.get("resolution_rate_first_party"),
        Some(&"0.5000"),
        "resolved 1 / first-party candidates 2: {m:?}"
    );
    assert_eq!(
        m.get("wildcard_import_share"),
        Some(&"0.3333"),
        "one wildcard (crate::missing::*) / total 3: {m:?}"
    );
}

/// When a repo has imports but none are first-party candidates (every import
/// is an unresolved absolute — external crates / stdlib only), the
/// `resolution_rate_first_party` rate is undefined (0/0) and must be OMITTED
/// rather than rendered as a misleading `0.00`. The share and headline rows
/// still appear at 0. The fixture's lone file imports only `std::…`.
#[test]
fn architecture_metrics_omits_first_party_rate_when_no_candidates() {
    let dir = tempfile::tempdir().expect("tempdir");
    let p = dir.path();
    git(p, &["init", "-b", "main", "--quiet"]);
    git(p, &["config", "user.email", "m@example.com"]);
    git(p, &["config", "user.name", "M"]);
    write(
        p,
        "Cargo.toml",
        "[package]\nname=\"m\"\nversion=\"0.1.0\"\nedition=\"2021\"\n",
    );
    write(
        p,
        "src/lib.rs",
        "use std::fmt;\nuse std::io;\npub fn f() {}\n",
    );
    git(p, &["add", "."]);
    let status = Command::new("git")
        .arg("-C")
        .arg(p)
        .args(["commit", "-m", "init", "--quiet"])
        .env("GIT_AUTHOR_DATE", "2026-01-01T10:00:00Z")
        .env("GIT_COMMITTER_DATE", "2026-01-01T10:00:00Z")
        .status()
        .expect("spawn git commit");
    assert!(status.success(), "git commit failed");

    let repo = GixRepo::open(p).expect("open repo");
    let db = FactsDb::new_in_memory().expect("in-memory db");
    let opts = permissive_coupling_opts(p.to_path_buf());
    db.ingest(&repo, &opts).expect("ingest repo");

    let rows = run_architecture_metrics(&db, &opts).expect("run architecture-metrics");
    let m: HashMap<&str, &str> = rows
        .iter()
        .map(|r| (r.metric.as_str(), r.value.as_str()))
        .collect();

    assert_eq!(m.get("import_resolution_rate"), Some(&"0.0000"), "{m:?}");
    assert_eq!(m.get("first_party_import_share"), Some(&"0.0000"), "{m:?}");
    assert!(
        !m.contains_key("resolution_rate_first_party"),
        "undefined first-party rate must be omitted, never a 0.00: {m:?}"
    );
}

// ─── corpus-relative percentile rows ─────────────────────────────────────────

/// Serialize a synthetic [`CalibrationArtifact`] to a temp `.calib.json` file
/// and return its path, so it can be passed via `opts.calibration`. Mirrors
/// `calibration_test.rs`'s `write_temp_json` helper (each integration test
/// binary is compiled separately, so it isn't shared directly).
fn write_temp_calibration_artifact(art: &CalibrationArtifact) -> tempfile::TempPath {
    let mut f = tempfile::Builder::new()
        .prefix("arch-metrics-corpus")
        .suffix(".calib.json")
        .tempfile()
        .expect("create temp artifact");
    let bytes = serde_json::to_vec(art).expect("serialize artifact");
    f.write_all(&bytes).expect("write artifact bytes");
    f.into_temp_path()
}

/// Additivity contract: an artifact that is active but carries no
/// `repo_metrics` section (as every artifact built before the section
/// existed does) must leave the row set byte-identical to the seven base
/// metric names architecture-metrics has always emitted — the
/// corpus-percentile rows stay silent.
#[test]
fn architecture_metrics_additivity_without_repo_metrics_pool() {
    let (_dir, db, mut opts) = ingested_cycle_repo();

    // A valid artifact with no `repo_metrics` key at all — serialization
    // omits the `None` field, matching pre-section artifacts on disk.
    let artifact = CalibrationArtifact {
        format_version: CALIBRATION_FORMAT_VERSION,
        corpus_vintage: "test-corpus-no-pools".to_string(),
        generated_at: "2026-07-14T00:00:00Z".to_string(),
        repos_included: 1,
        repos_attempted: 1,
        languages: vec![],
        repo_metrics: None,
    };
    let path = write_temp_calibration_artifact(&artifact);
    opts.calibration = Some(path.to_path_buf());

    let rows = run_architecture_metrics(&db, &opts).expect("run architecture-metrics");
    let names: Vec<&str> = rows.iter().map(|r| r.metric.as_str()).collect();
    assert_eq!(
        names,
        vec![
            "propagation_cost",
            "acd",
            "nccd",
            "dependency_cycles",
            "largest_cycle",
            "files",
            "architecture_type",
            "import_resolution_rate",
            "first_party_import_share",
            "resolution_rate_first_party",
            "wildcard_import_share",
        ],
        "no active repo_metrics pool -> the base rows plus the four \
         import-resolution disclosure rows, no corpus rows: {names:?}"
    );
}

/// The default (no `--calibration` override) path resolves to the embedded
/// world artifact, which carries repo-level corpus pools — so the three
/// corpus rows appear after the seven base rows, with a percentile in
/// `[0, 1]` and `corpus_n` matching the embedded pool length.
#[test]
fn architecture_metrics_default_embedded_artifact_emits_corpus_rows() {
    let (_dir, db, opts) = ingested_cycle_repo();
    assert!(
        opts.calibration.is_none(),
        "fixture must exercise the default (embedded-artifact) path"
    );
    let rows = run_architecture_metrics(&db, &opts).expect("run architecture-metrics");
    let m: HashMap<&str, &str> = rows
        .iter()
        .map(|r| (r.metric.as_str(), r.value.as_str()))
        .collect();

    let p: f64 = m
        .get("corpus_percentile:propagation_cost")
        .expect("embedded world artifact must carry a propagation_cost pool")
        .parse()
        .expect("percentile parses");
    assert!(
        (0.0..=1.0).contains(&p),
        "percentile must be in [0, 1], got {p}"
    );

    let embedded =
        codelore_lib::calibration::embedded_world().expect("embedded world artifact resolves");
    let pool_len = embedded
        .repo_metrics
        .as_ref()
        .expect("embedded world artifact must carry repo_metrics")
        .values
        .get("propagation_cost")
        .expect("propagation_cost pool present")
        .len();
    assert_eq!(
        m.get("corpus_n").copied(),
        Some(pool_len.to_string().as_str()),
        "corpus_n must state the embedded pool size"
    );

    // The additive Wilson CI rows accompany the percentile, stay in [0, 1], and
    // bracket the point estimate.
    let lo: f64 = m
        .get("corpus_percentile:propagation_cost:ci_low")
        .expect("ci_low row present alongside the percentile")
        .parse()
        .expect("ci_low parses");
    let hi: f64 = m
        .get("corpus_percentile:propagation_cost:ci_high")
        .expect("ci_high row present alongside the percentile")
        .parse()
        .expect("ci_high parses");
    assert!(
        (0.0..=1.0).contains(&lo) && (0.0..=1.0).contains(&hi),
        "CI bounds must be in [0, 1], got [{lo}, {hi}]"
    );
    assert!(
        lo <= p && p <= hi,
        "CI must bracket the percentile p={p}: [{lo}, {hi}]"
    );
}

/// With a synthetic calibration artifact carrying a `repo_metrics` section
/// passed via `--calibration`, the three corpus-percentile rows appear with
/// hand-computed values.
///
/// The fixture's import graph (`a ↔ b` 2-cycle, `c → a`, plus the isolated
/// `src/lib.rs` singleton) has, per
/// `architecture_metrics_report_the_cycle_and_type` above and
/// `import_graph::graph_metrics`'s definition: `n = 4`, `cyclic_nodes = 2`
/// (`a`, `b`), so `propagation_cost = 8/16 = 0.5` (`ccd = vfo(a) + vfo(b) +
/// vfo(c) + vfo(lib) = 2 + 2 + 3 + 1 = 8`, `n² = 16`) and
/// `cycle_file_share = 2/4 = 0.5`.
///
/// Pools are chosen so neither this-repo value collides with a pool member,
/// keeping the `raw_percentile` midpoint-rank arithmetic unambiguous:
/// - `propagation_cost` pool `[0.1, 0.3, 0.9]`: 0.5 sits strictly between
///   0.3 and 0.9, so `count_less = 2`, `count_equal = 0`, `n = 3` →
///   `p = 2/3 ≈ 0.6667` → `"0.67"`.
/// - `cycle_file_share` pool `[0.0, 0.2]`: 0.5 sits strictly above both,
///   so `count_less = 2`, `count_equal = 0`, `n = 2` → `p = 2/2 = 1.0` →
///   `"1.00"`.
/// - `corpus_n` uses the `propagation_cost` pool's length (3), per the
///   documented precedence rule.
/// - A Wilson 95% CI wraps each percentile at that pool's `n`:
///   `propagation_cost` (p = 2/3, n = 3) → centre ≈ 0.573, radius ≈ 0.365 →
///   `[0.21, 0.94]`; `cycle_file_share` (p = 1.0, n = 2) → centre ≈ 0.671,
///   radius ≈ 0.329 →
///   `[0.34, 1.00]` (upper bound clamps to 1.0).
#[test]
fn architecture_metrics_emits_corpus_percentiles_when_pool_active() {
    let (_dir, db, mut opts) = ingested_cycle_repo();

    let mut artifact = CalibrationArtifact {
        format_version: CALIBRATION_FORMAT_VERSION,
        corpus_vintage: "test-corpus".to_string(),
        generated_at: "2026-07-14T00:00:00Z".to_string(),
        repos_included: 3,
        repos_attempted: 3,
        languages: vec![],
        repo_metrics: None,
    };
    let mut values = BTreeMap::new();
    values.insert("propagation_cost".to_string(), vec![0.1, 0.3, 0.9]);
    values.insert("cycle_file_share".to_string(), vec![0.0, 0.2]);
    attach_repo_metrics(&mut artifact, RepoMetrics { values });

    let path = write_temp_calibration_artifact(&artifact);
    opts.calibration = Some(path.to_path_buf());

    let rows = run_architecture_metrics(&db, &opts).expect("run architecture-metrics");
    let names: Vec<&str> = rows.iter().map(|r| r.metric.as_str()).collect();
    assert_eq!(
        names,
        vec![
            "propagation_cost",
            "acd",
            "nccd",
            "dependency_cycles",
            "largest_cycle",
            "files",
            "architecture_type",
            "import_resolution_rate",
            "first_party_import_share",
            "resolution_rate_first_party",
            "wildcard_import_share",
            "corpus_percentile:propagation_cost",
            "corpus_percentile:propagation_cost:ci_low",
            "corpus_percentile:propagation_cost:ci_high",
            "corpus_percentile:cycle_file_share",
            "corpus_percentile:cycle_file_share:ci_low",
            "corpus_percentile:cycle_file_share:ci_high",
            "corpus_n",
        ],
        "the corpus rows (percentile + its paired Wilson CI) must append, in \
         order, after the base rows and the four import-resolution \
         disclosure rows: {names:?}"
    );

    let m: HashMap<&str, &str> = rows
        .iter()
        .map(|r| (r.metric.as_str(), r.value.as_str()))
        .collect();
    assert_eq!(
        m.get("corpus_percentile:propagation_cost"),
        Some(&"0.67"),
        "hand-computed midpoint-rank percentile: {m:?}"
    );
    assert_eq!(
        m.get("corpus_percentile:cycle_file_share"),
        Some(&"1.00"),
        "hand-computed midpoint-rank percentile: {m:?}"
    );
    assert_eq!(
        m.get("corpus_n"),
        Some(&"3"),
        "corpus_n uses the propagation_cost pool length: {m:?}"
    );

    // Hand-computed Wilson 95% intervals on the SAME midpoint-rank percentiles,
    // at each pool's own `n` (3 and 2 repos) — deliberately wide, the honest
    // read of a tiny corpus.
    assert_eq!(
        m.get("corpus_percentile:propagation_cost:ci_low"),
        Some(&"0.21"),
        "Wilson lower bound for p=2/3, n=3: {m:?}"
    );
    assert_eq!(
        m.get("corpus_percentile:propagation_cost:ci_high"),
        Some(&"0.94"),
        "Wilson upper bound for p=2/3, n=3: {m:?}"
    );
    assert_eq!(
        m.get("corpus_percentile:cycle_file_share:ci_low"),
        Some(&"0.34"),
        "Wilson lower bound for p=1.0, n=2: {m:?}"
    );
    assert_eq!(
        m.get("corpus_percentile:cycle_file_share:ci_high"),
        Some(&"1.00"),
        "Wilson upper bound clamps to 1.0 for p=1.0, n=2: {m:?}"
    );
}