ripr 0.5.0

Find Rust test-oracle gaps before mutation testing with static RIPR evidence
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
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
//! Private badge summary model and renderer.
//!
//! This module is the rendering substrate for the `ripr` and (future)
//! `ripr+` badges. Its types are intentionally crate-private — the public
//! contract is the JSON wire shape, not the Rust types. See
//! [`docs/BADGE_POLICY.md`](../../../../../docs/BADGE_POLICY.md) for the
//! locked semantics, color thresholds, and JSON shape.
//!
//! Both `ripr` (exposure-gap count) and `ripr+` (exposure + actionable
//! test-efficiency, minus declared intent) badge formats are supported.
//! Suppressions, CI artifacts, and the published Shields endpoint live
//! in their own scoped PRs.

#[cfg(test)]
use crate::analysis::ClassifiedSeam;
use crate::analysis::SeamGripClassCounts;
use crate::analysis::seams::SeamGripClass;
use crate::app::CheckOutput;
use crate::config::{ConfigSeverity, RiprConfig};
use crate::domain::ExposureClass;
use crate::output::json::escape as json_escape;
use crate::output::suppressions::{
    SuppressionEntry, apply_exposure_suppressions, apply_test_efficiency_suppressions,
};
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BadgeKind {
    /// Counts unsuppressed static exposure gaps only.
    Ripr,
    /// Counts unsuppressed exposure gaps plus unsuppressed actionable
    /// test-efficiency findings (excluding declared intent).
    RiprPlus,
}

