testing-conventions 0.0.63

Enforce testing conventions in libraries (Python, TypeScript, and Rust).
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
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
//! Diff-scoped coverage floor (Python — #132; TypeScript — #135; Rust — #136;
//! folded into `unit coverage --base` — #162; parent #46).
//!
//! Enforces the README Coverage rule over the lines a diff touches: where
//! [`crate::coverage`] measures the *whole* suite against the configured floor
//! (#26), the `measure*` functions here measure that same floor over only the
//! lines `<base>...HEAD` added or modified — `covered ÷ total-changed-executable`,
//! against the thresholds `unit coverage` enforces whole-tree. `unit coverage
//! --base` routes here, so a diff that clears the configured floor passes even with
//! an uncovered changed line, and one below it fails no matter how small (#162).
//!
//! Two inputs are combined:
//!   - the **diff** — [`changed_lines`] runs `git diff --unified=0 <base>...HEAD`
//!     and returns the new-side line numbers each file gained. This diff machinery
//!     is language-agnostic, shared by all three arms.
//!   - the **coverage** — per the language. Python ([`measure`]) reads coverage.py's
//!     per-file lines and branch arcs ([`crate::coverage::measure_patch_report`]),
//!     restricting the `percent_covered` ratio to the changed lines
//!     ([`evaluate_patch`]). TypeScript ([`measure_typescript`]) reduces vitest's v8
//!     export to the four per-metric counts
//!     ([`crate::coverage::measure_patch_typescript_detail`]) and Rust
//!     ([`measure_rust`]) reduces `cargo llvm-cov`'s export to the per-region counts
//!     ([`crate::coverage::measure_patch_rust_detail`]); each metric's ratio is then
//!     restricted to the changed lines ([`evaluate_patch_typescript`] /
//!     [`evaluate_patch_rust`]). Either way, non-executable changed lines (comments,
//!     blanks) and `coverage`-exempt files have nothing to cover and drop out of the
//!     ratio.
//!
//! Relationship to the commit-scoped co-change rule ([`crate::co_change`], #33):
//! co-change enforces that a changed source and its colocated *test* move
//! together; the diff-scoped floor enforces that the changed *lines* are actually
//! exercised. They are complementary, not overlapping — co-change can pass (the
//! test file changed) while the floor fails (the change isn't covered), and
//! vice versa.

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

use anyhow::{bail, Context, Result};

use crate::coverage::{
    self, FileCoverage, Outcome, RustThresholds, Thresholds, TypeScriptThresholds,
};

/// TypeScript source extensions the diff-scoped floor scopes to — the set
/// `coverage`'s `TS_INCLUDE` measures. A `.d.ts` declaration ends in `.ts` but
/// carries no runtime code; vitest excludes it from the report, so its changed
/// lines find nothing to cover and are skipped without a special case here.
const TS_EXTENSIONS: [&str; 4] = [".ts", ".tsx", ".mts", ".cts"];

/// Diff-scoped Python coverage floor (#162): measure `thresholds` over the
/// `<base>...HEAD` changed `.py` lines instead of the whole tree. `omit` is the
/// `coverage`-rule exemptions, as in [`crate::coverage::measure`] — an exempt file
/// is omitted from the run, so its changed lines drop out of the ratio.
///
/// Scopes to `.py` sources and returns early — with no coverage run — when the diff
/// touches none, so a PR that changes only docs or other languages doesn't pay for a
/// measurement (and is vacuously covered). Requires coverage.py + pytest + git; an
/// unresolvable `base` surfaces as an error rather than a silent pass.
pub fn measure(
    root: &Path,
    base: &str,
    thresholds: Thresholds,
    omit: &[String],
    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
) -> Result<Outcome> {
    let mut changed = changed_lines(root, base)?;
    changed.retain(|path, _| path.ends_with(".py"));
    lift_exempt_lines(&mut changed, exempt_lines);
    if changed.is_empty() {
        return Ok(Outcome::Pass);
    }
    let report = coverage::measure_patch_report(root, omit)?;
    let files = relative_keys(report.files, root);
    Ok(evaluate_patch(&changed, &files, thresholds))
}

/// Drop the line-scoped `coverage` exemptions (#226) from a `--base` diff's changed-line
/// set, so a changed line that is line-exempt is lifted from the diff floor — the
/// counterpart to a whole-file exemption dropping the file. The over-exemption guard is
/// the whole-tree floor's job ([`measure_line_exempt`], the `unit coverage` job the
/// reusable workflow runs alongside `--base`); the diff job can't classify a line its
/// diff didn't touch, so here the exempt lines are simply removed.
fn lift_exempt_lines(
    changed: &mut BTreeMap<String, BTreeSet<u64>>,
    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
) {
    for (file, exempt) in exempt_lines {
        if let Some(lines) = changed.get_mut(file) {
            lines.retain(|&line| !u32::try_from(line).is_ok_and(|line| exempt.contains(&line)));
        }
    }
}

/// Pure: the configured floor measured over the changed lines. Reproduces
/// coverage.py's `percent_covered` — (executed lines + taken branch arcs) ÷
/// (executable lines + all branch arcs) — restricted to the lines the diff touched,
/// so the same number `unit coverage` enforces whole-tree is judged on the diff.
///
/// A changed line absent from `files` (a comment or blank, a test file, or a
/// `coverage`-exempt file omitted from the run) has nothing to cover and is skipped;
/// when nothing executable changed, the diff is vacuously covered (`Pass`). With
/// `branch`, a branch arc counts toward the ratio when its source line is in the diff
/// — taken arcs as covered, untaken as missed — exactly as the whole-tree total folds
/// branches in. No small-diff carve-out: a tiny diff below the floor fails like any
/// other (#162).
fn evaluate_patch(
    changed: &BTreeMap<String, BTreeSet<u64>>,
    files: &BTreeMap<String, FileCoverage>,
    thresholds: Thresholds,
) -> Outcome {
    let (covered, total) = python_ratio(changed, files, thresholds.branch);
    if total == 0 {
        return Outcome::Pass;
    }
    let actual = 100.0 * covered as f64 / total as f64;
    // A hair of tolerance so a percent that rounds to the floor isn't failed by float
    // noise (matches the whole-tree `coverage::evaluate`).
    if actual + 1e-9 >= f64::from(thresholds.fail_under) {
        Outcome::Pass
    } else {
        Outcome::Fail(format!(
            "changed-line coverage {actual:.2}% is below the required {}%",
            thresholds.fail_under
        ))
    }
}

/// Pure: coverage.py's `percent_covered` numerator/denominator restricted to the lines
/// in `selected` — (executed lines + taken branch arcs) over (executable lines + all
/// branch arcs), counting only the selected lines and the arcs whose source is selected.
/// Shared by the diff-scoped floor ([`evaluate_patch`], where `selected` is the changed
/// lines) and the line-scoped exemption floor ([`measure_line_exempt`], where it's the
/// measured lines minus the exempt ones). Over *every* measured line it reproduces the
/// whole-tree total exactly.
fn python_ratio(
    selected: &BTreeMap<String, BTreeSet<u64>>,
    files: &BTreeMap<String, FileCoverage>,
    branch: bool,
) -> (u64, u64) {
    let mut covered: u64 = 0;
    let mut total: u64 = 0;
    for (file, lines) in selected {
        let Some(cov) = files.get(file) else {
            continue;
        };
        let executed: BTreeSet<u64> = cov.executed_lines.iter().copied().collect();
        let missing: BTreeSet<u64> = cov.missing_lines.iter().copied().collect();
        for &line in lines {
            if executed.contains(&line) {
                covered += 1;
                total += 1;
            } else if missing.contains(&line) {
                total += 1;
            }
        }
        if branch {
            for arc in &cov.executed_branches {
                if arc_source_in(arc, lines) {
                    covered += 1;
                    total += 1;
                }
            }
            for arc in &cov.missing_branches {
                if arc_source_in(arc, lines) {
                    total += 1;
                }
            }
        }
    }
    (covered, total)
}

