hotspots-cli 1.40.0

CLI that finds the riskiest code in your codebase by combining complexity with git change history (Local Risk Score) across TypeScript, JavaScript, Go, Python, Rust, and Java
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
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
use crate::output::{explain, policy};
use crate::util::{find_repo_root, write_html_report};
use crate::{OutputFormat, OutputLevel, OutputMode};
use anyhow::Context;
use hotspots_core::delta::Delta;
use hotspots_core::gate::{check_gate_smoothed, GateConfig, GateVerdict};
use hotspots_core::snapshot::{self, Snapshot};
use hotspots_core::TouchMode;
use hotspots_core::{analyze_with_progress, AnalysisOptions};
use hotspots_core::{delta, git};
use std::io::IsTerminal;
use std::path::{Path, PathBuf};

pub(crate) struct AnalyzeArgs {
    pub path: PathBuf,
    pub format: OutputFormat,
    pub mode: Option<OutputMode>,
    pub policy: bool,
    pub top: Option<usize>,
    pub min_lrs: Option<f64>,
    pub config_path: Option<PathBuf>,
    pub output: Option<PathBuf>,
    pub explain: bool,
    pub force: bool,
    pub no_persist: bool,
    pub level: Option<OutputLevel>,
    pub per_function_touches: bool,
    pub all_functions: bool,
    pub include_models: bool,
    pub explain_patterns: bool,
    /// URL of the corresponding written analysis post, embedded as a banner in HTML output.
    pub source_url: Option<String>,
    /// Number of rayon worker threads; None = use all logical CPUs.
    pub jobs: Option<usize>,
    /// CLI override for callgraph_skip_above; None = use resolved config value.
    pub callgraph_skip_above: Option<usize>,
    /// When true, force-disable per-function touches regardless of config.
    pub no_per_function_touches: bool,
    /// When true, skip all touch metrics (no git log calls at all).
    pub skip_touch_metrics: bool,
    /// Hybrid touch threshold: file-level first, per-function for files with ≥N touches/30d.
    pub hybrid_touches: Option<usize>,
    /// `--touch-mode`: supersedes per_function_touches/no_per_function_touches/
    /// skip_touch_metrics/hybrid_touches (kept as deprecated aliases).
    pub touch_mode: Option<TouchModeArg>,
    /// Skip the suppression gate check entirely.
    pub skip_gate: bool,
    /// Rank via Gini-gated cold-start routing (F62/F63) instead of a trained ranker.
    /// Explicit opt-in only; reads no fix-commit label data.
    pub cold_start: bool,
    /// Print four independent ranked sections (Risk, Coupling, Ownership,
    /// Centrality) instead of a single merged list (F05).
    pub axes: bool,
}

/// Validate flag combinations that are mode/format-specific.
pub(crate) fn validate_analyze_flags(args: &AnalyzeArgs) -> anyhow::Result<()> {
    validate_mode_bypass_flags(args)?;
    validate_policy_flag(args)?;
    validate_explain_flag(args)?;
    validate_per_function_touches_flag(args)?;
    validate_no_persist_flag(args)?;
    validate_level_flag(args)?;
    validate_all_functions_flag(args)?;
    validate_models_mode_format(args)?;
    validate_include_models_flag(args)?;
    validate_explain_patterns_flag(args)?;
    validate_format_mode_requirements(args)?;
    Ok(())
}

/// `--cold-start`/`--axes` both bypass the trained-ranker/snapshot pipeline
/// entirely, so neither is compatible with `--mode`, and they're mutually
/// exclusive with each other.
fn validate_mode_bypass_flags(args: &AnalyzeArgs) -> anyhow::Result<()> {
    if args.cold_start && args.mode.is_some() {
        anyhow::bail!("--cold-start is not compatible with --mode (it bypasses the trained-ranker/snapshot pipeline entirely)");
    }
    if args.axes && args.mode.is_some() {
        anyhow::bail!("--axes is not compatible with --mode (it bypasses the trained-ranker/snapshot pipeline entirely)");
    }
    if args.axes && args.cold_start {
        anyhow::bail!("--axes and --cold-start are mutually exclusive");
    }
    Ok(())
}

fn validate_policy_flag(args: &AnalyzeArgs) -> anyhow::Result<()> {
    if args.policy && args.mode != Some(OutputMode::Delta) {
        anyhow::bail!("--policy flag is only valid with --mode delta");
    }
    Ok(())
}

fn validate_explain_flag(args: &AnalyzeArgs) -> anyhow::Result<()> {
    if args.explain && args.mode.is_some() && args.mode != Some(OutputMode::Snapshot) {
        anyhow::bail!("--explain is not compatible with --mode delta or --mode models");
    }
    Ok(())
}

fn validate_per_function_touches_flag(args: &AnalyzeArgs) -> anyhow::Result<()> {
    if args.per_function_touches && args.mode.is_none() {
        anyhow::bail!(
            "--per-function-touches is only valid with --mode snapshot, --mode delta, or --mode models"
        );
    }
    Ok(())
}

fn validate_no_persist_flag(args: &AnalyzeArgs) -> anyhow::Result<()> {
    if !args.no_persist {
        return Ok(());
    }
    if args.mode.is_none() || args.mode == Some(OutputMode::Models) {
        anyhow::bail!("--no-persist is only valid with --mode snapshot or --mode delta");
    }
    if args.force {
        anyhow::bail!("--no-persist and --force are mutually exclusive");
    }
    Ok(())
}

fn validate_level_flag(args: &AnalyzeArgs) -> anyhow::Result<()> {
    if args.level.is_none() {
        return Ok(());
    }
    if args.mode != Some(OutputMode::Snapshot) {
        anyhow::bail!("--level is only valid with --mode snapshot");
    }
    if !matches!(args.format, OutputFormat::Text) {
        anyhow::bail!("--level is only valid with --format text");
    }
    if args.explain {
        anyhow::bail!("--level and --explain are mutually exclusive");
    }
    Ok(())
}

fn validate_all_functions_flag(args: &AnalyzeArgs) -> anyhow::Result<()> {
    if args.all_functions
        && (args.mode != Some(OutputMode::Snapshot) || !matches!(args.format, OutputFormat::Json))
    {
        anyhow::bail!("--all-functions is only valid with --mode snapshot --format json");
    }
    Ok(())
}

fn validate_models_mode_format(args: &AnalyzeArgs) -> anyhow::Result<()> {
    if args.mode == Some(OutputMode::Models)
        && !matches!(args.format, OutputFormat::Text | OutputFormat::Json)
    {
        anyhow::bail!("--mode models supports --format text or --format json");
    }
    Ok(())
}

fn validate_include_models_flag(args: &AnalyzeArgs) -> anyhow::Result<()> {
    if args.include_models
        && (args.mode != Some(OutputMode::Snapshot)
            || !matches!(args.format, OutputFormat::Json | OutputFormat::Html))
    {
        anyhow::bail!("--include-models is only valid with --mode snapshot --format json/html");
    }
    Ok(())
}

fn validate_explain_patterns_flag(args: &AnalyzeArgs) -> anyhow::Result<()> {
    if args.explain_patterns && args.mode != Some(OutputMode::Snapshot) && args.mode.is_some() {
        anyhow::bail!("--explain-patterns is only valid with --mode snapshot or without --mode");
    }
    Ok(())
}

