crap-core 0.1.0

Language-agnostic foundation for the CRAP analyzer family — domain types, port traits, and shared invariants for crap4rs / future crap4ts.
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
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
//! CLI entry point — thin shell over the library crate.
//!
//! Parses args with clap, validates inputs, delegates to `core::analyze()`.
//! No business logic lives here.
//!
//! Relocated from `crap4rs::cli` in S4 (#136). The orchestrator
//! `cli::run<P>` is generic over the coverage adapter's parse-diagnostic
//! type so the same dispatch shell drives every adapter binary
//! (`crap4rs`, future `crap4ts`). Per-binary main.rs supplies the
//! complexity + coverage ports as `&dyn` trait objects (ADR D9).

use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::SystemTime;

use anyhow::{Result, bail};
use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum, ValueHint};
use clap_complete::Shell as ClapShell;

use crate::adapters::baseline::{self, BaselineSnapshot};
use crate::adapters::config::{self, FileConfig};
use crate::adapters::reporters;
use crate::adapters::reporters::json::DeltaContext;
use crate::core::{AnalysisOutput, AnalyzeOptions};
use crate::domain::delta::{self, AnalysisDelta, DeltaView};
use crate::domain::threshold::{
    DEFAULT_THRESHOLD, LENIENT_THRESHOLD, STRICT_THRESHOLD, ThresholdConfig, is_valid_threshold,
};
use crate::domain::types::{AnalysisDiagnostics, ComplexityMetric};
use crate::domain::view::{self, GroupKey, SortKey};
use crate::ports::{ComplexityPort, CoveragePort, ParseDiagnostic};

mod delta_args;
mod view_args;

// ── ValueEnum wrappers (keep domain types clap-free) ────────────────

/// Complexity metric for CRAP score computation.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum MetricArg {
    /// Nesting depth + structural complexity (default for Rust)
    Cognitive,
    /// Decision-point count, classic CRAP metric
    Cyclomatic,
}

impl From<MetricArg> for ComplexityMetric {
    fn from(arg: MetricArg) -> Self {
        match arg {
            MetricArg::Cognitive => ComplexityMetric::Cognitive,
            MetricArg::Cyclomatic => ComplexityMetric::Cyclomatic,
        }
    }
}

/// Output format for the CRAP report.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum FormatArg {
    /// Human-readable table with ANSI colors
    Table,
    /// Nested JSON envelope (pipe to jq for filtering)
    Json,
    /// GitHub-flavored Markdown — paste into PR comments or issues
    Markdown,
    /// RFC 4180 CSV — one row per function, no summary
    Csv,
    /// SARIF v2.1.0 — for GitHub Code Scanning (upload-sarif@v3)
    Sarif,
    /// Agent-oriented JSON with Diagnostic remediation hints (experimental)
    Advice,
    /// Single mokumo-scorecard `Row::CrapDelta` JSON object — for scorecard
    /// aggregator consumption (mokumo schema_version=2). Issue #111.
    ScorecardRow,
    /// Self-contained HTML dashboard with summary stats, risk
    /// distribution, and per-file collapsible function tables. Inline
    /// CSS, no external assets, mobile-responsive. Issue #71.
    Html,
}

/// One requested output: a format and an optional file destination.
///
/// Parsed from `--format X` (stdout) or `--format X:FILE` (write to file).
/// `--format` accepts a comma-separated list of these specs so a single
/// analysis pass can fan out to multiple shapes (issue #100).
#[derive(Debug, Clone)]
pub struct FormatSpec {
    pub format: FormatArg,
    pub output: Option<PathBuf>,
}

impl std::str::FromStr for FormatSpec {
    type Err = String;

    fn from_str(spec: &str) -> Result<Self, Self::Err> {
        let (fmt_str, output) = match spec.split_once(':') {
            Some((f, path)) if !path.is_empty() => (f, Some(PathBuf::from(path))),
            Some((_, _)) => return Err(format!("empty file path in `--format {spec}`")),
            None => (spec, None),
        };
        let format = FormatArg::from_str(fmt_str, true)
            .map_err(|e| format!("invalid format `{fmt_str}`: {e}"))?;
        Ok(FormatSpec { format, output })
    }
}

/// Clap value parser for `FormatSpec` — delegates to the `FromStr` impl.
fn parse_format_spec(s: &str) -> Result<FormatSpec, String> {
    s.parse()
}

/// Sort key for the displayed view (issue #68).
///
/// CLI-side wrapper that keeps `clap::ValueEnum` out of the domain.
/// `From<SortKeyArg> for SortKey` is the boundary; `build_view_spec`
/// translates at the edge so `domain::view::SortKey` stays clap-free.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum SortKeyArg {
    /// CRAP score descending (default — investigator's first cut)
    Crap,
    /// Coverage percent ascending (lowest coverage first)
    Coverage,
    /// Complexity descending (most complex first)
    Complexity,
    /// Alphabetical by file_path, then CRAP descending within file
    Path,
}

impl From<SortKeyArg> for SortKey {
    fn from(arg: SortKeyArg) -> Self {
        match arg {
            SortKeyArg::Crap => SortKey::Crap,
            SortKeyArg::Coverage => SortKey::Coverage,
            SortKeyArg::Complexity => SortKey::Complexity,
            SortKeyArg::Path => SortKey::Path,
        }
    }
}

/// Reverse mapping for saved view presets (issue #80) — preset stores
/// domain `SortKey`, but `FilterArgs.sort_by` is the clap-side wrapper.
///
/// `SortKey` is `#[non_exhaustive]` for cross-crate consumers, but
/// post-S4 (#136) the cli module lives in the same crate as the domain
/// `SortKey` definition, so the compiler treats the match as exhaustive
/// without a wildcard arm. New domain variants must still land with a
/// paired CLI variant in the same PR — clippy's missing-pattern error
/// is now the loud failure point (the formerly-required wildcard arm
/// triggered `unreachable_patterns` post-relocation).
impl From<SortKey> for SortKeyArg {
    fn from(key: SortKey) -> Self {
        match key {
            SortKey::Crap => SortKeyArg::Crap,
            SortKey::Coverage => SortKeyArg::Coverage,
            SortKey::Complexity => SortKeyArg::Complexity,
            SortKey::Path => SortKeyArg::Path,
        }
    }
}

/// Group key for the displayed view (issue #64).
///
/// Today only `file` is supported. The wrapper keeps `clap::ValueEnum`
/// out of the domain; `From<GroupByArg> for GroupKey` is the boundary.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum GroupByArg {
    /// Aggregate by source file path
    File,
}

impl From<GroupByArg> for GroupKey {
    fn from(arg: GroupByArg) -> Self {
        match arg {
            GroupByArg::File => GroupKey::File,
        }
    }
}

/// Reverse mapping for saved view presets (issue #80). See `From<SortKey>`
/// above for the wildcard-arm rationale (post-S4 in-crate exhaustive).
impl From<GroupKey> for GroupByArg {
    fn from(key: GroupKey) -> Self {
        match key {
            GroupKey::File => GroupByArg::File,
        }
    }
}

/// Sort key for the delta block (issue #81).
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum DeltaSortKeyArg {
    /// Magnitude of change descending — regressions first (default)
    ScoreDelta,
    /// Current CRAP score descending; `Removed` rows last
    CurrentCrap,
    /// Baseline CRAP score descending; `Added` rows last
    BaselineCrap,
    /// Alphabetical by file_path then qualified_name
    Path,
}

impl From<DeltaSortKeyArg> for crate::domain::delta::DeltaSortKey {
    fn from(arg: DeltaSortKeyArg) -> Self {
        use crate::domain::delta::DeltaSortKey;
        match arg {
            DeltaSortKeyArg::ScoreDelta => DeltaSortKey::ScoreDelta,
            DeltaSortKeyArg::CurrentCrap => DeltaSortKey::CurrentCrap,
            DeltaSortKeyArg::BaselineCrap => DeltaSortKey::BaselineCrap,
            DeltaSortKeyArg::Path => DeltaSortKey::Path,
        }
    }
}

/// Change-kind subset for `--delta-only` (issue #81).
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum DeltaKindArg {
    Added,
    Removed,
    Modified,
}

impl From<DeltaKindArg> for crate::domain::delta::ChangeKind {
    fn from(arg: DeltaKindArg) -> Self {
        use crate::domain::delta::ChangeKind;
        match arg {
            DeltaKindArg::Added => ChangeKind::Added,
            DeltaKindArg::Removed => ChangeKind::Removed,
            DeltaKindArg::Modified => ChangeKind::Modified,
        }
    }
}

/// When to colorize output.
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
pub enum ColorArg {
    /// Colorize when writing to a terminal
    #[default]
    Auto,
    /// Always colorize output
    Always,
    /// Never colorize output
    Never,
}

// ── Arg groups ──────────────────────────────────────────────────────

/// Shell name for completion script generation (#69).
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ShellArg {
    Bash,
    Zsh,
    Fish,
    Powershell,
    Elvish,
    Nushell,
}

/// Top-level subcommands. Optional — when absent, crap4rs runs the
/// default analysis path that requires `--coverage`.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Generate a shell completion script to stdout.
    Completions {
        #[arg(value_enum)]
        shell: ShellArg,
    },
}

#[derive(Debug, Args)]
#[command(next_help_heading = "Input")]
pub struct InputArgs {
    /// Path to LCOV coverage file (from `cargo llvm-cov --lcov`).
    /// Required for analysis; not required for `crap4rs completions`.
    #[arg(long, value_name = "FILE", value_hint = ValueHint::FilePath)]
    pub coverage: Option<PathBuf>,

    /// Root directory of Rust source files to analyze [default: src]
    #[arg(long, value_name = "DIR", value_hint = ValueHint::DirPath)]
    pub src: Option<PathBuf>,

    /// Complexity metric to use [default: cognitive]
    #[arg(long, value_enum)]
    pub metric: Option<MetricArg>,

    /// Path to config file (default: auto-discover crap4rs.toml)
    #[arg(long, value_name = "FILE", value_hint = ValueHint::FilePath)]
    pub config: Option<PathBuf>,