impl BadgeKind {
    pub fn as_str(self) -> &'static str {
        match self {
            BadgeKind::Ripr => "ripr",
            BadgeKind::RiprPlus => "ripr_plus",
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            BadgeKind::Ripr => "ripr",
            BadgeKind::RiprPlus => "ripr+",
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BadgeStatus {
    Pass,
    Warn,
    Fail,
}

impl BadgeStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            BadgeStatus::Pass => "pass",
            BadgeStatus::Warn => "warn",
            BadgeStatus::Fail => "fail",
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BadgeBasis {
    /// Counts legacy diff/repo `Finding` exposure classes.
    FindingExposure,
    /// Counts classified repo seams using configured seam severity.
    SeamNative,
}

impl BadgeBasis {
    pub fn as_str(self) -> &'static str {
        match self {
            BadgeBasis::FindingExposure => "finding_exposure",
            BadgeBasis::SeamNative => "seam_native",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BadgeCounts {
    pub unsuppressed_exposure_gaps: usize,
    pub unsuppressed_test_efficiency_findings: usize,
    pub intentional_test_efficiency_findings: usize,
    pub suppressed_exposure_gaps: usize,
    pub suppressed_test_efficiency_findings: usize,
    pub unknowns: usize,
    pub unknowns_test_efficiency: usize,
    pub analyzed_findings: usize,
    pub analyzed_seams: usize,
    pub analyzed_tests: usize,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BadgePolicy {
    pub include_unknowns: bool,
    pub fail_on_nonzero: bool,
    pub test_intent_path: String,
    pub suppressions_path: String,
}

impl Default for BadgePolicy {
    fn default() -> Self {
        Self {
            include_unknowns: false,
            fail_on_nonzero: false,
            test_intent_path: ".ripr/test_intent.toml".to_string(),
            suppressions_path: ".ripr/suppressions.toml".to_string(),
        }
    }
}

/// Whether a badge represents the changed-behavior diff under analysis
/// or the full-repo baseline. Diff-scoped badges feed PR step summaries
/// and PR artifact uploads; only repo-scoped badges are safe as
/// README / store / public Shields endpoints because a no-diff `main`
/// run of the diff-scoped path always reports `0` regardless of the
/// repo's actual exposure profile.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BadgeScope {
    Diff,
    Repo,
}

impl BadgeScope {
    pub fn as_str(&self) -> &'static str {
        match self {
            BadgeScope::Diff => "diff",
            BadgeScope::Repo => "repo",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BadgeSummary {
    pub kind: BadgeKind,
    pub scope: BadgeScope,
    pub basis: BadgeBasis,
    pub message: String,
    pub status: BadgeStatus,
    pub color: &'static str,
    pub counts: BadgeCounts,
    pub reason_counts: BTreeMap<&'static str, usize>,
    pub policy: BadgePolicy,
    /// Advisory warnings surfaced to the badge consumer — currently
    /// expired suppressions and unmatched suppression selectors. Empty
    /// for the common-case green badge.
    pub warnings: Vec<String>,
}

/// The schema_version of the native badge JSON. Bumping it is a public
/// contract change — call it out in the PR. v0.3 added `basis` and
/// `counts.analyzed_seams` so consumers can distinguish legacy
/// finding-exposure badges from seam-native repo badges.
pub const BADGE_SCHEMA_VERSION: &str = "0.3";

/// All test-efficiency reason strings the badge JSON reports as zero
/// defaults until later PRs read the test-efficiency report. The order
/// matches `RIPR-SPEC-0004` and the existing emitter in `xtask`.
const BADGE_REASON_KEYS: &[&str] = &[
    "no_assertion_detected",
    "smoke_oracle_only",
    "relational_oracle",
    "broad_oracle",
    "assertion_may_not_match_detected_owner",
    "opaque_helper_or_fixture_boundary",
    "no_activation_literal_detected",
    "expected_value_computed_from_detected_owner_path",
    "duplicate_activation_and_oracle_shape",
];

/// Builds the `ripr` badge summary from a `CheckOutput`, applying any
/// `kind = "exposure_gap"` suppressions whose `finding_id` matches a
/// currently-counted exposure gap. Expired and unmatched suppressions
/// surface as `warnings` so silently-stale debt cannot keep the badge
/// green. `today` is the ISO date used for expiry comparison.
pub fn ripr_badge_summary_with_suppressions(
    output: &CheckOutput,
    suppressions: &[SuppressionEntry],
    today: &str,
    policy: BadgePolicy,
) -> BadgeSummary {
    let mut candidate_ids: Vec<String> = Vec::new();
    let mut unknowns = 0usize;
    let mut unique_tests: BTreeSet<(String, String, usize)> = BTreeSet::new();

    for finding in &output.findings {
        match finding.class {
            ExposureClass::WeaklyExposed
            | ExposureClass::ReachableUnrevealed
            | ExposureClass::NoStaticPath => {
                candidate_ids.push(finding.id.clone());
            }
            ExposureClass::InfectionUnknown
            | ExposureClass::PropagationUnknown
            | ExposureClass::StaticUnknown => {
                unknowns += 1;
            }
            ExposureClass::Exposed => {}
        }
        for test in &finding.related_tests {
            unique_tests.insert((
                test.file.to_string_lossy().into_owned(),
                test.name.clone(),
                test.line,
            ));
        }
    }

    let suppression_app = apply_exposure_suppressions(&candidate_ids, suppressions, today);
    let suppressed = suppression_app.suppressed_findings.len();
    let unsuppressed_exposure_gaps = candidate_ids.len().saturating_sub(suppressed);

    let counts = BadgeCounts {
        unsuppressed_exposure_gaps,
        unsuppressed_test_efficiency_findings: 0,
        intentional_test_efficiency_findings: 0,
        suppressed_exposure_gaps: suppressed,
        suppressed_test_efficiency_findings: 0,
        unknowns,
        unknowns_test_efficiency: 0,
        analyzed_findings: output.findings.len(),
        analyzed_seams: 0,
        analyzed_tests: unique_tests.len(),
    };

    let mut reason_counts: BTreeMap<&'static str, usize> = BTreeMap::new();
    for key in BADGE_REASON_KEYS {
        reason_counts.insert(key, 0);
    }

    let headline = counts.unsuppressed_exposure_gaps
        + if policy.include_unknowns {
            counts.unknowns
        } else {
            0
        };
    let (status, color) = badge_status_color(headline, policy.fail_on_nonzero);

    BadgeSummary {
        kind: BadgeKind::Ripr,
        scope: BadgeScope::Diff,
        basis: BadgeBasis::FindingExposure,
        message: headline.to_string(),
        status,
        color,
        counts,
        reason_counts,
        policy,
        warnings: suppression_app.warnings,
    }
}

/// Convenience wrapper: builds the `ripr` badge with no suppressions.
/// Equivalent to calling [`ripr_badge_summary_with_suppressions`] with
/// an empty slice. Test-only since production callers always go through
/// [`crate::app::render_check`] which threads the loaded suppressions.
#[cfg(test)]
pub fn ripr_badge_summary(output: &CheckOutput, policy: BadgePolicy) -> BadgeSummary {
    ripr_badge_summary_with_suppressions(output, &[], "", policy)
}

/// Builds the repo-scoped `ripr` badge summary from classified seams.
///
/// This is the seam-native badge path used by public repo badges. It counts
/// configured-visible headline-eligible seam classes as unresolved gaps,
/// keeps opaque seams in the `unknowns` bucket, and omits classes configured
/// as `off` from both the headline and visible count buckets.
#[cfg(test)]
pub(crate) fn ripr_seam_badge_summary(
    classified: &[ClassifiedSeam],
    config: &RiprConfig,
    policy: BadgePolicy,
) -> BadgeSummary {
    let mut counts = SeamGripClassCounts::new(classified.len());
    for entry in classified {
        counts.increment(entry.class);
    }
    ripr_seam_badge_summary_from_counts(&counts, config, policy)
}

/// Builds the repo-scoped `ripr` badge summary from compact seam grip
/// class counts.
pub(crate) fn ripr_seam_badge_summary_from_counts(
    class_counts: &SeamGripClassCounts,
    config: &RiprConfig,
    policy: BadgePolicy,
) -> BadgeSummary {
    let mut unresolved = 0usize;
    let mut suppressed = 0usize;
    let mut unknowns = 0usize;

    for class in SeamGripClass::ALL {
        let count = class_counts.count_for(class);
        if count == 0 || config.severity().for_seam(class) == ConfigSeverity::Off {
            continue;
        }
        if class.is_headline_eligible() {
            unresolved += count;
        } else if class == SeamGripClass::Suppressed {
            suppressed += count;
        } else if class == SeamGripClass::Opaque {
            unknowns += count;
        }
    }

    let counts = BadgeCounts {
        unsuppressed_exposure_gaps: unresolved,
        unsuppressed_test_efficiency_findings: 0,
        intentional_test_efficiency_findings: 0,
        suppressed_exposure_gaps: suppressed,
        suppressed_test_efficiency_findings: 0,
        unknowns,
        unknowns_test_efficiency: 0,
        analyzed_findings: 0,
        analyzed_seams: class_counts.analyzed_seams(),
        analyzed_tests: 0,
    };

    let mut reason_counts: BTreeMap<&'static str, usize> = BTreeMap::new();
    for key in BADGE_REASON_KEYS {
        reason_counts.insert(key, 0);
    }

    let headline = counts.unsuppressed_exposure_gaps
        + if policy.include_unknowns {
            counts.unknowns
        } else {
            0
        };
    let (status, color) = badge_status_color(headline, policy.fail_on_nonzero);

    BadgeSummary {
        kind: BadgeKind::Ripr,
        scope: BadgeScope::Repo,
        basis: BadgeBasis::SeamNative,
        message: headline.to_string(),
        status,
        color,
        counts,
        reason_counts,
        policy,
        warnings: Vec::new(),
    }
}

fn badge_status_color(count: usize, fail_on_nonzero: bool) -> (BadgeStatus, &'static str) {
    if fail_on_nonzero && count > 0 {
        return (BadgeStatus::Fail, "red");
    }
    match count {
        0 => (BadgeStatus::Pass, "brightgreen"),
        1..=3 => (BadgeStatus::Warn, "yellow"),
        _ => (BadgeStatus::Warn, "orange"),
    }
}

/// One test-efficiency entry seen by the badge, retained so suppressions
/// can be applied per-`(test, path)` after the report is parsed and so
/// scope-aware aggregation can filter by relationship to the diff.
///
/// `class` is the per-test class string from the test-efficiency report
/// (e.g. `smoke_only`, `likely_vacuous`, `opaque`, `strong_discriminator`).
/// `reached_owners` is the per-test owner list — the same shape used by
/// the analyzer's `Finding.probe.owner.0` (`SymbolId.0`) — so a
/// diff-scope filter can intersect them with the changed/probed owner
/// set without an extra fact-extraction pass.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TestEfficiencyBadgeEntry {
    pub test: String,
    pub path: String,
    pub has_intent: bool,
    pub class: String,
    pub reached_owners: Vec<String>,
}

/// Test-efficiency contribution to the `ripr+` badge. Built by parsing
/// `target/ripr/reports/test-efficiency.json`; the per-test ledger is
/// the source of truth because `declared_intent` exclusion is per-test
/// and cannot be derived from aggregate `class_counts` alone.
///
/// `entries` carries every parsed entry (actionable, intentional,
/// opaque, and visible-only) with its class and reached owners so that
/// diff-scope aggregation can filter and recount without re-parsing.
/// The aggregate counters (`unsuppressed_*`, `intentional_*`,
/// `unknowns_te`) are the **repo-wide** totals; diff-scope aggregation
/// recomputes its own counts from `entries`.
///
/// `actionable_entries` is the legacy projection preserved for the
/// suppression matcher: only actionable, non-intentional entries.
/// Repo-scope aggregation pairs it with the repo-wide totals; diff-scope
/// aggregation derives its own filtered view from `entries`.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct TestEfficiencyBadgeSummary {
    pub unsuppressed_test_efficiency_findings: usize,
    pub intentional_test_efficiency_findings: usize,
    pub unknowns_test_efficiency: usize,
    pub analyzed_tests: usize,
    pub reason_counts: BTreeMap<&'static str, usize>,
    /// Actionable, non-intentional entries — i.e., the candidate set for
    /// `ripr+` suppression matching under repo scope. Empty when no
    /// test-efficiency entry is actionable.
    pub actionable_entries: Vec<TestEfficiencyBadgeEntry>,
    /// Every parsed entry (actionable, intentional, opaque, and
    /// visible-only) with class and reached owners. Used by diff-scope
    /// aggregation to filter to tests related to the changed code.
    pub entries: Vec<TestEfficiencyBadgeEntry>,
}

/// The test-efficiency `class` strings that contribute to `ripr+` when not
/// covered by `declared_intent`. Mirrors the locked vocabulary in
/// `docs/BADGE_POLICY.md`. `strong_discriminator` and `useful_but_broad`
/// never count by default; `opaque` flows into `unknowns_test_efficiency`
/// rather than the headline.
const ACTIONABLE_TE_CLASSES: &[&str] = &[
    "likely_vacuous",
    "possibly_circular",
    "smoke_only",
    "duplicative",
];

const NON_ACTIONABLE_TE_CLASSES: &[&str] = &["strong_discriminator", "useful_but_broad"];

/// Parses `target/ripr/reports/test-efficiency.json` into the
/// `ripr+`-shaped summary. Validates the schema_version, requires the
/// per-test ledger, and rejects unknown class strings so a class name
/// drift in the emitter surfaces as a parse error rather than a silent
/// undercount.
pub fn parse_test_efficiency_badge_summary(
    text: &str,
) -> Result<TestEfficiencyBadgeSummary, String> {
    let value: Value = serde_json::from_str(text)
        .map_err(|err| format!("test-efficiency.json is not valid JSON: {err}"))?;

    let schema_version = value
        .get("schema_version")
        .and_then(Value::as_str)
        .ok_or_else(|| "test-efficiency.json is missing `schema_version`".to_string())?;
    if schema_version != "0.1" {
        return Err(format!(
            "test-efficiency.json schema_version `{schema_version}` is not supported (expected `0.1`)"
        ));
    }

    let tests = value
        .get("tests")
        .and_then(Value::as_array)
        .ok_or_else(|| "test-efficiency.json is missing the `tests` array".to_string())?;

    let mut unsuppressed = 0usize;
    let mut intentional = 0usize;
    let mut unknowns_te = 0usize;
    let mut actionable_entries: Vec<TestEfficiencyBadgeEntry> = Vec::new();
    let mut all_entries: Vec<TestEfficiencyBadgeEntry> = Vec::new();

    for entry in tests {
        let class = entry
            .get("class")
            .and_then(Value::as_str)
            .ok_or_else(|| "test-efficiency entry is missing `class`".to_string())?;
        let has_intent = entry.get("declared_intent").is_some();

        let test_name = entry
            .get("name")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let path = entry
            .get("path")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let reached_owners: Vec<String> = entry
            .get("reached_owners")
            .and_then(Value::as_array)
            .map(|values| {
                values
                    .iter()
                    .filter_map(|v| v.as_str().map(str::to_string))
                    .collect()
            })
            .unwrap_or_default();

        if ACTIONABLE_TE_CLASSES.contains(&class) {
            if has_intent {
                intentional += 1;
            } else {
                unsuppressed += 1;
                actionable_entries.push(TestEfficiencyBadgeEntry {
                    test: test_name.clone(),
                    path: path.clone(),
                    has_intent: false,
                    class: class.to_string(),
                    reached_owners: reached_owners.clone(),
                });
            }
        } else if class == "opaque" {
            unknowns_te += 1;
        } else if NON_ACTIONABLE_TE_CLASSES.contains(&class) {
            // strong_discriminator / useful_but_broad: visible only.
        } else {
            return Err(format!(
                "test-efficiency entry has unknown class `{class}`; recognized classes are {}",
                [
                    ACTIONABLE_TE_CLASSES,
                    NON_ACTIONABLE_TE_CLASSES,
                    &["opaque"],
                ]
                .concat()
                .join(", ")
            ));
        }

        all_entries.push(TestEfficiencyBadgeEntry {
            test: test_name,
            path,
            has_intent,
            class: class.to_string(),
            reached_owners,
        });
    }

    let analyzed_tests = value
        .get("metrics")
        .and_then(|m| m.get("tests_scanned"))
        .and_then(Value::as_u64)
        .ok_or_else(|| "test-efficiency.json is missing `metrics.tests_scanned`".to_string())?
        as usize;

    let mut reason_counts: BTreeMap<&'static str, usize> = BTreeMap::new();
    for key in BADGE_REASON_KEYS {
        reason_counts.insert(key, 0);
    }
    if let Some(counts) = value
        .get("metrics")
        .and_then(|m| m.get("reason_counts"))
        .and_then(Value::as_object)
    {
        for (key, value) in counts {
            if let Some(known) = BADGE_REASON_KEYS
                .iter()
                .find(|known| **known == key.as_str())
                && let Some(count) = value.as_u64()
            {
                reason_counts.insert(*known, count as usize);
            }
        }
    }

    Ok(TestEfficiencyBadgeSummary {
        unsuppressed_test_efficiency_findings: unsuppressed,
        intentional_test_efficiency_findings: intentional,
        unknowns_test_efficiency: unknowns_te,
        analyzed_tests,
        reason_counts,
        actionable_entries,
        entries: all_entries,
    })
}

/// The set of tests + owners considered "related to the diff" for
/// scope-aware `ripr+` aggregation. Built from `CheckOutput.findings`:
///
/// - `related_test_keys` contains both the bare test name and a
///   `<path>::<name>` qualified form so the filter can match either
///   shape from the test-efficiency report.
/// - `changed_owners` is the set of owner symbol strings extracted from
///   `Finding.probe.owner` — same shape as the test-efficiency JSON's
///   `reached_owners` field.
///
/// A test-efficiency entry is *related* to the diff if either:
/// 1. its bare or qualified name appears in `related_test_keys`, or
/// 2. its `reached_owners` intersect `changed_owners`.
#[derive(Clone, Debug, Default)]
pub struct DiffRelatedTests {
    pub related_test_keys: BTreeSet<String>,
    pub changed_owners: BTreeSet<String>,
}

impl DiffRelatedTests {
    pub fn from_check_output(output: &CheckOutput) -> Self {
        let mut related_test_keys = BTreeSet::new();
        let mut changed_owners = BTreeSet::new();
        for finding in &output.findings {
            if let Some(owner) = finding.probe.owner.as_ref() {
                changed_owners.insert(owner.0.clone());
            }
            for test in &finding.related_tests {
                let path = test.file.to_string_lossy().into_owned();
                related_test_keys.insert(test.name.clone());
                related_test_keys.insert(format!("{}::{}", path, test.name));
            }
        }
        Self {
            related_test_keys,
            changed_owners,
        }
    }

    fn includes(&self, entry: &TestEfficiencyBadgeEntry) -> bool {
        if self.related_test_keys.contains(&entry.test) {
            return true;
        }
        let qualified = format!("{}::{}", entry.path, entry.test);
        if self.related_test_keys.contains(&qualified) {
            return true;
        }
        entry
            .reached_owners
            .iter()
            .any(|owner| self.changed_owners.contains(owner))
    }
}

/// Aggregation scope for the `ripr+` test-efficiency contribution.
/// `cargo xtask test-efficiency-report` is repo-wide as a fact source;
/// badge aggregation must be scope-aware so a PR badge is not noisy
/// with unrelated whole-repo test-efficiency debt.
#[derive(Clone, Debug)]
pub enum TestEfficiencyAggregationScope<'a> {
    /// Repo-scoped aggregation: count every entry from the repo-wide
    /// ledger (current behavior, used by `repo-badge-plus-*` formats).
    Repo,
    /// Diff-scoped aggregation: filter to entries whose tests appear in
    /// the diff's related-tests set or whose `reached_owners` intersect
    /// the diff's changed/probed owners.
    Diff(&'a DiffRelatedTests),
}

/// Builds the `ripr+` badge summary from a `CheckOutput` plus a parsed
/// test-efficiency contribution and a slice of suppressions. Applies
/// `exposure_gap` suppressions to the exposure side and
/// `test_efficiency` suppressions to the actionable test-efficiency
/// entries; expired and unmatched selectors surface as `warnings`.
///
/// `scope` controls whether the test-efficiency contribution comes
/// from the repo-wide ledger (`Repo`) or is filtered to entries
/// related to the diff under analysis (`Diff`). The exposure side is
/// already scope-aware via the underlying `CheckOutput` (built by the
/// diff or repo analysis), so only the test-efficiency contribution
/// needs scope-awareness here.
pub fn ripr_plus_badge_summary_with_suppressions(
    output: &CheckOutput,
    test_efficiency: TestEfficiencyBadgeSummary,
    suppressions: &[SuppressionEntry],
    today: &str,
    policy: BadgePolicy,
    scope: TestEfficiencyAggregationScope<'_>,
) -> BadgeSummary {
    let exposure =
        ripr_badge_summary_with_suppressions(output, suppressions, today, policy.clone());
    ripr_plus_badge_summary_from_exposure(
        exposure,
        test_efficiency,
        suppressions,
        today,
        policy,
        scope,
    )
}

/// Builds the repo-scoped `ripr+` badge summary from compact seam grip
/// class counts plus the parsed test-efficiency ledger.
pub(crate) fn ripr_plus_seam_badge_summary_from_counts_with_suppressions(
    class_counts: &SeamGripClassCounts,
    config: &RiprConfig,
    test_efficiency: TestEfficiencyBadgeSummary,
    suppressions: &[SuppressionEntry],
    today: &str,
    policy: BadgePolicy,
    scope: TestEfficiencyAggregationScope<'_>,
) -> BadgeSummary {
    let exposure = ripr_seam_badge_summary_from_counts(class_counts, config, policy.clone());
    ripr_plus_badge_summary_from_exposure(
        exposure,
        test_efficiency,
        suppressions,
        today,
        policy,
        scope,
    )
}

fn ripr_plus_badge_summary_from_exposure(
    exposure: BadgeSummary,
    test_efficiency: TestEfficiencyBadgeSummary,
    suppressions: &[SuppressionEntry],
    today: &str,
    policy: BadgePolicy,
    scope: TestEfficiencyAggregationScope<'_>,
) -> BadgeSummary {
    // Decide which entries contribute to this scope's headline. For
    // repo scope, take the parser's pre-computed repo-wide totals and
    // the existing actionable list. For diff scope, recompute counts
    // from the filtered entry list — `related_test_keys` from
    // `Finding.related_tests` and `changed_owners` from
    // `Finding.probe.owner` are the only inputs.
    let (actionable_pairs, unsuppressed_te_before_suppression, intentional_te, unknowns_te) =
        match scope {
            TestEfficiencyAggregationScope::Repo => (
                test_efficiency
                    .actionable_entries
                    .iter()
                    .map(|entry| (entry.test.clone(), entry.path.clone()))
                    .collect::<Vec<_>>(),
                test_efficiency.unsuppressed_test_efficiency_findings,
                test_efficiency.intentional_test_efficiency_findings,
                test_efficiency.unknowns_test_efficiency,
            ),
            TestEfficiencyAggregationScope::Diff(filter) => {
                let mut pairs: Vec<(String, String)> = Vec::new();
                let mut unsuppressed_count = 0usize;
                let mut intentional_count = 0usize;
                let mut unknowns_count = 0usize;
                for entry in &test_efficiency.entries {
                    if !filter.includes(entry) {
                        continue;
                    }
                    if ACTIONABLE_TE_CLASSES.contains(&entry.class.as_str()) {
                        if entry.has_intent {
                            intentional_count += 1;
                        } else {
                            unsuppressed_count += 1;
                            pairs.push((entry.test.clone(), entry.path.clone()));
                        }
                    } else if entry.class == "opaque" {
                        unknowns_count += 1;
                    }
                    // strong_discriminator / useful_but_broad stay visible only.
                }
                (pairs, unsuppressed_count, intentional_count, unknowns_count)
            }
        };

    // Apply test-efficiency suppressions against the (scope-filtered)
    // candidate pairs. Suppressed entries shift from
    // `unsuppressed_test_efficiency_findings` to
    // `suppressed_test_efficiency_findings`. `intentional_*` is
    // unaffected — declared intent and suppressions are distinct.
    let te_application = apply_test_efficiency_suppressions(&actionable_pairs, suppressions, today);
    let suppressed_te = te_application.suppressed_tests.len();
    let unsuppressed_te = unsuppressed_te_before_suppression.saturating_sub(suppressed_te);

    let counts = BadgeCounts {
        unsuppressed_exposure_gaps: exposure.counts.unsuppressed_exposure_gaps,
        unsuppressed_test_efficiency_findings: unsuppressed_te,
        intentional_test_efficiency_findings: intentional_te,
        suppressed_exposure_gaps: exposure.counts.suppressed_exposure_gaps,
        suppressed_test_efficiency_findings: suppressed_te,
        unknowns: exposure.counts.unknowns,
        unknowns_test_efficiency: unknowns_te,
        analyzed_findings: exposure.counts.analyzed_findings,
        analyzed_seams: exposure.counts.analyzed_seams,
        analyzed_tests: test_efficiency.analyzed_tests,
    };

    let unknown_contribution = if policy.include_unknowns {
        counts.unknowns + counts.unknowns_test_efficiency
    } else {
        0
    };
    let headline = counts.unsuppressed_exposure_gaps
        + counts.unsuppressed_test_efficiency_findings
        + unknown_contribution;
    let (status, color) = badge_status_color(headline, policy.fail_on_nonzero);

    let mut warnings = exposure.warnings;
    warnings.extend(te_application.warnings);

    BadgeSummary {
        kind: BadgeKind::RiprPlus,
        scope: exposure.scope,
        basis: exposure.basis,
        message: headline.to_string(),
        status,
        color,
        counts,
        reason_counts: test_efficiency.reason_counts,
        policy,
        warnings,
    }
}

/// Convenience wrapper: builds the `ripr+` badge with no suppressions
/// and **repo** aggregation scope. Test-only — production calls
/// [`ripr_plus_badge_summary_with_suppressions`] directly via
/// [`crate::app::render_check`], which threads the right scope from
/// the requested `OutputFormat`.
#[cfg(test)]
pub fn ripr_plus_badge_summary(
    output: &CheckOutput,
    test_efficiency: TestEfficiencyBadgeSummary,
    policy: BadgePolicy,
) -> BadgeSummary {
    ripr_plus_badge_summary_with_suppressions(
        output,
        test_efficiency,
        &[],
        "",
        policy,
        TestEfficiencyAggregationScope::Repo,
    )
}

/// Renders the native badge JSON (snake_case, full counts/reasons/policy).
pub fn render_native_json(summary: &BadgeSummary) -> String {
    let mut out = String::new();
    out.push_str("{\n");
    out.push_str(&format!(
        "  \"schema_version\": \"{BADGE_SCHEMA_VERSION}\",\n"
    ));
    out.push_str(&format!("  \"kind\": \"{}\",\n", summary.kind.as_str()));
    out.push_str(&format!("  \"scope\": \"{}\",\n", summary.scope.as_str()));
    out.push_str(&format!("  \"basis\": \"{}\",\n", summary.basis.as_str()));
    out.push_str(&format!(
        "  \"label\": \"{}\",\n",
        json_escape(summary.kind.label())
    ));
    out.push_str(&format!(
        "  \"message\": \"{}\",\n",
        json_escape(&summary.message)
    ));
    out.push_str(&format!("  \"status\": \"{}\",\n", summary.status.as_str()));
    out.push_str(&format!("  \"color\": \"{}\",\n", summary.color));

    let counts = &summary.counts;
    out.push_str("  \"counts\": {\n");
    out.push_str(&format!(
        "    \"unsuppressed_exposure_gaps\": {},\n",
        counts.unsuppressed_exposure_gaps
    ));
    out.push_str(&format!(
        "    \"unsuppressed_test_efficiency_findings\": {},\n",
        counts.unsuppressed_test_efficiency_findings
    ));
    out.push_str(&format!(
        "    \"intentional_test_efficiency_findings\": {},\n",
        counts.intentional_test_efficiency_findings
    ));
    out.push_str(&format!(
        "    \"suppressed_exposure_gaps\": {},\n",
        counts.suppressed_exposure_gaps
    ));
    out.push_str(&format!(
        "    \"suppressed_test_efficiency_findings\": {},\n",
        counts.suppressed_test_efficiency_findings
    ));
    out.push_str(&format!("    \"unknowns\": {},\n", counts.unknowns));
    out.push_str(&format!(
        "    \"unknowns_test_efficiency\": {},\n",
        counts.unknowns_test_efficiency
    ));
    out.push_str(&format!(
        "    \"analyzed_findings\": {},\n",
        counts.analyzed_findings
    ));
    out.push_str(&format!(
        "    \"analyzed_seams\": {},\n",
        counts.analyzed_seams
    ));
    out.push_str(&format!(
        "    \"analyzed_tests\": {}\n",
        counts.analyzed_tests
    ));
    out.push_str("  },\n");

    out.push_str("  \"reason_counts\": {");
    if summary.reason_counts.is_empty() {
        out.push_str("},\n");
    } else {
        out.push('\n');
        // Render in the canonical order the badge reserves, not BTreeMap
        // alpha order, so consumers see the policy-aligned sequence.
        let mut wrote_any = false;
        for key in BADGE_REASON_KEYS {
            if let Some(count) = summary.reason_counts.get(*key) {
                if wrote_any {
                    out.push_str(",\n");
                }
                out.push_str(&format!("    \"{}\": {}", json_escape(key), count));
                wrote_any = true;
            }
        }
        out.push_str("\n  },\n");
    }

    let policy = &summary.policy;
    out.push_str("  \"policy\": {\n");
    out.push_str(&format!(
        "    \"include_unknowns\": {},\n",
        policy.include_unknowns
    ));
    out.push_str(&format!(
        "    \"fail_on_nonzero\": {},\n",
        policy.fail_on_nonzero
    ));
    out.push_str(&format!(
        "    \"test_intent_path\": \"{}\",\n",
        json_escape(&policy.test_intent_path)
    ));
    out.push_str(&format!(
        "    \"suppressions_path\": \"{}\"\n",
        json_escape(&policy.suppressions_path)
    ));
    out.push_str("  },\n");

    // Always emit `warnings` as an array (possibly empty) so consumers
    // can rely on a stable shape. Currently used for expired
    // suppressions and unmatched suppression selectors.
    out.push_str("  \"warnings\": [");
    if summary.warnings.is_empty() {
        out.push_str("]\n}\n");
    } else {
        out.push('\n');
        for (index, warning) in summary.warnings.iter().enumerate() {
            if index > 0 {
                out.push_str(",\n");
            }
            out.push_str(&format!("    \"{}\"", json_escape(warning)));
        }
        out.push_str("\n  ]\n}\n");
    }
    out
}

/// Renders the Shields-compatible projection: exactly four top-level
/// fields (`schemaVersion`, `label`, `message`, `color`).
pub fn render_shields_json(summary: &BadgeSummary) -> String {
    format!(
        "{{\n  \"schemaVersion\": 1,\n  \"label\": \"{}\",\n  \"message\": \"{}\",\n  \"color\": \"{}\"\n}}\n",
        json_escape(summary.kind.label()),
        json_escape(&summary.message),
        summary.color
    )
}

#[cfg(test)]
mod tests {
    use super::{
        BADGE_REASON_KEYS, BadgePolicy, BadgeScope, BadgeStatus, TestEfficiencyBadgeSummary,
        badge_status_color, parse_test_efficiency_badge_summary, render_native_json,
        render_shields_json, ripr_badge_summary, ripr_plus_badge_summary, ripr_seam_badge_summary,
    };
    use crate::analysis::ClassifiedSeam;
    use crate::analysis::seams::{
        ExpectedSink, RepoSeam, RequiredDiscriminator, SeamGripClass, SeamKind,
    };
    use crate::analysis::test_grip_evidence::TestGripEvidence;
    use crate::app::{CheckInput, CheckOutput, Mode};
    use crate::config::RiprConfig;
    use crate::domain::{
        ActivationEvidence, Confidence, DeltaKind, ExposureClass, Finding, OracleKind,
        OracleStrength, Probe, ProbeFamily, ProbeId, RelatedTest, RevealEvidence, RiprEvidence,
        SourceLocation, StageEvidence, StageState, Summary,
    };
    use std::path::PathBuf;

    fn finding(class: ExposureClass, related: Vec<RelatedTest>) -> Finding {
        Finding {
            id: "probe:src_lib_rs:1:predicate".to_string(),
            probe: Probe {
                id: ProbeId("probe:src_lib_rs:1:predicate".to_string()),
                family: ProbeFamily::Predicate,
                location: SourceLocation::new("src/lib.rs", 1, 1),
                owner: None,
                delta: DeltaKind::Control,
                before: None,
                after: None,
                expression: "expr".to_string(),
                expected_sinks: Vec::new(),
                required_oracles: Vec::new(),
            },
            class,
            ripr: RiprEvidence {
                reach: StageEvidence::new(StageState::Yes, Confidence::Medium, "reached"),
                infect: StageEvidence::new(StageState::Weak, Confidence::Low, "infected"),
                propagate: StageEvidence::new(StageState::No, Confidence::Medium, "not propagated"),
                reveal: RevealEvidence {
                    observe: StageEvidence::new(StageState::Weak, Confidence::Low, "observed"),
                    discriminate: StageEvidence::new(
                        StageState::No,
                        Confidence::Medium,
                        "no discriminator",
                    ),
                },
            },
            confidence: 0.5,
            evidence: Vec::new(),
            missing: Vec::new(),
            flow_sinks: Vec::new(),
            activation: ActivationEvidence::default(),
            stop_reasons: Vec::new(),
            related_tests: related,
            recommended_next_step: None,
        }
    }

    fn related_test(name: &str, file: &str, line: usize) -> RelatedTest {
        RelatedTest {
            name: name.to_string(),
            file: PathBuf::from(file),
            line,
            oracle: None,
            oracle_kind: OracleKind::Unknown,
            oracle_strength: OracleStrength::Weak,
        }
    }

    fn check_output(findings: Vec<Finding>) -> CheckOutput {
        let defaults = CheckInput::default();
        CheckOutput {
            schema_version: "0.1".to_string(),
            tool: "ripr".to_string(),
            mode: Mode::Draft,
            root: defaults.root,
            base: defaults.base,
            summary: Summary::default(),
            findings,
        }
    }

    fn stage(state: StageState) -> StageEvidence {
        StageEvidence::new(state, Confidence::Medium, "stage")
    }

    fn classified_seam(class: SeamGripClass) -> ClassifiedSeam {
        let seam = RepoSeam::new(
            "src/lib.rs",
            "crate::discounted_total",
            SeamKind::PredicateBoundary,
            10,
            2,
            "amount >= threshold",
            RequiredDiscriminator::BoundaryValue {
                description: "amount == threshold".to_string(),
            },
            ExpectedSink::ReturnValue,
        );
        ClassifiedSeam {
            evidence: TestGripEvidence {
                seam_id: seam.id().clone(),
                related_tests: Vec::new(),
                reach: stage(StageState::Yes),
                activate: stage(StageState::Yes),
                propagate: stage(StageState::Yes),
                observe: stage(StageState::Yes),
                discriminate: stage(StageState::Weak),
                observed_values: Vec::new(),
                missing_discriminators: Vec::new(),
            },
            seam,
            class,
        }
    }

    #[test]
    fn badge_summary_counts_weakly_exposed_reachable_unrevealed_and_no_static_path() {
        let output = check_output(vec![
            finding(ExposureClass::WeaklyExposed, vec![]),
            finding(ExposureClass::ReachableUnrevealed, vec![]),
            finding(ExposureClass::NoStaticPath, vec![]),
        ]);

        let summary = ripr_badge_summary(&output, BadgePolicy::default());

        assert_eq!(summary.counts.unsuppressed_exposure_gaps, 3);
        assert_eq!(summary.message, "3");
    }

    #[test]
    fn badge_summary_does_not_count_exposed_findings() {
        let output = check_output(vec![
            finding(ExposureClass::Exposed, vec![]),
            finding(ExposureClass::Exposed, vec![]),
        ]);

        let summary = ripr_badge_summary(&output, BadgePolicy::default());

        assert_eq!(summary.counts.unsuppressed_exposure_gaps, 0);
        assert_eq!(summary.counts.analyzed_findings, 2);
        assert_eq!(summary.message, "0");
        assert_eq!(summary.status, BadgeStatus::Pass);
        assert_eq!(summary.color, "brightgreen");
    }

    #[test]
    fn badge_summary_reports_unknowns_separately_from_headline() {
        let output = check_output(vec![
            finding(ExposureClass::InfectionUnknown, vec![]),
            finding(ExposureClass::PropagationUnknown, vec![]),
            finding(ExposureClass::StaticUnknown, vec![]),
            finding(ExposureClass::WeaklyExposed, vec![]),
        ]);

        let summary = ripr_badge_summary(&output, BadgePolicy::default());

        assert_eq!(summary.counts.unsuppressed_exposure_gaps, 1);
        assert_eq!(summary.counts.unknowns, 3);
        // Headline excludes unknowns by default.
        assert_eq!(summary.message, "1");
    }

    #[test]
    fn seam_badge_summary_counts_visible_headline_eligible_seams() {
        let classified = vec![
            classified_seam(SeamGripClass::WeaklyGripped),
            classified_seam(SeamGripClass::Ungripped),
            classified_seam(SeamGripClass::StronglyGripped),
            classified_seam(SeamGripClass::Opaque),
        ];

        let summary =
            ripr_seam_badge_summary(&classified, &RiprConfig::default(), BadgePolicy::default());

        assert_eq!(summary.scope, BadgeScope::Repo);
        assert_eq!(summary.basis.as_str(), "seam_native");
        assert_eq!(summary.counts.unsuppressed_exposure_gaps, 2);
        assert_eq!(summary.counts.unknowns, 1);
        assert_eq!(summary.counts.analyzed_findings, 0);
        assert_eq!(summary.counts.analyzed_seams, 4);
        assert_eq!(summary.message, "2");
    }

    #[test]
    fn seam_badge_summary_respects_configured_off_severity() -> Result<(), String> {
        let config = crate::config::tests_only_parse(
            r#"
[severity.seams]
weakly_gripped = "off"
"#,
        )?;
        let classified = vec![
            classified_seam(SeamGripClass::WeaklyGripped),
            classified_seam(SeamGripClass::Ungripped),
        ];

        let summary = ripr_seam_badge_summary(&classified, &config, BadgePolicy::default());

        assert_eq!(summary.counts.unsuppressed_exposure_gaps, 1);
        assert_eq!(summary.message, "1");
        Ok(())
    }

    #[test]
    fn badge_summary_message_never_contains_a_denominator() {
        let output = check_output(vec![
            finding(ExposureClass::WeaklyExposed, vec![]),
            finding(ExposureClass::Exposed, vec![]),
            finding(ExposureClass::Exposed, vec![]),
        ]);

        let summary = ripr_badge_summary(&output, BadgePolicy::default());

        assert!(!summary.message.contains('/'), "no denominator");
        assert!(!summary.message.to_ascii_lowercase().contains("coverage"));
        assert!(!summary.message.to_ascii_lowercase().contains("uncovered"));
        assert_eq!(summary.message, "1");
    }

    #[test]
    fn badge_status_color_zero_is_pass_brightgreen() {
        assert_eq!(
            badge_status_color(0, false),
            (BadgeStatus::Pass, "brightgreen")
        );
    }

    #[test]
    fn badge_status_color_one_to_three_is_warn_yellow() {
        for count in 1..=3 {
            assert_eq!(
                badge_status_color(count, false),
                (BadgeStatus::Warn, "yellow"),
                "count {count}",
            );
        }
    }

    #[test]
    fn badge_status_color_four_or_more_is_warn_orange() {
        for count in [4, 5, 12, 100] {
            assert_eq!(
                badge_status_color(count, false),
                (BadgeStatus::Warn, "orange"),
                "count {count}",
            );
        }
    }

    #[test]
    fn badge_status_color_fail_on_nonzero_promotes_warn_to_fail_red() {
        assert_eq!(
            badge_status_color(1, true),
            (BadgeStatus::Fail, "red"),
            "fail_on_nonzero with count 1"
        );
        assert_eq!(
            badge_status_color(7, true),
            (BadgeStatus::Fail, "red"),
            "fail_on_nonzero with count 7"
        );
        // Zero remains pass even with fail_on_nonzero.
        assert_eq!(
            badge_status_color(0, true),
            (BadgeStatus::Pass, "brightgreen"),
            "zero stays pass even with fail_on_nonzero"
        );
    }

    #[test]
    fn badge_native_json_uses_snake_case_schema_version_and_all_required_fields() {
        let output = check_output(vec![finding(ExposureClass::WeaklyExposed, vec![])]);
        let summary = ripr_badge_summary(&output, BadgePolicy::default());
        let json = render_native_json(&summary);

        assert!(json.contains("\"schema_version\": \"0.3\""));
        assert!(!json.contains("\"schemaVersion\""));
        assert!(json.contains("\"kind\": \"ripr\""));
        assert!(json.contains("\"scope\": \"diff\""));
        assert!(json.contains("\"basis\": \"finding_exposure\""));
        assert!(json.contains("\"label\": \"ripr\""));
        assert!(json.contains("\"message\": \"1\""));
        assert!(json.contains("\"status\": \"warn\""));
        assert!(json.contains("\"color\": \"yellow\""));
        for key in [
            "unsuppressed_exposure_gaps",
            "unsuppressed_test_efficiency_findings",
            "intentional_test_efficiency_findings",
            "suppressed_exposure_gaps",
            "suppressed_test_efficiency_findings",
            "unknowns",
            "unknowns_test_efficiency",
            "analyzed_findings",
            "analyzed_seams",
            "analyzed_tests",
        ] {
            assert!(
                json.contains(&format!("\"{key}\":")),
                "native JSON missing count key `{key}`"
            );
        }
        for key in [
            "include_unknowns",
            "fail_on_nonzero",
            "test_intent_path",
            "suppressions_path",
        ] {
            assert!(
                json.contains(&format!("\"{key}\":")),
                "native JSON missing policy key `{key}`"
            );
        }
    }

    #[test]
    fn badge_native_json_emits_repo_scope_when_summary_carries_repo_scope() {
        let output = check_output(vec![finding(ExposureClass::WeaklyExposed, vec![])]);
        let mut summary = ripr_badge_summary(&output, BadgePolicy::default());
        summary.scope = BadgeScope::Repo;
        let json = render_native_json(&summary);

        assert!(json.contains("\"scope\": \"repo\""));
        assert!(!json.contains("\"scope\": \"diff\""));
    }

    #[test]
    fn badge_shields_projection_omits_scope_field() {
        // Shields stays exactly four fields after the v0.3 schema bump:
        // schemaVersion, label, message, color. `scope` and `basis` are native-only.
        let output = check_output(vec![finding(ExposureClass::WeaklyExposed, vec![])]);
        let mut summary = ripr_badge_summary(&output, BadgePolicy::default());
        summary.scope = BadgeScope::Repo;
        let shields = render_shields_json(&summary);

        assert!(!shields.contains("\"scope\""));
        assert!(!shields.contains("\"basis\""));
        let top_level_keys = shields
            .lines()
            .filter_map(|line| {
                let stripped = line.trim().strip_prefix('"')?;
                let end = stripped.find('"')?;
                Some(stripped[..end].to_string())
            })
            .collect::<Vec<_>>();
        assert_eq!(top_level_keys.len(), 4);
    }

    #[test]
    fn badge_native_json_contains_all_nine_reason_defaults() {
        let output = check_output(vec![]);
        let summary = ripr_badge_summary(&output, BadgePolicy::default());
        let json = render_native_json(&summary);

        for reason in BADGE_REASON_KEYS {
            assert!(
                json.contains(&format!("\"{reason}\": 0")),
                "native JSON missing reason key `{reason}` with default 0"
            );
        }
        // Specifically sanity-check the new reason from #187/#188.
        assert!(json.contains("\"duplicate_activation_and_oracle_shape\": 0"));
    }

    #[test]
    fn badge_shields_projection_uses_camel_case_schema_version_key_and_exactly_four_fields() {
        let output = check_output(vec![finding(ExposureClass::WeaklyExposed, vec![])]);
        let summary = ripr_badge_summary(&output, BadgePolicy::default());
        let shields = render_shields_json(&summary);

        assert!(shields.contains("\"schemaVersion\": 1"));
        assert!(!shields.contains("\"schema_version\""));
        assert!(shields.contains("\"label\": \"ripr\""));
        assert!(shields.contains("\"message\": \"1\""));
        assert!(shields.contains("\"color\": \"yellow\""));

        // Exactly four top-level keys.
        let top_level_quoted_keys = shields
            .lines()
            .filter(|line| line.starts_with("  \""))
            .count();
        assert_eq!(
            top_level_quoted_keys, 4,
            "Shields projection must have exactly four top-level fields"
        );
        // No native-JSON-only fields leak in.
        for forbidden in [
            "counts",
            "reason_counts",
            "policy",
            "kind",
            "status",
            "scope",
            "basis",
        ] {
            assert!(
                !shields.contains(&format!("\"{forbidden}\":")),
                "Shields projection must not include `{forbidden}`"
            );
        }
    }

    #[test]
    fn badge_summary_counts_unique_related_tests_by_file_name_line() {
        let test_a = related_test("test_one", "tests/a.rs", 10);
        let test_b = related_test("test_two", "tests/a.rs", 20);
        // Same identity — should dedupe across findings.
        let test_a_again = related_test("test_one", "tests/a.rs", 10);

        let output = check_output(vec![
            finding(ExposureClass::WeaklyExposed, vec![test_a, test_b]),
            finding(ExposureClass::WeaklyExposed, vec![test_a_again]),
        ]);

        let summary = ripr_badge_summary(&output, BadgePolicy::default());

        assert_eq!(
            summary.counts.analyzed_tests, 2,
            "analyzed_tests counts unique (file, name, line) identities"
        );
    }

    #[test]
    fn badge_include_unknowns_policy_adds_unknowns_to_headline() {
        let output = check_output(vec![
            finding(ExposureClass::WeaklyExposed, vec![]),
            finding(ExposureClass::InfectionUnknown, vec![]),
            finding(ExposureClass::StaticUnknown, vec![]),
        ]);

        let policy = BadgePolicy {
            include_unknowns: true,
            ..BadgePolicy::default()
        };
        let summary = ripr_badge_summary(&output, policy);

        // 1 exposure gap + 2 unknowns = 3.
        assert_eq!(summary.message, "3");
        // Counts still report them separately.
        assert_eq!(summary.counts.unsuppressed_exposure_gaps, 1);
        assert_eq!(summary.counts.unknowns, 2);
    }

    #[test]
    fn badge_test_efficiency_counts_are_zero_until_later_prs() {
        let output = check_output(vec![finding(ExposureClass::WeaklyExposed, vec![])]);
        let summary = ripr_badge_summary(&output, BadgePolicy::default());

        // This PR does not yet read the test-efficiency report. Future PRs
        // (`badge/ripr-plus-count-v1`, `test-intent/v1`, `suppressions/v1`)
        // will populate these.
        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 0);
        assert_eq!(summary.counts.intentional_test_efficiency_findings, 0);
        assert_eq!(summary.counts.suppressed_test_efficiency_findings, 0);
        assert_eq!(summary.counts.suppressed_exposure_gaps, 0);
        assert_eq!(summary.counts.unknowns_test_efficiency, 0);
    }

    // -------- ripr+ test-efficiency parser --------

    fn te_json(tests_json: &str, reason_counts: &str) -> String {
        format!(
            r#"{{
  "schema_version": "0.1",
  "tests": [{tests_json}],
  "metrics": {{
    "tests_scanned": 42,
    "reason_counts": {{{reason_counts}}}
  }}
}}"#
        )
    }

    fn entry_json(class: &str, with_intent: bool) -> String {
        let intent = if with_intent {
            r#","declared_intent":{"intent":"smoke","owner":"x","reason":"y","source":".ripr/test_intent.toml"}"#
        } else {
            ""
        };
        format!(r#"{{"class":"{class}"{intent}}}"#)
    }

    #[test]
    fn badge_plus_parses_test_efficiency_metrics() -> Result<(), String> {
        let json = te_json(&entry_json("strong_discriminator", false), "");
        let summary = parse_test_efficiency_badge_summary(&json)?;

        assert_eq!(summary.analyzed_tests, 42);
        assert_eq!(summary.unsuppressed_test_efficiency_findings, 0);
        assert_eq!(summary.intentional_test_efficiency_findings, 0);
        assert_eq!(summary.unknowns_test_efficiency, 0);
        Ok(())
    }

    #[test]
    fn badge_plus_counts_actionable_classes() -> Result<(), String> {
        for class in [
            "likely_vacuous",
            "possibly_circular",
            "smoke_only",
            "duplicative",
        ] {
            let json = te_json(&entry_json(class, false), "");
            let summary = parse_test_efficiency_badge_summary(&json)?;
            assert_eq!(
                summary.unsuppressed_test_efficiency_findings, 1,
                "class `{class}` must count as actionable"
            );
            assert_eq!(summary.intentional_test_efficiency_findings, 0);
        }
        Ok(())
    }

    #[test]
    fn badge_plus_does_not_count_strong_discriminator_or_useful_but_broad() -> Result<(), String> {
        for class in ["strong_discriminator", "useful_but_broad"] {
            let json = te_json(&entry_json(class, false), "");
            let summary = parse_test_efficiency_badge_summary(&json)?;
            assert_eq!(
                summary.unsuppressed_test_efficiency_findings, 0,
                "class `{class}` must not count"
            );
            assert_eq!(summary.intentional_test_efficiency_findings, 0);
            assert_eq!(summary.unknowns_test_efficiency, 0);
        }
        Ok(())
    }

    #[test]
    fn badge_plus_reports_opaque_as_unknowns_test_efficiency() -> Result<(), String> {
        let json = te_json(&entry_json("opaque", false), "");
        let summary = parse_test_efficiency_badge_summary(&json)?;

        assert_eq!(summary.unsuppressed_test_efficiency_findings, 0);
        assert_eq!(summary.unknowns_test_efficiency, 1);
        Ok(())
    }

    #[test]
    fn badge_plus_declared_intent_excludes_actionable_finding() -> Result<(), String> {
        let json = te_json(&entry_json("smoke_only", true), "");
        let summary = parse_test_efficiency_badge_summary(&json)?;

        assert_eq!(
            summary.unsuppressed_test_efficiency_findings, 0,
            "declared intent must exclude the finding from unsuppressed"
        );
        assert_eq!(
            summary.intentional_test_efficiency_findings, 1,
            "declared intent must increment intentional count"
        );
        Ok(())
    }

    #[test]
    fn badge_plus_reason_counts_default_missing_keys_to_zero() -> Result<(), String> {
        let json = te_json(&entry_json("strong_discriminator", false), "");
        let summary = parse_test_efficiency_badge_summary(&json)?;

        for key in BADGE_REASON_KEYS {
            assert_eq!(
                summary.reason_counts.get(*key).copied(),
                Some(0),
                "reason `{key}` should default to 0"
            );
        }
        Ok(())
    }

    #[test]
    fn badge_plus_reason_counts_propagate_known_keys() -> Result<(), String> {
        let reasons =
            r#""smoke_oracle_only":4,"duplicate_activation_and_oracle_shape":2,"unrecognized":99"#;
        let json = te_json(&entry_json("strong_discriminator", false), reasons);
        let summary = parse_test_efficiency_badge_summary(&json)?;

        assert_eq!(
            summary.reason_counts.get("smoke_oracle_only").copied(),
            Some(4)
        );
        assert_eq!(
            summary
                .reason_counts
                .get("duplicate_activation_and_oracle_shape")
                .copied(),
            Some(2)
        );
        // Unknown reason names are silently dropped — they're not part of the
        // badge contract, only the nine allow-listed keys are.
        assert!(!summary.reason_counts.contains_key("unrecognized"));
        Ok(())
    }

    #[test]
    fn badge_plus_rejects_unknown_class_string() {
        let json = te_json(r#"{"class":"vibe_only"}"#, "");
        let result = parse_test_efficiency_badge_summary(&json);

        assert!(result.is_err(), "unknown class must fail parse");
        let err = result.err().unwrap_or_default();
        assert!(err.contains("vibe_only"));
    }

    #[test]
    fn badge_plus_rejects_unsupported_schema_version() {
        let json = r#"{"schema_version":"2.0","tests":[],"metrics":{"tests_scanned":0,"reason_counts":{}}}"#;
        let result = parse_test_efficiency_badge_summary(json);

        assert!(result.is_err());
        let err = result.err().unwrap_or_default();
        assert!(err.contains("schema_version"));
    }

    #[test]
    fn badge_plus_rejects_missing_metrics_tests_scanned() {
        let json = r#"{"schema_version":"0.1","tests":[],"metrics":{}}"#;
        let result = parse_test_efficiency_badge_summary(json);

        assert!(result.is_err());
        let err = result.err().unwrap_or_default();
        assert!(err.contains("metrics.tests_scanned"));
    }

    // -------- ripr+ summary builder + renderers --------

    #[test]
    fn ripr_plus_native_json_has_kind_ripr_plus_and_label_ripr_plus() {
        let summary = ripr_plus_badge_summary(
            &check_output(Vec::new()),
            TestEfficiencyBadgeSummary {
                unsuppressed_test_efficiency_findings: 0,
                intentional_test_efficiency_findings: 0,
                unknowns_test_efficiency: 0,
                analyzed_tests: 12,
                reason_counts: {
                    let mut m = std::collections::BTreeMap::new();
                    for k in BADGE_REASON_KEYS {
                        m.insert(*k, 0);
                    }
                    m
                },
                actionable_entries: Vec::new(),
                entries: Vec::new(),
            },
            BadgePolicy::default(),
        );
        let json = render_native_json(&summary);

        assert!(json.contains("\"kind\": \"ripr_plus\""));
        assert!(json.contains("\"label\": \"ripr+\""));
        assert!(json.contains("\"analyzed_tests\": 12"));
        assert!(json.contains("\"message\": \"0\""));
    }

    #[test]
    fn ripr_plus_message_sums_exposure_and_unsuppressed_test_efficiency() {
        // 1 weakly_exposed + 1 reachable_unrevealed = 2 exposure gaps.
        // 3 unsuppressed test-efficiency findings.
        // 2 declared intent (NOT in headline). Total: 2 + 3 = 5.
        let summary = ripr_plus_badge_summary(
            &check_output(vec![
                finding(ExposureClass::WeaklyExposed, vec![]),
                finding(ExposureClass::ReachableUnrevealed, vec![]),
                finding(ExposureClass::Exposed, vec![]),
            ]),
            TestEfficiencyBadgeSummary {
                unsuppressed_test_efficiency_findings: 3,
                intentional_test_efficiency_findings: 2,
                unknowns_test_efficiency: 1,
                analyzed_tests: 0,
                reason_counts: std::collections::BTreeMap::new(),
                actionable_entries: Vec::new(),
                entries: Vec::new(),
            },
            BadgePolicy::default(),
        );

        assert_eq!(summary.message, "5");
        assert_eq!(summary.counts.unsuppressed_exposure_gaps, 2);
        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 3);
        assert_eq!(summary.counts.intentional_test_efficiency_findings, 2);
        assert_eq!(summary.counts.unknowns_test_efficiency, 1);
    }

    #[test]
    fn ripr_plus_shields_projection_has_exactly_four_fields_with_ripr_plus_label() {
        let summary = ripr_plus_badge_summary(
            &check_output(vec![finding(ExposureClass::WeaklyExposed, vec![])]),
            TestEfficiencyBadgeSummary::default(),
            BadgePolicy::default(),
        );
        let shields = render_shields_json(&summary);

        assert!(shields.contains("\"schemaVersion\": 1"));
        assert!(shields.contains("\"label\": \"ripr+\""));
        assert!(shields.contains("\"message\": \"1\""));
        assert!(shields.contains("\"color\":"));

        let top_level_quoted_keys = shields
            .lines()
            .filter(|line| line.starts_with("  \""))
            .count();
        assert_eq!(top_level_quoted_keys, 4);
        for forbidden in [
            "counts",
            "reason_counts",
            "policy",
            "kind",
            "status",
            "scope",
            "basis",
        ] {
            assert!(
                !shields.contains(&format!("\"{forbidden}\":")),
                "ripr+ Shields projection must not contain `{forbidden}`"
            );
        }
    }

    #[test]
    fn ripr_plus_message_has_no_denominator_or_coverage_framing() {
        let summary = ripr_plus_badge_summary(
            &check_output(vec![
                finding(ExposureClass::WeaklyExposed, vec![]),
                finding(ExposureClass::Exposed, vec![]),
            ]),
            TestEfficiencyBadgeSummary {
                unsuppressed_test_efficiency_findings: 4,
                ..TestEfficiencyBadgeSummary::default()
            },
            BadgePolicy::default(),
        );
        let json = render_native_json(&summary);
        let shields = render_shields_json(&summary);

        for body in [&json, &shields] {
            let lower = body.to_ascii_lowercase();
            assert!(!lower.contains("coverage"));
            assert!(!lower.contains("uncovered"));
        }
        assert_eq!(summary.message, "5");
        assert!(!summary.message.contains('/'));
    }

    #[test]
    fn ripr_plus_include_unknowns_policy_adds_both_unknown_axes_to_headline() {
        let policy = BadgePolicy {
            include_unknowns: true,
            ..BadgePolicy::default()
        };
        let summary = ripr_plus_badge_summary(
            &check_output(vec![
                finding(ExposureClass::WeaklyExposed, vec![]), // 1 gap
                finding(ExposureClass::InfectionUnknown, vec![]), // 1 unknown
            ]),
            TestEfficiencyBadgeSummary {
                unsuppressed_test_efficiency_findings: 2,
                unknowns_test_efficiency: 3,
                ..TestEfficiencyBadgeSummary::default()
            },
            policy,
        );

        // 1 + 2 + 1 + 3 = 7
        assert_eq!(summary.message, "7");
    }

    // -------- suppressions wiring --------

    use super::{
        TestEfficiencyAggregationScope, TestEfficiencyBadgeEntry,
        ripr_badge_summary_with_suppressions, ripr_plus_badge_summary_with_suppressions,
    };
    use crate::output::suppressions::{SuppressionEntry, SuppressionKind};

    fn finding_at_id(id: &str, class: ExposureClass) -> Finding {
        let mut f = finding(class, vec![]);
        f.id = id.to_string();
        f
    }

    fn exposure_suppression(finding_id: &str, expires: Option<&str>) -> SuppressionEntry {
        SuppressionEntry {
            kind: SuppressionKind::ExposureGap,
            finding_id: Some(finding_id.to_string()),
            test: None,
            path: None,
            reason: "x".to_string(),
            owner: "y".to_string(),
            expires: expires.map(str::to_string),
            block_line: 10,
        }
    }

    fn te_suppression(test: &str, path: Option<&str>, expires: Option<&str>) -> SuppressionEntry {
        SuppressionEntry {
            kind: SuppressionKind::TestEfficiency,
            finding_id: None,
            test: Some(test.to_string()),
            path: path.map(str::to_string),
            reason: "x".to_string(),
            owner: "y".to_string(),
            expires: expires.map(str::to_string),
            block_line: 20,
        }
    }

    #[test]
    fn ripr_badge_with_suppressions_moves_matched_findings_into_suppressed_bucket() {
        let output = check_output(vec![
            finding_at_id("probe:a", ExposureClass::WeaklyExposed),
            finding_at_id("probe:b", ExposureClass::ReachableUnrevealed),
            finding_at_id("probe:c", ExposureClass::NoStaticPath),
        ]);
        let suppressions = vec![exposure_suppression("probe:b", None)];

        let summary = ripr_badge_summary_with_suppressions(
            &output,
            &suppressions,
            "2026-05-03",
            BadgePolicy::default(),
        );

        assert_eq!(summary.counts.unsuppressed_exposure_gaps, 2);
        assert_eq!(summary.counts.suppressed_exposure_gaps, 1);
        assert_eq!(summary.message, "2");
        assert!(summary.warnings.is_empty());
    }

    #[test]
    fn ripr_badge_with_expired_suppression_keeps_finding_in_headline_and_warns() {
        let output = check_output(vec![finding_at_id("probe:a", ExposureClass::WeaklyExposed)]);
        let suppressions = vec![exposure_suppression("probe:a", Some("2025-01-01"))];

        let summary = ripr_badge_summary_with_suppressions(
            &output,
            &suppressions,
            "2026-05-03",
            BadgePolicy::default(),
        );

        // Expired suppression must NOT apply.
        assert_eq!(summary.counts.unsuppressed_exposure_gaps, 1);
        assert_eq!(summary.counts.suppressed_exposure_gaps, 0);
        // Warning surfaces so debt is visible.
        assert_eq!(summary.warnings.len(), 1);
        assert!(summary.warnings[0].contains("expired"));
        assert!(summary.warnings[0].contains("probe:a"));
    }

    #[test]
    fn ripr_plus_badge_with_test_efficiency_suppressions_moves_into_suppressed_bucket() {
        let te = TestEfficiencyBadgeSummary {
            unsuppressed_test_efficiency_findings: 2,
            actionable_entries: vec![
                TestEfficiencyBadgeEntry {
                    test: "alpha".to_string(),
                    path: "tests/a.rs".to_string(),
                    has_intent: false,
                    class: "smoke_only".to_string(),
                    reached_owners: Vec::new(),
                },
                TestEfficiencyBadgeEntry {
                    test: "beta".to_string(),
                    path: "tests/b.rs".to_string(),
                    has_intent: false,
                    class: "smoke_only".to_string(),
                    reached_owners: Vec::new(),
                },
            ],
            ..TestEfficiencyBadgeSummary::default()
        };
        let output = check_output(vec![]);
        let suppressions = vec![te_suppression("alpha", Some("tests/a.rs"), None)];

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &suppressions,
            "2026-05-03",
            BadgePolicy::default(),
            TestEfficiencyAggregationScope::Repo,
        );

        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 1);
        assert_eq!(summary.counts.suppressed_test_efficiency_findings, 1);
        assert_eq!(summary.message, "1");
        assert!(summary.warnings.is_empty());
    }