/// Output formats that require `--mode snapshot` specifically.
fn validate_format_mode_requirements(args: &AnalyzeArgs) -> anyhow::Result<()> {
    if matches!(args.format, OutputFormat::Sarif) && args.mode != Some(OutputMode::Snapshot) {
        anyhow::bail!("--format sarif requires --mode snapshot");
    }
    if matches!(args.format, OutputFormat::Csv) && args.mode != Some(OutputMode::Snapshot) {
        anyhow::bail!("--format csv requires --mode snapshot");
    }
    if matches!(args.format, OutputFormat::Xlsx) && args.mode != Some(OutputMode::Snapshot) {
        anyhow::bail!("--format xlsx requires --mode snapshot");
    }
    Ok(())
}

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

    /// All-permissive baseline: no mode, text format, every bool false, every
    /// optional field unset. Individual tests override just the field(s) under test.
    fn base_args() -> AnalyzeArgs {
        AnalyzeArgs {
            path: PathBuf::new(),
            format: OutputFormat::Text,
            mode: None,
            policy: false,
            top: None,
            min_lrs: None,
            config_path: None,
            output: None,
            explain: false,
            force: false,
            no_persist: false,
            level: None,
            per_function_touches: false,
            all_functions: false,
            include_models: false,
            explain_patterns: false,
            source_url: None,
            jobs: None,
            callgraph_skip_above: None,
            no_per_function_touches: false,
            skip_touch_metrics: false,
            hybrid_touches: None,
            touch_mode: None,
            skip_gate: false,
            cold_start: false,
            axes: false,
        }
    }

    #[test]
    fn base_args_pass_validation() {
        assert!(validate_analyze_flags(&base_args()).is_ok());
    }

    #[test]
    fn cold_start_and_axes_reject_mode() {
        assert!(validate_analyze_flags(&AnalyzeArgs {
            cold_start: true,
            mode: Some(OutputMode::Snapshot),
            ..base_args()
        })
        .is_err());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            axes: true,
            mode: Some(OutputMode::Snapshot),
            ..base_args()
        })
        .is_err());
    }

    #[test]
    fn cold_start_and_axes_are_mutually_exclusive() {
        assert!(validate_analyze_flags(&AnalyzeArgs {
            cold_start: true,
            axes: true,
            ..base_args()
        })
        .is_err());
    }

    #[test]
    fn policy_requires_delta_mode() {
        assert!(validate_analyze_flags(&AnalyzeArgs {
            policy: true,
            mode: Some(OutputMode::Delta),
            ..base_args()
        })
        .is_ok());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            policy: true,
            mode: Some(OutputMode::Snapshot),
            ..base_args()
        })
        .is_err());
    }

    #[test]
    fn explain_rejects_delta_and_models_mode() {
        assert!(validate_analyze_flags(&AnalyzeArgs {
            explain: true,
            mode: Some(OutputMode::Snapshot),
            ..base_args()
        })
        .is_ok());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            explain: true,
            mode: Some(OutputMode::Delta),
            ..base_args()
        })
        .is_err());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            explain: true,
            mode: Some(OutputMode::Models),
            ..base_args()
        })
        .is_err());
    }

    #[test]
    fn no_persist_requires_snapshot_or_delta_mode_and_rejects_force() {
        assert!(validate_analyze_flags(&AnalyzeArgs {
            no_persist: true,
            mode: None,
            ..base_args()
        })
        .is_err());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            no_persist: true,
            mode: Some(OutputMode::Models),
            ..base_args()
        })
        .is_err());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            no_persist: true,
            force: true,
            mode: Some(OutputMode::Snapshot),
            ..base_args()
        })
        .is_err());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            no_persist: true,
            mode: Some(OutputMode::Snapshot),
            ..base_args()
        })
        .is_ok());
    }

    #[test]
    fn level_requires_snapshot_mode_text_format_and_rejects_explain() {
        assert!(validate_analyze_flags(&AnalyzeArgs {
            level: Some(OutputLevel::File),
            mode: Some(OutputMode::Delta),
            ..base_args()
        })
        .is_err());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            level: Some(OutputLevel::File),
            mode: Some(OutputMode::Snapshot),
            format: OutputFormat::Json,
            ..base_args()
        })
        .is_err());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            level: Some(OutputLevel::File),
            mode: Some(OutputMode::Snapshot),
            explain: true,
            ..base_args()
        })
        .is_err());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            level: Some(OutputLevel::File),
            mode: Some(OutputMode::Snapshot),
            ..base_args()
        })
        .is_ok());
    }

    #[test]
    fn all_functions_requires_snapshot_mode_and_json_format() {
        assert!(validate_analyze_flags(&AnalyzeArgs {
            all_functions: true,
            mode: Some(OutputMode::Snapshot),
            format: OutputFormat::Json,
            ..base_args()
        })
        .is_ok());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            all_functions: true,
            mode: Some(OutputMode::Snapshot),
            format: OutputFormat::Text,
            ..base_args()
        })
        .is_err());
    }

    #[test]
    fn models_mode_supports_only_text_or_json() {
        assert!(validate_analyze_flags(&AnalyzeArgs {
            mode: Some(OutputMode::Models),
            format: OutputFormat::Text,
            ..base_args()
        })
        .is_ok());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            mode: Some(OutputMode::Models),
            format: OutputFormat::Html,
            ..base_args()
        })
        .is_err());
    }

    #[test]
    fn include_models_requires_snapshot_mode_and_json_or_html_format() {
        assert!(validate_analyze_flags(&AnalyzeArgs {
            include_models: true,
            mode: Some(OutputMode::Snapshot),
            format: OutputFormat::Html,
            ..base_args()
        })
        .is_ok());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            include_models: true,
            mode: Some(OutputMode::Snapshot),
            format: OutputFormat::Text,
            ..base_args()
        })
        .is_err());
    }

    #[test]
    fn explain_patterns_rejects_non_snapshot_mode_only_when_mode_is_set() {
        assert!(validate_analyze_flags(&AnalyzeArgs {
            explain_patterns: true,
            mode: None,
            ..base_args()
        })
        .is_ok());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            explain_patterns: true,
            mode: Some(OutputMode::Snapshot),
            ..base_args()
        })
        .is_ok());
        assert!(validate_analyze_flags(&AnalyzeArgs {
            explain_patterns: true,
            mode: Some(OutputMode::Delta),
            ..base_args()
        })
        .is_err());
    }

    #[test]
    fn sarif_csv_xlsx_formats_require_snapshot_mode() {
        for format in [OutputFormat::Sarif, OutputFormat::Csv, OutputFormat::Xlsx] {
            assert!(validate_analyze_flags(&AnalyzeArgs {
                format,
                mode: None,
                ..base_args()
            })
            .is_err());
            assert!(validate_analyze_flags(&AnalyzeArgs {
                format,
                mode: Some(OutputMode::Snapshot),
                ..base_args()
            })
            .is_ok());
        }
    }
}

pub(crate) fn handle_analyze(args: AnalyzeArgs) -> anyhow::Result<()> {
    validate_analyze_flags(&args)?;

    let AnalyzeArgs {
        path,
        format,
        mode,
        policy,
        top,
        min_lrs,
        config_path,
        output,
        explain,
        force,
        no_persist,
        level,
        per_function_touches,
        no_per_function_touches,
        skip_touch_metrics,
        hybrid_touches,
        touch_mode,
        all_functions,
        include_models,
        explain_patterns,
        source_url,
        jobs,
        callgraph_skip_above,
        skip_gate,
        cold_start,
        axes,
    } = args;

    warn_deprecated_touch_flags(
        no_per_function_touches,
        per_function_touches,
        skip_touch_metrics,
        hybrid_touches,
    );

    // Configure the global rayon thread pool before any parallel work begins.
    // Worker threads default to a 2MB stack (std::thread default), which is too
    // small for the recursive-descent CFG builders on deeply nested or generated
    // source files (e.g. rust-lang/rust's tests/ui/ fixtures) and can overflow
    // and abort the whole process. Give worker threads a larger stack unconditionally.
    // Errors are ignored: build_global() fails if rayon was already initialized
    // (e.g. in tests), which is harmless.
    {
        let mut builder = rayon::ThreadPoolBuilder::new().stack_size(32 * 1024 * 1024);
        if let Some(n) = jobs {
            builder = builder.num_threads(n);
        }
        let _ = builder.build_global();
    }

    let normalized_path = if path.is_relative() {
        std::env::current_dir()?.join(&path)
    } else {
        path
    };

    if !normalized_path.exists() {
        anyhow::bail!("Path does not exist: {}", normalized_path.display());
    }

    let project_root = find_repo_root(&normalized_path).unwrap_or_else(|_| normalized_path.clone());
    let resolved_config =
        hotspots_core::config::load_and_resolve(&project_root, config_path.as_deref())
            .context("failed to load configuration")?;

    if let Some(ref p) = resolved_config.config_path {
        eprintln!("Using config: {}", p.display());
    }

    let effective_min_lrs = min_lrs.or(resolved_config.min_lrs);
    let effective_top = top.or(resolved_config.top_n);
    let (effective_touch_mode, effective_skip_touch_metrics) = resolve_touch_mode_and_skip(
        touch_mode,
        no_per_function_touches,
        per_function_touches,
        hybrid_touches,
        skip_touch_metrics,
        resolved_config.per_function_touches,
        resolved_config.hybrid_touch_threshold,
    );

    if cold_start {
        return handle_cold_start(
            &normalized_path,
            &resolved_config,
            effective_touch_mode,
            effective_top,
        );
    }

    if axes {
        return handle_axes(
            &normalized_path,
            &resolved_config,
            effective_touch_mode,
            effective_top,
            format,
        );
    }

    if let Some(output_mode) = mode {
        let result = handle_mode_output(
            &normalized_path,
            output_mode,
            &resolved_config,
            ModeOutputOptions {
                format,
                policy,
                top: effective_top,
                min_lrs: effective_min_lrs,
                output,
                explain,
                force,
                no_persist,
                level,
                touch_mode: effective_touch_mode,
                all_functions,
                include_models,
                explain_patterns,
                source_url,
                callgraph_skip_above,
                skip_touch_metrics: effective_skip_touch_metrics,
                skip_gate,
            },
        );
        return result;
    }

    // If a trained ranker exists, promote to snapshot mode so activity_risk
    // fields are populated and the ranker can be applied. The ranker has no
    // effect in the default LRS-only path.
    let repo_root_for_ranker =
        find_repo_root(&normalized_path).unwrap_or_else(|_| normalized_path.clone());
    let ranker_path = snapshot::hotspots_dir(&repo_root_for_ranker).join("ranker.json");
    if ranker_path.exists() {
        let result = handle_mode_output(
            &normalized_path,
            OutputMode::Snapshot,
            &resolved_config,
            ModeOutputOptions {
                format,
                policy: false,
                top: effective_top,
                min_lrs: effective_min_lrs,
                output,
                explain: matches!(format, OutputFormat::Text),
                force,
                no_persist: true, // default analyze doesn't persist snapshots
                level,
                touch_mode: effective_touch_mode,
                all_functions: false,
                include_models: false,
                explain_patterns,
                source_url,
                callgraph_skip_above,
                skip_touch_metrics: effective_skip_touch_metrics,
                skip_gate,
            },
        );
        return result;
    }

    // Default behavior (no --mode): simple text/JSON output
    handle_default_output(
        &normalized_path,
        format,
        explain_patterns,
        effective_min_lrs,
        effective_top,
        &resolved_config,
    )
}

/// `hotspots analyze --cold-start`: Gini-gated cold-start routing (F62/F63).
///
/// Skips the trained-ranker lookup entirely. Builds a snapshot with the cold-start
/// history signals populated (but no touch/churn/call-graph work — not needed for the
/// 8-feature cold-start vector), runs `cold_start_rank()`, and prints the routing
/// decision (Formula / Anomaly / UniformPrior) before the ranked list. Reads no
/// fix-commit label data.
fn handle_cold_start(
    path: &Path,
    resolved_config: &hotspots_core::ResolvedConfig,
    touch_mode: TouchMode,
    top: Option<usize>,
) -> anyhow::Result<()> {
    let repo_root = find_repo_root(path)?;
    let analysis_progress = make_analysis_progress();
    let reports = analyze_with_progress(
        path,
        AnalysisOptions {
            min_lrs: None,
            top_n: None,
        },
        Some(resolved_config),
        Some(analysis_progress.as_ref()),
    )?;

    let mut snapshot = build_enriched_snapshot(
        &repo_root,
        resolved_config,
        reports,
        touch_mode,
        None,
        true, // skip touch metrics — not part of the cold-start feature set
    )
    .context("failed to build snapshot for cold-start ranking")?;
    snapshot.populate_history_signals(&repo_root);
    snapshot.populate_authors_90d(&repo_root);

    let train_cfg = hotspots_core::trainer::TrainConfig {
        gini_dead_zone: resolved_config.cold_start_gini_dead_zone,
        ..Default::default()
    };
    let result = hotspots_core::trainer::cold_start_rank(&snapshot, &repo_root, &train_cfg);

    let route_label = match result.route {
        hotspots_core::trainer::ColdStartRoute::Formula => "formula",
        hotspots_core::trainer::ColdStartRoute::Anomaly => "anomaly",
        hotspots_core::trainer::ColdStartRoute::UniformPrior => "uniform-prior",
    };
    println!("cold-start route: {route_label}");

    if result.ranked.is_empty() {
        println!("(uniform prior — no ranking to show; all files equally likely)");
        return Ok(());
    }

    let limit = match top {
        Some(0) => result.ranked.len(),
        Some(n) => n,
        None => 20,
    };
    for scored in result.ranked.iter().take(limit) {
        println!("{:.4}  {}", scored.score, scored.function_id);
    }

    Ok(())
}