    /// Resolve and apply a saved view preset from `crap4rs.toml`.
    ///
    /// The preset's fields (`top`, `min_coverage`, `max_coverage`, `sort`,
    /// `only_failing`, `no_fail`, `group_by`, `minimal_view`) are folded
    /// into the parsed CLI before the report is shaped. CLI flags
    /// override the preset's `Option<T>` fields. Bare-bool flags
    /// OR-merge with the preset (an explicit `--no-fail` adds to a
    /// preset's value but cannot turn off `no_fail = true`).
    #[arg(long, value_name = "NAME")]
    pub view: Option<String>,

    /// Path to a previously-emitted crap4rs JSON envelope, used as the
    /// baseline for delta analysis.
    ///
    /// Crap4rs runs the current analysis as usual, then compares against
    /// the baseline's `result` block to produce a `delta` block in the
    /// output (see `--format json`, `--format markdown` for rendering).
    /// Generate the baseline file by piping a previous run:
    /// `crap4rs --coverage lcov.info --format json > baseline.json`.
    ///
    /// **Delta is informational by default.** Pass `--delta-gate` to
    /// make the delta contribute to the exit code (fails on new
    /// threshold violations introduced by this PR).
    #[arg(long, value_name = "FILE", value_hint = ValueHint::FilePath)]
    pub baseline: Option<PathBuf>,
}

#[derive(Debug, Args)]
#[command(next_help_heading = "Output")]
pub struct OutputArgs {
    /// Output format(s).
    ///
    /// Accepts a single format (`--format json`) for stdout, or a comma-
    /// separated list to fan out a single analysis pass to multiple
    /// destinations (`--format json:envelope.json,markdown:report.md`).
    /// Each entry is `FORMAT` (stdout) or `FORMAT:FILE` (write to file).
    /// Multi-format invocations require every entry to specify a file —
    /// stdout cannot multiplex (issue #100).
    #[arg(
        short,
        long,
        value_delimiter = ',',
        default_value = "table",
        value_parser = parse_format_spec
    )]
    pub format: Vec<FormatSpec>,

    /// CRAP score threshold — functions above this fail the check [default: 25]
    // allow_hyphen_values: lets clap parse `--threshold -5` as a value
    // (not a flag), so our validate_inputs can give an actionable error.
    #[arg(long, allow_hyphen_values = true, group = "threshold_select")]
    pub threshold: Option<f64>,

    /// Use strict threshold (15) — for high-quality or safety-critical code
    #[arg(long, group = "threshold_select")]
    pub strict: bool,

    /// Use lenient threshold (40) — for legacy or transitional code
    #[arg(long, group = "threshold_select")]
    pub lenient: bool,

    /// Always exit 0, even when threshold violations exist.
    ///
    /// Overrides only the exit-code translation; the underlying analysis
    /// is untouched and `result.passed` in JSON output still reflects
    /// the truthful pass/fail state, so consumers can detect "would
    /// have failed" even when the process exits 0. Composes with
    /// `--quiet` for silent success in CI. With `--delta-gate`, also
    /// overrides the delta-gate exit-code translation (truth still in
    /// `delta.summary.passed`).
    #[arg(long)]
    pub no_fail: bool,

    /// Fail the build (exit 1) when the baseline comparison introduces
    /// new threshold violations.
    ///
    /// Off by default — delta is informational unless this flag is set.
    /// Drives off `delta.summary.passed`, which is true iff
    /// `new_violations == 0`. Pre-existing violations (functions that
    /// already exceeded threshold in the baseline) do NOT contribute,
    /// so re-running with no code changes never trips the gate. Only
    /// meaningful with `--baseline`. Composes with `--no-fail` (which
    /// overrides BOTH gates).
    #[arg(long, requires = "baseline")]
    pub delta_gate: bool,

    /// Omit the denormalized `view.shown` row array from JSON output.
    ///
    /// Payload-size escape hatch for very large codebases. The
    /// envelope's `result` block (the gate) is unaffected; `view.spec`,
    /// `view.eligible_count`, `view.truncated`, and `view.shown_summary`
    /// remain so consumers retain full scope context. Only meaningful
    /// with `--format json`.
    #[arg(long)]
    pub minimal_view: bool,
}

#[derive(Debug, Args)]
#[command(next_help_heading = "Filtering")]
pub struct FilterArgs {
    /// Glob patterns to exclude from analysis (repeatable)
    ///
    /// Build artifacts (target/) are excluded automatically via .gitignore.
    /// Test files are NOT excluded by default — use `--exclude "tests/**"`
    /// if you want to skip them.
    #[arg(long, action = clap::ArgAction::Append)]
    pub exclude: Vec<String>,

    /// Do not respect .gitignore files
    ///
    /// By default, paths in .gitignore are skipped (e.g., target/).
    /// Pass this flag to analyze all files regardless of .gitignore.
    #[arg(long)]
    pub no_gitignore: bool,

    /// Git ref to diff against — only analyze functions in changed files/hunks
    ///
    /// Scopes analysis to functions in files that changed since the given ref.
    /// Useful for CI PR gating: `crap4rs --coverage lcov.info --diff main`
    #[arg(long, value_name = "REF")]
    pub diff: Option<String>,

    /// Only show functions that exceed the threshold
    ///
    /// Display-only filter: the underlying analysis (the gate) and its
    /// summary remain over the full unfiltered set, so the exit code and
    /// every aggregate (`average_crap`, `median_crap`, `distribution`,
    /// etc.) reflect the whole codebase. Only the row list and
    /// `view.shown_summary` are reduced.
    #[arg(long)]
    pub only_failing: bool,

    /// Lower bound (inclusive) on coverage_percent for the displayed view.
    ///
    /// `allow_hyphen_values`: lets clap parse `--min-coverage -5` as a
    /// value (not an unknown flag) so `validate_view_args` can report
    /// the right error.
    #[arg(long, allow_hyphen_values = true, value_name = "PCT")]
    pub min_coverage: Option<f64>,

    /// Upper bound (inclusive) on coverage_percent for the displayed view.
    #[arg(long, allow_hyphen_values = true, value_name = "PCT")]
    pub max_coverage: Option<f64>,

    /// Sort key for the displayed view (default: crap descending).
    ///
    /// `crap` (default) — CRAP score descending; `coverage` — coverage
    /// percent ascending (lowest first); `complexity` — complexity
    /// descending; `path` — alphabetical by file, then CRAP descending
    /// within file. Sorting reorders without reducing rows, so the gate
    /// (exit code) is unaffected. Unknown values are rejected by clap
    /// at parse time with an `invalid value` error attributed to
    /// `--sort-by`, so no custom validation is needed here.
    #[arg(long, value_enum, value_name = "KEY")]
    pub sort_by: Option<SortKeyArg>,

    /// Truncate the displayed view to the top N highest-CRAP rows.
    ///
    /// `--top 0` means "no limit" — equivalent to omitting the flag.
    /// The full unfiltered analysis still drives the gate (exit code),
    /// so truncating violations out of the view does not change the outcome.
    ///
    /// `allow_hyphen_values`: lets clap parse `--top -3` as a value (not an
    /// unknown flag) so the resulting error message is attributed to `--top`.
    #[arg(long, allow_hyphen_values = true, value_name = "N")]
    pub top: Option<u32>,

    /// Aggregate the displayed view by a key. Today: `file` only.
    ///
    /// When set, the report shifts to per-file rows. `--top N` truncates
    /// to the top N **files** (not functions); `--sort-by` keys at the
    /// file level (`crap` → average CRAP descending; `coverage` →
    /// average coverage ascending; `complexity` → max complexity
    /// descending; `path` → alphabetical). The full per-function row
    /// list still appears in JSON `view.shown` for drill-down. The
    /// gate (exit code) is unaffected.
    #[arg(long, value_enum, value_name = "KEY")]
    pub group_by: Option<GroupByArg>,

    /// Truncate the delta block to the top N rows by `--delta-sort`.
    /// `--delta-top 0` means "no limit". Independent of `--top`, which
    /// truncates the analysis view (`view.shown`).
    ///
    /// `allow_hyphen_values`: parses `--delta-top -3` as a value (not
    /// an unknown flag) so the error attribution to `--delta-top` is
    /// readable.
    #[arg(long, allow_hyphen_values = true, value_name = "N")]
    pub delta_top: Option<u32>,

    /// Sort key for the delta block.
    ///
    /// `score-delta` (default) — magnitude of change descending
    /// (regressions first). `current-crap` — current CRAP descending,
    /// `Removed` rows last. `baseline-crap` — baseline CRAP descending,
    /// `Added` rows last. `path` — alphabetical by file then qualified
    /// name.
    #[arg(long, value_enum, value_name = "KEY")]
    pub delta_sort: Option<DeltaSortKeyArg>,

    /// Comma-separated list of change kinds to include in the delta
    /// block: `added`, `removed`, `modified`. Default: all three.
    #[arg(long, value_delimiter = ',', value_name = "KINDS")]
    pub delta_only: Vec<DeltaKindArg>,
}

#[derive(Debug, Args)]
#[command(next_help_heading = "Display")]
pub struct DisplayArgs {
    /// When to use terminal colors
    #[arg(long, value_enum, default_value_t = ColorArg::Auto)]
    pub color: ColorArg,

    /// Show parse diagnostics and matching statistics
    #[arg(short, long)]
    pub verbose: bool,

    /// Suppress report output, only set exit code
    #[arg(short, long)]
    pub quiet: bool,

    /// Show complexity contributors for functions exceeding threshold.
    ///
    /// JSON output always includes contributors regardless of this flag.
    #[arg(long)]
    pub breakdown: bool,

    /// Explain nested breakdown increments in table output.
    ///
    /// Only affects table output, and only when `--breakdown` is enabled.
    #[arg(long)]
    pub explain: bool,

    /// Render the full per-function table in markdown output.
    ///
    /// By default `--format markdown` produces a compact summary plus a
    /// top-N table (failures if any exist, otherwise the worst by CRAP).
    /// This flag appends the legacy row-per-function table — useful when
    /// piping into a longer document instead of a PR comment. Has no
    /// effect on other output formats.
    #[arg(long)]
    pub md_full_table: bool,

    /// Number of rows in the markdown top-N table (default 10).
    ///
    /// Bounds the failures list (or worst-by-CRAP list when nothing
    /// exceeds threshold). The summary block is unaffected — its stats
    /// always reflect the full unshapeable analysis.
    #[arg(long, value_name = "N", default_value_t = 10)]
    pub md_top: usize,
}

// ── Top-level CLI ───────────────────────────────────────────────────