    #[test]
    fn native_json_emits_warnings_array_always_even_when_empty() {
        let summary = ripr_badge_summary(&check_output(vec![]), BadgePolicy::default());
        let json = render_native_json(&summary);

        // Empty case still emits the field for stable shape.
        assert!(json.contains("\"warnings\": []"));
    }

    #[test]
    fn native_json_emits_warnings_when_suppressions_have_warnings() {
        let output = check_output(vec![finding_at_id("probe:a", ExposureClass::WeaklyExposed)]);
        let suppressions = vec![exposure_suppression("probe:a", Some("2025-01-01"))];
        let summary = ripr_badge_summary_with_suppressions(
            &output,
            &suppressions,
            "2026-05-03",
            BadgePolicy::default(),
        );
        let json = render_native_json(&summary);

        assert!(json.contains("\"warnings\": ["));
        assert!(json.contains("expired"));
        assert!(json.contains("probe:a"));
    }

    #[test]
    fn shields_projection_remains_four_fields_even_with_warnings_present() {
        let output = check_output(vec![finding_at_id("probe:a", ExposureClass::WeaklyExposed)]);
        let suppressions = vec![exposure_suppression("probe:does_not_match", None)];
        let summary = ripr_badge_summary_with_suppressions(
            &output,
            &suppressions,
            "2026-05-03",
            BadgePolicy::default(),
        );
        let shields = render_shields_json(&summary);

        // Warnings must NOT bleed into the Shields projection.
        assert!(!shields.contains("warnings"));
        assert!(!shields.contains("probe:does_not_match"));
        let top_level = shields.lines().filter(|l| l.starts_with("  \"")).count();
        assert_eq!(top_level, 4);
    }