/// `--axes` (F05): prints four independent ranked sections — Risk, Coupling,
/// Ownership, Centrality — in that fixed order, instead of a single merged
/// list. Files may appear in more than one section; overlap is not
/// deduplicated, and the axes are never blended into a composite score
/// (`docs/promotion-briefs/f05-multi-axis-report.md`).
fn handle_axes(
    path: &Path,
    resolved_config: &hotspots_core::ResolvedConfig,
    touch_mode: TouchMode,
    top: Option<usize>,
    format: OutputFormat,
) -> anyhow::Result<()> {
    use hotspots_core::ranking::{rank_by_axis, HotspotAxis};

    if !matches!(format, OutputFormat::Text | OutputFormat::Json) {
        anyhow::bail!("--axes only supports --format text or --format json");
    }

    let repo_root = find_repo_root(path)?;
    let analysis_progress = make_analysis_progress();
    let reports = analyze_with_progress(
        path,
        AnalysisOptions {
            min_lrs: None,
            top_n: None,
        },
        Some(resolved_config),
        Some(analysis_progress.as_ref()),
    )?;

    let mut snapshot = build_enriched_snapshot(
        &repo_root,
        resolved_config,
        reports,
        touch_mode,
        None,
        false, // needed for directed_coupling and newcomer_rate below
    )
    .context("failed to build snapshot for --axes ranking")?;
    snapshot.populate_history_signals(&repo_root);

    use hotspots_core::trainer::{make_rel, repo_prefixes};
    let (prefix_can, prefix_raw) = repo_prefixes(&repo_root);
    let partner_scores: std::collections::HashMap<String, f64> = snapshot
        .functions
        .iter()
        .map(|f| {
            let rel = make_rel(&f.file, &prefix_can, &prefix_raw);
            (rel, f.activity_risk.unwrap_or(f.lrs))
        })
        .collect();
    snapshot.populate_directed_coupling(&repo_root, &partner_scores);

    let top_n = match top {
        Some(0) => snapshot.functions.len(),
        Some(n) => n,
        None => 10,
    };

    let sections = [
        (HotspotAxis::Risk, "Risk Hotspots", "risk"),
        (HotspotAxis::Coupling, "Coupling Hotspots", "coupling"),
        (HotspotAxis::Ownership, "Ownership Hotspots", "ownership"),
        (HotspotAxis::Centrality, "Centrality Hotspots", "centrality"),
    ];

    if matches!(format, OutputFormat::Json) {
        let obj: serde_json::Map<String, serde_json::Value> = sections
            .iter()
            .map(|(axis, _, key)| {
                let ranked = rank_by_axis(&snapshot.functions, *axis, top_n);
                (key.to_string(), serde_json::to_value(ranked).unwrap())
            })
            .collect();
        println!("{}", serde_json::to_string_pretty(&obj)?);
        return Ok(());
    }

    for (axis, header, _) in sections {
        println!("{header}");
        let ranked = rank_by_axis(&snapshot.functions, axis, top_n);
        if ranked.is_empty() {
            println!("  (no qualifying files)");
        }
        for r in &ranked {
            println!("  {:.4}  {}", r.score, r.file);
        }
        println!();
    }

    Ok(())
}

fn handle_default_output(
    path: &Path,
    format: OutputFormat,
    explain_patterns: bool,
    min_lrs: Option<f64>,
    top: Option<usize>,
    resolved_config: &hotspots_core::ResolvedConfig,
) -> anyhow::Result<()> {
    let analysis_progress = make_analysis_progress();
    let explicit_top = top.or(resolved_config.top_n);
    // 0 is the sentinel for "show all"; otherwise default to 20 for text output
    let limit = match explicit_top {
        Some(0) => usize::MAX,
        Some(n) => n,
        None => 20,
    };
    let mut reports = analyze_with_progress(
        path,
        AnalysisOptions {
            min_lrs,
            top_n: if matches!(format, OutputFormat::Text) {
                Some(limit).filter(|&n| n != usize::MAX)
            } else {
                explicit_top.filter(|&n| n != 0)
            },
        },
        Some(resolved_config),
        Some(analysis_progress.as_ref()),
    )?;

    if explain_patterns {
        populate_pattern_details(&mut reports, resolved_config);
    }

    match format {
        OutputFormat::Text => {
            let color = std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none();
            print!(
                "{}",
                hotspots_core::render_text_grouped(&reports, limit, color)
            );
        }
        OutputFormat::Json => println!("{}", hotspots_core::render_json(&reports)),
        OutputFormat::Html | OutputFormat::Jsonl => {
            anyhow::bail!("HTML/JSONL format requires --mode snapshot or --mode delta");
        }
        OutputFormat::Sarif => anyhow::bail!("SARIF format requires --mode snapshot"),
        OutputFormat::Csv => anyhow::bail!("--format csv requires --mode snapshot"),
        OutputFormat::Xlsx => anyhow::bail!("--format xlsx requires --mode snapshot"),
    }
    Ok(())
}

fn populate_pattern_details(
    reports: &mut [hotspots_core::FunctionRiskReport],
    resolved_config: &hotspots_core::ResolvedConfig,
) {
    for report in reports.iter_mut() {
        let t1 = hotspots_core::patterns::Tier1Input {
            cc: report.metrics.cc as usize,
            nd: report.metrics.nd as usize,
            fo: report.metrics.fo as usize,
            ns: report.metrics.ns as usize,
            loc: report.metrics.loc as usize,
        };
        let t2 = hotspots_core::patterns::Tier2Input {
            fan_in: None,
            scc_size: None,
            churn_lines: None,
            days_since_last_change: None,
            neighbor_churn: None,
            is_entrypoint: false,
        };
        report.pattern_details = Some(hotspots_core::patterns::classify_detailed(
            &t1,
            &t2,
            &resolved_config.pattern_thresholds,
        ));
    }
}

pub(crate) struct ModeOutputOptions {
    pub format: OutputFormat,
    pub policy: bool,
    pub top: Option<usize>,
    pub min_lrs: Option<f64>,
    pub output: Option<PathBuf>,
    pub explain: bool,
    pub force: bool,
    pub no_persist: bool,
    pub level: Option<OutputLevel>,
    pub touch_mode: TouchMode,
    pub all_functions: bool,
    pub include_models: bool,
    pub explain_patterns: bool,
    pub source_url: Option<String>,
    pub callgraph_skip_above: Option<usize>,
    pub skip_touch_metrics: bool,
    pub skip_gate: bool,
}

pub(crate) fn handle_mode_output(
    path: &Path,
    mode: OutputMode,
    resolved_config: &hotspots_core::ResolvedConfig,
    opts: ModeOutputOptions,
) -> anyhow::Result<()> {
    let repo_root = find_repo_root(path)?;
    let analysis_progress = make_analysis_progress();
    let reports = analyze_with_progress(
        path,
        AnalysisOptions {
            min_lrs: opts.min_lrs,
            top_n: None,
        },
        Some(resolved_config),
        Some(analysis_progress.as_ref()),
    )?;
    let pr_context = git::detect_pr_context();

    match mode {
        OutputMode::Snapshot => {
            handle_snapshot_mode(path, &repo_root, resolved_config, reports, pr_context, opts)
        }
        OutputMode::Delta => {
            handle_delta_mode(&repo_root, resolved_config, reports, pr_context, opts)
        }
        OutputMode::Models => handle_models_mode(path, &repo_root, resolved_config, reports, opts),
    }
}