// `long_version` is overridden at runtime in `cli::run` so the binary's
// build script (`crap4rs/build.rs`) can splice the git hash + build date
// into the Rust adapter's `--version` output without forcing crap-core
// to read an env var that's only set during crap4rs's compile. The
// derive's `version` here resolves to the **adapter** crate's
// `CARGO_PKG_VERSION` because clap captures the env at the macro
// expansion site — that's the binary crate's version when compiling
// the binary, but the lib crate's version when compiling the lib.
// Production callers always reach `cli::run` through the binary, so
// `--version` displays the adapter's version. Tests that go through
// the lib see crap-core's version, which is fine for tests.
//
// Threading per S4 lesson 7 (tool-version threading): consumer-visible
// version strings flow as parameters from the bin where `env!` resolves
// against the bin's package, not against this module's home crate.

#[derive(Debug, Parser)]
#[command(
    version,
    author,
    about = "CRAP score analyzer for Rust",
    long_about = "CRAP (Change Risk Anti-Patterns) score analyzer for Rust codebases.\n\n\
                  Combines complexity analysis (via syn) with line coverage data \
                  (LCOV from cargo-llvm-cov) to identify functions that are both \
                  complex and under-tested.\n\n\
                  Default metric is cognitive complexity (not cyclomatic), which \
                  better captures Rust idioms like match arms and nested control flow.",
    after_help = "\
EXAMPLES:
  crap4rs --coverage lcov.info
  crap4rs --coverage lcov.info --threshold 15 --metric cyclomatic
  crap4rs --coverage lcov.info --format json | jq '.functions[] | select(.exceeds)'
  crap4rs --coverage lcov.info --only-failing
  crap4rs --coverage lcov.info --exclude \"tests/**\" --exclude \"benches/**\"

INVESTIGATION PATTERNS:
  # First-run scan: keep the report short
  crap4rs --coverage lcov.info --top 20

  # Worst partially-covered functions, sorted by coverage ascending,
  # never fail the build — useful when investigating an untested codebase
  crap4rs --coverage lcov.info --min-coverage 1 --max-coverage 90 --sort-by coverage --top 10 --no-fail

  # Saved view preset: bake a flag set under [views.ci] in crap4rs.toml,
  # then invoke it by name. CLI flags override preset values.
  crap4rs --coverage lcov.info --view ci

  # GitHub Code Scanning: emit SARIF and let upload-sarif annotate the PR
  # diff inline. Use --no-fail so the gate exit code doesn't skip the
  # upload step on regressions.
  crap4rs --coverage lcov.info --format sarif --no-fail > crap.sarif

COMPARING TWO ANALYSES (issue #81):
  # Capture a baseline (e.g., from main):
  crap4rs --coverage lcov.info --format json > baseline.json

  # Then compare the working tree to it (informational by default):
  crap4rs --coverage lcov.info --baseline baseline.json

  # CI usage: fail the build when new threshold violations land
  crap4rs --coverage lcov.info --baseline baseline.json --delta-gate

  # PR-comment scorecard (markdown — drop into the comment body verbatim)
  crap4rs --coverage lcov.info --baseline baseline.json --format markdown"
)]
pub struct Cli {
    #[command(flatten)]
    pub input: InputArgs,

    #[command(flatten)]
    pub output: OutputArgs,

    #[command(flatten)]
    pub filter: FilterArgs,

    #[command(flatten)]
    pub display: DisplayArgs,

    #[command(subcommand)]
    pub command: Option<Command>,
}

// ── Entry point ─────────────────────────────────────────────────────

/// Parse process args and produce a `Cli`. Splits in half from `run`
/// so the binary `main.rs` can consult `cli.input.src` (config-aware)
/// before constructing its `LcovParser` (which needs the source root
/// at construction time per the LCOV adapter's path-stripping
/// invariant). `run` then consumes the parsed `Cli` directly.
///
/// `tool_version` (e.g. `crap4rs`'s `0.4.0`) and `long_version`
/// (e.g. `0.4.0 (abc1234 2026-05-09)`) are spliced into clap's help
/// and `--version` output at runtime so the binary's build-script
/// metadata reaches the help text — the derive macro's `version`
/// reads `CARGO_PKG_VERSION` at lib-crate compile time (crap-core's
/// `0.1.0`), and `CRAP4RS_LONG_VERSION` is only set during the
/// binary's compile.
///
/// `clap::Command::{version,long_version}` take
/// `IntoResettable<Str>` which implements `From<&'static str>` but
/// not `From<String>`. The strings live for the program's lifetime,
/// so leaking once at startup is the cheapest path that satisfies
/// clap's expected lifetime. The leak is fixed-size and one-shot.
pub fn parse_args(tool_version: &str, long_version: &str) -> Cli {
    let cmd = build_command(tool_version, long_version);
    let matches = cmd.get_matches();
    Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit())
}

/// Read the adapter binary's name from `argv[0]`. The clap-derive
/// `Cli::command()` defaults to `CARGO_PKG_NAME` of the lib crate
/// (crap-core) which would print `--version` lines as
/// `crap-core 0.4.0 ...` and shape generated completion scripts to
/// the wrong identifier; runtime detection ensures the displayed
/// name matches whichever adapter binary (`crap4rs`, future
/// `crap4ts`) actually ran.
fn current_bin_name() -> String {
    std::env::args()
        .next()
        .and_then(|first| {
            // `file_stem()` (not `file_name()`) so Windows builds drop
            // the `.exe` suffix — without it `--version` prints
            // `crap4rs.exe 0.4.0` and breaks scripts (and the
            // version-stamp integration tests) that match `^crap4rs `.
            // No-op on Linux/macOS.
            std::path::PathBuf::from(first)
                .file_stem()
                .map(|os| os.to_string_lossy().into_owned())
        })
        .unwrap_or_else(|| "crap4rs".to_string())
}

/// Build the clap `Command` with the binary's runtime metadata
/// spliced in. Used by `parse_args`; `emit_completions` reads the
/// bin name through `current_bin_name` directly because
/// `clap_complete::generate` takes the bin name as a separate arg.
fn build_command(tool_version: &str, long_version: &str) -> clap::Command {
    let bin_static: &'static str = Box::leak(current_bin_name().into_boxed_str());
    let version_static: &'static str = Box::leak(tool_version.to_string().into_boxed_str());
    let long_version_static: &'static str = Box::leak(long_version.to_string().into_boxed_str());
    Cli::command()
        .name(bin_static)
        .bin_name(bin_static)
        .version(version_static)
        .long_version(long_version_static)
}

/// Run the CRAP CLI pipeline end-to-end. Generic over `P:
/// ParseDiagnostic` so the same orchestrator drives every adapter
/// crate's binary (per ADR D9, mixed-dispatch).
///
/// `tool_version` is the binary's own version (e.g. `crap4rs`'s
/// `CARGO_PKG_VERSION` resolves to `0.4.0`, not crap-core's `0.1.0`).
/// It feeds the JSON envelope's `tool_version` field, the SARIF run
/// metadata, the markdown header, the HTML report header, and clap's
/// long-version splice when the caller threads it through.
pub fn run<P: ParseDiagnostic + std::fmt::Display>(
    cli: Cli,
    complexity: &dyn ComplexityPort,
    coverage: &dyn CoveragePort<Diagnostic = P>,
    tool_version: &str,
) -> ExitCode {
    match run_inner(cli, complexity, coverage, tool_version) {
        Ok(true) => ExitCode::from(0),
        Ok(false) => ExitCode::from(1),
        Err(e) => {
            eprintln!("error: {e:#}");
            ExitCode::from(2)
        }
    }
}

fn run_inner<P: ParseDiagnostic + std::fmt::Display>(
    mut cli: Cli,
    complexity: &dyn ComplexityPort,
    coverage: &dyn CoveragePort<Diagnostic = P>,
    tool_version: &str,
) -> Result<bool> {
    if let Some(Command::Completions { shell }) = cli.command {
        emit_completions(shell, &current_bin_name());
        return Ok(true);
    }

    let prep = prepare_pipeline(&mut cli, complexity, coverage)?;

    // Build the spec, then shape the result through the View pipeline.
    // V1b: `--only-failing` flows through `Filters::only_failing` here.
    // W2 fills in `--top`, `--min/max-coverage`, `--sort-by`. The
    // underlying `result` is never mutated — the gate is unshapeable.
    let spec = view_args::build_view_spec(&cli);
    let view = view::apply(&prep.analysis.result, spec);

    // Shape the delta. Spec is built from --delta-top / --delta-sort /
    // --delta-only (VS4); defaults match the dominant scorecard use
    // case (regressions first, all kinds, no truncation). `Option::map`
    // is `FnOnce`, so the closure moves the spec rather than cloning —
    // `DeltaView` owns its `spec` field, no further uses upstream.
    let delta_spec = delta_args::build_delta_view_spec(&cli);
    let delta_view: Option<DeltaView<'_>> = prep
        .delta_state
        .as_ref()
        .map(move |s| delta::apply(&s.delta, delta_spec));

    if !cli.display.quiet {
        print_formatted_output(
            &cli,
            &view,
            delta_view.as_ref(),
            prep.delta_state.as_ref(),
            &prep.analysis,
            &prep.inputs,
            tool_version,
        )?;
    }

    // Exit code derives from `view.full.passed` — i.e., the underlying
    // analysis. The View shapes the display, never the gate.
    //
    // Delta is informational by default (issue #81 §gate semantics).
    // `--delta-gate` opts in: a passing analysis with delta regressions
    // that introduce new violations will exit 1 when `--delta-gate` is
    // set. `--no-fail` overrides BOTH gates — truth lives in JSON
    // (`result.passed` and `delta.summary.passed`) so consumers can
    // still detect "would have failed."
    Ok(compute_exit_code(
        &cli,
        prep.analysis.result.passed,
        prep.delta_state.as_ref(),
    ))
}

// ── Run-inner orchestration helpers ────────────────────────────────

/// Effective inputs after CLI / config-file / preset / default merging.
/// Everything `core::analyze` needs except the coverage path (which is
/// validated separately and may be borrowed from `cli`).
struct EffectiveInputs {
    src: PathBuf,
    metric: ComplexityMetric,
    threshold_config: ThresholdConfig,
    threshold: f64,
    exclude: Vec<String>,
}