/// Whether a branch arc's source line (the first of its `[src, dst]` pair; `dst` may
/// be a negative exit, which is irrelevant) falls in `lines`.
fn arc_source_in(arc: &[i64], lines: &BTreeSet<u64>) -> bool {
    arc.first()
        .and_then(|&src| u64::try_from(src).ok())
        .is_some_and(|src| lines.contains(&src))
}

/// Diff-scoped TypeScript coverage floor (#162): the four vitest metrics measured
/// over the `<base>...HEAD` changed `.ts`/`.tsx`/`.mts`/`.cts` lines instead of the
/// whole tree. `exclude` is the `coverage`-rule exemptions, as in
/// [`crate::coverage::measure_typescript`] — an excluded file is left out of the
/// run, so its changed lines drop out of the ratios.
///
/// Scopes to TypeScript sources and returns early — with no coverage run — when the
/// diff touches none, so a PR that changes only docs or other languages doesn't pay
/// for a measurement (and is vacuously covered). Requires vitest + git; an
/// unresolvable `base` surfaces as an error rather than a silent pass.
pub fn measure_typescript(
    root: &Path,
    base: &str,
    thresholds: TypeScriptThresholds,
    exclude: &[String],
    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
) -> Result<Outcome> {
    let mut changed = changed_lines(root, base)?;
    changed.retain(|path, _| TS_EXTENSIONS.iter().any(|ext| path.ends_with(ext)));
    lift_exempt_lines(&mut changed, exempt_lines);
    if changed.is_empty() {
        return Ok(Outcome::Pass);
    }
    let detail = relative_keys(
        coverage::measure_patch_typescript_detail(root, exclude)?,
        root,
    );
    Ok(evaluate_patch_typescript(&changed, &detail, thresholds))
}

/// Pure: the four vitest floors measured over the changed lines. Each metric's
/// ratio is restricted to the lines the diff touched, so the same numbers
/// `unit coverage` enforces whole-tree are judged on the diff:
///   - **statements**: a `statementMap` entry counts when any line in its
///     `start..=end` is a changed line; covered when its flag is set.
///   - **lines**: a changed line counts when ≥1 statement *starts* on it; covered
///     when ≥1 statement starting on it is covered.
///   - **branches**: a branch arm counts when its `source_line` is a changed line;
///     covered when its flag is set.
///   - **functions**: a function counts when its `decl_line` is a changed line;
///     covered when its flag is set.
///
/// A changed file absent from `detail` (a test file, a declaration file, or a
/// `coverage`-exempt file left out of the run) has nothing to cover and is skipped.
/// Each metric's percent is `100 * covered / total`, or `100` when its denominator
/// is empty — a diff-scoped empty denominator is **vacuously satisfied**, not the
/// "measured no code" failure the whole-tree [`coverage::evaluate_typescript`]
/// returns (a diff may legitimately touch no branches or functions). The fail
/// message lists every metric below its floor, matching
/// [`coverage::evaluate_typescript`]'s. No small-diff carve-out: a tiny diff below
/// the floor fails like any other (#162).
fn evaluate_patch_typescript(
    changed: &BTreeMap<String, BTreeSet<u64>>,
    detail: &BTreeMap<String, coverage::TsPatchCoverage>,
    thresholds: TypeScriptThresholds,
) -> Outcome {
    let (mut s_cov, mut s_tot) = (0u64, 0u64);
    let (mut l_cov, mut l_tot) = (0u64, 0u64);
    let (mut b_cov, mut b_tot) = (0u64, 0u64);
    let (mut f_cov, mut f_tot) = (0u64, 0u64);

    for (file, lines) in changed {
        let Some(cov) = detail.get(file) else {
            continue;
        };

        // Statements: count one whenever any line it spans was changed.
        for &(start, end, covered) in &cov.statements {
            if (start..=end).any(|line| lines.contains(&line)) {
                s_tot += 1;
                if covered {
                    s_cov += 1;
                }
            }
        }

        // Lines: a changed line on which ≥1 statement *starts* counts; covered when
        // ≥1 statement starting on it is covered.
        for &line in lines {
            let mut starts_here = false;
            let mut covered_here = false;
            for &(start, _end, covered) in &cov.statements {
                if start == line {
                    starts_here = true;
                    covered_here |= covered;
                }
            }
            if starts_here {
                l_tot += 1;
                if covered_here {
                    l_cov += 1;
                }
            }
        }

        // Branch arms: count one whenever its source line was changed.
        for &(source_line, covered) in &cov.branch_arms {
            if lines.contains(&source_line) {
                b_tot += 1;
                if covered {
                    b_cov += 1;
                }
            }
        }

        // Functions: count one whenever its declaration line was changed.
        for &(decl_line, covered) in &cov.functions {
            if lines.contains(&decl_line) {
                f_tot += 1;
                if covered {
                    f_cov += 1;
                }
            }
        }
    }

    // An empty denominator is vacuously full (100%) — a diff may touch no branch or
    // function, which is satisfied, not the whole-tree "measured no code" failure.
    let pct = |covered: u64, total: u64| {
        if total == 0 {
            100.0
        } else {
            100.0 * covered as f64 / total as f64
        }
    };
    let checks = [
        ("lines", pct(l_cov, l_tot), thresholds.lines),
        ("branches", pct(b_cov, b_tot), thresholds.branches),
        ("functions", pct(f_cov, f_tot), thresholds.functions),
        ("statements", pct(s_cov, s_tot), thresholds.statements),
    ];
    let mut shortfalls = Vec::new();
    for (name, actual, required) in checks {
        // A hair of tolerance so a percent that rounds to the floor isn't failed by
        // float noise (matches the whole-tree `coverage::evaluate_typescript`).
        if actual + 1e-9 < f64::from(required) {
            shortfalls.push(format!("{name} {actual:.2}% < {required}%"));
        }
    }
    if shortfalls.is_empty() {
        Outcome::Pass
    } else {
        Outcome::Fail(format!(
            "coverage below thresholds: {}",
            shortfalls.join(", ")
        ))
    }
}

/// Diff-scoped Rust coverage floor (#162): the `cargo llvm-cov` regions/lines
/// metrics measured over the `<base>...HEAD` changed `.rs` lines instead of the
/// whole tree. `ignore` is the `coverage`-rule exemptions, as in
/// [`crate::coverage::measure_rust`] — an exempt file is dropped from the run, so
/// its changed lines drop out of the ratios.
///
/// Scopes to `.rs` sources and returns early — with no coverage run — when the diff
/// touches none, so a PR that changes only docs or other languages doesn't pay for a
/// measurement (and is vacuously covered). Requires `cargo-llvm-cov` + git; an
/// unresolvable `base` surfaces as an error rather than a silent pass.
pub fn measure_rust(
    root: &Path,
    base: &str,
    thresholds: RustThresholds,
    ignore: &[String],
    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
    features: &[String],
) -> Result<Outcome> {
    let mut changed = changed_lines(root, base)?;
    changed.retain(|path, _| path.ends_with(".rs"));
    lift_exempt_lines(&mut changed, exempt_lines);
    if changed.is_empty() {
        return Ok(Outcome::Pass);
    }
    let detail = relative_keys(
        coverage::measure_patch_rust_detail(root, ignore, features)?,
        root,
    );
    Ok(evaluate_patch_rust(&changed, &detail, thresholds))
}