fn handle_snapshot_mode(
    path: &Path,
    repo_root: &Path,
    resolved_config: &hotspots_core::ResolvedConfig,
    reports: Vec<hotspots_core::FunctionRiskReport>,
    pr_context: hotspots_core::git::PrContext,
    opts: ModeOutputOptions,
) -> anyhow::Result<()> {
    let ModeOutputOptions {
        format,
        explain,
        force,
        no_persist,
        level,
        touch_mode,
        all_functions,
        include_models,
        explain_patterns,
        source_url,
        callgraph_skip_above,
        skip_touch_metrics,
        skip_gate,
        top,
        output,
        ..
    } = opts;
    let mut snapshot = build_snapshot_via_db(
        repo_root,
        resolved_config,
        reports,
        touch_mode,
        callgraph_skip_above,
        skip_touch_metrics,
    )
    .context("failed to build enriched snapshot")?;

    snapshot.populate_patterns(&resolved_config.pattern_thresholds);
    if explain_patterns {
        snapshot.populate_pattern_details(&resolved_config.pattern_thresholds);
    }

    // Populate DC before persisting so the snapshot on disk includes the values,
    // and before apply_trained_ranker so the ranker reads real DC instead of 0.0.
    // Partner scores use make_rel so keys match the repo-relative paths that
    // compute_directed_coupling_for_repo produces from git log output.
    //
    // Gated behind skip_touch_metrics: like touch metrics, this runs a
    // potentially unbounded `git log` walk (see coupling.rs), so
    // --skip-touch-metrics must skip it too rather than leaving it as a
    // hidden cost the flag doesn't cover.
    if !skip_touch_metrics {
        use hotspots_core::trainer::{make_rel, repo_prefixes};
        let (prefix_can, prefix_raw) = repo_prefixes(repo_root);
        let partner_scores: std::collections::HashMap<String, f64> = snapshot
            .functions
            .iter()
            .map(|f| {
                let rel = make_rel(&f.file, &prefix_can, &prefix_raw);
                (rel, f.activity_risk.unwrap_or(f.lrs))
            })
            .collect();
        snapshot.populate_directed_coupling(repo_root, &partner_scores);
    }

    // `--format csv`/`--format xlsx`'s Ownership column needs `newcomer_rate`,
    // which the standard snapshot pipeline otherwise never populates (only the
    // `--cold-start` and `--axes` paths call this today) — gated to these two
    // formats so others don't pay for an extra full-history `git log` walk.
    if !skip_touch_metrics && matches!(format, OutputFormat::Csv | OutputFormat::Xlsx) {
        snapshot.populate_history_signals(repo_root);
    }

    if !pr_context.is_pr && !no_persist {
        snapshot::persist_snapshot(repo_root, &snapshot, force)
            .context("failed to persist snapshot")?;
        snapshot::append_to_index(repo_root, &snapshot).context("failed to update index")?;
    }

    let applied_model_class = apply_trained_ranker(repo_root, &mut snapshot);
    let ranker_applied = applied_model_class.is_some();

    if let Some(model_class) = &applied_model_class {
        let label = match model_class {
            hotspots_core::trainer::ModelClass::Ridge => "Ridge",
            hotspots_core::trainer::ModelClass::RandomForest => "RandomForest",
        };
        eprintln!("hotspots: using trained ranker (model class: {label})");
    }

    // Re-run quadrant assignment now that activity_risk reflects trained RF scores.
    // This promotes debt→fire for functions with high predicted fix probability (≥0.7)
    // even if they haven't been touched in the last 30 days.
    if ranker_applied {
        snapshot.compute_quadrants(resolved_config.driver_threshold_percentile, true);
    }

    // Populate explanation phrases for CRITICAL/HIGH functions when --explain is set
    // and a trained ranker was applied. Percentiles are computed over all functions
    // before top-N truncation so the reference distribution is repo-wide.
    if ranker_applied && explain {
        populate_explanations(&mut snapshot);
    }

    let total_function_count = snapshot.functions.len();

    // Suppression gate: check if the activity ranker is working on this repo.
    // Run on the full sorted snapshot (before top-N truncation) so calibration
    // sees a representative top-50. The verdict is smoothed across runs
    // (`.hotspots/gate_history.json`) so a single sparse/bursty 90-day window
    // can't flip the reported verdict — see `GateConfig::consecutive_suppressed`.
    // Inconclusive is silent — it fires on greenfield repos or non-conventional
    // commit histories and is not actionable.
    if !skip_gate {
        let gate_verdict =
            check_gate_smoothed(repo_root, &snapshot.functions, &GateConfig::default());
        if let GateVerdict::Suppressed {
            p_at_10, threshold, ..
        } = &gate_verdict
        {
            if ranker_applied {
                eprintln!(
                    "hotspots: activity ranker P@10={p_at_10:.2} (< {threshold:.2}); using trained ranker instead."
                );
            } else {
                eprintln!(
                    "hotspots: warning: activity ranker P@10={p_at_10:.2} < {threshold:.2} — rankings may be misleading."
                );
                eprintln!("          Run `hotspots train` to fit a local ranker from this repo's fix history.");
            }
        }
    }

    apply_top_n(&mut snapshot, format, explain, level, top);

    emit_snapshot_output(
        &mut snapshot,
        SnapshotOutputOpts {
            format,
            explain,
            level,
            top,
            total_function_count,
            output,
            co_change_window_days: resolved_config.co_change_window_days,
            co_change_min_count: resolved_config.co_change_min_count,
            all_functions,
            include_models,
            source_url: source_url.clone(),
            risk_thresholds: hotspots_core::risk::RiskThresholds {
                moderate: resolved_config.moderate_threshold,
                high: resolved_config.high_threshold,
                critical: resolved_config.critical_threshold,
            },
        },
        repo_root,
        path,
    )
}

fn handle_delta_mode(
    repo_root: &Path,
    resolved_config: &hotspots_core::ResolvedConfig,
    reports: Vec<hotspots_core::FunctionRiskReport>,
    pr_context: hotspots_core::git::PrContext,
    opts: ModeOutputOptions,
) -> anyhow::Result<()> {
    let ModeOutputOptions {
        format,
        policy,
        output,
        source_url,
        touch_mode,
        callgraph_skip_above,
        skip_touch_metrics,
        ..
    } = opts;
    let snapshot = build_enriched_snapshot(
        repo_root,
        resolved_config,
        reports,
        touch_mode,
        callgraph_skip_above,
        skip_touch_metrics,
    )
    .context("failed to build enriched snapshot")?;

    let delta_val = if pr_context.is_pr {
        compute_pr_delta(repo_root, &snapshot)?
    } else {
        delta::compute_delta(repo_root, &snapshot)?
    };

    let delta_with_extras = enrich_delta(repo_root, resolved_config, &snapshot, delta_val, policy)?;

    if emit_delta_output(
        &delta_with_extras,
        format,
        policy,
        output,
        source_url.as_deref(),
    )? {
        std::process::exit(1);
    }
    Ok(())
}

fn enrich_delta(
    repo_root: &Path,
    resolved_config: &hotspots_core::ResolvedConfig,
    snapshot: &Snapshot,
    delta_val: delta::Delta,
    policy: bool,
) -> anyhow::Result<delta::Delta> {
    let mut unique_files: Vec<String> = snapshot
        .functions
        .iter()
        .map(|f| f.file.clone())
        .collect::<std::collections::HashSet<_>>()
        .into_iter()
        .collect();
    unique_files.sort();
    let files_as_str: Vec<&str> = unique_files.iter().map(|s| s.as_str()).collect();
    let import_edges = hotspots_core::imports::resolve_file_deps(&files_as_str, repo_root);
    let mut current_co_change = hotspots_core::git::extract_co_change_pairs(
        repo_root,
        resolved_config.co_change_window_days,
        resolved_config.co_change_min_count,
    )
    .unwrap_or_default();
    hotspots_core::aggregates::annotate_static_deps(
        &mut current_co_change,
        &import_edges,
        repo_root,
    );

    let parent_sha = snapshot.commit.parents.first().cloned();
    let prev_co_change: Vec<hotspots_core::git::CoChangePair> = parent_sha
        .as_deref()
        .and_then(|sha| {
            hotspots_core::delta::load_parent_snapshot(repo_root, sha)
                .ok()
                .flatten()
        })
        .and_then(|s| s.aggregates)
        .map(|a| a.co_change)
        .unwrap_or_default();

    let mut enriched = delta_val.clone();
    if policy {
        let policy_results = hotspots_core::policy::evaluate_policies(
            &delta_val,
            snapshot,
            repo_root,
            resolved_config,
        )
        .context("failed to evaluate policies")?;
        if let Some(results) = policy_results {
            enriched.policy = Some(results);
        }
    }
    enriched.aggregates = Some(hotspots_core::aggregates::compute_delta_aggregates(
        &delta_val,
        &current_co_change,
        &prev_co_change,
    ));
    Ok(enriched)
}

fn handle_models_mode(
    path: &Path,
    repo_root: &Path,
    resolved_config: &hotspots_core::ResolvedConfig,
    reports: Vec<hotspots_core::FunctionRiskReport>,
    opts: ModeOutputOptions,
) -> anyhow::Result<()> {
    let ModeOutputOptions {
        format,
        top,
        touch_mode,
        callgraph_skip_above,
        skip_touch_metrics,
        ..
    } = opts;
    let snapshot = build_enriched_snapshot(
        repo_root,
        resolved_config,
        reports,
        touch_mode,
        callgraph_skip_above,
        skip_touch_metrics,
    )
    .context("failed to build enriched snapshot")?;
    let model_map = hotspots_core::models::compute_model_risk_map(path, repo_root, &snapshot, top)
        .context("failed to compute model risk map")?;
    match format {
        OutputFormat::Text => {
            print!(
                "{}",
                hotspots_core::models::render_model_risk_text(&model_map, top)
            );
        }
        OutputFormat::Json => {
            println!(
                "{}",
                hotspots_core::models::render_model_risk_json(&model_map)?
            );
        }
        OutputFormat::Html
        | OutputFormat::Jsonl
        | OutputFormat::Sarif
        | OutputFormat::Csv
        | OutputFormat::Xlsx => {
            unreachable!("validated by validate_analyze_flags")
        }
    }
    Ok(())
}

struct SnapshotOutputOpts {
    format: OutputFormat,
    explain: bool,
    level: Option<OutputLevel>,
    top: Option<usize>,
    total_function_count: usize,
    output: Option<PathBuf>,
    co_change_window_days: u64,
    co_change_min_count: usize,
    all_functions: bool,
    include_models: bool,
    source_url: Option<String>,
    risk_thresholds: hotspots_core::risk::RiskThresholds,
}

fn emit_snapshot_output(
    snapshot: &mut Snapshot,
    opts: SnapshotOutputOpts,
    repo_root: &Path,
    analysis_path: &Path,
) -> anyhow::Result<()> {
    match opts.format {
        OutputFormat::Json => emit_json_output(snapshot, repo_root, analysis_path, opts),
        OutputFormat::Jsonl => emit_jsonl_output(snapshot),
        OutputFormat::Text => emit_text_output(snapshot, repo_root, opts),
        OutputFormat::Html => emit_html_output(snapshot, repo_root, analysis_path, opts),
        OutputFormat::Sarif => emit_sarif_output(snapshot, repo_root, opts),
        OutputFormat::Csv => emit_csv_output(snapshot, repo_root, opts),
        OutputFormat::Xlsx => emit_xlsx_output(snapshot, repo_root, opts),
    }
}