    #[test]
    fn declared_intent_remains_distinct_from_suppression_in_counts() {
        // 1 unsuppressed actionable, 2 intentional, 0 unknowns_te.
        let te = TestEfficiencyBadgeSummary {
            unsuppressed_test_efficiency_findings: 1,
            intentional_test_efficiency_findings: 2,
            actionable_entries: vec![TestEfficiencyBadgeEntry {
                test: "alpha".to_string(),
                path: "tests/a.rs".to_string(),
                has_intent: false,
                class: "smoke_only".to_string(),
                reached_owners: Vec::new(),
            }],
            ..TestEfficiencyBadgeSummary::default()
        };
        let output = check_output(vec![]);
        let suppressions = vec![te_suppression("alpha", Some("tests/a.rs"), None)];

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &suppressions,
            "2026-05-03",
            BadgePolicy::default(),
            TestEfficiencyAggregationScope::Repo,
        );

        // The actionable becomes suppressed, leaving 0 unsuppressed.
        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 0);
        assert_eq!(summary.counts.suppressed_test_efficiency_findings, 1);
        // Intentional count is unaffected — intent and suppression are distinct.
        assert_eq!(summary.counts.intentional_test_efficiency_findings, 2);
    }

    // -------- diff-scope `ripr+` aggregation --------
    //
    // `cargo xtask test-efficiency-report` is repo-wide as a fact source.
    // Diff-scoped `ripr+` must filter that ledger to entries related to
    // the changed code; repo-scoped `ripr+` aggregates the full ledger.
    // The `DiffRelatedTests` filter uses `Finding.related_tests` names
    // (rule 1) and `Finding.probe.owner` ∩ entry `reached_owners`
    // (rule 2). These tests pin both rules and the bucket-by-class
    // behavior under diff scope.

    use super::{DiffRelatedTests, TestEfficiencyAggregationScope as Scope};
    use crate::domain::SymbolId;
    use std::collections::BTreeMap;

    fn finding_with_owner(owner: &str, related: Vec<RelatedTest>) -> Finding {
        let mut f = finding(ExposureClass::WeaklyExposed, related);
        f.probe.owner = Some(SymbolId(owner.to_string()));
        f
    }

    fn te_entry(
        name: &str,
        path: &str,
        class: &str,
        has_intent: bool,
        reached_owners: &[&str],
    ) -> TestEfficiencyBadgeEntry {
        TestEfficiencyBadgeEntry {
            test: name.to_string(),
            path: path.to_string(),
            has_intent,
            class: class.to_string(),
            reached_owners: reached_owners.iter().map(|s| s.to_string()).collect(),
        }
    }

    fn te_summary(
        unsuppressed: usize,
        intentional: usize,
        unknowns: usize,
        actionable: Vec<TestEfficiencyBadgeEntry>,
        all: Vec<TestEfficiencyBadgeEntry>,
    ) -> TestEfficiencyBadgeSummary {
        TestEfficiencyBadgeSummary {
            unsuppressed_test_efficiency_findings: unsuppressed,
            intentional_test_efficiency_findings: intentional,
            unknowns_test_efficiency: unknowns,
            analyzed_tests: all.len(),
            reason_counts: BTreeMap::new(),
            actionable_entries: actionable,
            entries: all,
        }
    }

    #[test]
    fn diff_related_tests_extracts_owners_and_test_keys_from_findings() {
        let output = check_output(vec![
            finding_with_owner(
                "pricing::quote",
                vec![related_test(
                    "premium_customer_gets_discount",
                    "tests/pricing.rs",
                    12,
                )],
            ),
            finding_with_owner("billing::charge", vec![]),
        ]);
        let filter = DiffRelatedTests::from_check_output(&output);

        assert!(filter.changed_owners.contains("pricing::quote"));
        assert!(filter.changed_owners.contains("billing::charge"));
        // Both bare and qualified test keys are present so the filter
        // can match either shape from the test-efficiency report.
        assert!(
            filter
                .related_test_keys
                .contains("premium_customer_gets_discount")
        );
        assert!(
            filter
                .related_test_keys
                .contains("tests/pricing.rs::premium_customer_gets_discount")
        );
    }

    #[test]
    fn diff_ripr_plus_counts_related_smoke_only_via_related_tests_match() {
        // Entry's `(name, path)` matches a Finding.related_tests entry.
        let related = related_test("premium_customer_gets_discount", "tests/pricing.rs", 12);
        let output = check_output(vec![finding_with_owner("pricing::quote", vec![related])]);
        let entry = te_entry(
            "premium_customer_gets_discount",
            "tests/pricing.rs",
            "smoke_only",
            false,
            &[], // no reached_owners — rule 1 still wins
        );
        let te = te_summary(1, 0, 0, vec![entry.clone()], vec![entry]);
        let filter = DiffRelatedTests::from_check_output(&output);

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &[],
            "2026-05-04",
            BadgePolicy::default(),
            Scope::Diff(&filter),
        );

        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 1);
    }

    #[test]
    fn diff_ripr_plus_counts_related_smoke_only_via_owner_intersection() {
        // No related_tests match; rule 2 (reached_owners ∩ changed_owners) wins.
        let output = check_output(vec![finding_with_owner("pricing::quote", vec![])]);
        let entry = te_entry(
            "unrelated_name",
            "tests/elsewhere.rs",
            "smoke_only",
            false,
            &["pricing::quote", "billing::charge"],
        );
        let te = te_summary(1, 0, 0, vec![entry.clone()], vec![entry]);
        let filter = DiffRelatedTests::from_check_output(&output);

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &[],
            "2026-05-04",
            BadgePolicy::default(),
            Scope::Diff(&filter),
        );

        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 1);
    }

    #[test]
    fn diff_ripr_plus_counts_related_duplicative_entry() {
        let output = check_output(vec![finding_with_owner("pricing::quote", vec![])]);
        let entry = te_entry(
            "premium_customer_gets_discount",
            "tests/pricing.rs",
            "duplicative",
            false,
            &["pricing::quote"],
        );
        let te = te_summary(1, 0, 0, vec![entry.clone()], vec![entry]);
        let filter = DiffRelatedTests::from_check_output(&output);

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &[],
            "2026-05-04",
            BadgePolicy::default(),
            Scope::Diff(&filter),
        );

        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 1);
    }

    #[test]
    fn diff_ripr_plus_ignores_unrelated_likely_vacuous_test() {
        // Diff touches `pricing::quote`; the test-efficiency entry
        // reaches `unrelated::module` and has no related_tests match.
        let output = check_output(vec![finding_with_owner("pricing::quote", vec![])]);
        let unrelated = te_entry(
            "totally_unrelated_test",
            "tests/elsewhere.rs",
            "likely_vacuous",
            false,
            &["unrelated::module"],
        );
        let te = te_summary(1, 0, 0, vec![unrelated.clone()], vec![unrelated]);
        let filter = DiffRelatedTests::from_check_output(&output);

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &[],
            "2026-05-04",
            BadgePolicy::default(),
            Scope::Diff(&filter),
        );

        assert_eq!(
            summary.counts.unsuppressed_test_efficiency_findings, 0,
            "unrelated repo-wide test-efficiency debt must NOT move the diff headline"
        );
    }

    #[test]
    fn diff_ripr_plus_ignores_unrelated_duplicative_group() {
        let output = check_output(vec![finding_with_owner("pricing::quote", vec![])]);
        let entries = vec![
            te_entry(
                "dup_a",
                "tests/elsewhere.rs",
                "duplicative",
                false,
                &["unrelated::a"],
            ),
            te_entry(
                "dup_b",
                "tests/elsewhere.rs",
                "duplicative",
                false,
                &["unrelated::b"],
            ),
            te_entry(
                "dup_c",
                "tests/elsewhere.rs",
                "duplicative",
                false,
                &["unrelated::c"],
            ),
        ];
        let te = te_summary(3, 0, 0, entries.clone(), entries);
        let filter = DiffRelatedTests::from_check_output(&output);

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &[],
            "2026-05-04",
            BadgePolicy::default(),
            Scope::Diff(&filter),
        );

        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 0);
    }

    #[test]
    fn repo_ripr_plus_still_counts_whole_repo_actionable_test_efficiency() {
        // Same fixture as the diff-ignores test above; under repo
        // scope the whole-repo unsuppressed total still counts.
        let output = check_output(vec![finding_with_owner("pricing::quote", vec![])]);
        let unrelated = te_entry(
            "totally_unrelated_test",
            "tests/elsewhere.rs",
            "likely_vacuous",
            false,
            &["unrelated::module"],
        );
        let te = te_summary(1, 0, 0, vec![unrelated.clone()], vec![unrelated]);

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &[],
            "2026-05-04",
            BadgePolicy::default(),
            Scope::Repo,
        );

        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 1);
    }

    #[test]
    fn diff_ripr_plus_excludes_related_declared_intent_finding() {
        // A related entry with declared intent counts toward
        // `intentional_*`, never toward the unsuppressed headline.
        let output = check_output(vec![finding_with_owner("pricing::quote", vec![])]);
        let intent_entry = te_entry(
            "premium_customer_gets_discount",
            "tests/pricing.rs",
            "smoke_only",
            true,
            &["pricing::quote"],
        );
        // unsuppressed count from the parser is 0 (intent excluded);
        // intentional total is 1.
        let te = te_summary(0, 1, 0, Vec::new(), vec![intent_entry]);
        let filter = DiffRelatedTests::from_check_output(&output);

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &[],
            "2026-05-04",
            BadgePolicy::default(),
            Scope::Diff(&filter),
        );

        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 0);
        assert_eq!(summary.counts.intentional_test_efficiency_findings, 1);
    }

    #[test]
    fn diff_ripr_plus_excludes_related_suppressed_finding() {
        let output = check_output(vec![finding_with_owner("pricing::quote", vec![])]);
        let entry = te_entry(
            "premium_customer_gets_discount",
            "tests/pricing.rs",
            "smoke_only",
            false,
            &["pricing::quote"],
        );
        let te = te_summary(1, 0, 0, vec![entry.clone()], vec![entry]);
        let suppressions = vec![te_suppression(
            "premium_customer_gets_discount",
            Some("tests/pricing.rs"),
            None,
        )];
        let filter = DiffRelatedTests::from_check_output(&output);

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &suppressions,
            "2026-05-04",
            BadgePolicy::default(),
            Scope::Diff(&filter),
        );

        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 0);
        assert_eq!(summary.counts.suppressed_test_efficiency_findings, 1);
    }

    #[test]
    fn diff_ripr_plus_keeps_related_opaque_visible_but_not_headline() {
        // Use an exposure-side `Exposed` finding (which does not count
        // as an exposure gap) so the headline isolates the
        // test-efficiency contribution. The owner is still set so the
        // diff filter has something to intersect against.
        let mut f = finding(ExposureClass::Exposed, vec![]);
        f.probe.owner = Some(SymbolId("pricing::quote".to_string()));
        let output = check_output(vec![f]);
        let opaque_entry = te_entry(
            "opaque_oracle_test",
            "tests/pricing.rs",
            "opaque",
            false,
            &["pricing::quote"],
        );
        // Parser totals: 0 unsuppressed (opaque doesn't go there), 1 unknowns_te.
        let te = te_summary(0, 0, 1, Vec::new(), vec![opaque_entry]);
        let filter = DiffRelatedTests::from_check_output(&output);

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &[],
            "2026-05-04",
            BadgePolicy::default(),
            Scope::Diff(&filter),
        );

        assert_eq!(summary.counts.unsuppressed_test_efficiency_findings, 0);
        assert_eq!(summary.counts.unknowns_test_efficiency, 1);
        // Headline excludes both unknowns and unsuppressed_te here:
        // 0 exposure gaps + 0 te + 0 (unknowns excluded by default policy).
        assert_eq!(summary.message, "0");
    }

    #[test]
    fn diff_ripr_plus_count_unaffected_by_unrelated_repo_wide_te_debt() {
        // Mix one related actionable with many unrelated repo-wide
        // entries. The diff headline should reflect only the related
        // entry; unrelated debt stays in the repo-wide counts but does
        // NOT move the diff signal.
        let output = check_output(vec![finding_with_owner("pricing::quote", vec![])]);
        let related = te_entry(
            "premium_customer_gets_discount",
            "tests/pricing.rs",
            "smoke_only",
            false,
            &["pricing::quote"],
        );
        let unrelated = (0..5)
            .map(|i| {
                te_entry(
                    &format!("unrelated_{i}"),
                    "tests/elsewhere.rs",
                    "duplicative",
                    false,
                    &["other::module"],
                )
            })
            .collect::<Vec<_>>();

        let mut all_entries = vec![related.clone()];
        all_entries.extend(unrelated.iter().cloned());
        let mut all_actionable = vec![related];
        all_actionable.extend(unrelated);

        let te = te_summary(6, 0, 0, all_actionable, all_entries);
        let filter = DiffRelatedTests::from_check_output(&output);

        let summary = ripr_plus_badge_summary_with_suppressions(
            &output,
            te,
            &[],
            "2026-05-04",
            BadgePolicy::default(),
            Scope::Diff(&filter),
        );

        assert_eq!(
            summary.counts.unsuppressed_test_efficiency_findings, 1,
            "diff headline should only count the related entry, not the 5 unrelated ones"
        );
    }
}