/// Pure: the two `cargo llvm-cov` floors (regions, lines) measured over the changed
/// lines. Each metric's ratio is restricted to the lines the diff touched, so the
/// same numbers `unit coverage` enforces whole-tree are judged on the diff:
///   - **regions**: a code region counts when any line in its `start..=end` is a
///     changed line; covered when its flag is set.
///   - **lines**: a changed line counts when ≥1 region covers it (`start <= line <=
///     end`); covered when ≥1 covering region has its flag set.
///
/// A changed file absent from `detail` (a test-only file or a `coverage`-exempt file
/// dropped from the run) has nothing to cover and is skipped. Each metric's percent
/// is `100 * covered / total`, or `100` when its denominator is empty — a
/// diff-scoped empty denominator is **vacuously satisfied**, not the "measured no
/// code" failure the whole-tree [`coverage::evaluate_rust`] returns (a diff may
/// legitimately touch no measured region). The fail message lists every metric below
/// its floor, matching [`coverage::evaluate_rust`]'s. No small-diff carve-out: a tiny
/// diff below the floor fails like any other (#162).
fn evaluate_patch_rust(
    changed: &BTreeMap<String, BTreeSet<u64>>,
    detail: &BTreeMap<String, coverage::RustPatchCoverage>,
    thresholds: RustThresholds,
) -> Outcome {
    let (mut r_cov, mut r_tot) = (0u64, 0u64);
    let (mut l_cov, mut l_tot) = (0u64, 0u64);

    for (file, lines) in changed {
        let Some(cov) = detail.get(file) else {
            continue;
        };

        // Regions: count one whenever any line it spans was changed.
        for &(start, end, covered) in &cov.regions {
            if (start..=end).any(|line| lines.contains(&line)) {
                r_tot += 1;
                if covered {
                    r_cov += 1;
                }
            }
        }

        // Lines: a changed line covered by ≥1 region counts; covered when ≥1 region
        // covering it has its flag set.
        for &line in lines {
            let mut measured = false;
            let mut covered_here = false;
            for &(start, end, covered) in &cov.regions {
                if start <= line && line <= end {
                    measured = true;
                    covered_here |= covered;
                }
            }
            if measured {
                l_tot += 1;
                if covered_here {
                    l_cov += 1;
                }
            }
        }
    }

    // An empty denominator is vacuously full (100%) — a diff may touch no measured
    // region, which is satisfied, not the whole-tree "measured no code" failure.
    let pct = |covered: u64, total: u64| {
        if total == 0 {
            100.0
        } else {
            100.0 * covered as f64 / total as f64
        }
    };
    // `regions` is opt-in (#206): skip the region check unless a config set a floor,
    // matching the whole-tree `coverage::evaluate_rust`.
    let mut checks: Vec<(&str, f64, u8)> = Vec::new();
    if let Some(regions) = thresholds.regions {
        checks.push(("regions", pct(r_cov, r_tot), regions));
    }
    checks.push(("lines", pct(l_cov, l_tot), thresholds.lines));
    let mut shortfalls = Vec::new();
    for (name, actual, required) in checks {
        // A hair of tolerance so a percent that rounds to the floor isn't failed by
        // float noise (matches the whole-tree `coverage::evaluate_rust`).
        if actual + 1e-9 < f64::from(required) {
            shortfalls.push(format!("{name} {actual:.2}% < {required}%"));
        }
    }
    if shortfalls.is_empty() {
        Outcome::Pass
    } else {
        Outcome::Fail(format!(
            "coverage below thresholds: {}",
            shortfalls.join(", ")
        ))
    }
}