fn emit_json_output(
    snapshot: &mut Snapshot,
    repo_root: &Path,
    analysis_path: &Path,
    opts: SnapshotOutputOpts,
) -> anyhow::Result<()> {
    let SnapshotOutputOpts {
        all_functions,
        include_models,
        co_change_window_days,
        co_change_min_count,
        output,
        ..
    } = opts;
    let aggregates = hotspots_core::aggregates::compute_snapshot_aggregates_with_models(
        snapshot,
        repo_root,
        co_change_window_days,
        co_change_min_count,
        include_models.then_some(analysis_path),
    );
    if all_functions {
        snapshot.aggregates = Some(aggregates);
        write_json_snapshot(snapshot, output)
    } else {
        let agent_output = hotspots_core::aggregates::compute_agent_snapshot_output(
            snapshot,
            &aggregates,
            repo_root,
        );
        write_json_agent(&agent_output, output)
    }
}

fn emit_jsonl_output(snapshot: &mut Snapshot) -> anyhow::Result<()> {
    let stdout = std::io::stdout();
    let mut out = std::io::BufWriter::new(stdout.lock());
    snapshot
        .write_jsonl_to(&mut out)
        .context("failed to write snapshot JSONL")
}

fn emit_text_output(
    snapshot: &mut Snapshot,
    repo_root: &Path,
    opts: SnapshotOutputOpts,
) -> anyhow::Result<()> {
    let SnapshotOutputOpts {
        level,
        explain,
        top,
        total_function_count,
        co_change_window_days,
        co_change_min_count,
        ..
    } = opts;
    let aggregates = hotspots_core::aggregates::compute_snapshot_aggregates(
        snapshot,
        repo_root,
        co_change_window_days,
        co_change_min_count,
    );
    if level == Some(OutputLevel::File) {
        explain::print_file_risk_output(&aggregates.file_risk, top)?;
    } else if level == Some(OutputLevel::Module) {
        explain::print_module_output(&aggregates.modules, top)?;
    } else if explain {
        let color = std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none();
        explain::print_explain_output(snapshot, total_function_count, color)?;
    } else {
        anyhow::bail!(
            "text format without --explain is not supported for snapshot mode (use --format json or add --explain)"
        );
    }
    Ok(())
}

fn emit_html_output(
    snapshot: &mut Snapshot,
    repo_root: &Path,
    analysis_path: &Path,
    opts: SnapshotOutputOpts,
) -> anyhow::Result<()> {
    let SnapshotOutputOpts {
        co_change_window_days,
        co_change_min_count,
        include_models,
        source_url,
        risk_thresholds,
        output,
        ..
    } = opts;
    let aggregates = hotspots_core::aggregates::compute_snapshot_aggregates_with_models(
        snapshot,
        repo_root,
        co_change_window_days,
        co_change_min_count,
        include_models.then_some(analysis_path),
    );
    snapshot.aggregates = Some(aggregates);
    let history: Vec<_> = hotspots_core::trends::load_snapshot_window(repo_root, 30)
        .unwrap_or_default()
        .into_iter()
        .filter_map(|s| s.summary.map(|sum| (s.commit, sum)))
        .collect();
    let html = hotspots_core::html::render_html_snapshot(
        snapshot,
        &history,
        source_url.as_deref(),
        &risk_thresholds,
    );
    let output_path = output.unwrap_or_else(|| PathBuf::from(".hotspots/report.html"));
    write_html_report(&output_path, &html)?;
    eprintln!("HTML report written to: {}", output_path.display());
    Ok(())
}

fn emit_sarif_output(
    snapshot: &mut Snapshot,
    repo_root: &Path,
    opts: SnapshotOutputOpts,
) -> anyhow::Result<()> {
    let sarif = hotspots_core::sarif::render_sarif(snapshot, repo_root);
    if let Some(output_path) = opts.output {
        if let Some(parent) = output_path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create directory: {}", parent.display()))?;
        }
        std::fs::write(&output_path, &sarif)
            .with_context(|| format!("failed to write SARIF to {}", output_path.display()))?;
        eprintln!("SARIF report written to: {}", output_path.display());
    } else {
        println!("{sarif}");
    }
    Ok(())
}

/// `--format csv`: one row per file, full inventory (ignores `--top` — a
/// spreadsheet is for sorting/filtering everything, not a truncated view).
/// See `hotspots_core::csv_report` for the triage/planning audience and
/// column rationale. Single file, single table — coupling data lives only in
/// `--format xlsx` (a real workbook can hold it as a separate sheet; CSV has
/// no notion of multiple tables in one file, so it doesn't try to).
fn emit_csv_output(
    snapshot: &mut Snapshot,
    repo_root: &Path,
    opts: SnapshotOutputOpts,
) -> anyhow::Result<()> {
    let csv = hotspots_core::csv_report::render_csv(&snapshot.functions, repo_root)
        .context("failed to render CSV report")?;
    if let Some(output_path) = opts.output {
        if let Some(parent) = output_path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create directory: {}", parent.display()))?;
        }
        std::fs::write(&output_path, &csv)
            .with_context(|| format!("failed to write CSV to {}", output_path.display()))?;
        eprintln!("CSV report written to: {}", output_path.display());
    } else {
        print!("{csv}");
    }
    Ok(())
}

/// `--format xlsx`: a real multi-sheet workbook — "Files" (the main triage
/// table) and "Coupling" (files with a real `directed_coupling` value only).
/// Binary format, so it always writes to a file: `--output`, or
/// `.hotspots/report.xlsx` by default (mirrors HTML's default path).
fn emit_xlsx_output(
    snapshot: &mut Snapshot,
    repo_root: &Path,
    opts: SnapshotOutputOpts,
) -> anyhow::Result<()> {
    let bytes = hotspots_core::xlsx_report::render_xlsx(&snapshot.functions, repo_root)
        .context("failed to render XLSX report")?;
    let output_path = opts
        .output
        .unwrap_or_else(|| snapshot::hotspots_dir(repo_root).join("report.xlsx"));
    if let Some(parent) = output_path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create directory: {}", parent.display()))?;
    }
    std::fs::write(&output_path, &bytes)
        .with_context(|| format!("failed to write XLSX to {}", output_path.display()))?;
    eprintln!("XLSX report written to: {}", output_path.display());
    Ok(())
}

fn apply_top_n(
    snapshot: &mut Snapshot,
    format: OutputFormat,
    explain: bool,
    level: Option<OutputLevel>,
    top: Option<usize>,
) {
    let is_aggregate_level = level == Some(OutputLevel::File) || level == Some(OutputLevel::Module);
    let is_text = matches!(format, OutputFormat::Text);
    // CSV/XLSX always emit the full file inventory — a spreadsheet is for
    // sorting/filtering everything, not a truncated view (see csv_report.rs).
    let is_spreadsheet = matches!(format, OutputFormat::Csv | OutputFormat::Xlsx);
    if !is_aggregate_level && !is_spreadsheet && (top.is_some() || (is_text && explain)) {
        snapshot.functions.sort_by(|a, b| {
            let a_score = a.activity_risk.unwrap_or(a.lrs);
            let b_score = b.activity_risk.unwrap_or(b.lrs);
            b_score
                .partial_cmp(&a_score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        // 0 = show all; None in text+explain defaults to 20
        let limit = match top {
            Some(0) => usize::MAX,
            Some(n) => n,
            None if is_text => 20,
            None => usize::MAX,
        };
        if limit != usize::MAX {
            snapshot.functions.truncate(limit);
        }
    }
}

/// If `.hotspots/ranker.json` exists, overwrite each function's `activity_risk`
/// with the trained model's score. Returns the model class that was applied.
/// Silent no-op (returns `None`) if the model is absent or fails to load.
fn apply_trained_ranker(
    repo_root: &Path,
    snapshot: &mut Snapshot,
) -> Option<hotspots_core::trainer::ModelClass> {
    let model_path = snapshot::hotspots_dir(repo_root).join("ranker.json");
    if !model_path.exists() {
        return None;
    }
    let model = match hotspots_core::trainer::RankerModel::load(&model_path) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("hotspots: warning: failed to load ranker.json: {e}");
            return None;
        }
    };
    for func in &mut snapshot.functions {
        func.activity_risk = Some(hotspots_core::trainer::score(&model, func));
    }
    Some(model.model_class.clone())
}

/// Compute per-feature repo-wide percentile ranks and populate `explanation` on
/// every CRITICAL/HIGH function. Called only when `--explain` and a ranker are active.
fn populate_explanations(snapshot: &mut Snapshot) {
    use hotspots_core::phrases::{top_phrases, FeaturePercentiles};
    use hotspots_core::risk::RiskBand;
    use hotspots_core::trainer::extract_features;

    let n = snapshot.functions.len();
    if n == 0 {
        return;
    }

    // Extract feature vectors for all functions up front.
    let feature_vecs: Vec<[f64; 10]> = snapshot.functions.iter().map(extract_features).collect();

    // For each feature column, build a sorted copy for percentile lookups.
    // Feature indices: 0=lrs, 1=cc, 2=nd, 3=loc, 4=fo, 5=fan_in,
    //                  6=total_churn, 7=authors_90d, 8=directed_coupling
    let mut sorted: Vec<Vec<f64>> = (0..10usize).map(|_| Vec::with_capacity(n)).collect();
    for fv in &feature_vecs {
        for (j, &v) in fv.iter().enumerate() {
            sorted[j].push(v);
        }
    }
    for col in sorted.iter_mut() {
        col.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    }

    let pct = |col: usize, val: f64| -> f32 {
        let pos = sorted[col].partition_point(|&x| x < val);
        pos as f32 / n as f32
    };

    for (i, func) in snapshot.functions.iter_mut().enumerate() {
        if !matches!(func.band, RiskBand::Critical | RiskBand::High) {
            continue;
        }
        let fv = &feature_vecs[i];
        let fp = FeaturePercentiles {
            lrs: pct(0, fv[0]),
            cc: pct(1, fv[1]),
            nd: pct(2, fv[2]),
            loc: pct(3, fv[3]),
            fo: pct(4, fv[4]),
            // Require fan_in >= 3 before "depended on by many callers" fires;
            // fan_in=1 can clear the 90th percentile on sparse repos, producing
            // a misleading phrase.
            fan_in: if fv[5] >= 3.0 { pct(5, fv[5]) } else { 0.0 },
            total_churn: pct(6, fv[6]),
            authors_90d: pct(7, fv[7]),
            directed_coupling: pct(8, fv[8]),
        };
        let phrase = top_phrases(&fp, 3);
        if !phrase.is_empty() {
            func.explanation = Some(phrase);
        }
    }
}

fn write_snapshot_json_file<F>(output_path: &Path, write: F) -> anyhow::Result<()>
where
    F: FnOnce(&mut std::io::BufWriter<std::fs::File>) -> anyhow::Result<()>,
{
    if let Some(parent) = output_path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create directory: {}", parent.display()))?;
    }
    let file = std::fs::File::create(output_path)
        .with_context(|| format!("failed to create {}", output_path.display()))?;
    let mut out = std::io::BufWriter::new(file);
    write(&mut out)
}