/// In-flight pipeline state assembled by `prepare_pipeline`. Owns the
/// analysis output and the optional delta state so the dispatch layer
/// borrows through references. Generic over `P: ParseDiagnostic` so
/// `AnalysisOutput<P>` and `DeltaState<P>` carry the adapter's diagnostic
/// shape (LCOV, future Istanbul, …) end-to-end.
struct PipelinePrep<P: ParseDiagnostic> {
    inputs: EffectiveInputs,
    analysis: AnalysisOutput<P>,
    delta_state: Option<DeltaState<P>>,
}

fn merge_effective_inputs(cli: &Cli, file_config: &Option<FileConfig>) -> EffectiveInputs {
    let src = cli
        .input
        .src
        .clone()
        .or_else(|| file_config.as_ref().and_then(|c| c.src.clone()))
        .unwrap_or_else(|| PathBuf::from("src"));
    let metric: ComplexityMetric = cli
        .input
        .metric
        .map(Into::into)
        .or_else(|| file_config.as_ref().and_then(|c| c.metric))
        .unwrap_or_default();
    let (threshold_config, threshold) = merge_threshold(cli, file_config);
    let exclude = merge_exclude(cli, file_config);
    EffectiveInputs {
        src,
        metric,
        threshold_config,
        threshold,
        exclude,
    }
}

fn validate_runtime_inputs<'a>(cli: &'a Cli, inputs: &EffectiveInputs) -> Result<&'a Path> {
    // `--coverage` is required on the analysis path; subcommands like
    // `completions` skip this branch. Clap can't express "required
    // unless subcommand X" in derive, so we enforce it here.
    let Some(coverage_path) = cli.input.coverage.as_deref() else {
        bail!(
            "--coverage <FILE> is required (run `crap4rs --help` for usage, or `crap4rs completions <SHELL>` for shell completion scripts)"
        );
    };

    validate_inputs(coverage_path, &inputs.src, inputs.threshold)?;
    preflight_checks(coverage_path, &inputs.src)?;

    if let Some(diff_ref) = cli.filter.diff.as_deref() {
        validate_diff_ref(diff_ref)?;
        preflight_git_worktree(&inputs.src)?;
    }

    Ok(coverage_path)
}

fn build_analyze_options(cli: &Cli, inputs: &EffectiveInputs, coverage: &Path) -> AnalyzeOptions {
    AnalyzeOptions {
        src: inputs.src.clone(),
        coverage: coverage.to_path_buf(),
        threshold_config: inputs.threshold_config.clone(),
        metric: inputs.metric,
        exclude: inputs.exclude.clone(),
        respect_gitignore: !cli.filter.no_gitignore,
        diff_ref: cli.filter.diff.clone(),
        compute_diagnostics: cli
            .output
            .format
            .iter()
            .any(|s| matches!(s.format, FormatArg::Advice | FormatArg::Sarif)),
        ..AnalyzeOptions::default()
    }
}

fn apply_diagnostics<P: ParseDiagnostic + std::fmt::Display>(
    cli: &Cli,
    diagnostics: &AnalysisDiagnostics<P>,
) {
    // Always warn about non-fatal issues (details require --verbose)
    warn_if_issues(diagnostics);
    if cli.display.verbose {
        print_diagnostics(diagnostics);
    }
}

/// Validates inputs, merges effective config, runs the analyzer, and
/// resolves the optional baseline delta. The bulk of `run_inner`'s
/// pre-render work lives here so `run_inner` itself stays a flat dispatch.
fn prepare_pipeline<P: ParseDiagnostic + std::fmt::Display>(
    cli: &mut Cli,
    complexity: &dyn ComplexityPort,
    coverage: &dyn CoveragePort<Diagnostic = P>,
) -> Result<PipelinePrep<P>> {
    validate_display_flags(cli)?;
    apply_color(cli.display.color);

    // Load config file (explicit path or auto-discovered)
    let file_config = load_file_config(cli)?;

    // Resolve `--view <NAME>` (issue #80) before validate_view_args runs
    // so preset fields participate in the same validation pass as CLI
    // flags. `apply_preset_to_cli` mutates `cli` in place: CLI explicit
    // values win on `Option<T>` fields, bools OR-merge.
    view_args::resolve_view_preset(cli, file_config.as_ref())?;
    view_args::validate_view_args(cli)?;

    let inputs = merge_effective_inputs(cli, &file_config);
    let coverage_path = validate_runtime_inputs(cli, &inputs)?;
    let options = build_analyze_options(cli, &inputs, coverage_path);

    let analysis = crate::core::analyze(&options, complexity, coverage)?;
    apply_diagnostics(cli, &analysis.diagnostics);

    // Resolve --baseline (issue #81): load a previously-emitted JSON
    // envelope and compute the AnalysisDelta. None when --baseline is
    // absent — the JSON envelope omits the `delta` block entirely so
    // existing consumers see byte-identical output.
    let delta_state = load_delta_state(cli, &analysis.result)?;

    Ok(PipelinePrep {
        inputs,
        analysis,
        delta_state,
    })
}

// ── Format dispatch ────────────────────────────────────────────────

fn format_as_json<P: ParseDiagnostic>(
    cli: &Cli,
    view: &view::AnalysisView<'_>,
    delta_view: Option<&DeltaView<'_>>,
    delta_state: Option<&DeltaState<P>>,
    analysis: &AnalysisOutput<P>,
    inputs: &EffectiveInputs,
    tool_version: &str,
) -> Result<String> {
    let delta_ctx = delta_state.zip(delta_view).map(|(s, dv)| DeltaContext {
        view: dv,
        baseline_tool_version: &s.snapshot.tool_version,
        baseline_timestamp: &s.snapshot.timestamp,
        baseline_diagnostics: s.snapshot.diagnostics.as_ref(),
    });
    let config = reporters::json::JsonConfig {
        tool_version: tool_version.to_string(),
        metric: inputs.metric,
        threshold: inputs.threshold,
        timestamp: now_unix_epoch(),
        diagnostics: cli.display.verbose.then_some(&analysis.diagnostics),
        diff_ref: cli.filter.diff.as_deref(),
        minimal_view: cli.output.minimal_view,
        delta: delta_ctx,
    };
    reporters::json::format_json(view, &config).map_err(Into::into)
}

/// ScorecardRow projects the unshaped analysis + delta into a mokumo
/// `Row::CrapDelta` JSON object (issue #111). View shaping does NOT
/// alter scorecard-row — the aggregator consumes truth, not a filtered
/// subset.
fn format_as_scorecard_row<P: ParseDiagnostic>(
    delta_state: Option<&DeltaState<P>>,
    result: &crate::domain::types::AnalysisResult,
    threshold: f64,
) -> String {
    let baseline_result = delta_state.map(|s| &s.snapshot.result);
    let delta_inputs = delta_state.map(|s| (&s.delta.summary, s.delta.changes.as_slice()));
    let row_data = crate::domain::summary::project_crap_delta_row(
        result,
        baseline_result,
        delta_inputs,
        threshold.round() as u32,
    );
    reporters::format_scorecard_row(&row_data)
}

// 8-arg dispatch is the cost of threading `<P>` + `tool_version` through
// the format match without restructuring the per-reporter call sites
// (which carry heterogeneous, irreducible signatures per `adapters.md`
// rule 1). Bundling them into a context struct would shadow the per-arm
// argument list that's the whole point of this match. Tracked under v1.0
// follow-up for the broader cli refactor.
#[allow(clippy::too_many_arguments)]
fn render_format<P: ParseDiagnostic>(
    cli: &Cli,
    spec: &FormatSpec,
    view: &view::AnalysisView<'_>,
    delta_view: Option<&DeltaView<'_>>,
    delta_state: Option<&DeltaState<P>>,
    analysis: &AnalysisOutput<P>,
    inputs: &EffectiveInputs,
    tool_version: &str,
) -> Result<String> {
    Ok(match spec.format {
        FormatArg::Table => reporters::format_table_with_explain(
            view,
            delta_view,
            inputs.threshold,
            cli.display.breakdown,
            cli.display.explain,
            tool_version,
        ),
        FormatArg::Json | FormatArg::Advice => format_as_json(
            cli,
            view,
            delta_view,
            delta_state,
            analysis,
            inputs,
            tool_version,
        )?,
        FormatArg::Markdown => reporters::format_markdown(
            view,
            delta_view,
            inputs.threshold,
            cli.display.breakdown,
            cli.display.explain,
            cli.display.md_full_table,
            cli.display.md_top,
            tool_version,
        ),
        FormatArg::Csv => reporters::format_csv(view, delta_view, inputs.metric),
        // SARIF is a gate translation, not a display: it iterates
        // `view.full.functions` internally regardless of how the View
        // was shaped. `--top`, `--sort-by`, `--only-failing`, and
        // `--baseline` do NOT alter SARIF output — PR annotations
        // must reflect truth.
        FormatArg::Sarif => reporters::format_sarif(view, tool_version),
        FormatArg::ScorecardRow => {
            format_as_scorecard_row(delta_state, &analysis.result, inputs.threshold)
        }
        FormatArg::Html => reporters::format_html(view, inputs.threshold, tool_version),
    })
}

fn print_formatted_output<P: ParseDiagnostic>(
    cli: &Cli,
    view: &view::AnalysisView<'_>,
    delta_view: Option<&DeltaView<'_>>,
    delta_state: Option<&DeltaState<P>>,
    analysis: &AnalysisOutput<P>,
    inputs: &EffectiveInputs,
    tool_version: &str,
) -> Result<()> {
    for spec in &cli.output.format {
        let output = render_format(
            cli,
            spec,
            view,
            delta_view,
            delta_state,
            analysis,
            inputs,
            tool_version,
        )?;
        match &spec.output {
            Some(path) => std::fs::write(path, &output)
                .map_err(|e| anyhow::anyhow!("failed to write {}: {e}", path.display()))?,
            None => print!("{output}"),
        }
    }

    // Advice's stderr summary fires once even if Advice appears multiple
    // times in `--format`. SARIF stays silent — its primary deliverable
    // is the `.sarif` file uploaded to Code Scanning; stderr would noise
    // up CI logs.
    if cli
        .output
        .format
        .iter()
        .any(|s| matches!(s.format, FormatArg::Advice))
    {
        let mut stderr = std::io::stderr();
        let _ = reporters::render_advice_summary(view, &mut stderr);
    }

    Ok(())
}