/// The new-side lines each file gained in `repo`'s `<base>...HEAD` diff, keyed by
/// `repo`-relative path. The diff machinery shared by the TS / Rust twins.
///
/// `<base>...HEAD` is the merge-base diff — the changes this branch introduced
/// (what a PR shows). `--unified=0` drops context lines so every `+` line is a
/// real addition; `--no-renames` keeps a rename a delete + an add (the added side
/// is held to coverage); `--relative` reports paths relative to `repo`. Returns an
/// error if `git diff` fails (e.g. `base` names no resolvable ref).
pub fn changed_lines(repo: &Path, base: &str) -> Result<BTreeMap<String, BTreeSet<u64>>> {
    let range = format!("{base}...HEAD");
    let output = Command::new("git")
        .current_dir(repo)
        .args([
            "diff",
            "--no-color",
            "--no-renames",
            "--unified=0",
            "--relative",
            &range,
        ])
        .output()
        .with_context(|| format!("running `git diff` in `{}`", repo.display()))?;
    if !output.status.success() {
        bail!(
            "`git diff {range}` failed in `{}`: {}",
            repo.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(parse_unified_diff(&String::from_utf8_lossy(&output.stdout)))
}

/// Pure: parse `git diff --unified=0` output into the new-side lines each file
/// gained. Tracks the current file from each `+++` header and the new-side line
/// counter from each `@@ … +c,d @@` hunk header, then records every following `+`
/// line (a deletion `-` consumes no new-side number). A deleted file
/// (`+++ /dev/null`) yields no entry.
fn parse_unified_diff(diff: &str) -> BTreeMap<String, BTreeSet<u64>> {
    let mut changed: BTreeMap<String, BTreeSet<u64>> = BTreeMap::new();
    let mut current: Option<String> = None;
    let mut next_line: u64 = 0;
    for line in diff.lines() {
        if let Some(header) = line.strip_prefix("+++ ") {
            current = new_side_path(header);
        } else if line.starts_with("@@") {
            if let Some(start) = hunk_new_start(line) {
                next_line = start;
            }
        } else if line.starts_with('+') {
            // An added new-side line — the `+++` header is handled above, so this
            // is diff body. Record it against the current file and advance.
            if let Some(file) = &current {
                changed.entry(file.clone()).or_default().insert(next_line);
            }
            next_line += 1;
        }
        // `-` (deleted) and metadata lines consume no new-side line and are skipped.
    }
    changed
}

/// The `repo`-relative new-side path from a `+++` diff header, or `None` for a
/// deletion (`+++ /dev/null`). Strips git's `b/` prefix and a trailing tab.
fn new_side_path(header: &str) -> Option<String> {
    let path = header
        .split('\t')
        .next()
        .unwrap_or(header)
        .trim_end_matches('\r');
    if path == "/dev/null" {
        return None;
    }
    let path = path.strip_prefix("b/").unwrap_or(path);
    Some(path.replace('\\', "/"))
}

/// The new-side start line from a hunk header `@@ -a,b +c,d @@ …` — the `c`. With
/// `--unified=0` the added lines that follow are numbered consecutively from it.
fn hunk_new_start(header: &str) -> Option<u64> {
    let plus = header.split_whitespace().find(|t| t.starts_with('+'))?;
    let digits = plus.trim_start_matches('+');
    digits.split(',').next().unwrap_or(digits).parse().ok()
}

/// Re-key a report's per-file map to `root`-relative `/`-joined paths so they match
/// the diff's paths. coverage.py reports paths relative to where it ran (here
/// `root`) and vitest reports absolute paths; an absolute path is stripped to
/// `root`, a relative one left as-is.
fn relative_keys<V>(files: BTreeMap<String, V>, root: &Path) -> BTreeMap<String, V> {
    files
        .into_iter()
        .map(|(key, value)| {
            let path = Path::new(&key);
            let rel = path
                .strip_prefix(root)
                .unwrap_or(path)
                .to_string_lossy()
                .replace('\\', "/");
            (rel, value)
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Line-scoped coverage exemptions — issue #226.
//
// A `coverage` exemption with a `lines` list excuses only those lines from the floor,
// not the whole file. No coverage tool excludes individual line *numbers* from the
// outside (coverage.py / v8 / llvm-cov all do it through source pragmas, which this
// tool can't write), so the floor is recomputed from the same per-file detail the
// diff-scoped floor reads — the measured lines minus the exempt ones. A determinism
// guard (the counterpart to the stale-path rule) keeps the list honest: every listed
// line must be genuinely uncovered, and an unlisted uncovered line still fails.
// ---------------------------------------------------------------------------

/// Diff-free Python coverage floor with line-scoped exemptions (#226): measure
/// `thresholds` over every measured line *except* the `exempt_lines`. `omit` is the
/// whole-file `coverage` exemptions, as in [`crate::coverage::measure`]. Requires
/// coverage.py + pytest. The line-exempt path runs only when `exempt_lines` is
/// non-empty; otherwise the caller takes the unchanged tool-total path.
pub fn measure_line_exempt(
    root: &Path,
    thresholds: Thresholds,
    omit: &[String],
    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
) -> Result<Outcome> {
    let report = coverage::measure_report(root, omit)?;
    let files = relative_keys(report.files, root);
    let detail: BTreeMap<String, (BTreeSet<u64>, BTreeSet<u64>)> = files
        .iter()
        .map(|(file, cov)| (file.clone(), python_measured_missed(cov, thresholds.branch)))
        .collect();
    let line_set = apply_line_exemptions(&detail, exempt_lines)?;
    let (covered, total) = python_ratio(&line_set, &files, thresholds.branch);
    Ok(floor_outcome(covered, total, thresholds.fail_under))
}

/// TypeScript twin of [`measure_line_exempt`] (#226): the four vitest metrics measured
/// over every measured line except the `exempt_lines`. `exclude` is the whole-file
/// `coverage` exemptions, as in [`crate::coverage::measure_typescript`]. Requires
/// vitest + `@vitest/coverage-v8`.
pub fn measure_line_exempt_typescript(
    root: &Path,
    thresholds: TypeScriptThresholds,
    exclude: &[String],
    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
) -> Result<Outcome> {
    let detail = relative_keys(
        coverage::measure_patch_typescript_detail(root, exclude)?,
        root,
    );
    let measured_missed: BTreeMap<String, (BTreeSet<u64>, BTreeSet<u64>)> = detail
        .iter()
        .map(|(file, cov)| (file.clone(), ts_measured_missed(cov)))
        .collect();
    let line_set = apply_line_exemptions(&measured_missed, exempt_lines)?;
    Ok(evaluate_patch_typescript(&line_set, &detail, thresholds))
}

/// Rust twin of [`measure_line_exempt`] (#226): the `cargo llvm-cov` regions/lines
/// metrics measured over every measured line except the `exempt_lines`. `ignore` is the
/// whole-file `coverage` exemptions, as in [`crate::coverage::measure_rust`]. Requires
/// `cargo-llvm-cov`.
pub fn measure_line_exempt_rust(
    root: &Path,
    thresholds: RustThresholds,
    ignore: &[String],
    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
    features: &[String],
) -> Result<Outcome> {
    let detail = relative_keys(
        coverage::measure_patch_rust_detail(root, ignore, features)?,
        root,
    );
    let measured_missed: BTreeMap<String, (BTreeSet<u64>, BTreeSet<u64>)> = detail
        .iter()
        .map(|(file, cov)| (file.clone(), rust_measured_missed(cov, thresholds)))
        .collect();
    let line_set = apply_line_exemptions(&measured_missed, exempt_lines)?;
    Ok(evaluate_patch_rust(&line_set, &detail, thresholds))
}

/// The whole-tree floor verdict for a recomputed `covered`/`total`, with the same
/// message and float tolerance as the tool-total [`crate::coverage::evaluate`] — a
/// from-detail total with the exempt lines removed is judged exactly as the tool's own.
fn floor_outcome(covered: u64, total: u64, fail_under: u8) -> Outcome {
    if total == 0 {
        return Outcome::Pass;
    }
    let actual = 100.0 * covered as f64 / total as f64;
    if actual + 1e-9 >= f64::from(fail_under) {
        Outcome::Pass
    } else {
        Outcome::Fail(format!(
            "coverage {actual:.2}% is below the required {fail_under}%"
        ))
    }
}

/// The `(measured, missed)` lines for one Python file. `measured` is every executable
/// line (executed or missing); `missed` is what the floor counts against you — the
/// uncovered lines, plus (under branch coverage) any line that is the source of an
/// untaken branch arc.
fn python_measured_missed(cov: &FileCoverage, branch: bool) -> (BTreeSet<u64>, BTreeSet<u64>) {
    let executed: BTreeSet<u64> = cov.executed_lines.iter().copied().collect();
    let missing: BTreeSet<u64> = cov.missing_lines.iter().copied().collect();
    let measured: BTreeSet<u64> = executed.union(&missing).copied().collect();
    let mut missed = missing;
    if branch {
        for arc in &cov.missing_branches {
            if let Some(src) = arc.first().and_then(|&s| u64::try_from(s).ok()) {
                if measured.contains(&src) {
                    missed.insert(src);
                }
            }
        }
    }
    (measured, missed)
}

/// The `(measured, missed)` lines for one TypeScript file. A unit is anchored on the
/// lines it spans — statements over `start..=end`, branch arms and function decls on
/// their line — and `missed` is that set restricted to the uncovered units, so a line
/// carrying any uncovered unit is exemptable.
fn ts_measured_missed(cov: &coverage::TsPatchCoverage) -> (BTreeSet<u64>, BTreeSet<u64>) {
    let mut measured = BTreeSet::new();
    let mut missed = BTreeSet::new();
    // Each unit contributes its line(s): a statement spans `start..=end`, a branch arm
    // and a function declaration sit on a single line. A line is `missed` when any unit
    // on it is uncovered.
    let units = cov
        .statements
        .iter()
        .flat_map(|&(start, end, covered)| (start..=end).map(move |line| (line, covered)))
        .chain(cov.branch_arms.iter().copied())
        .chain(cov.functions.iter().copied());
    for (line, covered) in units {
        measured.insert(line);
        if !covered {
            missed.insert(line);
        }
    }
    (measured, missed)
}

/// The `(measured, missed)` lines for one Rust file. `measured` is every line a code
/// region spans; `missed` honors the enforced metrics — with `regions` on, any line in
/// an uncovered region; with lines-only (`regions = None`), a line covered by regions
/// but by no *covered* one.
fn rust_measured_missed(
    cov: &coverage::RustPatchCoverage,
    thresholds: RustThresholds,
) -> (BTreeSet<u64>, BTreeSet<u64>) {
    let mut measured = BTreeSet::new();
    for &(start, end, _covered) in &cov.regions {
        for line in start..=end {
            measured.insert(line);
        }
    }
    let mut missed = BTreeSet::new();
    for &line in &measured {
        let mut covered_here = false;
        let mut uncovered_region = false;
        for &(start, end, covered) in &cov.regions {
            if start <= line && line <= end {
                if covered {
                    covered_here = true;
                } else {
                    uncovered_region = true;
                }
            }
        }
        let is_missed = if thresholds.regions.is_some() {
            uncovered_region
        } else {
            !covered_here
        };
        if is_missed {
            missed.insert(line);
        }
    }
    (measured, missed)
}

/// The per-file line set the floor is measured over — every measured line minus the
/// exempt ones — after the #226 determinism guard. Each exempt line must be in its
/// file's `missed` set (genuinely failing); a listed line that is covered, or carries
/// no measured code, is a hard error so the exemption can't excuse working code.
fn apply_line_exemptions(
    detail: &BTreeMap<String, (BTreeSet<u64>, BTreeSet<u64>)>,
    exempt_lines: &BTreeMap<String, BTreeSet<u32>>,
) -> Result<BTreeMap<String, BTreeSet<u64>>> {
    let mut over: Vec<String> = Vec::new();
    for (file, lines) in exempt_lines {
        let missed = detail.get(file).map(|(_, missed)| missed);
        for &line in lines {
            let failing = missed.is_some_and(|missed| missed.contains(&u64::from(line)));
            if !failing {
                over.push(format!("\n  {file}:{line}"));
            }
        }
    }
    if !over.is_empty() {
        bail!(
            "a line-scoped coverage exemption may only list uncovered lines, but these are \
             covered or carry no measured code:{}",
            over.concat()
        );
    }
    let mut line_set = BTreeMap::new();
    for (file, (measured, _)) in detail {
        let exempt = exempt_lines.get(file);
        let kept: BTreeSet<u64> = measured
            .iter()
            .copied()
            .filter(|&line| {
                !exempt.is_some_and(|exempt| {
                    u32::try_from(line).is_ok_and(|line| exempt.contains(&line))
                })
            })
            .collect();
        line_set.insert(file.clone(), kept);
    }
    Ok(line_set)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn changed(entries: &[(&str, &[u64])]) -> BTreeMap<String, BTreeSet<u64>> {
        entries
            .iter()
            .map(|(path, lines)| (path.to_string(), lines.iter().copied().collect()))
            .collect()
    }

    // ---- parse_unified_diff --------------------------------------------------

    #[test]
    fn parses_added_lines_from_a_hunk() {
        // `+4,2` → two added lines numbered from 4; the function context after the
        // second `@@` is ignored.
        let diff = "diff --git a/widget.py b/widget.py\n\
                    index abc..def 100644\n\
                    --- a/widget.py\n\
                    +++ b/widget.py\n\
                    @@ -3,0 +4,2 @@ def f(x):\n\
                    +    if x == 99:\n\
                    +        return 7\n";
        assert_eq!(parse_unified_diff(diff), changed(&[("widget.py", &[4, 5])]));
    }

    #[test]
    fn parses_a_new_file_as_added_from_line_one() {
        let diff = "diff --git a/lonely.py b/lonely.py\n\
                    new file mode 100644\n\
                    index 0000000..bbb\n\
                    --- /dev/null\n\
                    +++ b/lonely.py\n\
                    @@ -0,0 +1,2 @@\n\
                    +def lonely():\n\
                    +    return 41\n";
        assert_eq!(parse_unified_diff(diff), changed(&[("lonely.py", &[1, 2])]));
    }

    #[test]
    fn a_deletion_only_hunk_records_no_added_lines() {
        // `+3,0` adds nothing; the `-` lines consume no new-side number.
        let diff = "diff --git a/widget.py b/widget.py\n\
                    index abc..def 100644\n\
                    --- a/widget.py\n\
                    +++ b/widget.py\n\
                    @@ -4,2 +3,0 @@ def f(x):\n\
                    -    dead = 1\n\
                    -    return dead\n";
        assert!(parse_unified_diff(diff).is_empty());
    }

    #[test]
    fn a_deleted_file_yields_no_entry() {
        let diff = "diff --git a/gone.py b/gone.py\n\
                    deleted file mode 100644\n\
                    index abc..0000000\n\
                    --- a/gone.py\n\
                    +++ /dev/null\n\
                    @@ -1,2 +0,0 @@\n\
                    -def gone():\n\
                    -    return 0\n";
        assert!(parse_unified_diff(diff).is_empty());
    }

    #[test]
    fn parses_multiple_files_and_a_single_line_hunk() {
        // `+2` (no count) is one line at line 2; a nested path is kept verbatim.
        let diff = "diff --git a/a.py b/a.py\n\
                    --- a/a.py\n\
                    +++ b/a.py\n\
                    @@ -1,0 +2 @@ def a():\n\
                    +    x = 1\n\
                    diff --git a/pkg/b.py b/pkg/b.py\n\
                    --- a/pkg/b.py\n\
                    +++ b/pkg/b.py\n\
                    @@ -10,0 +11,1 @@\n\
                    +    y = 2\n";
        assert_eq!(
            parse_unified_diff(diff),
            changed(&[("a.py", &[2]), ("pkg/b.py", &[11])])
        );
    }

    // ---- evaluate_patch (diff-scoped floor, #162) ---------------------------

    fn cov(
        executed: &[u64],
        missing: &[u64],
        executed_branches: &[[i64; 2]],
        missing_branches: &[[i64; 2]],
    ) -> FileCoverage {
        FileCoverage {
            executed_lines: executed.to_vec(),
            missing_lines: missing.to_vec(),
            excluded_lines: Vec::new(),
            executed_branches: executed_branches.iter().map(|b| b.to_vec()).collect(),
            missing_branches: missing_branches.iter().map(|b| b.to_vec()).collect(),
        }
    }

    const FLOOR_85: Thresholds = Thresholds {
        fail_under: 85,
        branch: true,
    };

    #[test]
    fn patch_a_fully_covered_diff_passes() {
        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2, 3], &[], &[], &[]))]);
        assert_eq!(
            evaluate_patch(&changed(&[("w.py", &[1, 2, 3])]), &files, FLOOR_85),
            Outcome::Pass
        );
    }

    #[test]
    fn patch_below_floor_fails_and_names_the_percent() {
        // 3 of 4 changed executable lines covered → 75% < 85.
        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2, 3], &[4], &[], &[]))]);
        let out = evaluate_patch(&changed(&[("w.py", &[1, 2, 3, 4])]), &files, FLOOR_85);
        assert!(
            matches!(&out, Outcome::Fail(m) if m.contains("75.00%")),
            "got: {out:?}"
        );
    }

    #[test]
    fn patch_the_same_diff_clears_a_lower_floor() {
        // The #162 behavior: 75% passes a 70 floor despite the uncovered line.
        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2, 3], &[4], &[], &[]))]);
        let floor_70 = Thresholds {
            fail_under: 70,
            branch: true,
        };
        assert_eq!(
            evaluate_patch(&changed(&[("w.py", &[1, 2, 3, 4])]), &files, floor_70),
            Outcome::Pass
        );
    }

    #[test]
    fn patch_counts_branch_arcs_whose_source_is_a_changed_line() {
        // Lines 1,2 executed (2 covered) + a taken arc out of line 2 (covered) and an
        // untaken arc out of line 2 (missed): 3 covered of 4 → 75% < 85.
        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2], &[], &[[2, 3]], &[[2, 4]]))]);
        let out = evaluate_patch(&changed(&[("w.py", &[1, 2])]), &files, FLOOR_85);
        assert!(
            matches!(&out, Outcome::Fail(m) if m.contains("75.00%")),
            "got: {out:?}"
        );
    }

    #[test]
    fn patch_branches_off_ignores_arcs() {
        // Same data, branch disabled: only the two executed lines count → 100%.
        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2], &[], &[[2, 3]], &[[2, 4]]))]);
        let no_branch = Thresholds {
            fail_under: 85,
            branch: false,
        };
        assert_eq!(
            evaluate_patch(&changed(&[("w.py", &[1, 2])]), &files, no_branch),
            Outcome::Pass
        );
    }

    #[test]
    fn patch_a_changed_file_absent_from_coverage_is_skipped() {
        // A test file (never measured) contributes nothing; with no other executable
        // changed line the diff is vacuously covered.
        let files = BTreeMap::from([("w.py".to_string(), cov(&[1], &[], &[], &[]))]);
        assert_eq!(
            evaluate_patch(&changed(&[("w_test.py", &[1, 2])]), &files, FLOOR_85),
            Outcome::Pass
        );
    }

    #[test]
    fn patch_a_diff_with_no_executable_changed_lines_passes() {
        // Changed lines are comments/blanks (in neither executed nor missing) → vacuous.
        let files = BTreeMap::from([("w.py".to_string(), cov(&[1, 2], &[], &[], &[]))]);
        assert_eq!(
            evaluate_patch(&changed(&[("w.py", &[9, 10])]), &files, FLOOR_85),
            Outcome::Pass
        );
    }

    // ---- evaluate_patch_typescript (diff-scoped TS floor, #162) -------------

    use coverage::TsPatchCoverage;

    fn ts_detail(entries: &[(&str, TsPatchCoverage)]) -> BTreeMap<String, TsPatchCoverage> {
        entries
            .iter()
            .map(|(path, cov)| (path.to_string(), cov.clone()))
            .collect()
    }

    const TS_FLOOR_80: TypeScriptThresholds = TypeScriptThresholds {
        lines: 80,
        branches: 80,
        functions: 80,
        statements: 80,
    };

    #[test]
    fn ts_patch_a_fully_covered_diff_passes() {
        // Two statements on lines 1-2, both starting on their line and both covered;
        // a covered function on line 1; a taken branch arm off line 2 → 100% all four.
        let detail = ts_detail(&[(
            "w.ts",
            TsPatchCoverage {
                statements: vec![(1, 1, true), (2, 2, true)],
                branch_arms: vec![(2, true)],
                functions: vec![(1, true)],
            },
        )]);
        assert_eq!(
            evaluate_patch_typescript(&changed(&[("w.ts", &[1, 2])]), &detail, TS_FLOOR_80),
            Outcome::Pass
        );
    }

    #[test]
    fn ts_patch_below_floor_fails_and_names_the_metric() {
        // Four changed lines each carry one statement; three covered, one not →
        // statements (and lines) 75% < 80, named; branches/functions are empty
        // (vacuously 100) and not named.
        let detail = ts_detail(&[(
            "w.ts",
            TsPatchCoverage {
                statements: vec![(1, 1, true), (2, 2, true), (3, 3, true), (4, 4, false)],
                branch_arms: vec![],
                functions: vec![],
            },
        )]);
        let out =
            evaluate_patch_typescript(&changed(&[("w.ts", &[1, 2, 3, 4])]), &detail, TS_FLOOR_80);
        assert!(
            matches!(&out, Outcome::Fail(m)
                if m.contains("statements 75.00% < 80%")
                    && m.contains("lines 75.00% < 80%")
                    && !m.contains("branches")
                    && !m.contains("functions")),
            "got: {out:?}"
        );
    }

    #[test]
    fn ts_patch_the_same_diff_clears_a_lower_floor() {
        // The #162 behavior: the 75% diff passes a 70 floor despite the uncovered line.
        let detail = ts_detail(&[(
            "w.ts",
            TsPatchCoverage {
                statements: vec![(1, 1, true), (2, 2, true), (3, 3, true), (4, 4, false)],
                branch_arms: vec![],
                functions: vec![],
            },
        )]);
        let floor_70 = TypeScriptThresholds {
            lines: 70,
            branches: 70,
            functions: 70,
            statements: 70,
        };
        assert_eq!(
            evaluate_patch_typescript(&changed(&[("w.ts", &[1, 2, 3, 4])]), &detail, floor_70),
            Outcome::Pass
        );
    }

    #[test]
    fn ts_patch_an_untaken_branch_arm_on_a_changed_line_fails_branches() {
        // Line 3's statement ran (covered) but one of its two branch arms never did:
        // branches 50% < 80, named; lines/statements are 100 (the statement is covered).
        let detail = ts_detail(&[(
            "w.ts",
            TsPatchCoverage {
                statements: vec![(3, 3, true)],
                branch_arms: vec![(3, true), (3, false)],
                functions: vec![],
            },
        )]);
        let out = evaluate_patch_typescript(&changed(&[("w.ts", &[3])]), &detail, TS_FLOOR_80);
        assert!(
            matches!(&out, Outcome::Fail(m)
                if m.contains("branches 50.00% < 80%")
                    && !m.contains("lines")
                    && !m.contains("statements")),
            "got: {out:?}"
        );
    }

    #[test]
    fn ts_patch_an_uncovered_function_decl_on_a_changed_line_fails_functions() {
        // A function declared on changed line 9 was never called → functions 0% < 80.
        let detail = ts_detail(&[(
            "w.ts",
            TsPatchCoverage {
                statements: vec![],
                branch_arms: vec![],
                functions: vec![(9, false)],
            },
        )]);
        let out = evaluate_patch_typescript(&changed(&[("w.ts", &[9])]), &detail, TS_FLOOR_80);
        assert!(
            matches!(&out, Outcome::Fail(m) if m.contains("functions 0.00% < 80%")),
            "got: {out:?}"
        );
    }

    #[test]
    fn ts_patch_a_changed_file_absent_from_coverage_is_skipped() {
        // A test file (never measured) contributes nothing; with no other changed
        // executable line the diff is vacuously covered.
        let detail = ts_detail(&[(
            "w.ts",
            TsPatchCoverage {
                statements: vec![(1, 1, true)],
                branch_arms: vec![],
                functions: vec![],
            },
        )]);
        assert_eq!(
            evaluate_patch_typescript(&changed(&[("w.test.ts", &[1, 2])]), &detail, TS_FLOOR_80),
            Outcome::Pass
        );
    }

    #[test]
    fn ts_patch_a_comment_only_diff_passes() {
        // The changed lines carry no statement/branch/function (a comment or blank) →
        // every denominator empty → vacuously covered.
        let detail = ts_detail(&[(
            "w.ts",
            TsPatchCoverage {
                statements: vec![(1, 1, true), (2, 2, true)],
                branch_arms: vec![(2, true)],
                functions: vec![(1, true)],
            },
        )]);
        assert_eq!(
            evaluate_patch_typescript(&changed(&[("w.ts", &[9, 10])]), &detail, TS_FLOOR_80),
            Outcome::Pass
        );
    }

    #[test]
    fn ts_patch_an_empty_diff_passes() {
        // No changed lines at all → vacuously covered at any floor.
        assert_eq!(
            evaluate_patch_typescript(&changed(&[]), &BTreeMap::new(), TS_FLOOR_80),
            Outcome::Pass
        );
    }

    #[test]
    fn ts_patch_a_multiline_statement_counts_when_any_of_its_lines_changed() {
        // A statement spanning lines 3-5 that never ran; only line 4 is in the diff →
        // it still counts (and is uncovered) → statements 0% < 80. No statement
        // *starts* on line 4, so lines has an empty denominator (vacuously 100).
        let detail = ts_detail(&[(
            "w.ts",
            TsPatchCoverage {
                statements: vec![(3, 5, false)],
                branch_arms: vec![],
                functions: vec![],
            },
        )]);
        let out = evaluate_patch_typescript(&changed(&[("w.ts", &[4])]), &detail, TS_FLOOR_80);
        assert!(
            matches!(&out, Outcome::Fail(m)
                if m.contains("statements 0.00% < 80%") && !m.contains("lines")),
            "got: {out:?}"
        );
    }

    // ---- evaluate_patch_rust (diff-scoped Rust floor, #162) -----------------

    use coverage::RustPatchCoverage;

    fn rust_detail(entries: &[(&str, RustPatchCoverage)]) -> BTreeMap<String, RustPatchCoverage> {
        entries
            .iter()
            .map(|(path, cov)| (path.to_string(), cov.clone()))
            .collect()
    }

    const RUST_FLOOR_80: RustThresholds = RustThresholds {
        regions: Some(80),
        lines: 80,
        functions: None,
        branch: None,
    };

    #[test]
    fn rust_patch_a_fully_covered_diff_passes() {
        // Two single-line code regions on lines 1-2, both covered → regions and lines
        // both 100%.
        let detail = rust_detail(&[(
            "w.rs",
            RustPatchCoverage {
                regions: vec![(1, 1, true), (2, 2, true)],
            },
        )]);
        assert_eq!(
            evaluate_patch_rust(&changed(&[("w.rs", &[1, 2])]), &detail, RUST_FLOOR_80),
            Outcome::Pass
        );
    }

    #[test]
    fn rust_patch_below_floor_fails_and_names_the_metrics() {
        // Four single-line regions on lines 1-4; three covered, one not → regions (and
        // lines) 75% < 80, both named.
        let detail = rust_detail(&[(
            "w.rs",
            RustPatchCoverage {
                regions: vec![(1, 1, true), (2, 2, true), (3, 3, true), (4, 4, false)],
            },
        )]);
        let out = evaluate_patch_rust(&changed(&[("w.rs", &[1, 2, 3, 4])]), &detail, RUST_FLOOR_80);
        assert!(
            matches!(&out, Outcome::Fail(m)
                if m.contains("regions 75.00% < 80%")
                    && m.contains("lines 75.00% < 80%")),
            "got: {out:?}"
        );
    }

    #[test]
    fn rust_patch_the_same_diff_clears_a_lower_floor() {
        // The #162 behavior: the 75% diff passes a 70 floor despite the uncovered region.
        let detail = rust_detail(&[(
            "w.rs",
            RustPatchCoverage {
                regions: vec![(1, 1, true), (2, 2, true), (3, 3, true), (4, 4, false)],
            },
        )]);
        let floor_70 = RustThresholds {
            regions: Some(70),
            lines: 70,
            functions: None,
            branch: None,
        };
        assert_eq!(
            evaluate_patch_rust(&changed(&[("w.rs", &[1, 2, 3, 4])]), &detail, floor_70),
            Outcome::Pass
        );
    }

    #[test]
    fn rust_patch_skips_the_region_check_when_regions_is_opt_out() {
        // The zero-config default (#206) sets `regions: None`, so the diff-scoped floor
        // enforces lines only: a diff whose changed lines are all covered passes even
        // though one of its regions is uncovered (lines 1-4 are each covered by ≥1
        // region, but region 4 is not).
        let detail = rust_detail(&[(
            "w.rs",
            RustPatchCoverage {
                regions: vec![(1, 4, true), (4, 4, false)],
            },
        )]);
        let lines_only = RustThresholds {
            regions: None,
            lines: 100,
            functions: None,
            branch: None,
        };
        assert_eq!(
            evaluate_patch_rust(&changed(&[("w.rs", &[1, 2, 3, 4])]), &detail, lines_only),
            Outcome::Pass
        );
    }

    #[test]
    fn rust_patch_an_uncovered_region_on_a_changed_line_fails_both_metrics() {
        // A single uncovered region on changed line 5 → regions 0% and lines 0%, both
        // below the floor.
        let detail = rust_detail(&[(
            "w.rs",
            RustPatchCoverage {
                regions: vec![(5, 5, false)],
            },
        )]);
        let out = evaluate_patch_rust(&changed(&[("w.rs", &[5])]), &detail, RUST_FLOOR_80);
        assert!(
            matches!(&out, Outcome::Fail(m)
                if m.contains("regions 0.00% < 80%") && m.contains("lines 0.00% < 80%")),
            "got: {out:?}"
        );
    }

    #[test]
    fn rust_patch_a_changed_file_absent_from_coverage_is_skipped() {
        // A test-only file (never measured) contributes nothing; with no other changed
        // measured line the diff is vacuously covered.
        let detail = rust_detail(&[(
            "w.rs",
            RustPatchCoverage {
                regions: vec![(1, 1, true)],
            },
        )]);
        assert_eq!(
            evaluate_patch_rust(&changed(&[("other.rs", &[1, 2])]), &detail, RUST_FLOOR_80),
            Outcome::Pass
        );
    }

    #[test]
    fn rust_patch_a_comment_only_diff_passes() {
        // The changed lines (9-10) carry no region (a comment or blank) → both
        // denominators empty → vacuously covered.
        let detail = rust_detail(&[(
            "w.rs",
            RustPatchCoverage {
                regions: vec![(1, 1, true), (2, 2, true)],
            },
        )]);
        assert_eq!(
            evaluate_patch_rust(&changed(&[("w.rs", &[9, 10])]), &detail, RUST_FLOOR_80),
            Outcome::Pass
        );
    }

    #[test]
    fn rust_patch_an_empty_diff_passes() {
        // No changed lines at all → vacuously covered at any floor.
        assert_eq!(
            evaluate_patch_rust(&changed(&[]), &BTreeMap::new(), RUST_FLOOR_80),
            Outcome::Pass
        );
    }

    #[test]
    fn rust_patch_a_multiline_region_counts_when_any_of_its_lines_changed() {
        // A region spanning lines 3-5 that never ran; only line 4 is in the diff → it
        // still counts for both metrics (the region spans line 4, so line 4 is a
        // measured-but-uncovered line) → regions 0% and lines 0% < 80.
        let detail = rust_detail(&[(
            "w.rs",
            RustPatchCoverage {
                regions: vec![(3, 5, false)],
            },
        )]);
        let out = evaluate_patch_rust(&changed(&[("w.rs", &[4])]), &detail, RUST_FLOOR_80);
        assert!(
            matches!(&out, Outcome::Fail(m)
                if m.contains("regions 0.00% < 80%") && m.contains("lines 0.00% < 80%")),
            "got: {out:?}"
        );
    }

    #[test]
    fn rust_patch_a_line_covered_by_any_region_is_covered() {
        // Two overlapping regions span changed line 4 — one uncovered, one covered.
        // For the lines metric the line is covered (≥1 covering region's flag is set);
        // for regions, one of the two counts as covered → regions 50% (< 80, fails) but
        // lines 100% (≥ 80, not named).
        let detail = rust_detail(&[(
            "w.rs",
            RustPatchCoverage {
                regions: vec![(4, 4, false), (4, 6, true)],
            },
        )]);
        let out = evaluate_patch_rust(&changed(&[("w.rs", &[4])]), &detail, RUST_FLOOR_80);
        assert!(
            matches!(&out, Outcome::Fail(m)
                if m.contains("regions 50.00% < 80%") && !m.contains("lines")),
            "got: {out:?}"
        );
    }

    // ---- line-scoped exemptions (#226) --------------------------------------

    fn exempt(entries: &[(&str, &[u32])]) -> BTreeMap<String, BTreeSet<u32>> {
        entries
            .iter()
            .map(|(path, lines)| (path.to_string(), lines.iter().copied().collect()))
            .collect()
    }

    #[test]
    fn python_measured_missed_reads_lines_and_branch_sources() {
        // shim.py's shape: line 1 executed (the `def`), lines 2-4 the never-run body,
        // a missing branch out of line 2. measured = every executable line; missed =
        // the uncovered lines plus the branch source.
        let full = cov(&[1], &[2, 3, 4], &[], &[[2, 3], [2, 4]]);
        let (measured, missed) = python_measured_missed(&full, true);
        assert_eq!(measured, [1, 2, 3, 4].into_iter().collect());
        assert_eq!(missed, [2, 3, 4].into_iter().collect());
        // With branch coverage off, a partial-branch source isn't a miss on its own.
        let partial = cov(&[5], &[], &[], &[[5, 6]]);
        let (_, missed_no_branch) = python_measured_missed(&partial, false);
        assert!(missed_no_branch.is_empty());
        let (_, missed_branch) = python_measured_missed(&partial, true);
        assert_eq!(missed_branch, [5].into_iter().collect());
    }

    #[test]
    fn ts_measured_missed_anchors_units_on_their_lines() {
        // A covered statement on line 1, an uncovered one spanning 3-4, an uncovered
        // branch arm on 1, an uncovered function decl on 6.
        let cov = coverage::TsPatchCoverage {
            statements: vec![(1, 1, true), (3, 4, false)],
            branch_arms: vec![(1, false)],
            functions: vec![(6, false)],
        };
        let (measured, missed) = ts_measured_missed(&cov);
        assert_eq!(measured, [1, 3, 4, 6].into_iter().collect());
        // Line 1 is missed via its uncovered branch arm even though its statement ran.
        assert_eq!(missed, [1, 3, 4, 6].into_iter().collect());
    }

    #[test]
    fn rust_measured_missed_honors_the_enforced_metrics() {
        // An uncovered region on lines 5-6 and a covered one on line 1.
        let cov = coverage::RustPatchCoverage {
            regions: vec![(1, 1, true), (5, 6, false)],
        };
        let with_regions = RustThresholds {
            regions: Some(100),
            lines: 100,
            functions: None,
            branch: None,
        };
        let (measured, missed) = rust_measured_missed(&cov, with_regions);
        assert_eq!(measured, [1, 5, 6].into_iter().collect());
        assert_eq!(missed, [5, 6].into_iter().collect());
        // Lines-only: a line covered by ≥1 covered region isn't a miss; an uncovered
        // region with no covering one still is.
        let lines_only = RustThresholds {
            regions: None,
            lines: 100,
            functions: None,
            branch: None,
        };
        let (_, missed_lines) = rust_measured_missed(&cov, lines_only);
        assert_eq!(missed_lines, [5, 6].into_iter().collect());
    }

    #[test]
    fn apply_line_exemptions_drops_listed_misses_from_the_line_set() {
        // shim measured {1,2,3,4}, missed {2,3,4}; exempting 2-4 leaves {1}.
        let detail = BTreeMap::from([(
            "shim.py".to_string(),
            (
                [1u64, 2, 3, 4].into_iter().collect::<BTreeSet<u64>>(),
                [2u64, 3, 4].into_iter().collect::<BTreeSet<u64>>(),
            ),
        )]);
        let line_set = apply_line_exemptions(&detail, &exempt(&[("shim.py", &[2, 3, 4])])).unwrap();
        assert_eq!(line_set["shim.py"], [1].into_iter().collect());
    }

    #[test]
    fn apply_line_exemptions_rejects_a_covered_listed_line() {
        // Line 1 is measured but not missed (it's covered) — over-exemption is an error.
        let detail = BTreeMap::from([(
            "shim.py".to_string(),
            (
                [1u64, 2].into_iter().collect::<BTreeSet<u64>>(),
                [2u64].into_iter().collect::<BTreeSet<u64>>(),
            ),
        )]);
        let err = apply_line_exemptions(&detail, &exempt(&[("shim.py", &[1, 2])])).unwrap_err();
        assert!(
            err.to_string().contains("uncovered lines") && err.to_string().contains("shim.py:1"),
            "got: {err}"
        );
    }

    #[test]
    fn apply_line_exemptions_rejects_an_unmeasured_listed_line() {
        // A line not measured at all (a comment) can't be exempted either.
        let detail = BTreeMap::from([(
            "w.py".to_string(),
            (
                [2u64].into_iter().collect::<BTreeSet<u64>>(),
                [2u64].into_iter().collect::<BTreeSet<u64>>(),
            ),
        )]);
        let err = apply_line_exemptions(&detail, &exempt(&[("w.py", &[9])])).unwrap_err();
        assert!(err.to_string().contains("w.py:9"), "got: {err}");
    }

    #[test]
    fn floor_outcome_matches_the_whole_tree_message() {
        assert_eq!(floor_outcome(7, 7, 100), Outcome::Pass);
        let out = floor_outcome(7, 8, 100);
        assert!(
            matches!(&out, Outcome::Fail(m) if m == "coverage 87.50% is below the required 100%"),
            "got: {out:?}"
        );
        // An all-exempt file leaves nothing to measure — vacuously a pass.
        assert_eq!(floor_outcome(0, 0, 100), Outcome::Pass);
    }

    #[test]
    fn lift_exempt_lines_removes_exempt_lines_from_the_diff() {
        // The `--base` path drops a changed line that is line-exempt (lines 2-3 here),
        // leaving the rest of the diff to be judged; an exemption for an untouched file
        // is a no-op.
        let mut changed = changed(&[("shim.py", &[1, 2, 3, 4]), ("core.py", &[5])]);
        lift_exempt_lines(
            &mut changed,
            &exempt(&[("shim.py", &[2, 3]), ("gone.py", &[9])]),
        );
        assert_eq!(changed["shim.py"], [1, 4].into_iter().collect());
        assert_eq!(changed["core.py"], [5].into_iter().collect());
    }
}