fn write_json_snapshot(snapshot: &Snapshot, output: Option<PathBuf>) -> anyhow::Result<()> {
    if let Some(output_path) = output {
        write_snapshot_json_file(&output_path, |out| {
            snapshot
                .write_json_to(out)
                .context("failed to write snapshot JSON")
        })?;
        eprintln!("JSON report written to: {}", output_path.display());
    } else {
        let stdout = std::io::stdout();
        let mut out = std::io::BufWriter::new(stdout.lock());
        snapshot
            .write_json_to(&mut out)
            .context("failed to write snapshot JSON")?;
    }
    Ok(())
}

fn write_json_agent(
    agent_output: &hotspots_core::aggregates::AgentSnapshotOutput,
    output: Option<PathBuf>,
) -> anyhow::Result<()> {
    if let Some(output_path) = output {
        write_snapshot_json_file(&output_path, |out| {
            agent_output
                .write_json_to(out)
                .context("failed to write agent snapshot JSON")
        })?;
        eprintln!("JSON report written to: {}", output_path.display());
    } else {
        let stdout = std::io::stdout();
        let mut out = std::io::BufWriter::new(stdout.lock());
        agent_output
            .write_json_to(&mut out)
            .context("failed to write agent snapshot JSON")?;
    }
    Ok(())
}

/// Returns true if there are blocking policy failures (caller should exit non-zero).
fn emit_delta_output(
    delta_val: &Delta,
    format: OutputFormat,
    with_policy: bool,
    output: Option<PathBuf>,
    source_url: Option<&str>,
) -> anyhow::Result<bool> {
    let has_blocking_failures = delta_val
        .policy
        .as_ref()
        .map(|p| p.has_blocking_failures())
        .unwrap_or(false);

    match format {
        OutputFormat::Json => {
            println!("{}", delta_val.to_json()?);
        }
        OutputFormat::Jsonl => {
            anyhow::bail!("JSONL format is not supported for delta mode (use --mode snapshot)");
        }
        OutputFormat::Text => {
            emit_delta_text(delta_val, with_policy)?;
        }
        OutputFormat::Html => {
            emit_delta_html(delta_val, source_url, output)?;
        }
        OutputFormat::Sarif => {
            anyhow::bail!("SARIF format is not supported for delta mode (use --mode snapshot)");
        }
        OutputFormat::Csv => {
            anyhow::bail!("--format csv is not supported for delta mode (use --mode snapshot)");
        }
        OutputFormat::Xlsx => {
            anyhow::bail!("--format xlsx is not supported for delta mode (use --mode snapshot)");
        }
    }

    Ok(has_blocking_failures)
}

fn emit_delta_text(delta_val: &Delta, with_policy: bool) -> anyhow::Result<()> {
    if !with_policy {
        anyhow::bail!(
            "text format is not supported for delta mode without --policy (use --format json)"
        );
    }
    if let Some(ref policy_results) = delta_val.policy {
        policy::print_policy_text_output(delta_val, policy_results)?;
    } else {
        println!("Delta Analysis");
        println!("{}", "=".repeat(80));
        println!("Baseline delta (no parent snapshot) - policy evaluation skipped.");
        println!(
            "\nDelta contains {} function changes.",
            delta_val.deltas.len()
        );
    }
    Ok(())
}

fn emit_delta_html(
    delta_val: &Delta,
    source_url: Option<&str>,
    output: Option<PathBuf>,
) -> anyhow::Result<()> {
    let html = hotspots_core::html::render_html_delta(delta_val, source_url);
    let output_path = output.unwrap_or_else(|| PathBuf::from(".hotspots/report.html"));
    write_html_report(&output_path, &html)?;
    eprintln!("HTML report written to: {}", output_path.display());
    Ok(())
}

/// Compute delta for PR mode (compares vs merge-base).
fn compute_pr_delta(repo_root: &Path, snapshot: &Snapshot) -> anyhow::Result<delta::Delta> {
    let merge_base_sha = git::resolve_merge_base_auto();
    let fallback_sha = snapshot.commit.parents.first().map(|s| s.as_str());
    let parent = load_merge_base_or_fallback(repo_root, merge_base_sha.as_deref(), fallback_sha)?;
    delta::Delta::new(snapshot, parent.as_ref())
}

fn load_merge_base_or_fallback(
    repo_root: &Path,
    merge_base_sha: Option<&str>,
    fallback_sha: Option<&str>,
) -> anyhow::Result<Option<Snapshot>> {
    if let Some(sha) = merge_base_sha {
        match delta::load_parent_snapshot(repo_root, sha)? {
            Some(snap) => return Ok(Some(snap)),
            None => {
                eprintln!("Warning: merge-base snapshot not found, falling back to direct parent")
            }
        }
    } else {
        eprintln!("Warning: failed to resolve merge-base, falling back to direct parent");
    }
    if let Some(sha) = fallback_sha {
        delta::load_parent_snapshot(repo_root, sha)
    } else {
        Ok(None)
    }
}

/// Memory-efficient snapshot pipeline using SQLite as an in-process buffer.
///
/// Pipeline: insert reports → drop Vec → update churn → build call graph from DB →
/// update callgraph metrics → drop CallGraph → load FunctionSnapshot Vec → enrich → return.
///
/// Peak memory compared to `build_enriched_snapshot`:
///   Before: ~250 MB (reports + call graph + snapshot Vec all overlap)
///   After:  ~45 MB  (only call graph + SQLite overlap; reports freed before graph builds)
pub(crate) fn build_snapshot_via_db(
    repo_root: &Path,
    resolved_config: &hotspots_core::ResolvedConfig,
    reports: Vec<hotspots_core::FunctionRiskReport>,
    touch_mode: TouchMode,
    callgraph_skip_above: Option<usize>,
    skip_touch_metrics: bool,
) -> anyhow::Result<Snapshot> {
    use hotspots_core::db::TempDb;
    use hotspots_core::snapshot::{
        AnalysisInfo, CommitInfo, FORMULA_VERSION, SNAPSHOT_SCHEMA_VERSION,
    };

    let git_context =
        git::extract_git_context_at(repo_root).context("failed to extract git context")?;
    let merge_base = hotspots_core::git::find_merge_base(repo_root);

    let commit_info = CommitInfo::from(git_context.clone());
    let sha = commit_info.sha.clone();

    // Phase 1: write reports to DB, then free the Vec (~23 MB).
    let db = TempDb::new().context("failed to create pipeline TempDb")?;
    db.insert_reports(&commit_info, &reports)
        .context("failed to insert reports into pipeline DB")?;
    drop(reports);

    // Phase 2: churn (needed before callgraph so neighbor_churn can read it).
    if !git_context.parent_shas.is_empty() {
        match git::extract_commit_churn_at(repo_root, &sha) {
            Ok(churns) => {
                let churn_map: std::collections::HashMap<String, _> = churns
                    .into_iter()
                    .map(|c| {
                        let absolute_path = repo_root.join(&c.file);
                        let normalized_path = absolute_path.to_string_lossy().to_string();
                        (normalized_path, c)
                    })
                    .collect();
                db.update_churn(&sha, &churn_map)
                    .context("failed to update churn in pipeline DB")?;
            }
            Err(e) => eprintln!("Warning: failed to extract churn: {}", e),
        }
    }

    // Phase 3: build call graph from lean DB rows, run algorithms, write back, free graph.
    let effective_skip_above = callgraph_skip_above.unwrap_or(resolved_config.callgraph_skip_above);
    let function_count = db
        .function_count(&sha)
        .context("failed to count functions in pipeline DB")?;

    if function_count <= effective_skip_above {
        let call_graph = hotspots_core::build_call_graph_from_db(&db, &sha, repo_root)
            .context("failed to build call graph from DB")?;
        db.update_callgraph_metrics(
            &sha,
            &call_graph,
            resolved_config.betweenness_exact_threshold,
            resolved_config.betweenness_approx_k,
        )
        .context("failed to update callgraph metrics in pipeline DB")?;
        // call_graph dropped here, freeing ~25 MB.
    } else {
        eprintln!(
            "info: call graph skipped ({} functions > --callgraph-skip-above {})",
            function_count, effective_skip_above
        );
    }

    // Phase 4: load enriched functions from DB (churn + callgraph already set).
    let functions = db
        .load_snapshot_functions(&sha)
        .context("failed to load snapshot functions from pipeline DB")?;
    // SQLite connection dropped with `db` at end of scope; no longer needed.

    let total_functions = functions.len();
    let snapshot = Snapshot {
        schema_version: SNAPSHOT_SCHEMA_VERSION,
        commit: commit_info,
        analysis: AnalysisInfo {
            scope: "full".to_string(),
            tool_version: env!("CARGO_PKG_VERSION").to_string(),
            formula_version: FORMULA_VERSION,
        },
        functions,
        summary: None,
        aggregates: None,
    };

    // Phase 5: remaining enrichment (touch, activity risk, percentiles, driver, quadrant).
    let mut enricher = snapshot::SnapshotEnricher::new(snapshot).with_subsystems(repo_root);
    if !skip_touch_metrics {
        // burst_score does its own full-history `git log` walk (history_signals::
        // load_commits_with_author) — gate it alongside the other touch/churn git
        // log calls so --skip-touch-metrics actually skips it too.
        enricher = enricher.with_burst_score(repo_root);
        let needs_progress = matches!(
            touch_mode,
            TouchMode::PerFunction | TouchMode::Hybrid { .. }
        );
        let progress = if needs_progress {
            Some(make_progress_reporter(total_functions))
        } else {
            None
        };
        enricher = enricher.with_touch_metrics(repo_root, touch_mode, progress);
        enricher = enricher.with_branch_recency_adjustment(repo_root, merge_base.as_ref());
    }

    let result = enricher
        .enrich(
            Some(&resolved_config.scoring_weights),
            resolved_config.driver_threshold_percentile,
        )
        .build();
    Ok(result)
}

