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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
use std::io::Write as _;

use codelore_lib::Options;
use codelore_lib::analyses::code_health::run_code_health;
use codelore_lib::calibration::{
    CALIBRATION_FORMAT_VERSION, CalibrationArtifact, LanguageTable, MetricQuantiles,
    QUANTILE_POINTS, Stratum,
};
use codelore_lib::facts::FactsDb;
use codelore_lib::repo::GixRepo;

#[test]
fn code_health_for_tiny_repo() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo = GixRepo::open(tiny.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = Options {
        repo_path: tiny.dir.path().to_path_buf(),
        min_revs: 1,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    let rows = run_code_health(&db, &opts).expect("run");
    assert!(!rows.is_empty(), "should produce ≥1 row");

    for row in &rows {
        assert!(
            row.score >= 0.0 && row.score <= 100.0,
            "score should be in [0, 100], got {} for {}",
            row.score,
            row.path
        );
        assert!(
            row.cognitive >= 0.0,
            "cognitive should be >= 0, got {} for {}",
            row.cognitive,
            row.path
        );
    }
}

#[test]
fn code_health_ranks_least_healthy_first() {
    // Convention: ORDER BY score ASC — least healthy first (these are the
    // ones a developer should look at).
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo = GixRepo::open(tiny.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = Options {
        repo_path: tiny.dir.path().to_path_buf(),
        min_revs: 1,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    let rows = run_code_health(&db, &opts).expect("run");
    // Confirm ascending order
    for w in rows.windows(2) {
        assert!(
            w[0].score <= w[1].score,
            "expected ascending score order, got {} > {}",
            w[0].score,
            w[1].score
        );
    }
}

#[test]
fn code_health_penalizes_churn() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo = GixRepo::open(tiny.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = Options {
        repo_path: tiny.dir.path().to_path_buf(),
        min_revs: 1,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    let rows = run_code_health(&db, &opts).expect("run");
    // tiny_repo has src/main.rs (4 commits = high churn) and src/lib.rs (1 commit = low churn).
    // src/main.rs should rank LOWER (less healthy) than src/lib.rs in Code Health.
    // `.expect` (not `if let`) so a missing file fails loudly instead of
    // silently skipping the assertion.
    let m = rows
        .iter()
        .find(|r| r.path == "src/main.rs")
        .expect("src/main.rs should be scored");
    let l = rows
        .iter()
        .find(|r| r.path == "src/lib.rs")
        .expect("src/lib.rs should be scored");
    assert!(
        m.score <= l.score,
        "src/main.rs (4 commits) should rank <= src/lib.rs (1 commit) in code health, got main={} lib={}",
        m.score,
        l.score
    );
}

#[test]
fn code_health_reports_band_and_percentile() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo = codelore_lib::repo::GixRepo::open(tiny.dir.path()).expect("open");
    let db = codelore_lib::facts::FactsDb::new_in_memory().expect("db");
    let opts = codelore_lib::Options {
        repo_path: tiny.dir.path().to_path_buf(),
        min_revs: 1,
        ..codelore_lib::Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    let rows = codelore_lib::analyses::code_health::run_code_health(&db, &opts).expect("run");
    assert!(!rows.is_empty());
    for row in &rows {
        assert!(
            (0.0..=1.0).contains(&row.percentile),
            "percentile in [0,1]: {}",
            row.percentile
        );
        assert!(
            matches!(row.band.as_str(), "red" | "yellow" | "green"),
            "band must be red|yellow|green, got {}",
            row.band
        );
        assert!(
            (0.0..=1.0).contains(&row.structural_risk),
            "structural_risk in [0,1]: {}",
            row.structural_risk
        );
    }
}

#[test]
fn biomarkers_flag_complex_functions() {
    // Needs a language cohort at or above `MIN_COHORT_FILES` so the per-language
    // PERCENT_RANK produces structural-biomarker rows. tiny_repo's two-file Rust
    // cohort is below that floor and (correctly) yields none, so this uses
    // biomarker_repo, whose ten Rust files sit at the floor.
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = biomarker_opts(fx.dir.path());
    db.ingest(&repo, &opts).expect("ingest");

    // Running code-health materializes the biomarker table as a side effect.
    let _ = run_code_health(&db, &opts).expect("run");

    let count: i64 = db
        .query_row("SELECT COUNT(*) FROM code_health_biomarkers_v1", [], |r| {
            r.get(0)
        })
        .expect("query biomarkers");
    assert!(
        count >= 1,
        "biomarker_repo should produce >=1 biomarker row"
    );

    // intensities are valid probabilities
    let bad: i64 = db
        .query_row(
            "SELECT COUNT(*) FROM code_health_biomarkers_v1 WHERE intensity < 0.0 OR intensity > 1.0",
            [], |r| r.get(0),
        )
        .expect("query range");
    assert_eq!(bad, 0, "all intensities must be in [0,1]");
}

/// The per-language cohort floor: a language contributing fewer than
/// `MIN_COHORT_FILES` files to the HEAD complexity scan is too thin for a
/// `PERCENT_RANK` to mean anything — at two files it emits exactly `{0.0, 1.0}`,
/// which would pin the larger file to MAX intensity on every structural
/// biomarker regardless of its absolute complexity. Such a cohort must instead
/// produce NO per-language structural-biomarker rows, while a cohort at/above
/// the floor ranks normally. `tiny_repo`'s two Rust files are below the floor;
/// `biomarker_repo`'s ten sit at it.
#[test]
fn tiny_language_cohort_is_not_pinned_to_red() {
    const STRUCTURAL_IN: &str = "smell IN \
         ('complex-method','large-method','deep-nesting','many-args','complex-conditional')";

    let structural_count = |db: &FactsDb| -> i64 {
        db.query_row(
            &format!("SELECT COUNT(*) FROM code_health_biomarkers_v1 WHERE {STRUCTURAL_IN}"),
            [],
            |r| r.get(0),
        )
        .expect("count structural biomarker rows")
    };

    // Below-floor cohort (2 Rust files): no structural-biomarker rows at all, so
    // nothing is pinned to intensity 1.0 by a degenerate two-point percent-rank.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo = GixRepo::open(tiny.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = Options {
        repo_path: tiny.dir.path().to_path_buf(),
        min_revs: 1,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");
    let _ = run_code_health(&db, &opts).expect("run tiny");
    assert_eq!(
        structural_count(&db),
        0,
        "a below-floor language cohort must yield no per-language structural biomarkers"
    );

    // At-floor cohort (10 Rust files): the same biomarkers rank normally.
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo2 = GixRepo::open(fx.dir.path()).expect("open");
    let db2 = FactsDb::new_in_memory().expect("db");
    let opts2 = biomarker_opts(fx.dir.path());
    db2.ingest(&repo2, &opts2).expect("ingest");
    let _ = run_code_health(&db2, &opts2).expect("run biomarker");
    assert!(
        structural_count(&db2) >= 1,
        "an at-floor language cohort must still produce per-language structural biomarkers"
    );
}

#[test]
fn coupling_becomes_shotgun_surgery_biomarker() {
    let repo_fx = codelore_lib::test_support::differential_repo::build();
    let repo = codelore_lib::repo::GixRepo::open(repo_fx.dir.path()).expect("open");
    let db = codelore_lib::facts::FactsDb::new_in_memory().expect("db");
    let opts =
        codelore_lib::test_support::permissive_coupling_opts(repo_fx.dir.path().to_path_buf());
    db.ingest(&repo, &opts).expect("ingest");

    let _ = codelore_lib::analyses::code_health::run_code_health(&db, &opts).expect("run");

    let n: i64 = db
        .query_row(
            "SELECT COUNT(*) FROM code_health_biomarkers_v1 WHERE smell = 'shotgun-surgery'",
            [],
            |r| r.get(0),
        )
        .expect("query");
    assert!(
        n >= 1,
        "a coupling-heavy repo should yield shotgun-surgery biomarkers"
    );
}

#[test]
fn structural_risk_rewards_multiple_cooccurring_smells() {
    // Co-occurrence: a file flagged by MORE distinct biomarkers has higher
    // structural_risk than one flagged by fewer, because the weighted sum
    // accumulates terms. On the fixture, dup_a (complex-method + large-method +
    // dry + shotgun-surgery) vs trivial (no smells). Asserted on
    // structural_risk directly — the final score also mixes churn/ownership, so
    // it is not a clean single-variable invariant (the prior version asserted
    // that false invariant and passed only by tiny_repo coincidence).
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = biomarker_opts(fx.dir.path());
    db.ingest(&repo, &opts).expect("ingest");
    let rows = run_code_health(&db, &opts).expect("run");
    let dup = rows
        .iter()
        .find(|r| r.path.ends_with("dup_a.rs"))
        .expect("dup_a scored");
    let trivial = rows
        .iter()
        .find(|r| r.path.ends_with("trivial.rs"))
        .expect("trivial scored");
    assert!(
        dup.structural_risk > trivial.structural_risk,
        "a file with several co-occurring smells (dup_a={}) must have higher structural_risk than a smell-free file (trivial={})",
        dup.structural_risk,
        trivial.structural_risk
    );
}

#[test]
fn code_health_v2_is_deterministic() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo = codelore_lib::repo::GixRepo::open(tiny.dir.path()).expect("open");
    let opts = codelore_lib::Options {
        repo_path: tiny.dir.path().to_path_buf(),
        min_revs: 1,
        ..codelore_lib::Options::default()
    };
    let run = || {
        let db = codelore_lib::facts::FactsDb::new_in_memory().expect("db");
        db.ingest(&repo, &opts).expect("ingest");
        codelore_lib::analyses::code_health::run_code_health(&db, &opts).expect("run")
    };
    let a = run();
    let b = run();
    assert_eq!(a.len(), b.len());
    for (x, y) in a.iter().zip(b.iter()) {
        assert_eq!(x.path, y.path);
        assert!((x.score - y.score).abs() < 1e-9, "score must be stable");
        assert_eq!(x.band, y.band, "band must be stable");
    }
}

/// `--rows N` MUST NOT change the score computed for a path that survives
/// the truncation. The bug it regression-protects: `materialize_centrality`
/// used to pass the parent `opts` (with `rows_limit = N`) straight into
/// `run_coupling`, so the centrality term was computed over a sliver of
/// the coupling graph and the final score drifted by `rows_limit`.
#[test]
fn code_health_score_invariant_under_rows_limit() {
    let diff_repo = codelore_lib::test_support::differential_repo::build();
    let repo = GixRepo::open(diff_repo.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts_unlimited = Options {
        repo_path: diff_repo.dir.path().to_path_buf(),
        min_revs: 1,
        fisher_significance: 1.0,
        rows_limit: None,
        ..Options::default()
    };
    db.ingest(&repo, &opts_unlimited).expect("ingest");
    let baseline = run_code_health(&db, &opts_unlimited).expect("baseline");
    assert!(baseline.len() >= 2, "need ≥2 rows to test truncation");

    let opts_capped = Options {
        rows_limit: Some(2),
        ..opts_unlimited.clone()
    };
    let capped = run_code_health(&db, &opts_capped).expect("capped");
    assert!(capped.len() <= 2, "rows_limit=2 should truncate output");

    // Each capped row's score MUST match the baseline score for the same path.
    // If the centrality term were computed over a truncated coupling graph,
    // these would drift.
    for row in &capped {
        let baseline_row = baseline
            .iter()
            .find(|b| b.path == row.path)
            .expect("capped path must be in baseline");
        assert!(
            (row.score - baseline_row.score).abs() < 1e-9,
            "score drift for {}: capped={} baseline={} — rows_limit leaked into centrality?",
            row.path,
            row.score,
            baseline_row.score
        );
    }
}

fn biomarker_opts(dir: &std::path::Path) -> Options {
    Options {
        repo_path: dir.to_path_buf(),
        min_revs: 1,
        fisher_significance: 1.0,
        min_shared_revs: 1,
        min_coupling_pct: 0,
        max_coupling_pct: 100,
        ..Options::default()
    }
}

/// Distribution guard on a purpose-built fixture with a real complexity
/// gradient, a duplicated pair, and co-changed files. `structural_risk` must
/// DISCRIMINATE — spread across files, not collapse to the ceiling. This is the
/// regression guard the per-row invariant tests lacked: the prior formula
/// ranked functions then MAX-ed and OR-ed the intensities, pinning ~every file
/// at 1.0 on real repos while every range/monotonicity test still passed.
#[test]
fn code_health_structural_risk_discriminates() {
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = biomarker_opts(fx.dir.path());
    db.ingest(&repo, &opts).expect("ingest");
    let rows = run_code_health(&db, &opts).expect("run");
    assert!(rows.len() >= 5, "fixture should score several files");

    let distinct: std::collections::HashSet<String> = rows
        .iter()
        .map(|r| format!("{:.3}", r.structural_risk))
        .collect();
    assert!(
        distinct.len() >= 3,
        "structural_risk must spread across files, got {} distinct value(s)",
        distinct.len()
    );
    let max = rows
        .iter()
        .map(|r| r.structural_risk)
        .fold(0.0_f64, f64::max);
    let min = rows
        .iter()
        .map(|r| r.structural_risk)
        .fold(1.0_f64, f64::min);
    assert!(
        max < 1.0,
        "no file should saturate at the ceiling, got max={max}"
    );
    assert!(max - min > 0.2, "expected a real spread, got {min}..{max}");

    // Ordering sanity: the trivial file is healthiest; the deeply-nested file
    // is among the worst.
    let trivial = rows
        .iter()
        .find(|r| r.path.ends_with("trivial.rs"))
        .expect("trivial file scored");
    let complex = rows
        .iter()
        .find(|r| r.path.ends_with("complex.rs"))
        .expect("complex file scored");
    assert!(
        trivial.structural_risk < complex.structural_risk,
        "trivial ({}) must be less risky than complex ({})",
        trivial.structural_risk,
        complex.structural_risk
    );
}

/// The biomarker layer fires the expected DISTINCT smells on the fixture.
/// Closes the earlier gap where a test could pass while a `UNION` arm was
/// silently dropped (the vocabulary was only asserted as `>= 1` distinct).
/// god-class needs fan-in a tiny fixture can't manufacture, so it is not
/// required here.
#[test]
fn code_health_biomarkers_fire_distinct_smells() {
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = biomarker_opts(fx.dir.path());
    db.ingest(&repo, &opts).expect("ingest");
    let _ = run_code_health(&db, &opts).expect("run");

    let smells: std::collections::HashSet<String> =
        codelore_lib::analyses::query::query_map_collect(
            &db,
            "SELECT DISTINCT smell FROM code_health_biomarkers_v1",
            [],
            "smells",
            |r| r.get::<_, String>(0),
        )
        .expect("smells")
        .into_iter()
        .collect();
    for expected in [
        "complex-method",
        "large-method",
        "dry",
        "shotgun-surgery",
        "deep-nesting",
        "many-args",
        "complex-conditional",
    ] {
        assert!(
            smells.contains(expected),
            "expected smell {expected} to fire on the fixture, got {smells:?}"
        );
    }
}

/// The intensity a given smell carries for a file in the biomarker table.
/// Returns `None` when the file has no row for that smell. Used by the
/// per-smell firing tests below.
fn smell_intensity(db: &FactsDb, path: &str, smell: &str) -> Option<f64> {
    codelore_lib::analyses::query::query_map_collect(
        db,
        "SELECT intensity FROM code_health_biomarkers_v1 WHERE path = ? AND smell = ?",
        duckdb::params![path, smell],
        "smell-intensity",
        |r| r.get::<_, f64>(0),
    )
    .expect("query smell intensity")
    .into_iter()
    .next()
}

/// `deep-nesting` fires on `src/nested.rs` — its `deeply_nested` function
/// reaches `max_nesting == 5`, the top of the Rust file distribution, so the
/// per-language `PERCENT_RANK` of its per-file MAX nesting is a positive
/// intensity.
#[test]
fn deep_nesting_biomarker_fires_on_nested_file() {
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = biomarker_opts(fx.dir.path());
    db.ingest(&repo, &opts).expect("ingest");
    let _ = run_code_health(&db, &opts).expect("run");

    let intensity = smell_intensity(&db, "src/nested.rs", "deep-nesting")
        .expect("nested.rs should carry a deep-nesting biomarker row");
    assert!(
        intensity > 0.0,
        "deep-nesting intensity for src/nested.rs must be > 0, got {intensity}"
    );
}

/// `many-args` fires on `src/many_args.rs` — its `many_args` function takes
/// `nargs == 7`, the maximum in the Rust file distribution, so its per-file MAX
/// nargs ranks at the top of the per-language `PERCENT_RANK`.
#[test]
fn many_args_biomarker_fires_on_many_args_file() {
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = biomarker_opts(fx.dir.path());
    db.ingest(&repo, &opts).expect("ingest");
    let _ = run_code_health(&db, &opts).expect("run");

    let intensity = smell_intensity(&db, "src/many_args.rs", "many-args")
        .expect("many_args.rs should carry a many-args biomarker row");
    assert!(
        intensity > 0.0,
        "many-args intensity for src/many_args.rs must be > 0, got {intensity}"
    );
}

/// `complex-conditional` fires on `src/conditional.rs` — its `gate` function's
/// single `if` chains four boolean operators (`bool_ops == 3`), the only file
/// with a non-zero boolean-operator count, so it ranks at the top of the
/// per-language `PERCENT_RANK` over per-file MAX `bool_ops`. This also exercises
/// the `bool_ops` metric flowing end to end through the composite.
#[test]
fn complex_conditional_biomarker_fires_on_conditional_file() {
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = biomarker_opts(fx.dir.path());
    db.ingest(&repo, &opts).expect("ingest");
    let _ = run_code_health(&db, &opts).expect("run");

    let intensity = smell_intensity(&db, "src/conditional.rs", "complex-conditional")
        .expect("conditional.rs should carry a complex-conditional biomarker row");
    assert!(
        intensity > 0.0,
        "complex-conditional intensity for src/conditional.rs must be > 0, got {intensity}"
    );
}

/// Locks the code-health CSV column contract (order + names). refactoring-targets
/// had this; code-health did not — a column rename/reorder would have gone
/// undetected.
#[test]
fn code_health_csv_column_contract() {
    let rows = vec![codelore_lib::analyses::code_health::CodeHealthRow {
        path: "src/x.rs".to_string(),
        cognitive: 12.0,
        score: 88.5,
        structural_risk: 0.3,
        percentile: 0.5,
        band: "yellow".to_string(),
        corpus_percentile: None,
        beyond_corpus: false,
        corpus_percentile_ci_low: None,
        corpus_percentile_ci_high: None,
    }];
    let mut buf: Vec<u8> = Vec::new();
    codelore_lib::output::csv::write_code_health_csv(&rows, &mut buf).expect("csv");
    let out = String::from_utf8(buf).expect("utf8");
    assert_eq!(
        out.lines().next().unwrap(),
        "entity,cognitive,score,structural_risk,percentile,band,corpus-pct,corpus-pct-ci-low,corpus-pct-ci-high"
    );
    assert!(
        out.lines().nth(1).unwrap().starts_with("src/x.rs,"),
        "data row should carry the path"
    );
}

/// `corpus-pct` column: populated when `corpus_percentile` is `Some`,
/// empty when `None`, and `beyond_corpus` does not affect the rendered value.
#[test]
fn code_health_csv_corpus_pct_populated_and_none() {
    use codelore_lib::analyses::code_health::CodeHealthRow;
    let make = |cp: Option<f64>, bc: bool| CodeHealthRow {
        path: "f.rs".into(),
        cognitive: 1.0,
        score: 50.0,
        structural_risk: 0.1,
        percentile: 0.2,
        band: "green".into(),
        corpus_percentile: cp,
        beyond_corpus: bc,
        corpus_percentile_ci_low: cp.map(|_| 0.61),
        corpus_percentile_ci_high: cp.map(|_| 0.90),
    };
    let rows = vec![
        make(Some(0.75), false),
        make(Some(1.0), true),
        make(None, false),
    ];
    let mut buf: Vec<u8> = Vec::new();
    codelore_lib::output::csv::write_code_health_csv(&rows, &mut buf).expect("csv");
    let csv = String::from_utf8(buf).expect("utf8");
    let lines: Vec<&str> = csv.lines().collect();
    // header now carries the paired Wilson-CI columns after corpus-pct
    assert!(
        lines[0].ends_with(",corpus-pct,corpus-pct-ci-low,corpus-pct-ci-high"),
        "header must end with the corpus-pct + CI columns: {}",
        lines[0]
    );
    // row 0: populated percentile followed by its two CI bounds
    assert!(
        lines[1].ends_with(",0.75,0.61,0.90"),
        "populated row must carry corpus-pct and its CI: {}",
        lines[1]
    );
    // row 1: beyond_corpus true → percentile value unchanged, CI still present
    assert!(
        lines[2].ends_with(",1.00,0.61,0.90"),
        "beyond-corpus row must carry 1.00 and its CI: {}",
        lines[2]
    );
    // row 2: None → three empty trailing cells (percentile + both CI bounds)
    assert!(
        lines[3].ends_with(",,,"),
        "None row must emit empty corpus-pct + CI cells: {}",
        lines[3]
    );
}

/// `Corpus percentile` column in the markdown emitter: populated when
/// `corpus_percentile` is `Some`, em-dash when `None`.
#[test]
fn code_health_markdown_corpus_pct_column() {
    use codelore_lib::analyses::code_health::CodeHealthRow;
    let make = |cp: Option<f64>, bc: bool| CodeHealthRow {
        path: "f.rs".into(),
        cognitive: 1.0,
        score: 50.0,
        structural_risk: 0.1,
        percentile: 0.2,
        band: "green".into(),
        corpus_percentile: cp,
        beyond_corpus: bc,
        corpus_percentile_ci_low: cp.map(|_| 0.61),
        corpus_percentile_ci_high: cp.map(|_| 0.90),
    };
    let rows = vec![
        make(Some(0.74), false),
        make(Some(1.0), true),
        make(None, false),
    ];
    let mut buf: Vec<u8> = Vec::new();
    codelore_lib::output::markdown::write_code_health_markdown(&rows, &mut buf).expect("md");
    let md = String::from_utf8(buf).expect("utf8");
    // Header must include the corpus percentile column and its paired CI column
    assert!(
        md.contains("Corpus percentile"),
        "markdown header must contain 'Corpus percentile'"
    );
    assert!(
        md.contains("Corpus 95% CI"),
        "markdown header must contain the 'Corpus 95% CI' column: {md}"
    );
    // Populated row: rendered as integer percent
    assert!(
        md.contains("74%"),
        "populated corpus_percentile 0.74 must render as 74%: {md}"
    );
    // beyond_corpus row: rendered with '+' suffix
    assert!(
        md.contains("100%+"),
        "beyond_corpus row must render as 100%+: {md}"
    );
    // Populated rows render the Wilson interval as an integer-percent range
    assert!(
        md.contains("61–90%"),
        "populated CI bounds 0.61/0.90 must render as 61–90%: {md}"
    );
    // None row: em-dash (both the percentile and the CI cell)
    assert!(
        md.contains(""),
        "None corpus_percentile must render as em-dash"
    );
}

#[test]
fn scoped_no_clones_excludes_dry_and_renormalizes() {
    use codelore_lib::analyses::code_health::{
        CodeHealthRow, HealthScanCtx, run_code_health, run_code_health_scoped,
    };
    let repo = codelore_lib::test_support::biomarker_repo::build();
    let gix = codelore_lib::repo::GixRepo::open(repo.dir.path()).expect("open");
    let db = codelore_lib::facts::FactsDb::new_in_memory().expect("db");
    let opts = codelore_lib::test_support::permissive_coupling_opts(repo.dir.path().to_path_buf());
    db.ingest(&gix, &opts).expect("ingest");

    let head = run_code_health(&db, &opts).expect("head");
    let mut cx = HealthScanCtx::head();
    cx.include_clones = false;
    let no_dry = run_code_health_scoped(&db, &opts, &cx).expect("no-dry");

    assert_eq!(head.len(), no_dry.len(), "same file universe");

    let risk = |rows: &[CodeHealthRow], suffix: &str| -> f64 {
        rows.iter()
            .find(|r| r.path.ends_with(suffix))
            .unwrap_or_else(|| panic!("{suffix} should be scored"))
            .structural_risk
    };

    // `big.rs` (large-method, unique — no clone) carries no DRY term, so
    // dropping DRY leaves its weighted biomarker sum untouched: only the
    // `/0.88` renormalization applies. Its no-clones risk is therefore exactly
    // the HEAD risk divided by 0.88, proving the renormalization divisor is
    // wired. (Not a `>=` score relation — renormalization deliberately RAISES a
    // no-duplication file's risk; the no-clones series is internally consistent
    // with itself, not comparable to the with-DRY HEAD score.)
    let big_head = risk(&head, "big.rs");
    let big_nodry = risk(&no_dry, "big.rs");
    assert!(
        big_head > 0.0,
        "big.rs must carry a non-DRY smell for this check"
    );
    assert!(
        (big_nodry - big_head / 0.88).abs() < 1e-6,
        "renorm: big.rs no-clones risk {big_nodry} must equal HEAD {big_head} / 0.88"
    );

    // `dup_a.rs` is a clone of `dup_b.rs`, so at HEAD it carries a DRY term.
    // Excluding DRY removes that term; even after the `/0.88` bump the net risk
    // DROPS below HEAD, proving the DRY biomarker was present and is now gone.
    let dup_head = risk(&head, "dup_a.rs");
    let dup_nodry = risk(&no_dry, "dup_a.rs");
    assert!(
        dup_nodry < dup_head - 1e-6,
        "DRY excluded: dup_a.rs no-clones risk {dup_nodry} must drop below HEAD {dup_head}"
    );

    // Renormalization keeps every risk in range.
    for r in &no_dry {
        assert!(
            (0.0..=1.0).contains(&r.structural_risk),
            "structural_risk out of range for {}: {}",
            r.path,
            r.structural_risk
        );
    }
}

#[test]
fn head_wrapper_equals_scoped_head_ctx() {
    use codelore_lib::analyses::code_health::{
        HealthScanCtx, run_code_health, run_code_health_scoped,
    };
    let repo = codelore_lib::test_support::biomarker_repo::build();
    let gix = codelore_lib::repo::GixRepo::open(repo.dir.path()).expect("open");
    let db = codelore_lib::facts::FactsDb::new_in_memory().expect("db");
    let opts = codelore_lib::test_support::permissive_coupling_opts(repo.dir.path().to_path_buf());
    db.ingest(&gix, &opts).expect("ingest");

    let a = run_code_health(&db, &opts).expect("wrapper");
    let b = run_code_health_scoped(&db, &opts, &HealthScanCtx::head()).expect("scoped-head");
    // Non-vacuity: a regression guard that passed on an empty result would be
    // worthless — the fixture must yield scored rows for the parity loop to bite.
    assert!(!a.is_empty(), "biomarker_repo must yield scored rows");
    assert_eq!(a.len(), b.len());
    for (x, y) in a.iter().zip(b.iter()) {
        assert_eq!(x.path, y.path);
        assert!(
            (x.score - y.score).abs() < 1e-12,
            "score parity for {}",
            x.path
        );
        assert!((x.structural_risk - y.structural_risk).abs() < 1e-12);
        assert_eq!(x.band, y.band);
    }
}

/// Exercises the `history_cutoff` scoped path end to end: with a cutoff mid-way
/// through the fixture's history, the churn / author / coupling terms must see
/// only commits at-or-before the cutoff date, so at least one file's score
/// moves relative to a full-history scan. This is the only coverage of the
/// `changes_at_ts` view + `run_coupling_scoped` SQL — without it a broken
/// cutoff would ship silently and only surface in the timeline consumer.
#[test]
fn scoped_history_cutoff_limits_churn_and_coupling() {
    use codelore_lib::analyses::code_health::{HealthScanCtx, run_code_health_scoped};
    let repo = codelore_lib::test_support::biomarker_repo::build();
    let gix = codelore_lib::repo::GixRepo::open(repo.dir.path()).expect("open");
    let db = codelore_lib::facts::FactsDb::new_in_memory().expect("db");
    let opts = codelore_lib::test_support::permissive_coupling_opts(repo.dir.path().to_path_buf());
    db.ingest(&gix, &opts).expect("ingest");

    // Full history (cutoff None) vs a cutoff after the 3rd of six commits
    // (fixture dates run 2026-06-01 .. 2026-06-06; the dup co-changes and the
    // final complex touch land on 06-04..06-06 and are excluded here).
    let full = run_code_health_scoped(&db, &opts, &HealthScanCtx::head()).expect("full");
    let mut cx = HealthScanCtx::head();
    cx.history_cutoff = Some("2026-06-03T23:59:59Z".to_string());
    let cut = run_code_health_scoped(&db, &opts, &cx).expect("cutoff");

    // The cutoff path must execute (no SQL error above) and yield valid scores.
    assert!(!cut.is_empty(), "cutoff scan must yield rows");
    for r in &cut {
        assert!(
            (0.0..=100.0).contains(&r.score),
            "score in [0,100] for {}: {}",
            r.path,
            r.score
        );
    }

    // Excluding the later commits changes the churn/coupling inputs, so at
    // least one file's score must differ from the full-history scan.
    let full_by: std::collections::HashMap<_, _> =
        full.iter().map(|r| (r.path.clone(), r.score)).collect();
    let moved = cut.iter().any(|r| {
        full_by
            .get(&r.path)
            .is_none_or(|f| (r.score - f).abs() > 1e-9)
    });
    assert!(
        moved,
        "history cutoff must change at least one file's score vs full history"
    );
}

/// Locks the 0.55 / 0.28 band cut points: every row's band must equal the
/// threshold function applied to its `structural_risk`. Catches a silent
/// threshold change in the SQL that the range/membership tests would miss.
#[test]
fn code_health_band_matches_thresholds() {
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = biomarker_opts(fx.dir.path());
    db.ingest(&repo, &opts).expect("ingest");
    let rows = run_code_health(&db, &opts).expect("run");
    assert!(!rows.is_empty());
    for r in &rows {
        let expected = if r.structural_risk >= 0.55 {
            "red"
        } else if r.structural_risk >= 0.28 {
            "yellow"
        } else {
            "green"
        };
        assert_eq!(
            r.band, expected,
            "band {} != expected {} for structural_risk {}",
            r.band, expected, r.structural_risk
        );
    }
}

// ─── corpus-percentile lens (additive) ───────────────────────────────────────

/// A `QUANTILE_POINTS`-long breakpoint vector rising linearly from `min` to
/// `max`, so `q[i] == min + (max - min) * i / (QUANTILE_POINTS - 1)`. With
/// `min = 0`, `max = 1000` the breakpoint index equals the value, so a metric
/// value of `v` resolves to corpus percentile `v / 1000`.
#[allow(clippy::cast_precision_loss)]
fn linear_quantiles(min: f64, max: f64) -> Vec<f64> {
    let last = (QUANTILE_POINTS - 1) as f64;
    (0..QUANTILE_POINTS)
        .map(|i| min + (max - min) * (i as f64) / last)
        .collect()
}

/// Every corpus metric for `language` carries the same `0..=1000` linear ramp
/// and a sample count above the floor, so any file's per-metric percentile is
/// its raw value / 1000. Covers only the named language(s) — a file in any
/// other language falls outside the artifact and gets `corpus_percentile: None`.
fn ramp_artifact(languages: &[&str]) -> CalibrationArtifact {
    let metrics = ["cyclomatic", "cognitive", "sloc", "nargs", "max_nesting"];
    CalibrationArtifact {
        format_version: CALIBRATION_FORMAT_VERSION,
        corpus_vintage: "test-ramp".to_string(),
        generated_at: "2026-07-12T00:00:00Z".to_string(),
        repos_included: 2,
        repos_attempted: 2,
        languages: languages
            .iter()
            .map(|lang| LanguageTable {
                language: (*lang).to_string(),
                sample_functions: 4_000,
                strata: vec![Stratum {
                    sloc_min: 0,
                    sloc_max: u64::MAX,
                    metrics: metrics
                        .iter()
                        .map(|m| MetricQuantiles {
                            metric: (*m).to_string(),
                            quantiles: linear_quantiles(0.0, 1000.0),
                        })
                        .collect(),
                }],
            })
            .collect(),
        repo_metrics: None,
    }
}

fn write_calibration(art: &CalibrationArtifact) -> tempfile::TempPath {
    let mut f = tempfile::Builder::new()
        .prefix("code-health-calib")
        .suffix(".calib.json")
        .tempfile()
        .expect("create temp artifact");
    f.write_all(&serde_json::to_vec(art).expect("serialize"))
        .expect("write artifact");
    f.into_temp_path()
}

/// THE ADDITIVITY CONTRACT (the plan's non-negotiable). Running code-health with
/// a calibration artifact must not perturb ANY pre-existing field: the corpus
/// lens is a pure additive post-pass join. We run twice on `biomarker_repo` —
/// once with the default artifact resolution (the embedded world corpus),
/// once with an explicit covering rust ramp artifact — and
/// assert every shipped field (`path`, `cognitive`, `score`, `structural_risk`,
/// `percentile`, `band`) is byte-identical between the two runs. Since the new
/// fields carry `skip_serializing_if`, stripping them is equivalent to matching
/// the shipped serialized form.
#[test]
fn corpus_lens_is_additive_over_shipped_fields() {
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");

    let run = |calibration: Option<std::path::PathBuf>| {
        let db = FactsDb::new_in_memory().expect("db");
        db.ingest(&repo, &biomarker_opts(fx.dir.path()))
            .expect("ingest");
        let opts = Options {
            calibration,
            ..biomarker_opts(fx.dir.path())
        };
        run_code_health(&db, &opts).expect("run")
    };

    let calib = write_calibration(&ramp_artifact(&["rust"]));
    let without = run(None);
    let with = run(Some(calib.to_path_buf()));

    assert!(!without.is_empty(), "fixture must yield scored rows");
    assert_eq!(
        without.len(),
        with.len(),
        "the corpus pass must not add or drop rows"
    );

    // The shipped fields, serialized. Reuse the row's own serde but drop the two
    // additive keys — that is exactly the "strip the new fields" the plan asks.
    let shipped = |row: &codelore_lib::analyses::code_health::CodeHealthRow| -> serde_json::Value {
        let mut v = serde_json::to_value(row).expect("serialize row");
        let obj = v.as_object_mut().expect("row is an object");
        obj.remove("corpus_percentile");
        obj.remove("beyond_corpus");
        obj.remove("corpus_percentile_ci_low");
        obj.remove("corpus_percentile_ci_high");
        v
    };

    for (a, b) in without.iter().zip(with.iter()) {
        assert_eq!(
            shipped(a),
            shipped(b),
            "corpus calibration perturbed a shipped field for {}",
            a.path
        );
    }

    // Non-vacuity: at least one row must actually carry a corpus percentile in
    // the calibrated run, or the additivity check would pass trivially.
    assert!(
        with.iter().any(|r| r.corpus_percentile.is_some()),
        "the covering rust artifact must populate corpus_percentile on ≥1 rust file"
    );
}

/// With a covering artifact, every rust file's `corpus_percentile` is populated
/// and in range; when the artifact covers only a language the repo lacks, every
/// row stays `None` (unknown-language contract) and no shipped field moves.
#[test]
fn corpus_lens_populates_covered_language_and_skips_others() {
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    db.ingest(&repo, &biomarker_opts(fx.dir.path()))
        .expect("ingest");

    // Covering artifact (rust): rust files get a percentile in [0,1].
    let rust_calib = write_calibration(&ramp_artifact(&["rust"]));
    let covered = {
        let opts = Options {
            calibration: Some(rust_calib.to_path_buf()),
            ..biomarker_opts(fx.dir.path())
        };
        run_code_health(&db, &opts).expect("run covered")
    };
    let rust_rows: Vec<_> = covered
        .iter()
        .filter(|r| {
            codelore_lib::complexity::Tier1Language::from_path(&r.path)
                == Some(codelore_lib::complexity::Tier1Language::Rust)
        })
        .collect();
    assert!(!rust_rows.is_empty(), "fixture is rust");
    for r in &rust_rows {
        let p = r
            .corpus_percentile
            .unwrap_or_else(|| panic!("rust file {} must carry a corpus percentile", r.path));
        assert!(
            (0.0..=1.0).contains(&p),
            "corpus percentile in [0,1] for {}: {p}",
            r.path
        );
    }

    // Non-covering artifact (python only): rust files fall outside → all None.
    let py_calib = write_calibration(&ramp_artifact(&["python"]));
    let uncovered = {
        let opts = Options {
            calibration: Some(py_calib.to_path_buf()),
            ..biomarker_opts(fx.dir.path())
        };
        run_code_health(&db, &opts).expect("run uncovered")
    };
    for r in &uncovered {
        assert!(
            r.corpus_percentile.is_none() && !r.beyond_corpus,
            "a rust file must get None from a python-only artifact, got {:?} for {}",
            r.corpus_percentile,
            r.path
        );
    }
}

// ─── defect-calibration weight application ───────────────────────────────────

/// A syntactically valid defect-calibration artifact carrying `weights`,
/// stamped for `repo_path`, written into `dir`.
fn write_defect_artifact(
    dir: &std::path::Path,
    repo_path: &std::path::Path,
    weights: Vec<(String, f64)>,
) -> std::path::PathBuf {
    use codelore_lib::defect_calibration::{
        DEFECT_FORMAT_VERSION, DefectArtifact, MiningStats, OracleConfig, TuningDecision,
        ValidationMetrics, repo_identity, save,
    };
    let art = DefectArtifact {
        format_version: DEFECT_FORMAT_VERSION,
        repo_identity: repo_identity(repo_path),
        head_at_mining: "0".repeat(40),
        vintage: "defects-2026-07-16".to_string(),
        generated_at: "2026-07-16T00:00:00Z".to_string(),
        oracle: OracleConfig::default(),
        mining: MiningStats::default(),
        validation: ValidationMetrics::default(),
        weights,
        tuning: TuningDecision::Applied {
            auc_train: 0.7,
            auc_validation_default: 0.6,
            auc_validation_tuned: 0.7,
        },
    };
    let path = dir.join("defects.calib.json");
    save(&art, &path).expect("save artifact");
    path
}

/// The load-bearing opt-in contract: a run pointed at an artifact carrying
/// the DEFAULT weights must be byte-identical to a run with no artifact at
/// all — the threading is provably inert until a tuned set actually differs.
#[test]
fn defect_calibration_with_default_weights_is_byte_identical() {
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = Options {
        repo_path: fx.dir.path().to_path_buf(),
        min_revs: 1,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    let baseline = run_code_health(&db, &opts).expect("run without artifact");

    let art_dir = tempfile::tempdir().expect("tempdir");
    let path = write_defect_artifact(
        art_dir.path(),
        fx.dir.path(),
        codelore_lib::defect_calibration::validate::default_weights(),
    );
    let flagged_opts = Options {
        defect_calibration: Some(path),
        ..opts
    };
    let flagged = run_code_health(&db, &flagged_opts).expect("run with default-weights artifact");

    assert_eq!(
        serde_json::to_string(&baseline).expect("json"),
        serde_json::to_string(&flagged).expect("json"),
        "an artifact carrying the default weights must leave output byte-identical"
    );
}

/// Tuned weights must actually reshape `structural_risk` — and exactly as the
/// Rust-side formula predicts: for every scored file the SQL risk under the
/// shifted weights must match `structural_risk_from_intensities` on the same
/// captured intensities within 1e-9 (the hand-prediction, per file).
#[test]
fn defect_calibration_shifted_weights_apply_and_match_the_rust_side_prediction() {
    use codelore_lib::defect_calibration::validate::{
        capture_intensities, structural_risk_from_intensities,
    };

    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = Options {
        repo_path: fx.dir.path().to_path_buf(),
        min_revs: 1,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    let baseline = run_code_health(&db, &opts).expect("baseline run");

    // Move weight mass from god-class onto complex-method; sum stays 1.0.
    let shifted: Vec<(String, f64)> = codelore_lib::defect_calibration::validate::default_weights()
        .into_iter()
        .map(|(name, w)| match name.as_str() {
            "complex-method" => (name, w + 0.11),
            "god-class" => (name, w - 0.11),
            _ => (name, w),
        })
        .collect();
    let art_dir = tempfile::tempdir().expect("tempdir");
    let path = write_defect_artifact(art_dir.path(), fx.dir.path(), shifted.clone());
    let flagged_opts = Options {
        defect_calibration: Some(path),
        ..opts
    };
    let tuned = run_code_health(&db, &flagged_opts).expect("tuned run");
    // The tuned run's scan is the most recent, so the biomarker temp table
    // holds exactly the intensities that scan scored.
    let intensities = capture_intensities(&db).expect("capture intensities");

    assert_ne!(
        serde_json::to_string(&baseline).expect("json"),
        serde_json::to_string(&tuned).expect("json"),
        "a genuinely shifted weight set must change the output"
    );
    let mut parity_checked = 0usize;
    for row in &tuned {
        let Some(intens) = intensities.get(&row.path) else {
            continue;
        };
        let predicted = structural_risk_from_intensities(&shifted, intens);
        assert!(
            (row.structural_risk - predicted).abs() < 1e-9,
            "SQL risk {} diverges from Rust-side prediction {} for {}",
            row.structural_risk,
            predicted,
            row.path
        );
        parity_checked += 1;
    }
    assert!(
        parity_checked > 0,
        "at least one scored file must have captured intensities for the parity loop to bite"
    );
}

/// Applying an artifact mined from a different repository is a hard error;
/// `allow_foreign_calibration` is the explicit escape hatch — and the foreign
/// artifact's weights must then actually apply.
#[test]
fn defect_calibration_foreign_artifact_errors_unless_explicitly_allowed() {
    use codelore_lib::defect_calibration::{
        DEFECT_FORMAT_VERSION, DefectArtifact, MiningStats, OracleConfig, TuningDecision,
        ValidationMetrics, save,
    };

    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = Options {
        repo_path: fx.dir.path().to_path_buf(),
        min_revs: 1,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");
    let baseline = run_code_health(&db, &opts).expect("baseline run");

    let shifted: Vec<(String, f64)> = codelore_lib::defect_calibration::validate::default_weights()
        .into_iter()
        .map(|(name, w)| match name.as_str() {
            "complex-method" => (name, w + 0.11),
            "god-class" => (name, w - 0.11),
            _ => (name, w),
        })
        .collect();
    let art = DefectArtifact {
        format_version: DEFECT_FORMAT_VERSION,
        repo_identity: "0".repeat(64), // not this repo
        head_at_mining: "0".repeat(40),
        vintage: "defects-2026-07-16".to_string(),
        generated_at: "2026-07-16T00:00:00Z".to_string(),
        oracle: OracleConfig::default(),
        mining: MiningStats::default(),
        validation: ValidationMetrics::default(),
        weights: shifted,
        tuning: TuningDecision::DefaultsKept {
            reason: "test".to_string(),
            auc_validation_default: None,
            auc_validation_tuned: None,
        },
    };
    let art_dir = tempfile::tempdir().expect("tempdir");
    let path = art_dir.path().join("defects.calib.json");
    save(&art, &path).expect("save artifact");

    let foreign_opts = Options {
        defect_calibration: Some(path.clone()),
        ..opts.clone()
    };
    let err = run_code_health(&db, &foreign_opts).expect_err("foreign artifact must hard-error");
    assert!(
        format!("{err}").contains("different repository"),
        "error must name the mismatch: {err}"
    );

    let allowed_opts = Options {
        defect_calibration: Some(path),
        allow_foreign_calibration: true,
        ..opts
    };
    let rows = run_code_health(&db, &allowed_opts).expect("allow-foreign must apply");
    assert_ne!(
        serde_json::to_string(&baseline).expect("json"),
        serde_json::to_string(&rows).expect("json"),
        "with the escape hatch the foreign artifact's shifted weights must actually apply"
    );
}

/// With clones excluded (historical-rev scans), a tuned artifact must drive
/// the no-DRY renormalization divisor from ITS dry weight — per file, the SQL
/// risk must equal the non-DRY weighted intensity sum divided by
/// `1 - dry_weight`, clamped to 1.0.
#[test]
fn defect_calibration_recomputes_the_no_dry_scale_from_the_tuned_dry_weight() {
    use codelore_lib::analyses::code_health::{HealthScanCtx, run_code_health_scoped};
    use codelore_lib::defect_calibration::validate::capture_intensities;

    let fx = codelore_lib::test_support::biomarker_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = Options {
        repo_path: fx.dir.path().to_path_buf(),
        min_revs: 1,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    // Double the DRY weight (0.12 → 0.24) at complex-method's expense, so the
    // recomputed divisor (0.76) differs measurably from the default 0.88.
    let tuned: Vec<(String, f64)> = codelore_lib::defect_calibration::validate::default_weights()
        .into_iter()
        .map(|(name, w)| match name.as_str() {
            "dry" => (name, w + 0.12),
            "complex-method" => (name, w - 0.12),
            _ => (name, w),
        })
        .collect();
    let dry_weight = 0.24;
    let art_dir = tempfile::tempdir().expect("tempdir");
    let path = write_defect_artifact(art_dir.path(), fx.dir.path(), tuned.clone());
    let flagged_opts = Options {
        defect_calibration: Some(path),
        ..opts
    };

    let cx = HealthScanCtx {
        include_clones: false,
        ..HealthScanCtx::head()
    };
    let rows = run_code_health_scoped(&db, &flagged_opts, &cx).expect("scoped run");
    // With clones excluded the biomarker table carries no DRY rows, so the
    // captured DRY slot is 0 and the expected risk is the non-DRY dot product
    // rescaled by the tuned divisor.
    let intensities = capture_intensities(&db).expect("capture intensities");

    let mut checked = 0usize;
    for row in &rows {
        let Some(intens) = intensities.get(&row.path) else {
            continue;
        };
        let dot: f64 = tuned.iter().zip(intens).map(|((_, w), i)| w * i).sum();
        let expected = (dot / (1.0 - dry_weight)).min(1.0);
        assert!(
            (row.structural_risk - expected).abs() < 1e-9,
            "no-DRY risk {} diverges from tuned-divisor prediction {} for {}",
            row.structural_risk,
            expected,
            row.path
        );
        checked += 1;
    }
    assert!(
        checked > 0,
        "at least one scored file must have captured intensities for the divisor check to bite"
    );
}