fn compute_exit_code<P: ParseDiagnostic>(
    cli: &Cli,
    passed: bool,
    delta_state: Option<&DeltaState<P>>,
) -> bool {
    let delta_passed = delta_state.map(|s| s.delta.summary.passed).unwrap_or(true);
    let combined_passed = passed && (!cli.output.delta_gate || delta_passed);
    combined_passed || cli.output.no_fail
}

// ── Delta orchestration ─────────────────────────────────────────────

/// In-flight delta state — owned baseline metadata + computed delta.
/// `cli/mod.rs` keeps this for the lifetime of `run_inner` so reporters
/// can borrow through it. Constructed once per invocation when
/// `--baseline` is set; absent otherwise. Generic over `P:
/// ParseDiagnostic` so the snapshot's `BaselineSnapshot<P>` matches the
/// adapter's diagnostic shape.
struct DeltaState<P: ParseDiagnostic> {
    snapshot: BaselineSnapshot<P>,
    delta: AnalysisDelta,
}

fn load_delta_state<P: ParseDiagnostic>(
    cli: &Cli,
    current: &crate::domain::types::AnalysisResult,
) -> Result<Option<DeltaState<P>>> {
    let Some(path) = cli.input.baseline.as_ref() else {
        return Ok(None);
    };
    let snapshot = baseline::load::<P>(path).map_err(|e| anyhow::anyhow!("{e}"))?;
    // delta::compute consumes both — we own snapshot.result, clone the
    // current analysis so the surrounding pipeline keeps its handle.
    let delta = delta::compute(snapshot.result.clone(), current.clone());
    Ok(Some(DeltaState { snapshot, delta }))
}

fn validate_display_flags(cli: &Cli) -> Result<()> {
    let any_table = cli
        .output
        .format
        .iter()
        .any(|s| matches!(s.format, FormatArg::Table));
    if cli.display.explain && any_table && !cli.display.breakdown {
        bail!("--explain requires --breakdown for table output");
    }
    validate_format_destinations(&cli.output.format)?;
    Ok(())
}

/// Multi-format invocations require every entry to specify a file —
/// stdout cannot multiplex (issue #100).
fn validate_format_destinations(specs: &[FormatSpec]) -> Result<()> {
    if specs.len() > 1 {
        let stdout_specs: Vec<_> = specs
            .iter()
            .filter(|s| s.output.is_none())
            .map(|s| format_arg_kebab(s.format).to_string())
            .collect();
        if !stdout_specs.is_empty() {
            bail!(
                "multi-format `--format` requires every entry to specify a file (e.g. `json:envelope.json`); stdout-only entries: {}",
                stdout_specs.join(", ")
            );
        }
    }
    Ok(())
}

/// User-facing kebab-case name for a `FormatArg` (matches the clap CLI
/// surface `--format X`). Defaults to `Debug` lowercased if clap's
/// `ValueEnum` registry can't resolve a name.
fn format_arg_kebab(arg: FormatArg) -> String {
    use clap::ValueEnum;
    arg.to_possible_value()
        .map(|v| v.get_name().to_string())
        .unwrap_or_else(|| format!("{arg:?}").to_lowercase())
}

// ── Config loading & merging ───────────────────────────────────────

fn load_file_config(cli: &Cli) -> Result<Option<FileConfig>> {
    if let Some(path) = &cli.input.config {
        Ok(Some(config::load_config(path)?))
    } else {
        match config::discover_config()? {
            Some(path) => Ok(Some(config::load_config(&path)?)),
            None => Ok(None),
        }
    }
}

/// Merge CLI threshold with config file. Returns (ThresholdConfig, effective_display_threshold).
///
/// Resolution order (first match wins):
/// 1. `--threshold N`   — explicit CLI value
/// 2. `--strict`        → STRICT_THRESHOLD
/// 3. `--lenient`       → LENIENT_THRESHOLD
/// 4. config `preset`   → preset.threshold()
/// 5. config `threshold`
/// 6. DEFAULT_THRESHOLD
fn merge_threshold(cli: &Cli, file_config: &Option<FileConfig>) -> (ThresholdConfig, f64) {
    let global = cli
        .output
        .threshold
        .or_else(|| cli.output.strict.then_some(STRICT_THRESHOLD))
        .or_else(|| cli.output.lenient.then_some(LENIENT_THRESHOLD))
        .or_else(|| {
            file_config
                .as_ref()
                .and_then(|c| c.preset)
                .map(|p| p.threshold())
        })
        .or_else(|| file_config.as_ref().and_then(|c| c.threshold))
        .unwrap_or(DEFAULT_THRESHOLD);

    let overrides = file_config
        .as_ref()
        .map(|fc| fc.overrides.clone())
        .unwrap_or_default();

    let config = ThresholdConfig { global, overrides };
    (config, global)
}

fn merge_exclude(cli: &Cli, file_config: &Option<FileConfig>) -> Vec<String> {
    let mut exclude = cli.filter.exclude.clone();
    if let Some(fc) = file_config
        && let Some(fc_exclude) = &fc.exclude
    {
        let seen: std::collections::HashSet<String> = exclude.iter().cloned().collect();
        for pattern in fc_exclude {
            if !seen.contains(pattern) {
                exclude.push(pattern.clone());
            }
        }
    }
    exclude
}

// ── Validation ──────────────────────────────────────────────────────

fn validate_inputs(
    coverage: &std::path::Path,
    src: &std::path::Path,
    threshold: f64,
) -> Result<()> {
    match std::fs::metadata(coverage) {
        Ok(m) if m.is_file() => {}
        Ok(_) => bail!(
            "coverage path is not a file: {}\n  \
             hint: pass --coverage pointing to an LCOV file, not a directory",
            coverage.display()
        ),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => bail!(
            "coverage file not found: {}\n  \
             hint: run `cargo llvm-cov --lcov --output-path lcov.info` first",
            coverage.display()
        ),
        Err(e) => bail!(
            "cannot access coverage file: {}: {e}\n  \
             hint: check file permissions",
            coverage.display()
        ),
    }
    match std::fs::metadata(src) {
        Ok(m) if m.is_dir() => {}
        Ok(_) => bail!(
            "source path is not a directory: {}\n  \
             hint: pass --src <DIR> pointing to your Rust source root",
            src.display()
        ),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => bail!(
            "source directory not found: {}\n  \
             hint: pass --src <DIR> pointing to your Rust source root",
            src.display()
        ),
        Err(e) => bail!(
            "cannot access source directory: {}: {e}\n  \
             hint: check directory permissions",
            src.display()
        ),
    }
    if !is_valid_threshold(threshold) {
        bail!(
            "threshold must be a finite positive number, got: {}",
            threshold
        );
    }
    Ok(())
}

// ── Diff validation ────────────────────────────────────────────────

fn validate_diff_ref(diff_ref: &str) -> Result<()> {
    if diff_ref.is_empty() {
        bail!("invalid diff ref: ref must not be empty");
    }
    if diff_ref.starts_with('-') {
        bail!(
            "invalid diff ref: {diff_ref}\n  \
             hint: ref must not start with a dash"
        );
    }
    Ok(())
}

fn preflight_git_worktree(src: &Path) -> Result<()> {
    let output = std::process::Command::new("git")
        .current_dir(src)
        .args(["rev-parse", "--is-inside-work-tree"])
        .output();

    match output {
        Ok(o) if o.status.success() => Ok(()),
        Ok(o) => {
            let stderr = String::from_utf8_lossy(&o.stderr);
            bail!(
                "not inside a git work tree\n  \
                 hint: --diff requires a git repository\n  \
                 git: {stderr}",
            );
        }
        Err(e) => bail!(
            "not inside a git work tree\n  \
             hint: --diff requires git to be installed\n  \
             error: {e}",
        ),
    }
}

// ── Pre-flight checks ──────────────────────────────────────────────

fn preflight_checks(coverage: &std::path::Path, src: &std::path::Path) -> Result<()> {
    check_coverage_has_data(coverage)?;
    check_src_has_rust_files(src)?;
    Ok(())
}

fn check_coverage_has_data(path: &std::path::Path) -> Result<()> {
    use std::io::{BufRead, BufReader};

    let file = std::fs::File::open(path)?;
    let reader = BufReader::new(file);
    let mut in_sf_block = false;

    for line in reader.lines() {
        let line = line?;
        if line.starts_with("SF:") {
            in_sf_block = true;
            continue;
        }
        if in_sf_block
            && let Some(rest) = line.strip_prefix("DA:")
            && let Some((line_no, hits)) = rest.split_once(',')
            && line_no.parse::<usize>().is_ok()
            && hits.split(',').next().unwrap_or("").parse::<u64>().is_ok()
        {
            return Ok(());
        }
    }
    bail!(
        "no coverage data found in {}\n  \
         hint: ensure tests ran with coverage enabled (`cargo llvm-cov --lcov`)",
        path.display()
    );
}

fn check_src_has_rust_files(path: &std::path::Path) -> Result<()> {
    fn has_rs_files(dir: &std::path::Path) -> std::io::Result<bool> {
        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let ft = entry.file_type()?;
            if ft.is_file() && entry.path().extension().is_some_and(|ext| ext == "rs") {
                return Ok(true);
            }
            if ft.is_dir() && has_rs_files(&entry.path())? {
                return Ok(true);
            }
        }
        Ok(false)
    }

    if !has_rs_files(path)? {
        bail!(
            "no Rust source files found in {}\n  \
             hint: check that --src points to a directory containing .rs files",
            path.display()
        );
    }
    Ok(())
}

// ── Timestamp ──────────────────────────────────────────────────────

fn now_unix_epoch() -> String {
    let secs = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    format!("{secs}")
}

// ── Verbose diagnostics ────────────────────────────────────────────

fn majority_zero_coverage(files_analyzed: usize, files_zero_coverage: usize) -> bool {
    files_analyzed > 0 && files_zero_coverage * 2 > files_analyzed
}