/// Run the full enrichment pipeline: git context, churn, touch metrics, call graph, activity risk.
///
/// `callgraph_skip_above` overrides `resolved_config.callgraph_skip_above` when `Some`.
/// `skip_touch_metrics` bypasses all git-log touch calls (file-level and per-function).
pub(crate) fn build_enriched_snapshot(
    repo_root: &Path,
    resolved_config: &hotspots_core::ResolvedConfig,
    mut reports: Vec<hotspots_core::FunctionRiskReport>,
    touch_mode: TouchMode,
    callgraph_skip_above: Option<usize>,
    skip_touch_metrics: bool,
) -> anyhow::Result<Snapshot> {
    let git_context =
        git::extract_git_context_at(repo_root).context("failed to extract git context")?;

    let merge_base = hotspots_core::git::find_merge_base(repo_root);

    let effective_skip_above = callgraph_skip_above.unwrap_or(resolved_config.callgraph_skip_above);
    let call_graph = if reports.len() > effective_skip_above {
        eprintln!(
            "info: call graph skipped ({} functions > --callgraph-skip-above {})",
            reports.len(),
            effective_skip_above
        );
        None
    } else {
        hotspots_core::build_call_graph(&reports, repo_root).ok()
    };

    for r in &mut reports {
        r.callees.clear();
        r.callees.shrink_to_fit();
    }

    let total_functions = reports.len();
    let mut enricher = snapshot::SnapshotEnricher::new(Snapshot::new(git_context.clone(), reports))
        .with_subsystems(repo_root);

    if !git_context.parent_shas.is_empty() {
        match git::extract_commit_churn_at(repo_root, &git_context.head_sha) {
            Ok(churns) => {
                let churn_map: std::collections::HashMap<String, _> = churns
                    .into_iter()
                    .map(|c| {
                        let absolute_path = repo_root.join(&c.file);
                        let normalized_path = absolute_path.to_string_lossy().to_string();
                        (normalized_path, c)
                    })
                    .collect();
                enricher = enricher.with_churn(&churn_map);
            }
            Err(e) => {
                eprintln!("Warning: failed to extract churn: {}", e);
            }
        }
    }

    if !skip_touch_metrics {
        // burst_score does its own full-history `git log` walk (history_signals::
        // load_commits_with_author) — gate it alongside the other touch/churn git
        // log calls so --skip-touch-metrics actually skips it too.
        enricher = enricher.with_burst_score(repo_root);
        let needs_progress = matches!(
            touch_mode,
            TouchMode::PerFunction | TouchMode::Hybrid { .. }
        );
        let progress = if needs_progress {
            Some(make_progress_reporter(total_functions))
        } else {
            None
        };
        enricher = enricher.with_touch_metrics(repo_root, touch_mode, progress);
        enricher = enricher.with_branch_recency_adjustment(repo_root, merge_base.as_ref());
    }

    if let Some(ref graph) = call_graph {
        enricher = enricher.with_callgraph(
            graph,
            resolved_config.betweenness_exact_threshold,
            resolved_config.betweenness_approx_k,
        );
    }

    Ok(enricher
        .enrich(
            Some(&resolved_config.scoring_weights),
            resolved_config.driver_threshold_percentile,
        )
        .build())
}

fn make_progress_reporter(total: usize) -> Box<dyn Fn(usize, usize)> {
    use std::io::IsTerminal;
    if total == 0 {
        return Box::new(|_i: usize, _total: usize| {});
    }
    if std::io::stderr().is_terminal() {
        use indicatif::{ProgressBar, ProgressStyle};
        let pb = ProgressBar::new(total as u64);
        pb.set_style(
            ProgressStyle::default_bar()
                .template("Building touch cache [{bar:40}] {pos}/{len}")
                .unwrap()
                .progress_chars("##-"),
        );
        Box::new(move |i: usize, t: usize| {
            pb.set_position(i as u64);
            if i >= t {
                pb.finish_and_clear();
            }
        })
    } else {
        let last_print = std::sync::Mutex::new(std::time::Instant::now());
        Box::new(move |i: usize, t: usize| {
            if i >= t {
                eprintln!("touch cache: {t}/{t} functions (100%) [done]");
                return;
            }
            if let Ok(mut last) = last_print.try_lock() {
                if last.elapsed().as_secs() >= 30 {
                    let pct = (i * 100).checked_div(t).unwrap_or(0);
                    eprintln!("touch cache: {i}/{t} functions ({pct}%)");
                    *last = std::time::Instant::now();
                }
            }
        })
    }
}

/// Analyze the source tree at `sha`, enrich it, persist it to `repo_root`, and
/// return the resulting snapshot.
///
/// Used by `hotspots diff --auto-analyze` to generate missing snapshots on
/// demand. A temporary git worktree is created at `sha` and torn down
/// automatically when this function returns (or on error).
///
/// Per-function touch metrics are skipped (the touch cache lives in
/// `repo_root/.hotspots/` and cannot be pre-warmed for historical refs; file-
/// level batched metrics are still computed as normal).
pub(crate) fn analyze_and_persist_at_ref(
    repo_root: &Path,
    sha: &str,
    resolved_config: &hotspots_core::ResolvedConfig,
) -> anyhow::Result<hotspots_core::snapshot::Snapshot> {
    let worktree = hotspots_core::git::create_worktree(repo_root, sha)
        .with_context(|| format!("failed to create worktree for {sha}"))?;

    let options = AnalysisOptions {
        min_lrs: None,
        top_n: None,
    };
    let progress = make_analysis_progress();
    let reports = analyze_with_progress(
        &worktree.path,
        options,
        Some(resolved_config),
        Some(progress.as_ref()),
    )
    .with_context(|| format!("analysis failed for ref {sha}"))?;

    // Build enriched snapshot using the worktree as the repo root so that
    // git context (HEAD, parents, timestamp) is read from the checked-out ref.
    // Touch cache is skipped (per_function_touches = false).
    // callgraph_skip_above = None: always use the config value for historical refs.
    let mut snapshot = build_enriched_snapshot(
        &worktree.path,
        resolved_config,
        reports,
        TouchMode::File,
        None,
        false,
    )
    .with_context(|| format!("enrichment failed for ref {sha}"))?;

    let worktree_prefix = worktree.path.to_string_lossy().replace('\\', "/");
    let repo_prefix = repo_root.to_string_lossy().replace('\\', "/");
    rewrite_worktree_paths(&mut snapshot, &worktree_prefix, &repo_prefix);

    snapshot.populate_patterns(&resolved_config.pattern_thresholds);

    // Persist into the *real* repo's .hotspots/ directory, not the worktree.
    hotspots_core::snapshot::persist_snapshot(repo_root, &snapshot, false)
        .with_context(|| format!("failed to persist snapshot for {sha}"))?;
    hotspots_core::snapshot::append_to_index(repo_root, &snapshot)
        .with_context(|| format!("failed to update index for {sha}"))?;

    // Drop of `worktree` runs `git worktree remove` here.
    Ok(snapshot)
}

fn rewrite_worktree_paths(snapshot: &mut Snapshot, worktree_prefix: &str, repo_prefix: &str) {
    for f in &mut snapshot.functions {
        if f.file.starts_with(worktree_prefix) {
            let rel = f.file[worktree_prefix.len()..].to_string();
            let old_file = f.file.clone();
            f.file = format!("{}{}", repo_prefix, rel);
            if let Some(symbol) = f.function_id.strip_prefix(&format!("{old_file}::")) {
                f.function_id = format!("{}::{}", f.file, symbol);
            }
        }
    }
}

const DEFAULT_HYBRID_THRESHOLD: usize = 5;

fn resolve_touch_mode(
    no_per_function: bool,
    per_function: bool,
    hybrid_threshold: Option<usize>,
    config_per_function: bool,
) -> TouchMode {
    if no_per_function {
        TouchMode::File
    } else if let Some(threshold) = hybrid_threshold {
        TouchMode::Hybrid { threshold }
    } else if per_function || config_per_function {
        TouchMode::PerFunction
    } else {
        TouchMode::Hybrid {
            threshold: DEFAULT_HYBRID_THRESHOLD,
        }
    }
}

/// `--touch-mode` value (see issue #184). Supersedes `--per-function-touches`,
/// `--no-per-function-touches`, `--skip-touch-metrics`, and `--hybrid-touches`,
/// which are kept as deprecated aliases.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum TouchModeArg {
    /// Use the resolved config's `per_function_touches`/`hybrid_touch_threshold`,
    /// falling back to hybrid with the default threshold — today's implicit default.
    Auto,
    PerFunction,
    File,
    /// `hybrid` (bare) uses `DEFAULT_HYBRID_THRESHOLD`; `hybrid:N` uses N.
    Hybrid(Option<usize>),
    /// Skip all touch metrics, directed coupling, and burst_score (no git log calls).
    None,
}