fn warn_if_issues<P: ParseDiagnostic>(diag: &AnalysisDiagnostics<P>) {
    if !diag.parse_diagnostics.is_empty() {
        eprintln!(
            "warning: {} LCOV parse issue(s) encountered (use --verbose for details)",
            diag.parse_diagnostics.len()
        );
    }
    if diag.files_unparseable > 0 {
        eprintln!(
            "warning: {} source file(s) could not be parsed (use --verbose for details)",
            diag.files_unparseable
        );
    }
    if majority_zero_coverage(diag.files_analyzed, diag.files_zero_coverage) {
        eprintln!(
            "warning: in {}/{} analyzed files, all analyzed functions have 0% line coverage",
            diag.files_zero_coverage, diag.files_analyzed
        );
        eprintln!(
            "  hint: `cargo llvm-cov --lib` does not cover integration-only code (handlers, Tauri entry, BDD tests)"
        );
        eprintln!(
            "  hint: use --exclude to skip uncoverable paths (e.g., --exclude \"services/api/src/**\")"
        );
    }
}

fn print_diagnostics<P: ParseDiagnostic + std::fmt::Display>(diag: &AnalysisDiagnostics<P>) {
    eprintln!(
        "verbose: file discovery: {} files found, {} unparseable",
        diag.files_found, diag.files_unparseable
    );
    eprintln!(
        "verbose: complexity: {} functions extracted",
        diag.functions_extracted
    );
    eprintln!(
        "verbose: matching: {} matched with coverage, {} without coverage data",
        diag.functions_matched, diag.functions_no_coverage
    );
    eprintln!(
        "verbose: coverage: {} files analyzed, {} where all analyzed functions have 0% line coverage",
        diag.files_analyzed, diag.files_zero_coverage
    );
    if !diag.parse_diagnostics.is_empty() {
        eprintln!(
            "verbose: LCOV parse diagnostics ({}):",
            diag.parse_diagnostics.len()
        );
        for d in &diag.parse_diagnostics {
            eprintln!("  {d}");
        }
    }
}

// ── Shell completions ───────────────────────────────────────────────

/// Print a shell completion script to stdout for the given shell.
/// `clap_complete::generate` covers POSIX shells + PowerShell + Elvish;
/// nushell uses the separate `clap_complete_nushell` crate.
///
/// `bin_name` is the adapter binary's name (`crap4rs`, future
/// `crap4ts`, …) inferred at runtime from `argv[0]` — generated
/// completion scripts should reference the binary the user invoked,
/// not crap-core's library name.
fn emit_completions(shell: ShellArg, bin_name: &str) {
    let mut cmd = Cli::command();
    let stdout = &mut std::io::stdout();
    match shell {
        ShellArg::Bash => clap_complete::generate(ClapShell::Bash, &mut cmd, bin_name, stdout),
        ShellArg::Zsh => clap_complete::generate(ClapShell::Zsh, &mut cmd, bin_name, stdout),
        ShellArg::Fish => clap_complete::generate(ClapShell::Fish, &mut cmd, bin_name, stdout),
        ShellArg::Powershell => {
            clap_complete::generate(ClapShell::PowerShell, &mut cmd, bin_name, stdout)
        }
        ShellArg::Elvish => clap_complete::generate(ClapShell::Elvish, &mut cmd, bin_name, stdout),
        ShellArg::Nushell => {
            clap_complete::generate(clap_complete_nushell::Nushell, &mut cmd, bin_name, stdout)
        }
    }
}

// ── Color wiring ────────────────────────────────────────────────────

fn apply_color(choice: ColorArg) {
    match choice {
        ColorArg::Auto => colored::control::unset_override(),
        ColorArg::Always => colored::control::set_override(true),
        ColorArg::Never => colored::control::set_override(false),
    }
}

// ── Tests ───────────────────────────────────────────────────────────

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

    fn parse(args: &[&str]) -> Result<Cli, clap::Error> {
        let mut full = vec!["crap4rs"];
        full.extend_from_slice(args);
        Cli::try_parse_from(full)
    }

    #[test]
    fn no_args_parses_with_coverage_none() {
        // `--coverage` is enforced at runtime via run_inner (so that
        // the `completions` subcommand can skip it), not at clap parse
        // time. Bare `crap4rs` therefore parses successfully here but
        // would `bail!` once dispatched.
        let cli = parse(&[]).unwrap();
        assert!(cli.input.coverage.is_none());
        assert!(cli.command.is_none());
    }

    #[test]
    fn minimal_valid_args() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert_eq!(cli.input.coverage.as_deref(), Some(Path::new("lcov.info")));
        assert_eq!(cli.input.src, None);
    }

    #[test]
    fn completions_subcommand_does_not_require_coverage() {
        let cli = parse(&["completions", "bash"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Completions {
                shell: ShellArg::Bash
            })
        ));
        assert!(cli.input.coverage.is_none());
    }

    #[test]
    fn default_metric_is_none() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert!(cli.input.metric.is_none());
    }

    #[test]
    fn default_format_is_table() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert_eq!(cli.output.format.len(), 1);
        assert!(matches!(cli.output.format[0].format, FormatArg::Table));
        assert!(cli.output.format[0].output.is_none());
    }

    #[test]
    fn default_threshold_is_none() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert!(cli.output.threshold.is_none());
    }

    #[test]
    fn default_color_is_auto() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert!(matches!(cli.display.color, ColorArg::Auto));
    }

    #[test]
    fn metric_cyclomatic() {
        let cli = parse(&["--coverage", "lcov.info", "--metric", "cyclomatic"]).unwrap();
        assert!(matches!(cli.input.metric, Some(MetricArg::Cyclomatic)));
    }

    #[test]
    fn format_json() {
        let cli = parse(&["--coverage", "lcov.info", "--format", "json"]).unwrap();
        assert_eq!(cli.output.format.len(), 1);
        assert!(matches!(cli.output.format[0].format, FormatArg::Json));
        assert!(cli.output.format[0].output.is_none());
    }

    #[test]
    fn format_sarif() {
        let cli = parse(&["--coverage", "lcov.info", "--format", "sarif"]).unwrap();
        assert_eq!(cli.output.format.len(), 1);
        assert!(matches!(cli.output.format[0].format, FormatArg::Sarif));
    }

    #[test]
    fn format_with_file_destination() {
        let cli = parse(&["--coverage", "lcov.info", "--format", "json:env.json"]).unwrap();
        assert_eq!(cli.output.format.len(), 1);
        assert!(matches!(cli.output.format[0].format, FormatArg::Json));
        assert_eq!(cli.output.format[0].output, Some(PathBuf::from("env.json")));
    }

    #[test]
    fn format_multi_with_files() {
        let cli = parse(&[
            "--coverage",
            "lcov.info",
            "--format",
            "json:env.json,markdown:report.md",
        ])
        .unwrap();
        assert_eq!(cli.output.format.len(), 2);
        assert!(matches!(cli.output.format[0].format, FormatArg::Json));
        assert_eq!(cli.output.format[0].output, Some(PathBuf::from("env.json")));
        assert!(matches!(cli.output.format[1].format, FormatArg::Markdown));
        assert_eq!(
            cli.output.format[1].output,
            Some(PathBuf::from("report.md"))
        );
    }

    #[test]
    fn format_multi_without_files_rejected() {
        let cli = parse(&["--coverage", "lcov.info", "--format", "json,markdown"]).unwrap();
        let err = validate_display_flags(&cli).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("multi-format"));
        assert!(msg.contains("file"));
    }

    #[test]
    fn format_empty_path_rejected() {
        let err = parse(&["--coverage", "lcov.info", "--format", "json:"]).unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("empty file path"));
    }

    #[test]
    fn custom_threshold() {
        let cli = parse(&["--coverage", "lcov.info", "--threshold", "15.5"]).unwrap();
        assert_eq!(cli.output.threshold, Some(15.5));
    }

    #[test]
    fn custom_src() {
        let cli = parse(&["--coverage", "lcov.info", "--src", "crates/"]).unwrap();
        assert_eq!(cli.input.src, Some(PathBuf::from("crates/")));
    }

    #[test]
    fn exclude_repeatable() {
        let cli = parse(&[
            "--coverage",
            "lcov.info",
            "--exclude",
            "tests/**",
            "--exclude",
            "benches/**",
        ])
        .unwrap();
        assert_eq!(cli.filter.exclude, vec!["tests/**", "benches/**"]);
    }

    #[test]
    fn no_gitignore_flag() {
        let cli = parse(&["--coverage", "lcov.info", "--no-gitignore"]).unwrap();
        assert!(cli.filter.no_gitignore);
    }

    #[test]
    fn only_failing_flag() {
        let cli = parse(&["--coverage", "lcov.info", "--only-failing"]).unwrap();
        assert!(cli.filter.only_failing);
    }

    #[test]
    fn group_by_file_parses() {
        let cli = parse(&["--coverage", "lcov.info", "--group-by", "file"]).unwrap();
        assert!(matches!(cli.filter.group_by, Some(GroupByArg::File)));
    }

    #[test]
    fn group_by_absence_is_none() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert!(cli.filter.group_by.is_none());
    }

    #[test]
    fn group_by_invalid_value_rejected() {
        let err = parse(&["--coverage", "lcov.info", "--group-by", "module"]).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("invalid value"), "expected clap error: {msg}");
        assert!(
            msg.contains("--group-by") || msg.contains("module"),
            "error should attribute to --group-by: {msg}"
        );
    }

    #[test]
    fn group_by_arg_to_domain_file() {
        let domain: GroupKey = GroupByArg::File.into();
        assert_eq!(domain, GroupKey::File);
    }

    #[test]
    fn verbose_flag() {
        let cli = parse(&["--coverage", "lcov.info", "-v"]).unwrap();
        assert!(cli.display.verbose);
    }

    #[test]
    fn quiet_flag() {
        let cli = parse(&["--coverage", "lcov.info", "-q"]).unwrap();
        assert!(cli.display.quiet);
    }

    #[test]
    fn color_always() {
        let cli = parse(&["--coverage", "lcov.info", "--color", "always"]).unwrap();
        assert!(matches!(cli.display.color, ColorArg::Always));
    }

    #[test]
    fn color_never() {
        let cli = parse(&["--coverage", "lcov.info", "--color", "never"]).unwrap();
        assert!(matches!(cli.display.color, ColorArg::Never));
    }

    #[test]
    fn invalid_metric_rejected() {
        let err = parse(&["--coverage", "lcov.info", "--metric", "halstead"]).unwrap_err();
        assert!(err.to_string().contains("invalid value"));
    }

    #[test]
    fn invalid_format_rejected() {
        let err = parse(&["--coverage", "lcov.info", "--format", "xml"]).unwrap_err();
        assert!(err.to_string().contains("invalid value"));
    }

    #[test]
    fn metric_arg_to_domain_cognitive() {
        let domain: ComplexityMetric = MetricArg::Cognitive.into();
        assert_eq!(domain, ComplexityMetric::Cognitive);
    }

    #[test]
    fn metric_arg_to_domain_cyclomatic() {
        let domain: ComplexityMetric = MetricArg::Cyclomatic.into();
        assert_eq!(domain, ComplexityMetric::Cyclomatic);
    }

    #[test]
    fn validate_missing_coverage_file() {
        let err = validate_inputs(
            Path::new("nonexistent.info"),
            Path::new("src"),
            DEFAULT_THRESHOLD,
        )
        .unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("coverage file not found"));
        assert!(msg.contains("cargo llvm-cov"));
    }

    #[test]
    fn validate_missing_src_dir() {
        let err = validate_inputs(
            Path::new("Cargo.toml"),
            Path::new("nonexistent_dir"),
            DEFAULT_THRESHOLD,
        )
        .unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("source directory not found"));
    }

    #[test]
    fn validate_negative_threshold() {
        let err = validate_inputs(Path::new("Cargo.toml"), Path::new("src"), -5.0).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("threshold must be a finite positive number"));
    }

    #[test]
    fn validate_zero_threshold() {
        let err = validate_inputs(Path::new("Cargo.toml"), Path::new("src"), 0.0).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("threshold must be a finite positive number"));
    }

    #[test]
    fn validate_infinity_threshold() {
        let err =
            validate_inputs(Path::new("Cargo.toml"), Path::new("src"), f64::INFINITY).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("threshold must be a finite positive number"));
    }

    #[test]
    fn validate_src_is_file_not_dir() {
        let err = validate_inputs(
            Path::new("Cargo.toml"),
            Path::new("Cargo.toml"),
            DEFAULT_THRESHOLD,
        )
        .unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("source path is not a directory"));
    }

    #[test]
    fn validate_coverage_is_dir_not_file() {
        let err =
            validate_inputs(Path::new("src"), Path::new("src"), DEFAULT_THRESHOLD).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("coverage path is not a file"));
    }

    #[test]
    fn format_short_flag() {
        let cli = parse(&["--coverage", "lcov.info", "-f", "json"]).unwrap();
        assert!(matches!(cli.output.format[0].format, FormatArg::Json));
    }

    #[test]
    fn config_flag_accepts_path() {
        let cli = parse(&["--coverage", "lcov.info", "--config", "my-config.toml"]).unwrap();
        assert_eq!(cli.input.config, Some(PathBuf::from("my-config.toml")));
    }

    #[test]
    fn config_flag_defaults_to_none() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert_eq!(cli.input.config, None);
    }

    #[test]
    fn view_flag_accepts_name() {
        let cli = parse(&["--coverage", "lcov.info", "--view", "ci"]).unwrap();
        assert_eq!(cli.input.view, Some("ci".to_string()));
    }

    #[test]
    fn view_flag_defaults_to_none() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert_eq!(cli.input.view, None);
    }

    #[test]
    fn merge_threshold_cli_overrides_config() {
        let cli = parse(&["--coverage", "lcov.info", "--threshold", "15.0"]).unwrap();
        let file_config = Some(FileConfig {
            threshold: Some(10.0),
            ..FileConfig::default()
        });
        let (config, display) = merge_threshold(&cli, &file_config);
        assert_eq!(config.global, 15.0);
        assert_eq!(display, 15.0);
    }

    #[test]
    fn merge_threshold_uses_config_when_cli_default() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        let file_config = Some(FileConfig {
            threshold: Some(12.0),
            ..FileConfig::default()
        });
        let (config, display) = merge_threshold(&cli, &file_config);
        assert_eq!(config.global, 12.0);
        assert_eq!(display, 12.0);
    }

    #[test]
    fn merge_threshold_preserves_overrides() {
        use crate::domain::threshold::ThresholdOverride;
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        let file_config = Some(FileConfig {
            threshold: Some(10.0),
            overrides: vec![ThresholdOverride {
                pattern: "domain/**".to_string(),
                threshold: 5.0,
            }],
            ..FileConfig::default()
        });
        let (config, _) = merge_threshold(&cli, &file_config);
        assert_eq!(config.overrides.len(), 1);
        assert_eq!(config.overrides[0].pattern, "domain/**");
    }

    #[test]
    fn merge_threshold_no_config() {
        let cli = parse(&["--coverage", "lcov.info", "--threshold", "20.0"]).unwrap();
        let (config, display) = merge_threshold(&cli, &None);
        assert_eq!(config.global, 20.0);
        assert!(config.overrides.is_empty());
        assert_eq!(display, 20.0);
    }

    #[test]
    fn merge_threshold_explicit_default_overrides_config() {
        // User explicitly passes --threshold 8.0 (same as DEFAULT_THRESHOLD).
        // This MUST override the config file's threshold of 12.0.
        let cli = parse(&["--coverage", "lcov.info", "--threshold", "8.0"]).unwrap();
        let file_config = Some(FileConfig {
            threshold: Some(12.0),
            ..FileConfig::default()
        });
        let (config, display) = merge_threshold(&cli, &file_config);
        assert_eq!(
            config.global, 8.0,
            "explicit CLI default must override config"
        );
        assert_eq!(display, 8.0);
    }

    #[test]
    fn merge_threshold_no_cli_no_config_uses_hardcoded_default() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        let (config, display) = merge_threshold(&cli, &None);
        assert_eq!(config.global, DEFAULT_THRESHOLD);
        assert_eq!(display, DEFAULT_THRESHOLD);
    }

    #[test]
    fn merge_exclude_combines_cli_and_config() {
        let cli = parse(&["--coverage", "lcov.info", "--exclude", "tests/**"]).unwrap();
        let file_config = Some(FileConfig {
            exclude: Some(vec!["benches/**".to_string()]),
            ..FileConfig::default()
        });
        let exclude = merge_exclude(&cli, &file_config);
        assert_eq!(exclude, vec!["tests/**", "benches/**"]);
    }

    #[test]
    fn merge_exclude_deduplicates() {
        let cli = parse(&["--coverage", "lcov.info", "--exclude", "tests/**"]).unwrap();
        let file_config = Some(FileConfig {
            exclude: Some(vec!["tests/**".to_string()]),
            ..FileConfig::default()
        });
        let exclude = merge_exclude(&cli, &file_config);
        assert_eq!(exclude, vec!["tests/**"]);
    }

    // ── --diff flag tests ───────────────────────────────────────────

    #[test]
    fn diff_flag_accepts_ref() {
        let cli = parse(&["--coverage", "lcov.info", "--diff", "main"]).unwrap();
        assert_eq!(cli.filter.diff, Some("main".to_string()));
    }

    #[test]
    fn diff_flag_defaults_to_none() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert_eq!(cli.filter.diff, None);
    }

    #[test]
    fn diff_flag_accepts_commit_sha() {
        let cli = parse(&["--coverage", "lcov.info", "--diff", "abc123"]).unwrap();
        assert_eq!(cli.filter.diff, Some("abc123".to_string()));
    }

    #[test]
    fn diff_flag_accepts_head_tilde() {
        let cli = parse(&["--coverage", "lcov.info", "--diff", "HEAD~1"]).unwrap();
        assert_eq!(cli.filter.diff, Some("HEAD~1".to_string()));
    }

    #[test]
    fn validate_diff_ref_rejects_empty_string() {
        let err = validate_diff_ref("").unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("must not be empty"));
    }

    #[test]
    fn validate_diff_ref_rejects_dash_prefix() {
        let err = validate_diff_ref("--malicious").unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("invalid diff ref"));
        assert!(msg.contains("must not start with a dash"));
    }

    #[test]
    fn validate_diff_ref_accepts_normal_ref() {
        assert!(validate_diff_ref("main").is_ok());
        assert!(validate_diff_ref("HEAD~1").is_ok());
        assert!(validate_diff_ref("abc123").is_ok());
    }

    #[test]
    fn preflight_git_worktree_passes_in_git_repo() {
        // Initialize a fresh git repo in a temp dir so the test is self-contained
        // and works under tools (e.g. cargo-mutants) that copy the source tree
        // without `.git`.
        let tmp = tempfile::tempdir().unwrap();
        let status = std::process::Command::new("git")
            .arg("init")
            .arg("--quiet")
            .current_dir(tmp.path())
            .status()
            .expect("git init");
        assert!(status.success(), "git init failed");
        assert!(preflight_git_worktree(tmp.path()).is_ok());
    }

    #[test]
    fn breakdown_flag_parsed() {
        let cli = parse(&["--coverage", "lcov.info", "--breakdown"]).unwrap();
        assert!(cli.display.breakdown);
    }

    #[test]
    fn breakdown_flag_default_false() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert!(!cli.display.breakdown);
    }

    #[test]
    fn explain_flag_parsed() {
        let cli = parse(&["--coverage", "lcov.info", "--explain"]).unwrap();
        assert!(cli.display.explain);
    }

    #[test]
    fn explain_flag_default_false() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert!(!cli.display.explain);
    }

    #[test]
    fn explain_requires_breakdown_for_table_output() {
        let cli = parse(&["--coverage", "lcov.info", "--explain"]).unwrap();
        let err = validate_display_flags(&cli).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("--breakdown"));
        assert!(msg.contains("--explain"));
    }

    #[test]
    fn explain_allowed_for_json_output() {
        let cli = parse(&["--coverage", "lcov.info", "--format", "json", "--explain"]).unwrap();
        assert!(validate_display_flags(&cli).is_ok());
    }

    #[test]
    fn color_overrides_set_global_state() {
        // Combined into one test to avoid nondeterministic interleaving —
        // colored::control uses a process-global flag that parallel tests
        // can race on.
        apply_color(ColorArg::Never);
        assert!(!colored::control::SHOULD_COLORIZE.should_colorize());

        apply_color(ColorArg::Always);
        assert!(colored::control::SHOULD_COLORIZE.should_colorize());

        apply_color(ColorArg::Auto);
    }

    // ── Pre-flight check tests ─────────────────────────────────────────

    #[test]
    fn preflight_empty_coverage_file() {
        let dir = tempfile::tempdir().unwrap();
        let cov = dir.path().join("empty.info");
        std::fs::write(&cov, "").unwrap();

        let err = check_coverage_has_data(&cov).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("no coverage data found"));
        assert!(msg.contains("cargo llvm-cov"));
    }

    #[test]
    fn preflight_coverage_no_da_lines() {
        let dir = tempfile::tempdir().unwrap();
        let cov = dir.path().join("no_da.info");
        std::fs::write(&cov, "SF:src/main.rs\nend_of_record\n").unwrap();

        let err = check_coverage_has_data(&cov).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("no coverage data found"));
    }

    #[test]
    fn preflight_coverage_with_da_lines_passes() {
        let dir = tempfile::tempdir().unwrap();
        let cov = dir.path().join("good.info");
        std::fs::write(&cov, "SF:src/main.rs\nDA:1,5\nend_of_record\n").unwrap();

        assert!(check_coverage_has_data(&cov).is_ok());
    }

    #[test]
    fn preflight_coverage_da_outside_sf_block_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let cov = dir.path().join("orphan_da.info");
        std::fs::write(&cov, "DA:1,5\nend_of_record\n").unwrap();

        let err = check_coverage_has_data(&cov).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("no coverage data found"));
    }

    #[test]
    fn preflight_coverage_malformed_da_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let cov = dir.path().join("bad_da.info");
        std::fs::write(&cov, "SF:src/main.rs\nDA:not_a_number\nend_of_record\n").unwrap();

        let err = check_coverage_has_data(&cov).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("no coverage data found"));
    }

    #[test]
    fn preflight_src_dir_no_rust_files() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("readme.txt"), "hello").unwrap();

        let err = check_src_has_rust_files(dir.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("no Rust source files found"));
    }

    #[test]
    fn preflight_src_dir_empty() {
        let dir = tempfile::tempdir().unwrap();

        let err = check_src_has_rust_files(dir.path()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("no Rust source files found"));
    }

    #[test]
    fn preflight_src_dir_with_rs_files_passes() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("main.rs"), "fn main() {}").unwrap();

        assert!(check_src_has_rust_files(dir.path()).is_ok());
    }

    #[test]
    fn preflight_src_dir_nested_rs_files_passes() {
        let dir = tempfile::tempdir().unwrap();
        let nested = dir.path().join("sub");
        std::fs::create_dir(&nested).unwrap();
        std::fs::write(nested.join("lib.rs"), "pub fn foo() {}").unwrap();

        assert!(check_src_has_rust_files(dir.path()).is_ok());
    }

    // ── --strict / --lenient flag tests ───────────────────────────────

    #[test]
    fn strict_flag_parses() {
        let cli = parse(&["--coverage", "lcov.info", "--strict"]).unwrap();
        assert!(cli.output.strict);
    }

    #[test]
    fn lenient_flag_parses() {
        let cli = parse(&["--coverage", "lcov.info", "--lenient"]).unwrap();
        assert!(cli.output.lenient);
    }

    #[test]
    fn strict_and_threshold_mutually_exclusive() {
        parse(&["--coverage", "lcov.info", "--strict", "--threshold", "20"]).unwrap_err();
    }

    #[test]
    fn strict_and_lenient_mutually_exclusive() {
        parse(&["--coverage", "lcov.info", "--strict", "--lenient"]).unwrap_err();
    }

    #[test]
    fn merge_threshold_strict_flag() {
        use crate::domain::threshold::STRICT_THRESHOLD;
        let cli = parse(&["--coverage", "lcov.info", "--strict"]).unwrap();
        let (config, display) = merge_threshold(&cli, &None);
        assert_eq!(config.global, STRICT_THRESHOLD);
        assert_eq!(display, STRICT_THRESHOLD);
    }

    #[test]
    fn merge_threshold_lenient_flag() {
        use crate::domain::threshold::LENIENT_THRESHOLD;
        let cli = parse(&["--coverage", "lcov.info", "--lenient"]).unwrap();
        let (config, display) = merge_threshold(&cli, &None);
        assert_eq!(config.global, LENIENT_THRESHOLD);
        assert_eq!(display, LENIENT_THRESHOLD);
    }

    #[test]
    fn merge_threshold_toml_preset_used_when_no_cli_flag() {
        use crate::domain::threshold::{STRICT_THRESHOLD, ThresholdPreset};
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        let file_config = Some(FileConfig {
            preset: Some(ThresholdPreset::Strict),
            ..FileConfig::default()
        });
        let (config, _) = merge_threshold(&cli, &file_config);
        assert_eq!(config.global, STRICT_THRESHOLD);
    }

    #[test]
    fn merge_threshold_cli_threshold_overrides_toml_preset() {
        use crate::domain::threshold::ThresholdPreset;
        let cli = parse(&["--coverage", "lcov.info", "--threshold", "50.0"]).unwrap();
        let file_config = Some(FileConfig {
            preset: Some(ThresholdPreset::Strict),
            ..FileConfig::default()
        });
        let (config, _) = merge_threshold(&cli, &file_config);
        assert_eq!(config.global, 50.0);
    }

    // ── majority_zero_coverage predicate tests ─────────────────────────

    #[test]
    fn zero_coverage_warn_triggers_above_50_percent() {
        assert!(majority_zero_coverage(10, 6));
        assert!(majority_zero_coverage(1, 1));
        assert!(majority_zero_coverage(3, 2));
    }

    #[test]
    fn zero_coverage_warn_does_not_trigger_at_exactly_50_percent() {
        assert!(!majority_zero_coverage(10, 5));
        assert!(!majority_zero_coverage(2, 1));
    }

    #[test]
    fn zero_coverage_warn_does_not_trigger_when_no_files() {
        assert!(!majority_zero_coverage(0, 0));
    }

    // ── merge_effective_inputs tests ───────────────────────────────────

    #[test]
    fn merge_effective_inputs_default_src() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        let inputs = merge_effective_inputs(&cli, &None);
        assert_eq!(inputs.src, PathBuf::from("src"));
    }

    #[test]
    fn merge_effective_inputs_cli_src_wins_over_config() {
        let cli = parse(&["--coverage", "lcov.info", "--src", "crates/"]).unwrap();
        let file_config = Some(FileConfig {
            src: Some(PathBuf::from("from-config/")),
            ..FileConfig::default()
        });
        let inputs = merge_effective_inputs(&cli, &file_config);
        assert_eq!(inputs.src, PathBuf::from("crates/"));
    }

    #[test]
    fn merge_effective_inputs_config_src_when_cli_absent() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        let file_config = Some(FileConfig {
            src: Some(PathBuf::from("from-config/")),
            ..FileConfig::default()
        });
        let inputs = merge_effective_inputs(&cli, &file_config);
        assert_eq!(inputs.src, PathBuf::from("from-config/"));
    }

    #[test]
    fn merge_effective_inputs_default_metric_is_cognitive() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        let inputs = merge_effective_inputs(&cli, &None);
        assert!(matches!(inputs.metric, ComplexityMetric::Cognitive));
    }

    #[test]
    fn merge_effective_inputs_cli_metric_overrides_config() {
        let cli = parse(&["--coverage", "lcov.info", "--metric", "cyclomatic"]).unwrap();
        let file_config = Some(FileConfig {
            metric: Some(ComplexityMetric::Cognitive),
            ..FileConfig::default()
        });
        let inputs = merge_effective_inputs(&cli, &file_config);
        assert!(matches!(inputs.metric, ComplexityMetric::Cyclomatic));
    }

    #[test]
    fn merge_effective_inputs_threshold_default() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        let inputs = merge_effective_inputs(&cli, &None);
        assert_eq!(inputs.threshold, DEFAULT_THRESHOLD);
    }

    #[test]
    fn merge_effective_inputs_exclude_combines_cli_and_config() {
        let cli = parse(&["--coverage", "lcov.info", "--exclude", "tests/**"]).unwrap();
        let file_config = Some(FileConfig {
            exclude: Some(vec!["benches/**".to_string()]),
            ..FileConfig::default()
        });
        let inputs = merge_effective_inputs(&cli, &file_config);
        assert_eq!(inputs.exclude, vec!["tests/**", "benches/**"]);
    }

    // ── compute_exit_code tests ────────────────────────────────────────
    //
    // delta_state=None covers the analysis-only paths; the delta-gate +
    // delta_state=Some interactions are exercised end-to-end in
    // delta_gate_integration.rs (where AnalysisDelta is built through
    // the real `delta::compute` path rather than mocked).

    #[test]
    fn compute_exit_code_passing_no_delta() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert!(compute_exit_code::<
            crate::test_strategies::DummyParseDiagnostic,
        >(&cli, true, None));
    }

    #[test]
    fn compute_exit_code_failing_no_delta() {
        let cli = parse(&["--coverage", "lcov.info"]).unwrap();
        assert!(!compute_exit_code::<
            crate::test_strategies::DummyParseDiagnostic,
        >(&cli, false, None));
    }

    #[test]
    fn compute_exit_code_no_fail_overrides_failure() {
        let cli = parse(&["--coverage", "lcov.info", "--no-fail"]).unwrap();
        assert!(compute_exit_code::<
            crate::test_strategies::DummyParseDiagnostic,
        >(&cli, false, None));
    }

    #[test]
    fn compute_exit_code_delta_gate_without_runtime_baseline_treats_delta_as_passed() {
        // delta_state=None → delta_passed defaults to true even with
        // --delta-gate; this matches the runtime behavior when the
        // baseline file is missing or unreadable. Clap requires
        // --baseline to accompany --delta-gate at parse time, so we
        // pass a sentinel path to satisfy the parser without exercising
        // the file load (compute_exit_code only inspects the resolved
        // delta state, not cli.input.baseline).
        let cli = parse(&[
            "--coverage",
            "lcov.info",
            "--delta-gate",
            "--baseline",
            "/dev/null",
        ])
        .unwrap();
        assert!(compute_exit_code::<
            crate::test_strategies::DummyParseDiagnostic,
        >(&cli, true, None));
    }

    #[test]
    fn compute_exit_code_no_fail_with_delta_gate() {
        // --no-fail is the master override even when --delta-gate
        // is set.
        let cli = parse(&[
            "--coverage",
            "lcov.info",
            "--delta-gate",
            "--baseline",
            "/dev/null",
            "--no-fail",
        ])
        .unwrap();
        assert!(compute_exit_code::<
            crate::test_strategies::DummyParseDiagnostic,
        >(&cli, false, None));
    }
}