pub(crate) fn parse_touch_mode_arg(s: &str) -> Result<TouchModeArg, String> {
    let s = s.trim();
    if let Some(rest) = s.strip_prefix("hybrid") {
        return if rest.is_empty() {
            Ok(TouchModeArg::Hybrid(None))
        } else {
            let n_str = rest.strip_prefix(':').ok_or_else(|| {
                format!("invalid --touch-mode '{s}': expected 'hybrid' or 'hybrid:N'")
            })?;
            let n: usize = n_str.parse().map_err(|_| {
                format!("invalid --touch-mode '{s}': N must be a non-negative integer")
            })?;
            Ok(TouchModeArg::Hybrid(Some(n)))
        };
    }
    match s {
        "auto" => Ok(TouchModeArg::Auto),
        "per-function" => Ok(TouchModeArg::PerFunction),
        "file" => Ok(TouchModeArg::File),
        "none" => Ok(TouchModeArg::None),
        _ => Err(format!(
            "invalid --touch-mode '{s}': expected one of auto, per-function, file, hybrid[:N], none"
        )),
    }
}

/// Resolves `--touch-mode` (or, absent that, the four deprecated legacy flags) plus
/// config defaults into a `(TouchMode, skip_touch_metrics)` pair. `TouchMode` is
/// meaningless when `skip_touch_metrics` is true — callers already gate all touch
/// computation behind `!skip_touch_metrics` and never consult `TouchMode` otherwise.
fn resolve_touch_mode_and_skip(
    touch_mode_arg: Option<TouchModeArg>,
    legacy_no_per_function: bool,
    legacy_per_function: bool,
    legacy_hybrid: Option<usize>,
    legacy_skip: bool,
    config_per_function: bool,
    config_hybrid_threshold: Option<usize>,
) -> (TouchMode, bool) {
    match touch_mode_arg {
        Some(TouchModeArg::Auto) | None => {
            let touch_mode = resolve_touch_mode(
                legacy_no_per_function,
                legacy_per_function,
                legacy_hybrid.or(config_hybrid_threshold),
                config_per_function,
            );
            (touch_mode, legacy_skip)
        }
        Some(TouchModeArg::PerFunction) => (TouchMode::PerFunction, false),
        Some(TouchModeArg::File) => (TouchMode::File, false),
        Some(TouchModeArg::Hybrid(threshold)) => (
            TouchMode::Hybrid {
                threshold: threshold.unwrap_or(DEFAULT_HYBRID_THRESHOLD),
            },
            false,
        ),
        Some(TouchModeArg::None) => (TouchMode::File, true),
    }
}

/// Prints a one-line deprecation notice for each deprecated touch-metrics flag
/// actually used. No-op when `--touch-mode` was used instead (clap's `conflicts_with`
/// already rejects combining them).
fn warn_deprecated_touch_flags(
    no_per_function_touches: bool,
    per_function_touches: bool,
    skip_touch_metrics: bool,
    hybrid_touches: Option<usize>,
) {
    if no_per_function_touches {
        eprintln!("warning: --no-per-function-touches is deprecated, use --touch-mode file");
    }
    if per_function_touches {
        eprintln!("warning: --per-function-touches is deprecated, use --touch-mode per-function");
    }
    if skip_touch_metrics {
        eprintln!("warning: --skip-touch-metrics is deprecated, use --touch-mode none");
    }
    if let Some(n) = hybrid_touches {
        eprintln!("warning: --hybrid-touches is deprecated, use --touch-mode hybrid:{n}");
    }
}

pub(crate) fn make_analysis_progress() -> Box<dyn Fn(usize, usize) + Send + Sync> {
    use std::io::IsTerminal;
    if !std::io::stderr().is_terminal() {
        let last_print = std::sync::Mutex::new(std::time::Instant::now());
        return Box::new(move |done: usize, total: usize| {
            if done == 0 {
                eprintln!("Analyzing: 0/{total} files");
                return;
            }
            if done >= total {
                eprintln!("Analyzing: {done}/{total} files [done]");
                return;
            }
            if let Ok(mut last) = last_print.try_lock() {
                if last.elapsed().as_secs() >= 30 {
                    let pct = (done as f64 / total as f64 * 100.0) as usize;
                    eprintln!("Analyzing: {done}/{total} files ({pct}%)");
                    *last = std::time::Instant::now();
                }
            }
        });
    }
    use indicatif::{ProgressBar, ProgressStyle};
    let pb = ProgressBar::new(0);
    pb.set_style(
        ProgressStyle::default_bar()
            .template("Analyzing [{bar:40}] {pos}/{len} files  {elapsed} · ~{eta} remaining")
            .unwrap()
            .progress_chars("##-"),
    );
    Box::new(move |done: usize, total: usize| {
        if done == 0 {
            if total == 0 {
                pb.finish_and_clear();
                return;
            }
            pb.set_length(total as u64);
            pb.set_position(0);
        } else {
            pb.set_position(done as u64);
            if done >= total {
                pb.finish_and_clear();
            }
        }
    })
}

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

    #[test]
    fn parse_touch_mode_arg_all_named_values() {
        assert_eq!(parse_touch_mode_arg("auto"), Ok(TouchModeArg::Auto));
        assert_eq!(
            parse_touch_mode_arg("per-function"),
            Ok(TouchModeArg::PerFunction)
        );
        assert_eq!(parse_touch_mode_arg("file"), Ok(TouchModeArg::File));
        assert_eq!(parse_touch_mode_arg("none"), Ok(TouchModeArg::None));
    }

    #[test]
    fn parse_touch_mode_arg_hybrid_bare_and_with_threshold() {
        assert_eq!(
            parse_touch_mode_arg("hybrid"),
            Ok(TouchModeArg::Hybrid(None))
        );
        assert_eq!(
            parse_touch_mode_arg("hybrid:12"),
            Ok(TouchModeArg::Hybrid(Some(12)))
        );
        assert_eq!(
            parse_touch_mode_arg("hybrid:0"),
            Ok(TouchModeArg::Hybrid(Some(0)))
        );
    }

    #[test]
    fn parse_touch_mode_arg_rejects_garbage() {
        assert!(parse_touch_mode_arg("bogus").is_err());
        assert!(parse_touch_mode_arg("hybrid:").is_err());
        assert!(parse_touch_mode_arg("hybrid:abc").is_err());
        assert!(parse_touch_mode_arg("hybrid-5").is_err());
        assert!(parse_touch_mode_arg("hybrid:-1").is_err());
    }

    #[test]
    fn resolve_touch_mode_and_skip_auto_falls_back_to_config() {
        // No --touch-mode, no legacy flags, config says per_function_touches=true.
        let (mode, skip) = resolve_touch_mode_and_skip(None, false, false, None, false, true, None);
        assert_eq!(mode, TouchMode::PerFunction);
        assert!(!skip);

        // No config either: default hybrid threshold.
        let (mode, skip) =
            resolve_touch_mode_and_skip(None, false, false, None, false, false, None);
        assert_eq!(
            mode,
            TouchMode::Hybrid {
                threshold: DEFAULT_HYBRID_THRESHOLD
            }
        );
        assert!(!skip);
    }

    #[test]
    fn resolve_touch_mode_and_skip_explicit_auto_matches_none() {
        let (mode, skip) = resolve_touch_mode_and_skip(
            Some(TouchModeArg::Auto),
            false,
            false,
            None,
            false,
            true,
            Some(9),
        );
        // Explicit `--touch-mode auto` still honors config hybrid_touch_threshold,
        // same as omitting --touch-mode entirely (both resolve through resolve_touch_mode).
        assert_eq!(mode, TouchMode::Hybrid { threshold: 9 });
        assert!(!skip);
    }

    #[test]
    fn resolve_touch_mode_and_skip_per_function() {
        let (mode, skip) = resolve_touch_mode_and_skip(
            Some(TouchModeArg::PerFunction),
            false,
            false,
            None,
            false,
            false,
            None,
        );
        assert_eq!(mode, TouchMode::PerFunction);
        assert!(!skip);
    }

    #[test]
    fn resolve_touch_mode_and_skip_file() {
        let (mode, skip) = resolve_touch_mode_and_skip(
            Some(TouchModeArg::File),
            false,
            false,
            None,
            false,
            true, // config says per-function; --touch-mode file must still win
            None,
        );
        assert_eq!(mode, TouchMode::File);
        assert!(!skip);
    }

    #[test]
    fn resolve_touch_mode_and_skip_hybrid_default_and_explicit_threshold() {
        let (mode, skip) = resolve_touch_mode_and_skip(
            Some(TouchModeArg::Hybrid(None)),
            false,
            false,
            None,
            false,
            false,
            None,
        );
        assert_eq!(
            mode,
            TouchMode::Hybrid {
                threshold: DEFAULT_HYBRID_THRESHOLD
            }
        );
        assert!(!skip);

        let (mode, skip) = resolve_touch_mode_and_skip(
            Some(TouchModeArg::Hybrid(Some(42))),
            false,
            false,
            None,
            false,
            false,
            None,
        );
        assert_eq!(mode, TouchMode::Hybrid { threshold: 42 });
        assert!(!skip);
    }

    #[test]
    fn resolve_touch_mode_and_skip_none_sets_skip_true() {
        let (_, skip) = resolve_touch_mode_and_skip(
            Some(TouchModeArg::None),
            false,
            false,
            None,
            false,
            true,
            Some(3),
        );
        assert!(skip);
    }

    #[test]
    fn resolve_touch_mode_and_skip_legacy_flags_unchanged_when_touch_mode_absent() {
        // Legacy --skip-touch-metrics still works when --touch-mode isn't passed.
        let (_, skip) = resolve_touch_mode_and_skip(None, false, false, None, true, false, None);
        assert!(skip);

        // Legacy --no-per-function-touches still works.
        let (mode, skip) = resolve_touch_mode_and_skip(None, true, false, None, false, true, None);
        assert_eq!(mode, TouchMode::File);
        assert!(!skip);

        // Legacy --hybrid-touches still works.
        let (mode, skip) =
            resolve_touch_mode_and_skip(None, false, false, Some(7), false, false, None);
        assert_eq!(mode, TouchMode::Hybrid { threshold: 7 });
        assert!(!skip);
    }
}