codelore 0.26.0

CodeLore — Behavioral Code Analyzer CLI
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
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
use assert_cmd::Command;
use predicates::prelude::*;

/// Build a `codelore` command with GitHub Actions file-command env vars
/// stripped, so `check`/`gate` subprocesses never append to the CI
/// runner's real `$GITHUB_OUTPUT`/summary files (parallel test processes
/// would interleave writes and corrupt them).
fn codelore_cmd() -> Command {
    let mut cmd = Command::cargo_bin("codelore").unwrap();
    for var in [
        "GITHUB_OUTPUT",
        "GITHUB_STEP_SUMMARY",
        "GITHUB_ENV",
        "GITHUB_STATE",
        "GITHUB_PATH",
    ] {
        cmd.env_remove(var);
    }
    cmd
}

#[test]
fn analyze_revisions_emits_csv() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("entity,n-revs"))
        .stdout(predicate::str::contains("src/main.rs,4"))
        .stdout(predicate::str::contains("src/lib.rs,1"));
}

/// A reader closing our stdout early (`codelore … | head`, or a pager quit)
/// must exit 0 quietly — never erroring (exit 5) or panicking.
///
/// The assertion is deliberately lenient about *which* internal path fires:
/// on a tiny fixture the child usually finishes writing into the OS pipe
/// buffer before we drop the read end (a plain clean exit 0), whereas output
/// large enough to fill that buffer would block the child and surface a
/// `BrokenPipe` on the next write (mapped to a quiet exit 0 by the CLI's
/// central arm). Both outcomes are exit 0 with no error/panic on stderr, so the
/// test cannot flake on scheduling. The deterministic proof that the
/// `BrokenPipe` → exit-0 mapping itself fires lives in `main.rs`'s
/// `is_broken_pipe` unit tests.
#[test]
fn stdout_reader_closing_early_exits_quietly() {
    use std::io::Read as _;
    use std::process::{Command, Stdio};

    let tiny = codelore_lib::test_support::tiny_repo::build();
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_codelore"));
    for var in [
        "GITHUB_OUTPUT",
        "GITHUB_STEP_SUMMARY",
        "GITHUB_ENV",
        "GITHUB_STATE",
        "GITHUB_PATH",
    ] {
        cmd.env_remove(var);
    }
    let mut child = cmd
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
            "--no-banner",
        ])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn codelore");

    // Consume a few bytes, then drop the read end — closing our side of the
    // pipe while the child may still be writing.
    {
        let mut stdout = child.stdout.take().expect("child stdout piped");
        let mut buf = [0u8; 8];
        let _ = stdout.read(&mut buf);
    }

    let output = child.wait_with_output().expect("wait for child");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(0),
        "early pipe close must exit 0 quietly; stderr: {stderr}"
    );
    assert!(
        !stderr.contains("Broken pipe") && !stderr.contains("error:") && !stderr.contains("panic"),
        "stderr must stay quiet on early pipe close: {stderr}"
    );
}

#[test]
fn analyze_rejects_unknown_analysis() {
    // `--analysis` is a clap value_parser now, so a bad value is a parse error:
    // exit 2 (the documented CLI/arg-error code, unified with --format and
    // --complexity-sample) with the supported list rendered by clap.
    codelore_cmd()
        .args(["analyze", "--analysis", "not-real", "--repo", "."])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("invalid value"))
        .stderr(predicate::str::contains("hotspots"));
}

#[test]
fn analyze_unknown_analysis_suggests_nearest() {
    // A near-miss typo gets clap's native did-you-mean tip.
    codelore_cmd()
        .args(["analyze", "--analysis", "hotspot", "--repo", "."])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("hotspots"));
}

#[test]
fn version_flag_works() {
    // Compare against the package version Cargo resolves at compile time, not
    // a hardcoded literal — otherwise every version bump fails CI silently
    // until someone re-reads this test file.
    codelore_cmd()
        .arg("--version")
        .assert()
        .success()
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));
}

#[test]
fn diff_rejects_base_equals_head() {
    // A `--range` whose base resolves to the same SHA as head
    // used to run two identical analyses and emit an empty diff with
    // no signal. Now the entry point bails early with a typed error.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let output = codelore_cmd()
        .args([
            "diff",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "HEAD..HEAD",
        ])
        .output()
        .unwrap();
    assert!(!output.status.success(), "HEAD..HEAD should fail");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("base and head resolve to the same commit")
            && stderr.contains("nothing to diff"),
        "expected base==head error, got stderr: {stderr}"
    );
}

#[test]
fn invalid_repo_exits_with_code_3() {
    let output = codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            "/tmp/definitely-does-not-exist-codelore-test",
        ])
        .output()
        .unwrap();
    // CodeLoreError::Repo → exit 3 per spec §6.6
    assert_eq!(output.status.code(), Some(3));
}

/// A `--depth=1` clone of a merge-commit HEAD ingests zero commits: the merge
/// tip is the only object present locally, and the default
/// `include_merges = false` walk filter drops it, leaving an empty fact
/// store over a real HEAD — the exact truncated-checkout signature
/// `FactsDb::ensure_ingest_witnessed` exists to catch. No `--after`/
/// `--before` filter is passed, so the hard-error branch applies (an empty
/// store from a genuine date-window skip only warns; see the `analyze`
/// witness comment).
///
/// `git clone --depth` on a *local path* source silently ignores the flag
/// (git falls back to its hardlink-based local-clone optimization, which
/// cannot produce a shallow repo) — the `file://` URL form is required to
/// force the real, depth-respecting clone transport.
#[test]
fn analyze_exits_3_on_truncated_shallow_checkout() {
    let full = codelore_lib::test_support::mainline_advance_repo::build();
    let shallow = tempfile::tempdir().unwrap();
    let source_url = format!("file://{}", full.dir.path().display());
    let status = std::process::Command::new("git")
        .args(["clone", "--quiet", "--depth=1"])
        .arg(&source_url)
        .arg(shallow.path())
        .status()
        .unwrap();
    assert!(status.success(), "shallow clone from {source_url} failed");

    let output = codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--repo",
            shallow.path().to_str().unwrap(),
            "--no-cache",
        ])
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    // CodeLoreError::Repo → exit 3 per spec §6.6
    assert_eq!(output.status.code(), Some(3), "stderr: {stderr}");
    assert!(
        stderr.contains("truncated") && stderr.contains("shallow"),
        "expected the truncated-checkout witness message, got stderr: {stderr}"
    );
}

/// The shallow-checkout witness must survive a date filter. Under
/// `--after`/`--before`, a zero-commit walk on a FULL clone is a legitimate
/// empty selection (warn + exit 0), but on a shallow/truncated checkout it is
/// still a truncated checkout and must hard-error (exit 3). Same fixture as
/// [`analyze_exits_3_on_truncated_shallow_checkout`]; the wide-open `--after`
/// window includes all history, so the only cause of the empty store is the
/// shallow truncation, not the date filter.
#[test]
fn analyze_exits_3_on_shallow_checkout_even_under_date_filter() {
    let full = codelore_lib::test_support::mainline_advance_repo::build();
    let shallow = tempfile::tempdir().unwrap();
    let source_url = format!("file://{}", full.dir.path().display());
    let status = std::process::Command::new("git")
        .args(["clone", "--quiet", "--depth=1"])
        .arg(&source_url)
        .arg(shallow.path())
        .status()
        .unwrap();
    assert!(status.success(), "shallow clone from {source_url} failed");

    let output = codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--repo",
            shallow.path().to_str().unwrap(),
            "--after",
            "1970-01-01",
            "--no-cache",
        ])
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    // Shallow + date filter is still a truncated checkout → exit 3, not a
    // warn-and-exit-0 empty date selection.
    assert_eq!(output.status.code(), Some(3), "stderr: {stderr}");
    assert!(
        stderr.contains("truncated") && stderr.contains("shallow"),
        "expected the truncated-checkout witness message, got stderr: {stderr}"
    );
}

#[test]
fn invalid_options_exit_with_code_2() {
    // Inverted coupling range (`--min-coupling` > `--max-coupling`) is a
    // cross-field config error → `CodeLoreError::InvalidOptions` → exit 2.
    // Exit 2 (config errors) was the one bucket with no end-to-end CLI
    // coverage; a refactor dropping the typed error to a bare
    // `anyhow::bail!` would silently regress it to exit 1.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let output = codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--min-coupling",
            "80",
            "--max-coupling",
            "30",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
        ])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn analyze_hotspots_emits_csv() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "entity,revisions,cognitive,cognitive-health,hotspot-score",
        ));
}

#[test]
fn analyze_code_health_emits_csv() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "code-health",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("entity,cognitive,score"));
}

#[test]
fn analyze_code_age_emits_csv() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "code-age",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "entity,age_months,age_days,last_modified",
        ));
}

#[test]
fn analyze_abs_churn_emits_csv() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "abs-churn",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("date,added,deleted,commits"));
}

#[test]
fn analyze_author_churn_emits_csv() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "author-churn",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("author,added,deleted,commits"));
}

#[test]
fn analyze_entity_churn_emits_csv() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "entity-churn",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("entity,added,deleted,commits"));
}

#[test]
fn analyze_communication_emits_csv() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "communication",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "author-a,author-b,shared,average,strength",
        ));
}

#[test]
fn analyze_ownership_emits_csv() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "ownership",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "entity,main-author,total-revs,fractal-value",
        ));
}

#[test]
fn analyze_coupling_emits_csv() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "coupling",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "entity-a,entity-b,shared,revs-a,revs-b,average-revs,degree,fisher-p",
        ));
}

#[test]
fn analyze_summary_emits_csv() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "summary",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "0",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("metric,value"));
}

#[test]
fn analyze_hotspots_emits_sarif() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "sarif",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("CODELORE-HOTSPOT"))
        .stdout(predicate::str::contains(
            "json.schemastore.org/sarif-2.1.0.json",
        ));
}

#[test]
fn sarif_fingerprints_are_stable_across_repo_path_style() {
    // The SARIF fingerprint keys on `repo_root|path`; canonicalizing the repo
    // path makes `--repo .` and `--repo <absolute>` produce identical
    // fingerprints, so GitHub Code Scanning does not re-key (churn) the alerts
    // when the same repo is analysed with a different invocation style.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let abs = tiny.dir.path();

    let fingerprints = |mut cmd: Command| -> Vec<String> {
        let output = cmd.output().unwrap();
        assert!(
            output.status.success(),
            "stderr: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let sarif: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid SARIF");
        let mut fps: Vec<String> = sarif["runs"][0]["results"]
            .as_array()
            .expect("results array")
            .iter()
            .map(|r| {
                r["partialFingerprints"]["primaryLocationLineHash"]
                    .as_str()
                    .expect("each result carries a primaryLocationLineHash")
                    .to_string()
            })
            .collect();
        fps.sort();
        fps
    };

    let mut abs_cmd = codelore_cmd();
    abs_cmd.args([
        "analyze",
        "--analysis",
        "hotspots",
        "--repo",
        abs.to_str().unwrap(),
        "--format",
        "sarif",
        "--min-revs",
        "1",
    ]);
    let abs_fps = fingerprints(abs_cmd);

    // `--repo .` run from inside the repo — canonicalizes to the same path.
    let mut dot_cmd = codelore_cmd();
    dot_cmd.current_dir(abs).args([
        "analyze",
        "--analysis",
        "hotspots",
        "--repo",
        ".",
        "--format",
        "sarif",
        "--min-revs",
        "1",
    ]);
    let dot_fps = fingerprints(dot_cmd);

    assert!(!abs_fps.is_empty(), "expected at least one SARIF finding");
    assert_eq!(
        abs_fps, dot_fps,
        "SARIF fingerprints must match for `--repo .` and `--repo <absolute>`"
    );
}

#[test]
fn analyze_revisions_emits_json() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "json",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::starts_with("[").or(predicate::str::contains("\"entity\"")));
}

#[test]
fn analyze_hotspots_emits_markdown() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "markdown",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("# CodeLore hotspots"));
}

#[test]
fn analyze_hotspots_emits_parquet() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("hotspots.parquet");
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "parquet",
            "--min-revs",
            "1",
            "--output",
            path.to_str().unwrap(),
        ])
        .assert()
        .success();
    assert!(path.exists(), "parquet file should be written");
    assert!(
        path.metadata().unwrap().len() > 0,
        "parquet file should be non-empty"
    );
}

#[test]
fn analyze_emits_sqlite_dump() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("dump.db");
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "sqlite",
            "--min-revs",
            "1",
            "--output",
            path.to_str().unwrap(),
        ])
        .assert()
        .success();
    assert!(path.exists(), "sqlite file should be written");
}

#[test]
fn analyze_emits_provenance_sidecar_for_csv_output() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("hotspots.csv");
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
            "--output",
            path.to_str().unwrap(),
        ])
        .assert()
        .success();

    let sidecar = dir.path().join("hotspots.csv.provenance.json");
    assert!(sidecar.exists(), "provenance sidecar should be written");
    let body = std::fs::read_to_string(&sidecar).unwrap();
    assert!(
        body.contains("\"codelore_version\""),
        "manifest should include codelore_version"
    );
    assert!(
        body.contains("\"analysis\""),
        "manifest should include analysis"
    );
    assert!(
        body.contains("hotspots"),
        "manifest should record the analysis name"
    );
}

#[test]
fn analyze_emits_provenance_sidecar_for_parquet_output() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("hotspots.parquet");
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "parquet",
            "--min-revs",
            "1",
            "--output",
            path.to_str().unwrap(),
        ])
        .assert()
        .success();

    let sidecar = dir.path().join("hotspots.parquet.provenance.json");
    assert!(
        sidecar.exists(),
        "provenance sidecar should be written next to parquet"
    );
}

#[test]
fn analyze_skips_sidecar_for_sqlite_output() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("dump.db");
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "sqlite",
            "--min-revs",
            "1",
            "--output",
            path.to_str().unwrap(),
        ])
        .assert()
        .success();

    // Provenance is inside the .db (via ATTACH); no sidecar required.
    let sidecar = dir.path().join("dump.db.provenance.json");
    assert!(
        !sidecar.exists(),
        "no sidecar for sqlite — provenance lives in the DB"
    );
}

#[test]
fn analyze_skips_sidecar_for_stdout() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let dir = tempfile::tempdir().unwrap();
    // Run from inside the tempdir so any accidental relative-path sidecar shows up.
    let assert = codelore_cmd()
        .current_dir(dir.path())
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
            // no --output
        ])
        .assert()
        .success();
    drop(assert);

    let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
    let names: Vec<String> = entries
        .into_iter()
        .filter_map(|e| e.ok().and_then(|de| de.file_name().into_string().ok()))
        .collect();
    let has_sidecar = names.iter().any(|n| n.ends_with(".provenance.json"));
    assert!(
        !has_sidecar,
        "stdout output should not create a sidecar: found {names:?}"
    );
}

#[test]
fn parquet_requires_output_flag() {
    // A binary format with no --output is an output-side usage error →
    // CodeLoreError::Output → spec §6.6 exit 5 (not the generic 1).
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "parquet",
            "--min-revs",
            "1",
        ])
        .assert()
        .code(5)
        .stderr(predicate::str::contains("requires --output"));
}

#[test]
fn sarif_rejects_unsupported_analysis() {
    // SARIF support covers {hotspots, clones}.
    // clone-coupling is also covered.
    // `revisions` is still unsupported and must bail with a helpful
    // message naming the supported analyses.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "sarif",
            "--min-revs",
            "1",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains(
            "hotspots, clones, and clone-coupling",
        ))
        .stderr(predicate::str::contains("clones"));
}

#[test]
fn unknown_analysis_lists_supported_names() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "definitelybogus",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
        ])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("invalid value"))
        .stderr(predicate::str::contains("hotspots"))
        .stderr(predicate::str::contains("clones"));
}

// ---------------------------------------------------------------------------
// --no-cache + --cache-dir
// ---------------------------------------------------------------------------

/// `--no-cache` must succeed and produce the same CSV output as the default path.
#[test]
fn no_cache_flag_produces_valid_output() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
            "--no-cache",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("entity,n-revs"))
        .stdout(predicate::str::contains("src/main.rs"));
}

/// `--cache-dir` must succeed and write the cache file under the given dir.
#[test]
fn cache_dir_flag_writes_cache_to_custom_location() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let cache_dir = tempfile::tempdir().expect("tempdir");

    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
            "--cache-dir",
            cache_dir.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("entity,n-revs"));

    // At least one .duckdb file must have been created under the custom cache dir.
    let count = walkdir::WalkDir::new(cache_dir.path())
        .into_iter()
        .flatten()
        .filter(|e| {
            e.path()
                .extension()
                .and_then(|x| x.to_str())
                .is_some_and(|x| x == "duckdb")
        })
        .count();

    assert!(
        count >= 1,
        "expected at least 1 .duckdb file under cache_dir, got {count}"
    );
}

/// `--time-bucket` on an incompatible analysis
/// must be rejected at the CLI boundary with a descriptive error,
/// pointing the user at the supported analyses (coupling, soc,
/// hotspots, code-health). Previously this either crashed with
/// `Catalog Error: changes_bucketed does not exist` or silently
/// returned empty rows.
#[test]
fn time_bucket_rejected_for_incompatible_analysis() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--no-banner",
            "--no-cache",
            "--time-bucket",
            "week",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("--time-bucket is not supported"))
        .stderr(predicate::str::contains(
            "coupling, soc, hotspots, code-health",
        ));
}

/// `--group-file` combined with `function-hotspots` must be rejected at the
/// CLI boundary. Grouping rewrites the `changes` table but discards the hunks
/// of collapsed paths, and `function-hotspots` ranks over the raw `hunks`
/// table — so the ranking would be silently incomplete. Reject loudly (exit 2,
/// `InvalidOptions`) instead.
#[test]
fn group_file_rejected_for_function_hotspots() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let group_file = tiny.dir.path().join("groups.txt");
    std::fs::write(&group_file, "src/.* => src\n").unwrap();
    let output = codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "function-hotspots",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--no-banner",
            "--no-cache",
            "--group-file",
            group_file.to_str().unwrap(),
        ])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("--group-file is not supported for analysis function-hotspots"),
        "expected the group-file rejection message, got stderr: {stderr}"
    );
}

/// Control case: `--time-bucket` on a compatible analysis
/// (coupling) must succeed.
#[test]
fn time_bucket_accepted_for_coupling() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "coupling",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--no-banner",
            "--no-cache",
            "--time-bucket",
            "day",
            "--min-revs",
            "1",
            "--min-shared-revs",
            "1",
        ])
        .assert()
        .success();
}

#[test]
fn unsupported_format_bails_cleanly_instead_of_panicking() {
    // `--format ndjson`/`gha` pass top-level format validation but are only
    // wired for a few analyses. For the rest, the dispatch must bail with a
    // clean, descriptive error — NOT panic through a reachable
    // `unreachable!` (exit 101). An invalid format×analysis combination is a
    // CLI/argument mistake, so it carries CodeLoreError::InvalidOptions → exit
    // 2 (the CLI/arg-error code, unified with an unrecognised `--format`
    // value). Cover ndjson and gha.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    for fmt in ["ndjson", "gha"] {
        codelore_cmd()
            .args([
                "analyze",
                "--analysis",
                "abs-churn",
                "--repo",
                tiny.dir.path().to_str().unwrap(),
                "--format",
                fmt,
                "--no-banner",
                "--min-revs",
                "1",
            ])
            .assert()
            .code(2)
            .stderr(predicate::str::contains("abs-churn"))
            .stderr(predicate::str::contains("panicked").not())
            .stderr(predicate::str::contains("unreachable").not());
    }
}

#[test]
fn unknown_format_exits_with_arg_code() {
    // An unrecognised `--format` value is now rejected at the parser → clap arg
    // error → exit 2 (the documented CLI/arg-error code), listing the supported
    // formats. Previously it reached the analysis layer and exited 4.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "revisions",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "bogusfmt",
            "--no-banner",
            "--min-revs",
            "1",
        ])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("invalid value"))
        .stderr(predicate::str::contains("csv"))
        .stderr(predicate::str::contains("panicked").not());
}

#[test]
fn analyze_warns_when_analysis_scoped_flag_is_ignored() {
    // `--target` is honored only by function-xray/function-coupling. Passing it
    // to another analysis is not an error (scripts may share a flag set), but it
    // must surface a stderr advisory naming the honoring analyses — while the run
    // still succeeds and emits normal output.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
            "--no-banner",
            "--target",
            "src/main.rs",
        ])
        .assert()
        .success()
        .stdout(predicate::str::is_empty().not())
        .stderr(predicate::str::contains("--target"))
        .stderr(predicate::str::contains("function-xray"));
}

#[test]
fn complexity_sample_rejects_unimplemented_values() {
    // `--complexity-sample` advertises only `head` now (its sole implemented
    // strategy). `adaptive`/`full` are rejected honestly at the parser (exit 2)
    // rather than accepted-then-errored with a "not yet available" message.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "hotspots",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--complexity-sample",
            "adaptive",
            "--min-revs",
            "1",
        ])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("invalid value"))
        .stderr(predicate::str::contains("head"));
}

#[test]
fn schema_lists_every_registered_analysis() {
    // The schema row-type catalogue must cover every analysis the
    // registry knows about. `delivery-friction`, `main-dev-by-revs`,
    // and `main-dev-by-deletions` are registered analyses that were
    // missing from the hardcoded catalogue.
    for name in codelore_lib::analysis::AnalysisName::all() {
        codelore_cmd()
            .args(["schema", name.as_str()])
            .assert()
            .success()
            .stderr(predicate::str::contains("unknown row type").not());
    }
}

/// Analyses that intentionally have NO `codelore explain` topic yet —
/// either the formula is too involved to state accurately in one line, or
/// the analysis is low-value for the explain surface. Anti-drift contract:
/// to add a new analysis you must EITHER add an explain entry in
/// `run_explain_cmd` OR add the name here (and document why). A name listed
/// here that later gains an explain topic flips the assertion below, forcing
/// the stale allowlist entry to be removed.
const EXPLAIN_UNCOVERED: &[&str] = &[
    "coupling",
    "author-churn",
    "entity-churn",
    "communication",
    "summary",
    "clones",
    "clone-coupling",
    "messages",
    "main-dev",
    "main-dev-by-revs",
    "main-dev-by-deletions",
    "entity-effort",
    "entity-ownership",
    "top-committers",
    // Newly added analysis: explain topic not yet wired
    "finding-hotspot-overlap",
];

#[test]
fn explain_covers_every_registered_analysis_or_allowlists_it() {
    // Every registered analysis must either resolve to an `explain` topic
    // (exit 0) or be on the explicit uncovered allowlist (exit non-zero
    // with an "unknown topic" message). This stops a newly-added analysis
    // from silently shipping with no explain coverage and no decision
    // recorded about it.
    for name in codelore_lib::analysis::AnalysisName::all() {
        let allowlisted = EXPLAIN_UNCOVERED.contains(&name.as_str());
        let assert = codelore_cmd().args(["explain", name.as_str()]).assert();
        if allowlisted {
            assert
                .failure()
                .stderr(predicate::str::contains("unknown topic"));
        } else {
            assert.success();
        }
    }
}

#[test]
fn explain_unknown_topic_suggests_nearest() {
    // A free-string topic argument (not a clap enum) gets a hand-rolled
    // nearest-match suggestion. `hotspot` is an abbreviation of the real
    // `hotspots` topic.
    codelore_cmd()
        .args(["explain", "hotspot"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("unknown topic"))
        .stderr(predicate::str::contains("did you mean"))
        .stderr(predicate::str::contains("hotspots"));
}

#[test]
fn health_trend_csv_has_header_and_rows() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "health-trend",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "date,rev,files,arch-health,code-health,combined-health,arch-band,code-band,combined-band",
        ))
        // Header alone would pass on empty output — require at least one data row.
        .stdout(predicate::function(|out: &str| {
            out.lines().filter(|l| !l.trim().is_empty()).count() >= 2
        }));
}

#[test]
fn defect_validation_without_artifact_emits_header_only_and_stderr_hint() {
    // No --defect-calibration configured: honest absence, not an error. The
    // CSV header is still written (so downstream tooling gets a valid empty
    // table) with zero data rows, and a one-line hint points at
    // `codelore calibrate-defects` on stderr.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "defect-validation",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("metric,value"))
        // Header only — no data rows without an artifact.
        .stdout(predicate::function(|out: &str| {
            out.lines().filter(|l| !l.trim().is_empty()).count() == 1
        }))
        .stderr(predicate::str::contains("calibrate-defects"));
}

#[test]
fn effort_exposure_csv_has_header_and_rows() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "effort-exposure",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "band,files,loc-share-pct,commit-share-pct,churn-share-pct,commit-share-ci-low,commit-share-ci-high,churn-share-improving-pct,churn-share-degrading-pct",
        ))
        // Header alone would pass on empty output — require at least one data row.
        .stdout(predicate::function(|out: &str| {
            out.lines().filter(|l| !l.trim().is_empty()).count() >= 2
        }));
}

#[test]
fn code_familiarity_csv_has_header() {
    // tiny_repo has no recognized source files → complexity_metrics is empty
    // → no familiarity rows. This test only verifies the CSV header is present.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "code-familiarity",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "scope,familiarity-pct,active-authors,total-authors,islands-pct,verdict",
        ));
}

#[test]
fn code_familiarity_csv_has_header_and_rows() {
    // delivery_repo has src/*.rs files (Rust, Tier-1) → complexity_metrics
    // populated → knowledge_shares materialised → one familiarity row emitted.
    let delivery = codelore_lib::test_support::delivery_repo::build();
    let out = codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "code-familiarity",
            "--repo",
            delivery.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();
    let lines: Vec<&str> = text.lines().collect();
    assert!(
        lines.len() >= 2,
        "expected header + at least one data row, got:\n{text}"
    );
    assert!(
        lines[0].contains("scope") && lines[0].contains("familiarity-pct"),
        "first line must be the CSV header: {}",
        lines[0]
    );
    // Data row: scope=repo, verdict is good or risky, familiarity in [0,100].
    assert!(
        lines[1].starts_with("repo,"),
        "data row must start with 'repo,': {}",
        lines[1]
    );
}

#[test]
fn bus_factor_csv_contains_model_column() {
    // Verify the `model` column is present in both commits and doe mode output.
    let delivery = codelore_lib::test_support::delivery_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "bus-factor",
            "--repo",
            delivery.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "module,total_commits,bus_factor,top_contributor,top_contributor_share,model",
        ));
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "bus-factor",
            "--repo",
            delivery.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
            "--knowledge-model",
            "doe",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "module,total_commits,bus_factor,top_contributor,top_contributor_share,model",
        ))
        .stdout(predicate::str::contains(",doe"));
}

#[test]
fn team_composition_csv_has_header_and_rows() {
    // Verify CSV header columns and that delivery_repo produces author data.
    let delivery = codelore_lib::test_support::delivery_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "team-composition",
            "--repo",
            delivery.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "author,tenure-days,bucket,veteran-breadth-ok,active,commits,files-touched,onboarding-weeks",
        ))
        // The `__summary__` carrier row is not emitted as a CSV data row.
        .stdout(predicate::str::contains("__summary__").not())
        // At least one real per-author row is present — every author falls in
        // one of the three tenure buckets.
        .stdout(
            predicate::str::contains("onboarded")
                .or(predicate::str::contains("experienced"))
                .or(predicate::str::contains("veteran")),
        );
}

#[cfg(feature = "spa")]
#[test]
fn spa_without_output_defaults_to_dot_codelore() {
    // `--format spa` no longer requires --output; it defaults to
    // `.codelore/spa.html` under the current working directory.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let cwd = tempfile::tempdir().unwrap();
    codelore_cmd()
        .current_dir(cwd.path())
        .args([
            "analyze",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "spa",
            "--no-banner",
            "--min-revs",
            "1",
        ])
        .assert()
        .success();
    assert!(
        cwd.path().join(".codelore").join("spa.html").is_file(),
        "spa without --output should create .codelore/spa.html in the cwd"
    );
}

/// The Architecture factor tile's detail line carries the corpus-relative
/// propagation-cost annotation (`, P<nn> of <n> corpus repos`) exactly when
/// the active calibration artifact has repo-level pools: present on the
/// default path (the embedded world artifact carries `repo_metrics`), absent
/// when `--calibration` points at an artifact without the section.
#[cfg(feature = "spa")]
#[test]
fn spa_architecture_tile_corpus_detail_follows_repo_metrics_presence() {
    // The biomarker fixture carries one resolvable HEAD-time import edge
    // (`src/importer.rs → src/trivial.rs`) and enough dated commits for the
    // health-trend series, so the Architecture tile exists and
    // architecture-metrics has a non-empty import graph to rank.
    let fx = codelore_lib::test_support::biomarker_repo::build();

    let arch_detail = |extra_args: &[&str]| -> String {
        let cwd = tempfile::tempdir().unwrap();
        let mut args = vec![
            "analyze",
            "--repo",
            fx.dir.path().to_str().unwrap(),
            "--format",
            "spa",
            "--no-banner",
            "--min-revs",
            "1",
        ];
        args.extend_from_slice(extra_args);
        codelore_cmd()
            .current_dir(cwd.path())
            .args(&args)
            .assert()
            .success();
        let html = std::fs::read_to_string(cwd.path().join(".codelore").join("spa.html"))
            .expect("spa.html emitted");

        let start_tag = "<script type=\"application/json\" id=\"codelore-data\">";
        let start = html.find(start_tag).expect("embedded data script") + start_tag.len();
        let end = html[start..].find("</script>").expect("script close");
        let payload: serde_json::Value =
            serde_json::from_str(&html[start..start + end].replace(r"<\/", "</"))
                .expect("payload parses");
        payload["factors"]
            .as_array()
            .expect("factors array present")
            .iter()
            .find(|t| t["name"] == "Architecture")
            .expect("Architecture tile present")["detail"]
            .as_str()
            .expect("detail is a string")
            .to_owned()
    };

    // Default path: the embedded world artifact carries repo_metrics.
    let detail = arch_detail(&[]);
    assert!(
        detail.contains("corpus"),
        "embedded artifact has repo_metrics -> detail must carry the corpus annotation: {detail:?}"
    );

    // Override with an artifact that has no repo_metrics section: the
    // annotation must degrade to absent.
    let artifact = codelore_lib::calibration::CalibrationArtifact {
        format_version: codelore_lib::calibration::CALIBRATION_FORMAT_VERSION,
        corpus_vintage: "test-corpus-no-pools".to_string(),
        generated_at: "2026-07-14T00:00:00Z".to_string(),
        repos_included: 1,
        repos_attempted: 1,
        languages: vec![],
        repo_metrics: None,
    };
    let work = tempfile::tempdir().unwrap();
    let calib_path = work.path().join("no-pools.calib.json");
    std::fs::write(&calib_path, serde_json::to_vec(&artifact).unwrap()).unwrap();

    let detail = arch_detail(&["--calibration", calib_path.to_str().unwrap()]);
    assert!(
        !detail.contains("corpus"),
        "artifact without repo_metrics -> detail must not carry the corpus annotation: {detail:?}"
    );
}

// ---------------------------------------------------------------------------
// Delta health end-to-end tests
// ---------------------------------------------------------------------------

/// Build a two-commit repo: commit 1 has a trivial function, commit 2
/// adds a large, branchy function. Returns `(dir, base_sha, head_sha)`.
fn delta_health_fixture() -> (tempfile::TempDir, String, String) {
    use std::fmt::Write as _;
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path();
    let git = |args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?}: {out:?}");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    };
    git(&["init", "-q"]);
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(
        repo.join("src/lib.rs"),
        "pub fn tiny() -> i32 {\n    1\n}\n",
    )
    .unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "base"]);
    let base = git(&["rev-parse", "HEAD"]);

    // A >70-line, CC>10 function: 12 sequential if-blocks + filler lets
    // both the LOC and cyclomatic High thresholds trigger.
    let mut monster = String::from("pub fn monster(x: i32) -> i32 {\n    let mut acc = 0;\n");
    for i in 0..12 {
        let _ = write!(monster, "    if x > {i} {{\n        acc += {i};\n    }}\n");
    }
    for i in 0..40 {
        let _ = writeln!(monster, "    acc += {i};");
    }
    monster.push_str("    acc\n}\n");
    std::fs::write(
        repo.join("src/lib.rs"),
        format!("pub fn tiny() -> i32 {{\n    1\n}}\n\n{monster}"),
    )
    .unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "add monster"]);
    let head = git(&["rev-parse", "HEAD"]);
    (dir, base, head)
}

#[test]
fn diff_emits_degrading_delta_health_for_added_monster() {
    let (dir, base, head) = delta_health_fixture();
    let output = codelore_cmd()
        .args([
            "diff",
            "--repo",
            dir.path().to_str().unwrap(),
            "--min-revs",
            "1",
            "--format",
            "json",
            &format!("{base}..{head}"),
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    let dh = &json["delta_health"];
    assert_eq!(dh["verdict"], "degrading", "delta_health: {dh}");
    assert_eq!(dh["counts"]["added"].as_u64(), Some(1));
    let f = &dh["functions"][0];
    assert_eq!(f["function"], "monster");
    assert_eq!(f["after"], "high");
    assert_eq!(f["outcome"], "bad");
}

#[test]
fn diff_delta_health_gate_fails_the_run() {
    let (dir, base, head) = delta_health_fixture();
    let thresholds = dir.path().join("gates.toml");
    std::fs::write(&thresholds, "[diff]\ndeny_degrading_verdict = true\n").unwrap();
    let output = codelore_cmd()
        .args([
            "diff",
            "--repo",
            dir.path().to_str().unwrap(),
            "--min-revs",
            "1",
            "--thresholds-file",
            thresholds.to_str().unwrap(),
            "--format",
            "json",
            &format!("{base}..{head}"),
        ])
        .output()
        .unwrap();
    assert_eq!(
        output.status.code(),
        Some(1),
        "deny_degrading_verdict should fail the run via a gate violation (exit 1); stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert!(
        json["gate_violations"]
            .as_array()
            .unwrap()
            .iter()
            .any(|v| v["gate"] == "deny_degrading_verdict"),
        "violations: {}",
        json["gate_violations"]
    );
}

#[test]
fn diff_degenerate_thresholds_file_exits_with_config_code() {
    // A thresholds file with an out-of-range value is a configuration error →
    // CodeLoreError::InvalidOptions → exit 2, the same as `check`/`gate`. The
    // diff path used to flatten the typed error through `anyhow!` and exit 1.
    let (dir, base, head) = delta_health_fixture();
    let thresholds = dir.path().join("bad-thresholds.toml");
    std::fs::write(&thresholds, "[gates]\ncode_health_min = 200.0\n").unwrap();
    codelore_cmd()
        .args([
            "diff",
            "--repo",
            dir.path().to_str().unwrap(),
            "--min-revs",
            "1",
            "--thresholds-file",
            thresholds.to_str().unwrap(),
            &format!("{base}..{head}"),
        ])
        .assert()
        .code(2);
}

#[test]
fn diff_docs_only_change_is_no_code_change() {
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path();
    let git = |args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?}: {out:?}");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    };
    git(&["init", "-q"]);
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(
        repo.join("src/lib.rs"),
        "pub fn tiny() -> i32 {\n    1\n}\n",
    )
    .unwrap();
    std::fs::write(repo.join("README.md"), "hello\n").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "base"]);
    let base = git(&["rev-parse", "HEAD"]);
    std::fs::write(repo.join("README.md"), "hello world\n").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "docs"]);
    let head = git(&["rev-parse", "HEAD"]);

    let output = codelore_cmd()
        .args([
            "diff",
            "--repo",
            repo.to_str().unwrap(),
            "--min-revs",
            "1",
            "--format",
            "json",
            &format!("{base}..{head}"),
        ])
        .output()
        .unwrap();
    assert!(output.status.success());
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["delta_health"]["verdict"], "no-code-change");
    assert!(json["delta_health"]["ratio"].is_null());
}

/// Two-commit repo where `src/lib.rs` is identical at base and head (only
/// `README.md` changes between them) — the "populated-unchanged" fixture:
/// real commit history, real (non-empty) hotspot rows at both revisions,
/// zero code delta. Distinct from a blind ingest, which empties the hotspot
/// row SET itself rather than just the delta between two populated sets.
fn unchanged_code_fixture() -> (tempfile::TempDir, String, String) {
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path();
    let git = |args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?}: {out:?}");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    };
    git(&["init", "-q"]);
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(
        repo.join("src/lib.rs"),
        "pub fn tiny() -> i32 {\n    1\n}\n",
    )
    .unwrap();
    std::fs::write(repo.join("README.md"), "hello\n").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "base"]);
    let base = git(&["rev-parse", "HEAD"]);
    std::fs::write(repo.join("README.md"), "hello world\n").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "docs"]);
    let head = git(&["rev-parse", "HEAD"]);
    (dir, base, head)
}

#[test]
fn diff_gate_passes_on_populated_unchanged_range() {
    // A genuinely unchanged range with REAL (non-empty) hotspot rows at both
    // revisions must keep today's verdict byte-identical: no violations, and
    // — the case this fix must not regress — no skip disclosure either, since
    // real data was measured on both sides.
    let (dir, base, head) = unchanged_code_fixture();
    let thresholds = dir.path().join("gates.toml");
    std::fs::write(&thresholds, "[diff]\nno_new_cycles = true\n").unwrap();
    let output = codelore_cmd()
        .args([
            "diff",
            "--repo",
            dir.path().to_str().unwrap(),
            "--min-revs",
            "1",
            "--thresholds-file",
            thresholds.to_str().unwrap(),
            "--format",
            "json",
            &format!("{base}..{head}"),
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    // `gate_violations` is omitted from the JSON document entirely when
    // empty (`skip_serializing_if = "Vec::is_empty"`), so its absence IS the
    // empty-violations case.
    assert!(
        json.get("gate_violations").is_none(),
        "unchanged code ⇒ no violations: {json}"
    );
    assert!(
        json.get("gate_skip_reason").is_none(),
        "real rows on both sides ⇒ never a skip: {json}"
    );
}

#[test]
fn diff_gate_skipped_when_neither_revision_measures_any_hotspot_row() {
    // A `--min-revs` floor above every file's revision count empties the
    // hotspot row set at BOTH revisions — the same shape a blind ingest (a
    // shallow checkout) produces. Every scalar evaluate_diff_gate would see
    // (new_hotspot_count, delta_code_health, cycle counts) reads identically
    // to a genuinely unchanged repo; the gate must disclose a skip instead of
    // a silent pass, and must not fail the run (exit code unaffected).
    let (dir, base, head) = unchanged_code_fixture();
    let thresholds = dir.path().join("gates.toml");
    std::fs::write(&thresholds, "[diff]\nno_new_cycles = true\n").unwrap();
    let output = codelore_cmd()
        .args([
            "diff",
            "--repo",
            dir.path().to_str().unwrap(),
            "--min-revs",
            "50",
            "--thresholds-file",
            thresholds.to_str().unwrap(),
            "--format",
            "json",
            &format!("{base}..{head}"),
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "a skip must not fail the run — stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    // Omitted entirely when empty — see the sibling test's comment.
    assert!(
        json.get("gate_violations").is_none(),
        "nothing measured ⇒ no violations either: {json}"
    );
    let reason = json["gate_skip_reason"]
        .as_str()
        .expect("gate_skip_reason must be a disclosed string, not null");
    assert!(
        reason.contains("blind ingest"),
        "reason must name the cause: {reason}"
    );

    // The text format must surface the same skip, not silence.
    let text_output = codelore_cmd()
        .args([
            "diff",
            "--repo",
            dir.path().to_str().unwrap(),
            "--min-revs",
            "50",
            "--thresholds-file",
            thresholds.to_str().unwrap(),
            &format!("{base}..{head}"),
        ])
        .output()
        .unwrap();
    assert!(text_output.status.success());
    let stdout = String::from_utf8(text_output.stdout).unwrap();
    assert!(
        stdout.contains("SKIPPED"),
        "text format must disclose the skip: {stdout}"
    );
    assert!(
        !stdout.contains("VIOLATION"),
        "a skip is not a violation: {stdout}"
    );
}

#[test]
fn gate_delta_per_file_records_skipped_when_no_delta_is_measured() {
    // A working tree whose only change is a non-source file carries no
    // computable per-file health delta, so `delta_code_health_min_per_file`
    // measured nothing. Its gate-run verdict must be recorded "skipped" — not
    // the "passed" that keying "measured" off a merely-non-empty change-set
    // would wrongly record. Observed through the gate-run ledger via
    // `codelore check --history` over a shared `--cache-dir`.
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path();
    let cache = repo.join("cache");
    let git = |args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?}: {out:?}");
    };
    git(&["init", "-q"]);
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(
        repo.join("src/lib.rs"),
        "pub fn tiny() -> i32 {\n    1\n}\n",
    )
    .unwrap();
    std::fs::write(repo.join("README.md"), "hello\n").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "base"]);
    // Uncommitted modification to a tracked non-source file: the change-set is
    // non-empty, yet the file yields no code-health delta (delta = None).
    std::fs::write(repo.join("README.md"), "hello world\n").unwrap();
    std::fs::write(
        repo.join(".codelore-thresholds.toml"),
        "[diff]\ndelta_code_health_min_per_file = 0.0\n",
    )
    .unwrap();

    // The gate passes (no violation) but records the ledger verdict.
    codelore_cmd()
        .args([
            "gate",
            "--repo",
            repo.to_str().unwrap(),
            "--cache-dir",
            cache.to_str().unwrap(),
        ])
        .assert()
        .success();

    let history = codelore_cmd()
        .args([
            "check",
            "--history",
            "--repo",
            repo.to_str().unwrap(),
            "--cache-dir",
            cache.to_str().unwrap(),
        ])
        .output()
        .unwrap();
    assert!(history.status.success());
    let text = String::from_utf8_lossy(&history.stdout);
    assert!(
        text.contains("delta_code_health_min_per_file"),
        "the configured gate must appear in the ledger: {text}"
    );
    assert!(
        text.contains("skipped"),
        "an all-None change-set measures nothing, so the verdict is skipped: {text}"
    );
    assert!(
        !text.contains("passed"),
        "the pre-fix behaviour wrongly recorded passed here: {text}"
    );
}

#[test]
fn diff_fail_on_skipped_fails_a_skipped_gate_family() {
    // The blind-ingest skip from `diff_gate_skipped_when_neither_revision_...`
    // (a `--min-revs` floor above every file empties the hotspot set at both
    // revisions), but with `fail_on_skipped = true`: the skipped `[diff]` gate
    // family must now fail the run through diff's violation exit (code 1)
    // instead of passing. The default-false counterpart (exit 0) is that
    // sibling test, which runs the identical range without the policy.
    let (dir, base, head) = unchanged_code_fixture();
    let thresholds = dir.path().join("gates.toml");
    std::fs::write(
        &thresholds,
        "[gates]\nfail_on_skipped = true\n[diff]\nno_new_cycles = true\n",
    )
    .unwrap();
    let output = codelore_cmd()
        .args([
            "diff",
            "--repo",
            dir.path().to_str().unwrap(),
            "--min-revs",
            "50",
            "--thresholds-file",
            thresholds.to_str().unwrap(),
            "--format",
            "json",
            &format!("{base}..{head}"),
        ])
        .output()
        .unwrap();
    assert_eq!(
        output.status.code(),
        Some(1),
        "fail_on_skipped must fail a skipped gate via diff's exit 1; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    // The skip stays disclosed in the (already-emitted) JSON document.
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert!(
        json["gate_skip_reason"].as_str().is_some(),
        "the skip stays disclosed even when it now fails: {json}"
    );
}

#[test]
fn check_fail_on_skipped_fails_a_skipped_gate() {
    // `max_findings_in_hot_files` with no external-findings sidecar is recorded
    // "skipped". By default that skip does not fail the run; with
    // `fail_on_skipped = true` it must (check's exit 1).
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let thresholds = tiny.dir.path().join(".codelore-thresholds.toml");

    // Default: the skipped gate does not fail the run.
    std::fs::write(&thresholds, "[gates]\nmax_findings_in_hot_files = 0\n").unwrap();
    codelore_cmd()
        .args(["check", "--repo", tiny.dir.path().to_str().unwrap()])
        .assert()
        .success();

    // fail_on_skipped=true: the same skipped gate now fails.
    std::fs::write(
        &thresholds,
        "[gates]\nmax_findings_in_hot_files = 0\nfail_on_skipped = true\n",
    )
    .unwrap();
    codelore_cmd()
        .args(["check", "--repo", tiny.dir.path().to_str().unwrap()])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("FAIL"));
}

#[test]
fn gate_fail_on_skipped_fails_an_all_none_change_set() {
    // The M4 scenario (a non-source change yields no per-file delta →
    // delta_code_health_min_per_file is "skipped") combined with
    // `fail_on_skipped = true`: the gate must now fail (exit 1) instead of
    // passing. Without the policy the identical change-set passes (exit 0),
    // asserted first.
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path();
    let git = |args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?}: {out:?}");
    };
    git(&["init", "-q"]);
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(
        repo.join("src/lib.rs"),
        "pub fn tiny() -> i32 {\n    1\n}\n",
    )
    .unwrap();
    std::fs::write(repo.join("README.md"), "hello\n").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "base"]);
    // Uncommitted non-source change: change-set non-empty, delta = None.
    std::fs::write(repo.join("README.md"), "hello world\n").unwrap();
    let thresholds = repo.join(".codelore-thresholds.toml");

    // Default: the skipped per-file gate does not fail the run.
    std::fs::write(
        &thresholds,
        "[diff]\ndelta_code_health_min_per_file = 0.0\n",
    )
    .unwrap();
    codelore_cmd()
        .args(["gate", "--repo", repo.to_str().unwrap()])
        .assert()
        .success();

    // fail_on_skipped=true: the same skip now fails the gate.
    std::fs::write(
        &thresholds,
        "[gates]\nfail_on_skipped = true\n[diff]\ndelta_code_health_min_per_file = 0.0\n",
    )
    .unwrap();
    codelore_cmd()
        .args(["gate", "--repo", repo.to_str().unwrap()])
        .assert()
        .failure()
        .code(1);
}

#[test]
fn diff_sarif_schema_url_and_info_uri_use_canonical_constants() {
    // The diff SARIF schema URL and informationUri must use the constants from
    // codelore_lib::output::sarif, and degrading delta-health results must carry
    // codeFlows evidence chains (the monster function has one head commit).
    let (dir, base, head) = delta_health_fixture();
    let output = codelore_cmd()
        .args([
            "diff",
            "--repo",
            dir.path().to_str().unwrap(),
            "--min-revs",
            "1",
            "--format",
            "sarif",
            &format!("{base}..{head}"),
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let sarif: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid SARIF");

    // (a) schema URL must match the canonical constant from sarif.rs
    assert_eq!(
        sarif["$schema"], "https://json.schemastore.org/sarif-2.1.0.json",
        "wrong $schema"
    );

    // (b) informationUri must match the canonical constant from sarif.rs
    assert_eq!(
        sarif["runs"][0]["tool"]["driver"]["informationUri"], "https://github.com/emrecdr/codelore",
        "wrong informationUri"
    );

    // (c) The degrading delta-health result for src/lib.rs (monster function)
    // must carry at least one codeFlow with a threadFlow containing locations.
    let results = sarif["runs"][0]["results"]
        .as_array()
        .expect("results array");
    let degrading: Vec<_> = results
        .iter()
        .filter(|r| r["ruleId"] == "CODELORE-DELTA-HEALTH")
        .collect();
    assert!(
        !degrading.is_empty(),
        "expected at least one CODELORE-DELTA-HEALTH result (monster function)"
    );
    let r = degrading[0];
    let code_flows = r["codeFlows"]
        .as_array()
        .expect("codeFlows array on degrading result");
    assert!(
        !code_flows.is_empty(),
        "degrading result must carry at least one codeFlow"
    );
    let thread_flows = code_flows[0]["threadFlows"]
        .as_array()
        .expect("threadFlows array");
    assert!(
        !thread_flows.is_empty(),
        "codeFlow must have at least one threadFlow"
    );
    let locations = thread_flows[0]["locations"]
        .as_array()
        .expect("locations array");
    assert!(
        !locations.is_empty(),
        "threadFlow must have at least one location (evidence commit)"
    );

    // (d) The degrading result must also carry relatedLocations (plain location
    // array — the GitHub inline annotation panel source, distinct from codeFlows).
    let related = r["relatedLocations"]
        .as_array()
        .expect("relatedLocations array on degrading result");
    assert!(
        !related.is_empty(),
        "degrading result must carry at least one relatedLocation"
    );
    // relatedLocations entries are plain location objects (no "location" wrapper).
    assert!(
        related[0].get("physicalLocation").is_some(),
        "relatedLocations entry must have physicalLocation directly (no wrapper)"
    );
}

#[test]
fn diff_sarif_hotspot_rank_entrant_carries_code_flows_and_related_locations() {
    // Build a fixture where the base has no Rust files (no hotspots at base)
    // and the head introduces a Rust file that was changed twice — guaranteeing
    // it enters the hotspot list as a rank_entrant with ≥1 evidence commit.
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path();
    let git = |args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?}: {out:?}");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    };

    // base: no Rust files → no hotspots at base revision
    git(&["init", "-q"]);
    std::fs::write(repo.join("README.md"), "hello\n").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "base: no rust"]);
    let base = git(&["rev-parse", "HEAD"]);

    // head: src/hot.rs added and then changed — 2 revisions, enters hotspot list
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(repo.join("src/hot.rs"), "pub fn first() -> u32 { 1 }\n").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "feat: add hot file"]);

    std::fs::write(
        repo.join("src/hot.rs"),
        "pub fn first() -> u32 { 2 }\npub fn second() -> u32 { 3 }\n",
    )
    .unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "feat: extend hot file"]);
    let head = git(&["rev-parse", "HEAD"]);

    let output = codelore_cmd()
        .args([
            "diff",
            "--repo",
            repo.to_str().unwrap(),
            "--min-revs",
            "1",
            "--format",
            "sarif",
            &format!("{base}..{head}"),
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let sarif: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid SARIF");
    let results = sarif["runs"][0]["results"]
        .as_array()
        .expect("results array");

    // There must be at least one CODELORE-HOTSPOT rank-entrant result.
    let hotspot_results: Vec<_> = results
        .iter()
        .filter(|r| r["ruleId"] == "CODELORE-HOTSPOT")
        .collect();
    assert!(
        !hotspot_results.is_empty(),
        "expected ≥1 CODELORE-HOTSPOT rank-entrant result for src/hot.rs"
    );

    let r = hotspot_results[0];

    // Must carry codeFlows with at least one evidence location.
    let code_flows = r["codeFlows"]
        .as_array()
        .expect("codeFlows must be present on hotspot rank-entrant");
    assert!(!code_flows.is_empty(), "codeFlows must be non-empty");
    let tfl = code_flows[0]["threadFlows"][0]["locations"]
        .as_array()
        .expect("threadFlows[0].locations");
    assert!(
        !tfl.is_empty(),
        "hotspot result must carry at least one evidence commit in codeFlows"
    );

    // Must carry relatedLocations — plain location objects, no "location" wrapper.
    let related = r["relatedLocations"]
        .as_array()
        .expect("relatedLocations must be present on hotspot rank-entrant");
    assert!(
        !related.is_empty(),
        "hotspot result must carry at least one relatedLocation"
    );
    assert!(
        related[0].get("physicalLocation").is_some(),
        "relatedLocations entry must have physicalLocation directly (no wrapper)"
    );

    // Sanity: no stray "module" key on threadFlowLocations (was a spec error).
    assert!(
        tfl[0].get("module").is_none(),
        "threadFlowLocation must not carry 'module' (message_head goes in location.message.text)"
    );

    // partialFingerprints: both dedup keys must match the shared recipes.
    // primaryLocationLineHash must equal the check recipe for the same path.
    assert_diff_fingerprints(r, repo, "CODELORE-HOTSPOT", "src/hot.rs", "rank-entrant");
}

/// Assert a diff SARIF `result` carries both dedup fingerprint keys and that
/// each matches its shared recipe: `primaryLocationLineHash` = the check recipe
/// `sha256(canonical_repo_root|path)`, `diffFinding/v1` =
/// `sha256(rule|path|discriminant)`.
fn assert_diff_fingerprints(
    result: &serde_json::Value,
    repo: &std::path::Path,
    rule: &str,
    path: &str,
    discriminant: &str,
) {
    let fps = result["partialFingerprints"]
        .as_object()
        .expect("diff result must carry partialFingerprints");

    let canonical_root = repo.canonicalize().unwrap();
    let expected_primary = codelore_lib::output::sarif::primary_location_line_hash(
        &canonical_root.to_string_lossy(),
        path,
    );
    assert_eq!(
        fps.get("primaryLocationLineHash").and_then(|v| v.as_str()),
        Some(expected_primary.as_str()),
        "diff primaryLocationLineHash must match the check recipe sha256(repo_root|path)"
    );

    let expected_diff = codelore_lib::output::sarif::diff_finding_hash(rule, path, discriminant);
    assert_eq!(
        fps.get("diffFinding/v1").and_then(|v| v.as_str()),
        Some(expected_diff.as_str()),
        "diffFinding/v1 must be sha256(rule|path|discriminant)"
    );
}

const CLONE_ORIGINAL_SRC: &str = "\
pub fn original(x: i32) -> i32 {
    let mut acc = 0;
    if x > 0 {
        acc += 1;
    } else {
        acc -= 1;
    }
    if x > 10 {
        acc += 2;
    } else {
        acc -= 2;
    }
    if x > 20 {
        acc += 3;
    } else {
        acc -= 3;
    }
    if x > 30 {
        acc += 4;
    } else {
        acc -= 4;
    }
    if x > 40 {
        acc += 5;
    } else {
        acc -= 5;
    }
    acc
}
";
const CLONE_PASTED_COPY_SRC: &str = "\
pub fn pasted_copy(y: i64) -> i64 {
    let mut total = 0;
    if y > 0 {
        total += 1;
    } else {
        total -= 1;
    }
    if y > 10 {
        total += 2;
    } else {
        total -= 2;
    }
    if y > 20 {
        total += 3;
    } else {
        total -= 3;
    }
    if y > 30 {
        total += 4;
    } else {
        total -= 4;
    }
    if y > 40 {
        total += 5;
    } else {
        total -= 5;
    }
    total
}
";

/// Validates the clone→high-risk penalty through the real ingest pipeline.
///
/// Base commit: `src/lib.rs` with one named function `original`.
/// Head commit: add `src/copy.rs` with `pasted_copy` — a structural
/// Type-2 clone (same AST shape, different identifiers/types). The body
/// has five if/else blocks, giving it well over 30 structural nodes so it
/// clears the default `min_clone_node_count` filter.
///
/// The assertion proves that the clone extractor's function name (`pasted_copy`,
/// from the first identifier child of `function_item`) matches the complexity
/// name (stripped of the `@start-end` span by `run_function_metrics`) — the
/// alignment invariant that makes the clone penalty reachable in practice.
#[test]
fn diff_delta_health_flags_pasted_clone_as_high_risk() {
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path();
    let git = |args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?}: {out:?}");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    };

    // Base commit: one small function in src/lib.rs.  The original is also
    // the template whose structure will be duplicated in the head commit.
    git(&["init", "-q"]);
    std::fs::create_dir_all(repo.join("src")).unwrap();
    // Five if/else blocks — structurally rich enough to produce > 30
    // fingerprint nodes (the default min_clone_node_count).
    std::fs::write(repo.join("src/lib.rs"), CLONE_ORIGINAL_SRC).unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "base"]);
    let base = git(&["rev-parse", "HEAD"]);

    // Head commit: add src/copy.rs with pasted_copy — same structure,
    // different name and types (Type-2 clone).
    std::fs::write(repo.join("src/copy.rs"), CLONE_PASTED_COPY_SRC).unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "paste copy"]);
    let head = git(&["rev-parse", "HEAD"]);

    let output = codelore_cmd()
        .args([
            "diff",
            "--repo",
            repo.to_str().unwrap(),
            "--min-revs",
            "1",
            "--format",
            "json",
            &format!("{base}..{head}"),
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    let dh = &json["delta_health"];

    // pasted_copy is added in src/copy.rs — find it in the functions list.
    let fns = dh["functions"].as_array().expect("functions array");
    let pasted = fns
        .iter()
        .find(|f| f["function"] == "pasted_copy")
        .unwrap_or_else(|| panic!("pasted_copy not found in delta_health.functions; got: {fns:?}"));

    // Clone membership forces High regardless of LOC/cyclomatic.
    assert_eq!(
        pasted["after"], "high",
        "pasted_copy must be classified high-risk (clone penalty); row: {pasted}"
    );

    // reasons must mention the clone group.
    let reasons = pasted["reasons"].as_array().expect("reasons array");
    assert!(
        reasons
            .iter()
            .any(|r| r.as_str().unwrap_or("").contains("clone")),
        "reasons must mention clone membership; got: {reasons:?}"
    );
}

#[test]
fn coordination_needs_csv_has_header_and_rows() {
    // delivery_repo has src/*.rs Rust files → complexity ingest fires →
    // knowledge_shares materialised → coordination-needs rows produced.
    let delivery = codelore_lib::test_support::delivery_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "coordination-needs",
            "--repo",
            delivery.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "path,authors,fragmentation,interleave,cochange-entropy,tier,health-band,total-commits",
        ))
        // Header alone would pass on empty output — require at least one data row.
        .stdout(predicate::function(|out: &str| {
            out.lines().filter(|l| !l.trim().is_empty()).count() >= 2
        }));
}

#[test]
fn release_cadence_csv_has_header_and_rows() {
    // delivery_repo has v0.1.0, v0.2.0, v1.0.0 tags → 3 rows + summary.
    let delivery = codelore_lib::test_support::delivery_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "release-cadence",
            "--repo",
            delivery.dir.path().to_str().unwrap(),
            "--format",
            "csv",
            "--release-tag-glob",
            "v*",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("tag,date,days-since-prev,trend"))
        // Header + 3 tag rows + 1 summary row = ≥4 non-empty lines.
        .stdout(predicate::function(|out: &str| {
            out.lines().filter(|l| !l.trim().is_empty()).count() >= 4
        }));
}

#[test]
fn delivery_metrics_markdown_exits_zero() {
    // delivery_repo has two --no-ff merges and two author→committer gaps;
    // run with include_merges so the commit_parents table is populated.
    let delivery = codelore_lib::test_support::delivery_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "delivery-metrics",
            "--repo",
            delivery.dir.path().to_str().unwrap(),
            "--format",
            "markdown",
            "--include-merges",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("delivery-metrics"))
        .stdout(predicate::str::contains("branch_duration_hours"));
}

#[test]
fn check_quiet_suppresses_vacuous_pass_noise() {
    // Without a thresholds file the check vacuously passes and prints a
    // diagnostic to stderr. With --quiet that diagnostic is suppressed;
    // exit 0 is preserved.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args([
            "check",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--quiet",
        ])
        .assert()
        .success()
        .stderr(predicate::str::is_empty());
}

#[test]
fn check_without_quiet_prints_vacuous_pass_diagnostic() {
    // Without --quiet the vacuous-pass diagnostic appears on stderr so users
    // know the check did nothing.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args(["check", "--repo", tiny.dir.path().to_str().unwrap()])
        .assert()
        .success()
        .stderr(predicate::str::contains("vacuously passing"));
}

#[test]
fn function_xray_emits_markdown_header() {
    let repo = codelore_lib::test_support::function_xray_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "function-xray",
            "--repo",
            repo.dir.path().to_str().unwrap(),
            "--target",
            "src/target.rs",
            "--format",
            "markdown",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("# CodeLore function-xray"));
}

#[test]
fn function_coupling_emits_markdown_header() {
    let repo = codelore_lib::test_support::function_xray_repo::build();
    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "function-coupling",
            "--repo",
            repo.dir.path().to_str().unwrap(),
            "--target",
            "src/target.rs",
            "--format",
            "markdown",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("# CodeLore function-coupling"));
}

#[test]
fn check_quiet_violation_path_suppresses_detail_keeps_verdict() {
    // When gates are configured and violations occur, --quiet suppresses the
    // per-violation detail lines on stderr but preserves the FAIL verdict line
    // and exits 1.
    //
    // code_health_min = 100.0 is set impossibly high so every file in the repo
    // is a violation. code-health runs regardless of --min-revs so tiny_repo
    // (whose files don't reach the default min_revs = 5 threshold used by the
    // hotspot gate) still produces evaluable rows.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let thresholds = tiny.dir.path().join(".codelore-thresholds.toml");
    std::fs::write(&thresholds, "[gates]\ncode_health_min = 100.0\n").unwrap();
    codelore_cmd()
        .args([
            "check",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--quiet",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("FAIL"))
        // Per-violation detail lines name the gate; --quiet must suppress them.
        .stderr(predicate::str::contains("code_health_min").not());
}

#[test]
fn check_format_sarif_emits_valid_sarif_and_exits_1() {
    // `code_health_min = 100.0` is impossibly high so the gate always fires
    // against biomarker_repo, producing at least one per-file violation.
    // With --format sarif:
    //   - exit code must still be 1 (violations are present)
    //   - stdout must be a valid SARIF document with ≥1 result
    //   - the FAIL verdict goes to stderr (not stdout)
    // Note: a PASS produces a zero-result SARIF document on stdout (valid;
    // stderr gets the PASS verdict). This is intentional — the caller decides
    // whether an empty result set is interesting.
    let repo = codelore_lib::test_support::biomarker_repo::build();
    let thresholds = repo.dir.path().join(".codelore-thresholds.toml");
    std::fs::write(&thresholds, "[gates]\ncode_health_min = 100.0\n").unwrap();

    let output = codelore_cmd()
        .args([
            "check",
            "--repo",
            repo.dir.path().to_str().unwrap(),
            "--format",
            "sarif",
        ])
        .output()
        .expect("run codelore check --format sarif");

    // Exit code 1 — gate violation semantics unchanged by format.
    assert!(
        !output.status.success(),
        "expected exit 1 for gate violation, got {}",
        output.status
    );

    // stdout is valid SARIF with ≥1 result.
    let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("stdout must be valid JSON SARIF");
    assert_eq!(
        parsed["version"].as_str().unwrap(),
        "2.1.0",
        "SARIF version must be 2.1.0"
    );
    let results = parsed["runs"][0]["results"].as_array().unwrap();
    assert!(
        !results.is_empty(),
        "expected ≥1 SARIF result for code_health_min violation"
    );

    // The FAIL verdict line goes to stderr (stdout stays clean JSON).
    let stderr = String::from_utf8(output.stderr).expect("stderr is utf-8");
    assert!(
        stderr.contains("FAIL"),
        "FAIL verdict must appear on stderr even with --format sarif"
    );
}

#[test]
fn check_default_format_is_text_not_json() {
    // Omitting --format must yield text output (the PASS/FAIL verdict on
    // stdout/stderr), not a JSON/SARIF document. Verifies that the
    // default_value_t = CheckFormat::Text contract holds end-to-end.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let output = codelore_cmd()
        .args(["check", "--repo", tiny.dir.path().to_str().unwrap()])
        .output()
        .expect("run codelore check without --format");

    // Exit 0 — tiny_repo has no thresholds file → vacuous pass.
    assert!(output.status.success(), "expected exit 0 for vacuous pass");

    // stdout must not be JSON (text mode doesn't print SARIF to stdout).
    let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");
    assert!(
        serde_json::from_str::<serde_json::Value>(&stdout).is_err(),
        "stdout must not be a JSON document in text mode, got: {stdout}"
    );
}

/// A monster function: nested loops + match + boolean conditionals so its
/// cyclomatic / cognitive / nesting / bool-op counts dominate the fixture,
/// making the appended-to file's projected code-health score strictly worse
/// than its HEAD baseline.
const GATE_MONSTER_FN: &str = r"
fn monster(x: i32) -> i32 {
    let mut acc = 0;
    for a in 0..x {
        if a % 2 == 0 && a % 3 == 0 || a % 5 == 0 {
            for b in 0..a {
                if b > 1 {
                    match b % 4 {
                        0 => { if b > 10 { acc += 1; } else { acc += 2; } }
                        1 => { while acc < 100 { acc += 1; if acc % 7 == 0 { break; } } }
                        2 => { for c in 0..b { if c > 3 && c < 9 || c == 5 { acc += c; } } }
                        _ => { if a > b { acc -= 1; } else { acc += 1; } }
                    }
                }
            }
        }
    }
    acc
}
";

/// Append `text` to the file at `path`.
fn append_to_file(path: &std::path::Path, text: &str) {
    let mut content = std::fs::read_to_string(path).expect("read file");
    content.push_str(text);
    std::fs::write(path, content).expect("write file");
}

/// Write a scratch thresholds file with `body` into its own tempdir and
/// return the guard plus the file path (the guard keeps the dir alive).
fn scratch_thresholds(body: &str) -> (tempfile::TempDir, std::path::PathBuf) {
    let dir = tempfile::tempdir().expect("thresholds tempdir");
    let path = dir.path().join("gate-thresholds.toml");
    std::fs::write(&path, body).expect("write thresholds");
    (dir, path)
}

#[test]
fn gate_vacuous_passes_without_thresholds() {
    // Without a thresholds file the gate vacuously passes with the same
    // diagnostic contract as `check` (wording substitutes "gate"); exit 0.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    codelore_cmd()
        .args(["gate", "--repo", tiny.dir.path().to_str().unwrap()])
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "codelore gate: no thresholds configured",
        ))
        .stderr(predicate::str::contains("vacuously passing"));
}

#[test]
fn gate_passes_on_clean_tree_with_thresholds() {
    // A fresh clone has no working-tree changes: with gates configured the
    // run still passes (exit 0) and says so explicitly — a clean tree is a
    // pass, not a skipped evaluation.
    let fx = codelore_lib::test_support::differential_repo::build();
    let (_guard, thresholds) = scratch_thresholds("[diff]\ndelta_code_health_min_per_file = 0.0\n");
    let cache = tempfile::tempdir().expect("cache tempdir");
    codelore_cmd()
        .args([
            "gate",
            "--repo",
            fx.dir.path().to_str().unwrap(),
            "--thresholds-file",
            thresholds.to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("no working-tree changes"));
}

#[test]
fn gate_fails_on_per_file_floor() {
    // Appending a deeply-nested high-complexity function to a tracked file
    // makes its projected score strictly worse than its HEAD baseline, so a
    // per-file floor of 0.0 (no file may lower its own health) must fail the
    // gate with check's exit contract (1) and name the offending file.
    let fx = codelore_lib::test_support::differential_repo::build();
    append_to_file(&fx.dir.path().join("src/main.rs"), GATE_MONSTER_FN);
    let (_guard, thresholds) = scratch_thresholds("[diff]\ndelta_code_health_min_per_file = 0.0\n");
    let cache = tempfile::tempdir().expect("cache tempdir");
    codelore_cmd()
        .args([
            "gate",
            "--repo",
            fx.dir.path().to_str().unwrap(),
            "--thresholds-file",
            thresholds.to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("codelore gate: FAIL"))
        .stderr(predicate::str::contains("delta_code_health_min_per_file"))
        .stderr(predicate::str::contains("src/main.rs"));
}

#[test]
fn gate_json_shape() {
    // --format json puts the full change-set report plus the evaluated
    // violations on stdout as one JSON document: `changes`, `findings`, and
    // `violations` are the contract keys downstream consumers read.
    let fx = codelore_lib::test_support::differential_repo::build();
    append_to_file(&fx.dir.path().join("src/main.rs"), GATE_MONSTER_FN);
    // no_new_cycles is configured (non-empty thresholds) but the append
    // introduces no import edge, so the run passes: violations = [].
    let (_guard, thresholds) = scratch_thresholds("[diff]\nno_new_cycles = true\n");
    let cache = tempfile::tempdir().expect("cache tempdir");
    let output = codelore_cmd()
        .args([
            "gate",
            "--repo",
            fx.dir.path().to_str().unwrap(),
            "--thresholds-file",
            thresholds.to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
            "--format",
            "json",
        ])
        .output()
        .expect("run codelore gate --format json");
    assert!(
        output.status.success(),
        "no cycle introduced ⇒ pass, got {}: {}",
        output.status,
        String::from_utf8_lossy(&output.stderr),
    );
    let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");
    let doc: serde_json::Value =
        serde_json::from_str(&stdout).expect("stdout must be one JSON document");
    let changes = doc["changes"].as_array().expect("changes array");
    assert_eq!(changes.len(), 1, "one modified file: {changes:?}");
    assert!(doc["findings"].is_array(), "findings key present: {doc}");
    let violations = doc["violations"].as_array().expect("violations array");
    assert!(violations.is_empty(), "clean pass: {violations:?}");
    // The verdict line is emitted regardless of format; in JSON it goes to
    // stderr so stdout stays a pure document.
    let stderr = String::from_utf8(output.stderr).expect("stderr is utf-8");
    assert!(
        stderr.contains("codelore gate: PASS"),
        "JSON PASS must still print a verdict line to stderr: {stderr}",
    );
}

#[test]
fn gate_findings_render_capped_with_more_tail() {
    // Regression: the findings RENDER must cap at a fixed row count with
    // a "(+n more findings)" tail, mirroring the delta-table cap — otherwise
    // a big change set (13 newly-added files here, each producing its own
    // "new-file" finding) blows the text render's token budget even though
    // the underlying `ChangeSetReport.findings` stays unbounded by design.
    const ADDED: usize = 13; // > the render cap (10) — a tail is guaranteed.
    let fx = codelore_lib::test_support::differential_repo::build();
    for i in 0..ADDED {
        std::fs::write(
            fx.dir.path().join(format!("src/gate_extra_{i}.rs")),
            format!("pub fn extra_{i}() -> u32 {{ {i} }}\n"),
        )
        .expect("write extra file");
    }
    let add = std::process::Command::new("git")
        .args(["-C", fx.dir.path().to_str().unwrap(), "add", "-A"])
        .output()
        .expect("git add");
    assert!(add.status.success(), "git add failed: {add:?}");
    // A real (non-empty) thresholds file: the vacuous "no thresholds
    // configured" path returns before `build_change_set_report` ever runs, so
    // it never reaches the findings render this test is pinning. `no_new_cycles`
    // is a threshold none of these additions can violate (no import edges).
    let (_guard, thresholds) = scratch_thresholds("[diff]\nno_new_cycles = true\n");
    let cache = tempfile::tempdir().expect("cache tempdir");

    let output = codelore_cmd()
        .args([
            "gate",
            "--repo",
            fx.dir.path().to_str().unwrap(),
            "--thresholds-file",
            thresholds.to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
        ])
        .output()
        .expect("run codelore gate");
    assert!(
        output.status.success(),
        "no cycle introduced ⇒ pass: {}",
        String::from_utf8_lossy(&output.stderr),
    );
    let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");

    let finding_lines = stdout
        .lines()
        .filter(|l| l.starts_with("[new-file]"))
        .count();
    assert_eq!(
        finding_lines, 10,
        "the findings render must cap at 10 rows: {stdout}"
    );
    assert!(
        stdout.contains(&format!("(+{} more findings)", ADDED - 10)),
        "a '(+n more findings)' tail must disclose the hidden rows: {stdout}"
    );
}

#[test]
fn gate_vacuous_json_emits_contract_document() {
    // With no thresholds configured, `--format json` must still put one
    // contract document on stdout so an agent hook that always parses JSON
    // never special-cases a repo without a thresholds file.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let output = codelore_cmd()
        .args([
            "gate",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "json",
        ])
        .output()
        .expect("run codelore gate --format json");
    assert!(output.status.success(), "vacuous pass exits 0");
    let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");
    let doc: serde_json::Value =
        serde_json::from_str(&stdout).expect("vacuous JSON must be one parseable document");
    assert!(doc["changes"].is_array(), "changes key present: {doc}");
    assert!(doc["findings"].is_array(), "findings key present: {doc}");
    assert!(
        doc["violations"].is_array(),
        "violations key present: {doc}"
    );
}

#[test]
fn check_max_findings_gate_skips_gracefully_when_no_sidecar() {
    // Gate configured, but no prior `ingest-sarif` run → sidecar absent.
    // Expected contract:
    //   - exit code unaffected (0 — only the overlap gate is configured here)
    //   - ledger records a `verdict="skipped"` entry for max_findings_in_hot_files
    //   - the sidecar file is NOT created as a side-effect of the check
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo_path = tiny.dir.path();
    let thresholds = repo_path.join(".codelore-thresholds.toml");
    std::fs::write(&thresholds, "[gates]\nmax_findings_in_hot_files = 0\n").unwrap();

    // Compute the sidecar path the binary would use — same logic as the CLI.
    let cache_root = codelore_lib::cli_api::cache::default_cache_root();
    let sidecar_path = codelore_lib::cli_api::cache::repo_cache_dir(&cache_root, repo_path)
        .join("external-findings.duckdb-ext");

    // Pre-condition: sidecar must not exist before the run.
    assert!(
        !sidecar_path.exists(),
        "pre-condition: sidecar must not exist before check"
    );

    // Run check — should pass (no other gates configured) and skip the overlap gate.
    codelore_cmd()
        .args(["check", "--repo", repo_path.to_str().unwrap()])
        .assert()
        .success();

    // Post-condition: sidecar must NOT have been created by the check run.
    assert!(
        !sidecar_path.exists(),
        "check must not create the sidecar as a side-effect when ingest-sarif was never run"
    );

    // The ledger must record a skipped verdict for this gate.
    let records =
        codelore_lib::cli_api::quality_gates::ledger::read_gate_runs(&cache_root, repo_path)
            .expect("read ledger");
    let overlap_rec = records
        .iter()
        .rev()
        .find(|r| r.gate == "max_findings_in_hot_files")
        .expect("ledger must contain a max_findings_in_hot_files record");
    assert_eq!(
        overlap_rec.verdict, "skipped",
        "overlap gate must record verdict=skipped when sidecar is absent"
    );
}

#[test]
fn check_corpus_percentile_gate_skips_when_no_health_rows() {
    // Gate configured, but the tiny repo's files fall below the code-health churn
    // floor (`min_revs`), so the health scan yields no rows — there is nothing for
    // the corpus lens to populate, so no row carries `corpus_percentile` and the
    // gate skips (not pass, not fail). This holds regardless of whether a
    // calibration artifact is active. Expected contract:
    //   - exit code unaffected (0 — only the corpus gate is configured here)
    //   - ledger records a `verdict="skipped"` entry for corpus_percentile_max
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo_path = tiny.dir.path();
    let thresholds = repo_path.join(".codelore-thresholds.toml");
    std::fs::write(&thresholds, "[gates]\ncorpus_percentile_max = 0.9\n").unwrap();

    // Run check — should pass (no rows → gate skipped, no other gates).
    codelore_cmd()
        .args(["check", "--repo", repo_path.to_str().unwrap()])
        .assert()
        .success();

    // The ledger must record a skipped verdict for this gate.
    let cache_root = codelore_lib::cli_api::cache::default_cache_root();
    let records =
        codelore_lib::cli_api::quality_gates::ledger::read_gate_runs(&cache_root, repo_path)
            .expect("read ledger");
    let corpus_rec = records
        .iter()
        .rev()
        .find(|r| r.gate == "corpus_percentile_max")
        .expect("ledger must contain a corpus_percentile_max record");
    assert_eq!(
        corpus_rec.verdict, "skipped",
        "corpus gate must record verdict=skipped when the health scan yields no rows"
    );
}

/// SARIF 2.1.0 document that reports one finding for `engine` on `path`.
fn sarif_one_finding(engine: &str, path: &str) -> String {
    format!(
        r#"{{
            "version": "2.1.0",
            "runs": [{{
                "tool": {{ "driver": {{ "name": "{engine}", "version": "1.0" }} }},
                "results": [{{
                    "ruleId": "rule/one",
                    "level": "warning",
                    "message": {{ "text": "a finding" }},
                    "locations": [{{
                        "physicalLocation": {{
                            "artifactLocation": {{ "uri": "{path}" }},
                            "region": {{ "startLine": 1 }}
                        }}
                    }}]
                }}]
            }}]
        }}"#
    )
}

/// SARIF 2.1.0 document from `engine` that reports zero findings (a clean run).
fn sarif_zero_findings(engine: &str) -> String {
    format!(
        r#"{{
            "version": "2.1.0",
            "runs": [{{
                "tool": {{ "driver": {{ "name": "{engine}", "version": "1.0" }} }},
                "results": []
            }}]
        }}"#
    )
}

/// Ingest a zero-finding SARIF so the sidecar exists but holds no rows, then run
/// `check` with the overlap gate configured. The empty sidecar must take the
/// same skip path as an absent one: exit 0 and a ledger verdict of `skipped`.
#[test]
fn check_max_findings_gate_skips_when_sidecar_present_but_empty() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo_path = tiny.dir.path();
    let cache_dir = tempfile::tempdir().expect("tempdir");
    let cache_root = cache_dir.path();

    let thresholds = repo_path.join(".codelore-thresholds.toml");
    std::fs::write(&thresholds, "[gates]\nmax_findings_in_hot_files = 0\n").unwrap();

    // Create an EMPTY sidecar via ingest-sarif with a zero-finding SARIF.
    let empty_sarif = cache_dir.path().join("empty.sarif.json");
    std::fs::write(&empty_sarif, sarif_zero_findings("semgrep")).unwrap();
    codelore_cmd()
        .args([
            "ingest-sarif",
            "--repo",
            repo_path.to_str().unwrap(),
            "--cache-dir",
            cache_root.to_str().unwrap(),
            empty_sarif.to_str().unwrap(),
        ])
        .assert()
        .success();

    // The sidecar file now exists but holds zero rows.
    let store =
        codelore_lib::cli_api::external::ExternalStore::open_existing(cache_root, repo_path)
            .expect("open_existing")
            .expect("sidecar must exist after ingest-sarif");
    assert_eq!(store.count().expect("count"), 0, "sidecar must be empty");
    drop(store);

    // check must exit 0 — the empty sidecar is skipped, not an error.
    codelore_cmd()
        .args([
            "check",
            "--repo",
            repo_path.to_str().unwrap(),
            "--cache-dir",
            cache_root.to_str().unwrap(),
        ])
        .assert()
        .success();

    // The ledger must record a skipped verdict for the overlap gate.
    let records =
        codelore_lib::cli_api::quality_gates::ledger::read_gate_runs(cache_root, repo_path)
            .expect("read ledger");
    let overlap_rec = records
        .iter()
        .rev()
        .find(|r| r.gate == "max_findings_in_hot_files")
        .expect("ledger must contain a max_findings_in_hot_files record");
    assert_eq!(
        overlap_rec.verdict, "skipped",
        "overlap gate must record verdict=skipped when sidecar is present but empty"
    );
}

/// `analyze --analysis finding-hotspot-overlap --cache-dir X` must read the
/// sidecar under the SAME custom cache root that `ingest-sarif --cache-dir X`
/// wrote it to — not the default XDG root.
#[test]
fn analyze_finding_overlap_respects_cache_dir() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo_path = tiny.dir.path();
    let cache_dir = tempfile::tempdir().expect("tempdir");
    let cache_root = cache_dir.path();

    // Ingest one finding into the sidecar under the custom cache root.
    let sarif = cache_dir.path().join("one.sarif.json");
    std::fs::write(&sarif, sarif_one_finding("semgrep", "src/lib.rs")).unwrap();
    codelore_cmd()
        .args([
            "ingest-sarif",
            "--repo",
            repo_path.to_str().unwrap(),
            "--cache-dir",
            cache_root.to_str().unwrap(),
            sarif.to_str().unwrap(),
        ])
        .assert()
        .success();

    // The overlap analysis under the same cache-dir must FIND the ingested
    // finding (emit ≥1 row), not report the missing-sidecar pre-condition error.
    let output = codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "finding-hotspot-overlap",
            "--repo",
            repo_path.to_str().unwrap(),
            "--cache-dir",
            cache_root.to_str().unwrap(),
            "--format",
            "json",
            "--min-revs",
            "1",
        ])
        .output()
        .expect("run finding-hotspot-overlap");
    assert!(
        output.status.success(),
        "overlap analysis must succeed when the sidecar lives under --cache-dir; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8(output.stdout).expect("stdout utf-8");
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("overlap output must be valid JSON");
    let rows = parsed.as_array().expect("overlap JSON is an array");
    assert!(
        rows.iter().any(|r| r["path"] == "src/lib.rs"),
        "overlap must include the ingested finding's path, got: {stdout}"
    );
}

/// `analyze --analysis finding-hotspot-overlap` against an existing-but-EMPTY
/// sidecar must surface the same "requires prior ingest-sarif" pre-condition
/// error as an absent sidecar — an empty sidecar carries no findings to read.
#[test]
fn analyze_finding_overlap_empty_sidecar_reports_precondition_error() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo_path = tiny.dir.path();
    let cache_dir = tempfile::tempdir().expect("tempdir");
    let cache_root = cache_dir.path();

    // Create an EMPTY sidecar via ingest-sarif with a zero-finding SARIF.
    let empty_sarif = cache_dir.path().join("empty.sarif.json");
    std::fs::write(&empty_sarif, sarif_zero_findings("semgrep")).unwrap();
    codelore_cmd()
        .args([
            "ingest-sarif",
            "--repo",
            repo_path.to_str().unwrap(),
            "--cache-dir",
            cache_root.to_str().unwrap(),
            empty_sarif.to_str().unwrap(),
        ])
        .assert()
        .success();

    // The sidecar file now exists but holds zero rows.
    let store =
        codelore_lib::cli_api::external::ExternalStore::open_existing(cache_root, repo_path)
            .expect("open_existing")
            .expect("sidecar must exist after ingest-sarif");
    assert_eq!(store.count().expect("count"), 0, "sidecar must be empty");
    drop(store);

    // The overlap analysis must FAIL with the pre-condition error, not succeed
    // with an empty table.
    let output = codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "finding-hotspot-overlap",
            "--repo",
            repo_path.to_str().unwrap(),
            "--cache-dir",
            cache_root.to_str().unwrap(),
            "--format",
            "json",
            "--min-revs",
            "1",
        ])
        .output()
        .expect("run finding-hotspot-overlap");
    assert!(
        !output.status.success(),
        "overlap analysis must fail on an empty sidecar"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("ingest-sarif"),
        "error must mention the ingest-sarif pre-condition; got: {stderr}"
    );
}

/// Re-ingesting a clean (zero-result) scan for an engine must clear that
/// engine's stale rows. The stored count must reflect the current scanner run,
/// never an accumulation of a prior run's findings.
#[test]
fn ingest_sarif_clean_rescan_clears_stale_engine_rows() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let repo_path = tiny.dir.path();
    let cache_dir = tempfile::tempdir().expect("tempdir");
    let cache_root = cache_dir.path();

    // First scan: one finding for engine "semgrep".
    let with_finding = cache_dir.path().join("with_finding.sarif.json");
    std::fs::write(&with_finding, sarif_one_finding("semgrep", "src/lib.rs")).unwrap();
    codelore_cmd()
        .args([
            "ingest-sarif",
            "--repo",
            repo_path.to_str().unwrap(),
            "--cache-dir",
            cache_root.to_str().unwrap(),
            with_finding.to_str().unwrap(),
        ])
        .assert()
        .success();

    let store =
        codelore_lib::cli_api::external::ExternalStore::open_existing(cache_root, repo_path)
            .expect("open_existing")
            .expect("sidecar must exist");
    assert_eq!(
        store.count().expect("count"),
        1,
        "first scan must store one finding"
    );
    drop(store);

    // Second scan for the SAME engine reports zero findings (issue fixed).
    let clean = cache_dir.path().join("clean.sarif.json");
    std::fs::write(&clean, sarif_zero_findings("semgrep")).unwrap();
    codelore_cmd()
        .args([
            "ingest-sarif",
            "--repo",
            repo_path.to_str().unwrap(),
            "--cache-dir",
            cache_root.to_str().unwrap(),
            clean.to_str().unwrap(),
        ])
        .assert()
        .success();

    // The stale finding must be gone — the clean re-scan cleared the engine.
    let store =
        codelore_lib::cli_api::external::ExternalStore::open_existing(cache_root, repo_path)
            .expect("open_existing")
            .expect("sidecar must still exist");
    assert_eq!(
        store.count().expect("count"),
        0,
        "clean re-scan must clear the engine's stale rows"
    );
}

/// `check --format sarif` on a repo with no thresholds file must still emit a
/// valid zero-result SARIF document to stdout — the documented upload-sarif
/// pipeline breaks if a vacuous pass prints nothing.
#[test]
fn check_format_sarif_vacuous_pass_emits_zero_result_document() {
    // tiny_repo has no `.codelore-thresholds.toml` → vacuous pass.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let output = codelore_cmd()
        .args([
            "check",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--format",
            "sarif",
        ])
        .output()
        .expect("run codelore check --format sarif with no thresholds");

    // Exit 0 — vacuous pass.
    assert!(
        output.status.success(),
        "vacuous pass must exit 0, got {}",
        output.status
    );

    // stdout must be a valid SARIF document with an empty results array.
    let stdout = String::from_utf8(output.stdout).expect("stdout utf-8");
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_else(|e| {
        panic!("vacuous pass stdout must be valid SARIF JSON: {e}; got: {stdout}")
    });
    assert_eq!(parsed["version"].as_str().unwrap(), "2.1.0");
    let results = parsed["runs"][0]["results"]
        .as_array()
        .expect("runs[0].results must be an array");
    assert!(
        results.is_empty(),
        "vacuous pass must emit runs[0].results == [], got: {results:?}"
    );
}

/// `check --ratchet --format sarif` on a first run (no snapshot yet → the
/// ratchet-init exit path) must still emit a valid SARIF document to stdout,
/// exactly like every non-ratchet check path. Before the fix the init path
/// returned before the SARIF emission, so the flag combination silently emitted
/// nothing.
#[test]
fn check_ratchet_format_sarif_init_emits_valid_document() {
    // Fresh clone → no `.codelore-ratchet.toml`, so --ratchet takes the init
    // path. No thresholds file, but --ratchet bypasses the vacuous-pass guard.
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let output = codelore_cmd()
        .args([
            "check",
            "--repo",
            tiny.dir.path().to_str().unwrap(),
            "--ratchet",
            "--format",
            "sarif",
        ])
        .output()
        .expect("run codelore check --ratchet --format sarif");

    // Exit 0 — ratchet initialization is not a failure.
    assert!(
        output.status.success(),
        "ratchet init must exit 0, got {}; stderr: {}",
        output.status,
        String::from_utf8_lossy(&output.stderr)
    );

    // stdout must parse as a SARIF 2.1.0 document — not be empty.
    let stdout = String::from_utf8(output.stdout).expect("stdout utf-8");
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_else(|e| {
        panic!("ratchet+sarif stdout must be valid SARIF JSON: {e}; got: {stdout:?}")
    });
    assert_eq!(parsed["version"].as_str().unwrap(), "2.1.0");
    parsed["runs"][0]["results"]
        .as_array()
        .expect("runs[0].results must be an array");
}

// ── codelore calibrate ───────────────────────────────────────────────────────

/// Write a corpus manifest pointing at one or more local `(path, sha)` repos and
/// return the manifest path (kept alive by the caller-owned `dir`).
fn write_calibrate_manifest(dir: &std::path::Path, repos: &[(&str, &str)]) -> std::path::PathBuf {
    use std::fmt::Write as _;
    let mut toml = String::new();
    for (source, sha) in repos {
        let _ = write!(
            toml,
            "[[repos]]\nsource = {source:?}\nsha = {sha:?}\nlanguages = [\"rust\"]\n\n"
        );
    }
    let path = dir.join("corpus.toml");
    std::fs::write(&path, toml).expect("write manifest");
    path
}

/// A manifest of two local fixture repos builds an artifact that parses through
/// the library's own load/validate path, with a non-empty, monotone rust table.
#[test]
fn calibrate_builds_artifact_from_local_fixtures() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let bio = codelore_lib::test_support::biomarker_repo::build();
    let work = tempfile::tempdir().expect("tempdir");
    let cache = tempfile::tempdir().expect("cache tempdir");

    let manifest = write_calibrate_manifest(
        work.path(),
        &[
            (tiny.dir.path().to_str().unwrap(), &tiny.head_sha),
            (bio.dir.path().to_str().unwrap(), &bio.head_sha),
        ],
    );
    let out = work.path().join("world.calib.json");

    codelore_cmd()
        .args([
            "calibrate",
            "--repos",
            manifest.to_str().unwrap(),
            "--output",
            out.to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
        ])
        .assert()
        .success();

    assert!(out.exists(), "artifact file must be written");
    let art = codelore_lib::calibration::load(&out).expect("artifact parses + validates");
    assert_eq!(art.repos_attempted, 2);
    assert_eq!(art.repos_included, 2);

    let rust = art
        .languages
        .iter()
        .find(|l| l.language == "rust")
        .expect("rust table present");
    assert!(
        rust.sample_functions > 0,
        "rust must have pooled at least one function"
    );
    // Every metric's breakpoint vector is full-length and non-decreasing — the
    // same invariant `load` already enforced, re-asserted here as the test's
    // own contract on the built artifact.
    for stratum in &rust.strata {
        for metric in &stratum.metrics {
            assert_eq!(
                metric.quantiles.len(),
                codelore_lib::calibration::QUANTILE_POINTS
            );
            assert!(
                metric.quantiles.windows(2).all(|w| w[1] >= w[0]),
                "metric {:?} quantiles must be monotone",
                metric.metric
            );
        }
    }

    // Repo-level architecture metrics: `tiny_repo` has no resolvable HEAD-time
    // imports (empty import graph → skipped entirely per the pooling
    // contract), while `biomarker_repo` carries one resolvable
    // `src/importer.rs → src/trivial.rs` edge, so at most one of the two
    // repos contributes an observation to each pool.
    let rm = art
        .repo_metrics
        .expect("repo_metrics must be populated when at least one repo has a non-empty graph");
    let propagation_cost = rm
        .values
        .get("propagation_cost")
        .expect("propagation_cost pool present");
    let cycle_file_share = rm
        .values
        .get("cycle_file_share")
        .expect("cycle_file_share pool present");
    assert!(
        !propagation_cost.is_empty() && propagation_cost.len() <= 2,
        "propagation_cost must have between 1 and repos_included entries, got {}",
        propagation_cost.len()
    );
    assert!(
        !cycle_file_share.is_empty() && cycle_file_share.len() <= 2,
        "cycle_file_share must have between 1 and repos_included entries, got {}",
        cycle_file_share.len()
    );
    for &v in propagation_cost.iter().chain(cycle_file_share.iter()) {
        assert!(
            (0.0..=1.0).contains(&v),
            "repo-level metric value {v} must be in [0,1]"
        );
    }
}

/// A manifest with one good repo and one nonexistent path: the bad repo is
/// warned about and skipped, the run still exits 0, and the artifact records
/// `attempted == 2`, `included == 1`.
#[test]
fn calibrate_skips_unreachable_repo_and_exits_zero() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let work = tempfile::tempdir().expect("tempdir");
    let cache = tempfile::tempdir().expect("cache tempdir");

    let missing = work.path().join("does-not-exist");
    let manifest = write_calibrate_manifest(
        work.path(),
        &[
            (tiny.dir.path().to_str().unwrap(), &tiny.head_sha),
            (missing.to_str().unwrap(), "deadbeef"),
        ],
    );
    let out = work.path().join("world.calib.json");

    codelore_cmd()
        .args([
            "calibrate",
            "--repos",
            manifest.to_str().unwrap(),
            "--output",
            out.to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .stderr(predicate::str::contains("skip"));

    let art = codelore_lib::calibration::load(&out).expect("artifact parses");
    assert_eq!(art.repos_attempted, 2);
    assert_eq!(art.repos_included, 1);
}

/// A manifest where EVERY repo is unreachable (0-of-N included): `calibrate.rs`
/// hard-errors via `CodeLoreError::Analysis` rather than silently writing a
/// data-free artifact — spec §6.6 exit 4 — and no output file lands at all
/// (the atomic-publish write never runs). Locks in the existing total-failure
/// guard (`calibrate.rs`'s `attempted > 0 && included == 0` check).
#[test]
fn calibrate_all_repos_unreachable_exits_analysis_error() {
    let work = tempfile::tempdir().expect("tempdir");
    let cache = tempfile::tempdir().expect("cache tempdir");

    let missing_one = work.path().join("does-not-exist-1");
    let missing_two = work.path().join("does-not-exist-2");
    let manifest = write_calibrate_manifest(
        work.path(),
        &[
            (missing_one.to_str().unwrap(), "deadbeef"),
            (missing_two.to_str().unwrap(), "deadbeef"),
        ],
    );
    let out = work.path().join("world.calib.json");

    codelore_cmd()
        .args([
            "calibrate",
            "--repos",
            manifest.to_str().unwrap(),
            "--output",
            out.to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
        ])
        .assert()
        .code(4)
        .stderr(predicate::str::contains("skip"))
        .stderr(predicate::str::contains(
            "failed to fetch or ingest — no calibration data pooled",
        ));

    assert!(
        !out.exists(),
        "a total-failure run must not write an artifact file"
    );
}

/// `--merge` folds a prior artifact into a fresh build over the same repo, so
/// the pooled rust sample count doubles versus the standalone build.
#[test]
fn calibrate_merge_doubles_sample_counts() {
    let tiny = codelore_lib::test_support::tiny_repo::build();
    let work = tempfile::tempdir().expect("tempdir");
    let cache = tempfile::tempdir().expect("cache tempdir");

    let manifest = write_calibrate_manifest(
        work.path(),
        &[(tiny.dir.path().to_str().unwrap(), &tiny.head_sha)],
    );

    // Base build.
    let base = work.path().join("base.calib.json");
    codelore_cmd()
        .args([
            "calibrate",
            "--repos",
            manifest.to_str().unwrap(),
            "--output",
            base.to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
        ])
        .assert()
        .success();
    let base_art = codelore_lib::calibration::load(&base).expect("base parses");
    let base_rust = base_art
        .languages
        .iter()
        .find(|l| l.language == "rust")
        .expect("rust in base")
        .sample_functions;

    // Merge the base artifact into a rebuild over the same repo.
    let merged = work.path().join("merged.calib.json");
    codelore_cmd()
        .args([
            "calibrate",
            "--repos",
            manifest.to_str().unwrap(),
            "--output",
            merged.to_str().unwrap(),
            "--merge",
            base.to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
        ])
        .assert()
        .success();
    let merged_art = codelore_lib::calibration::load(&merged).expect("merged parses");
    let merged_rust = merged_art
        .languages
        .iter()
        .find(|l| l.language == "rust")
        .expect("rust in merged")
        .sample_functions;
    assert_eq!(merged_rust, base_rust * 2, "merge must sum sample counts");
    assert_eq!(merged_art.repos_included, 2, "merge sums repos_included");
}

/// A planted, dated fixture for `calibrate-defects`:
///   A — introduces `src/lib.rs` with a "buggy" line
///   B — unrelated churn in a different file
///   C — `fix: remove buggy line`, deleting A's buggy line (must link to A)
///   D — a comment-only reformat (adds a `//` line)
///   E — `fix: tidy`, deleting D's comment line (must be AG-filtered — the
///       deleted line is cosmetic, so it must yield NO link)
fn defect_calibration_fixture() -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path();
    let git = |args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?}: {out:?}");
    };
    let commit_at = |msg: &str, date: &str| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(["commit", "-q", "-m", msg])
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .env("GIT_AUTHOR_DATE", date)
            .env("GIT_COMMITTER_DATE", date)
            .output()
            .unwrap();
        assert!(out.status.success(), "git commit {msg:?}: {out:?}");
    };

    git(&["init", "-q", "-b", "main"]);
    std::fs::create_dir_all(repo.join("src")).unwrap();

    // A: introduces src/lib.rs with a "buggy" line (x + 999).
    std::fs::write(
        repo.join("src/lib.rs"),
        "pub fn compute(x: i32) -> i32 {\n    let result = x + 999;\n    result\n}\n",
    )
    .unwrap();
    git(&["add", "."]);
    commit_at("feat: add compute helper", "2026-01-01T10:00:00Z");

    // B: unrelated churn in a different file.
    std::fs::write(
        repo.join("src/other.rs"),
        "pub fn other() -> i32 {\n    42\n}\n",
    )
    .unwrap();
    git(&["add", "."]);
    commit_at(
        "chore: unrelated churn in another module",
        "2026-01-02T10:00:00Z",
    );

    // C: fix removing A's buggy line (x + 999 -> x + 1).
    std::fs::write(
        repo.join("src/lib.rs"),
        "pub fn compute(x: i32) -> i32 {\n    let result = x + 1;\n    result\n}\n",
    )
    .unwrap();
    git(&["add", "."]);
    commit_at("fix: remove buggy line", "2026-01-03T10:00:00Z");

    // D: comment-only reformat (pure addition).
    std::fs::write(
        repo.join("src/lib.rs"),
        "pub fn compute(x: i32) -> i32 {\n    let result = x + 1;\n    \
         // TODO: revisit this computation\n    result\n}\n",
    )
    .unwrap();
    git(&["add", "."]);
    commit_at("docs: annotate compute with a TODO", "2026-01-04T10:00:00Z");

    // E: "fix" that only deletes D's cosmetic comment line — must be
    // AG-filtered, yielding no link.
    std::fs::write(
        repo.join("src/lib.rs"),
        "pub fn compute(x: i32) -> i32 {\n    let result = x + 1;\n    result\n}\n",
    )
    .unwrap();
    git(&["add", "."]);
    commit_at("fix: tidy", "2026-01-05T10:00:00Z");

    dir
}

#[test]
fn calibrate_defects_links_planted_defect_and_ag_filters_cosmetic_fix() {
    let repo = defect_calibration_fixture();
    let out_dir = tempfile::tempdir().unwrap();
    let output = out_dir.path().join("defects.calib.json");

    codelore_cmd()
        .args([
            "calibrate-defects",
            "--repo",
            repo.path().to_str().unwrap(),
            "--output",
            output.to_str().unwrap(),
        ])
        .assert()
        .success();

    let bytes = std::fs::read(&output).expect("artifact written");
    let artifact: serde_json::Value =
        serde_json::from_slice(&bytes).expect("artifact parses as JSON");

    assert_eq!(
        artifact["mining"]["fixes_found"], 2,
        "C and E both classify as fixes"
    );
    assert_eq!(
        artifact["mining"]["links_found"], 1,
        "only C -> A must survive; E's cosmetic candidate must be AG-filtered"
    );
    // The persisted artifact never carries raw (defect, fix, path) triples
    // (DefectArtifact only stores aggregated MiningStats/ValidationMetrics) —
    // the aggregate counts below uniquely pin down the one surviving link as
    // (defect=A, fix=C, path=src/lib.rs), the only pair the fixture can
    // possibly produce.
    assert_eq!(
        artifact["validation"]["linked_defects"], 1,
        "exactly one distinct defect-introducing commit (A) must be linked"
    );
    assert_eq!(
        artifact["validation"]["implicated_files"], 1,
        "exactly one file (src/lib.rs) must be defect-implicated"
    );
    let band_table = artifact["validation"]["band_table"]
        .as_array()
        .expect("band_table present");
    assert_eq!(
        band_table.len(),
        3,
        "band_table always carries red/yellow/green"
    );

    assert_eq!(
        artifact["tuning"]["outcome"], "DefaultsKept",
        "1 linked defect is far below the 30-defect honesty floor"
    );
    assert_eq!(
        artifact["tuning"]["reason"], "fewer than 30 linked defect-changes",
        "the linked-defect-changes floor, not the implicated-file or margin branch, must fire"
    );
}

#[test]
fn cycle_health_csv_has_header() {
    // Build a minimal inline repo with an `a ↔ b` import cycle so
    // `cycle-health` has something to report. The smoke test only checks
    // the CSV header and exit 0; correctness is covered by the lib-level
    // cycle_health_test integration tests.
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path();
    let git = |args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .env("GIT_AUTHOR_DATE", "2026-06-01T10:00:00Z")
            .env("GIT_COMMITTER_DATE", "2026-06-01T10:00:00Z")
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?}: {out:?}");
    };
    git(&["init", "-q", "-b", "main"]);
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(
        repo.join("Cargo.toml"),
        "[package]\nname=\"cyc\"\nversion=\"0.1.0\"\nedition=\"2021\"\n",
    )
    .unwrap();
    std::fs::write(repo.join("src/lib.rs"), "pub mod a;\npub mod b;\n").unwrap();
    std::fs::write(
        repo.join("src/a.rs"),
        "use crate::b;\npub fn a() { b::b(); }\n",
    )
    .unwrap();
    std::fs::write(
        repo.join("src/b.rs"),
        "use crate::a;\npub fn b() { a::a(); }\n",
    )
    .unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "init"]);

    codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "cycle-health",
            "--repo",
            repo.to_str().unwrap(),
            "--format",
            "csv",
            "--min-revs",
            "1",
        ])
        .assert()
        .success()
        .stdout(predicate::str::starts_with(
            "cycle-id,size,members,heat-pct,verdict,extract-candidate,predicted-pc-drop",
        ));
}

/// End-to-end coverage for `explain <path>` — the deterministic per-file
/// evidence dossier and its opt-in `--llm` advisory narrative. The dossier
/// branch needs no network; the `--llm` cases point the client at a
/// test-local one-shot HTTP server so nothing touches an external endpoint.
mod explain_path {
    use std::io::{Read, Write};
    use std::net::{TcpListener, TcpStream};
    use std::path::Path;
    use std::thread;

    use crate::codelore_cmd;
    use predicates::prelude::*;

    /// The LLM environment variables the dossier surface reads. Cleared on every
    /// spawned CLI so an ambient developer configuration can never leak into a
    /// test's resolution. Shared with the `diff --llm` tests.
    pub(crate) const LLM_ENV_VARS: &[&str] = &[
        "CODELORE_LLM_PROVIDER",
        "CODELORE_LLM_BASE_URL",
        "CODELORE_LLM_API_KEY",
        "CODELORE_LLM_MODEL",
        "ANTHROPIC_API_KEY",
    ];

    /// Run `analyze code-health` (with `--min-revs 1`, matching the dossier
    /// branch) over the fixture and return the worst-scoring file's repo-relative
    /// path and code-health band. Deriving the target from the same engine the
    /// dossier uses keeps the assertions robust to fixture regeneration.
    fn code_health_worst_row(repo: &Path, cache: &Path) -> (String, String) {
        let out = codelore_cmd()
            .args([
                "analyze",
                "--analysis",
                "code-health",
                "--repo",
                repo.to_str().unwrap(),
                "--cache-dir",
                cache.to_str().unwrap(),
                "--min-revs",
                "1",
                "--format",
                "csv",
            ])
            .output()
            .expect("run code-health");
        assert!(
            out.status.success(),
            "code-health failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let stdout = String::from_utf8(out.stdout).expect("utf8 code-health output");
        let row = stdout
            .lines()
            .nth(1)
            .expect("code-health yields at least one row for the fixture");
        let fields: Vec<&str> = row.split(',').collect();
        // Header: entity,cognitive,score,structural_risk,percentile,band,corpus-pct
        (fields[0].to_string(), fields[5].to_string())
    }

    /// Every code-health entity path (one row per file), in engine order, for
    /// tests that need two distinct files from the fixture.
    fn code_health_entity_paths(repo: &Path, cache: &Path) -> Vec<String> {
        let out = codelore_cmd()
            .args([
                "analyze",
                "--analysis",
                "code-health",
                "--repo",
                repo.to_str().unwrap(),
                "--cache-dir",
                cache.to_str().unwrap(),
                "--min-revs",
                "1",
                "--format",
                "csv",
            ])
            .output()
            .expect("run code-health");
        assert!(
            out.status.success(),
            "code-health failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let stdout = String::from_utf8(out.stdout).expect("utf8 code-health output");
        stdout
            .lines()
            .skip(1)
            .filter_map(|line| line.split(',').next())
            .map(str::to_string)
            .collect()
    }

    /// Spawn a one-shot HTTP server on an ephemeral localhost port that answers a
    /// single OpenAI-compatible `/chat/completions` request with `narrative` as
    /// the assistant message, then exits. Returns the bound base URL. `narrative`
    /// must be free of `"`, `\`, and newlines so it embeds directly in the JSON.
    pub(crate) fn serve_one_completion(narrative: &str) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
        let base = format!("http://{}", listener.local_addr().expect("local addr"));
        let body = format!(
            "{{\"choices\":[{{\"message\":{{\"role\":\"assistant\",\"content\":\"{narrative}\"}}}}]}}"
        );
        thread::spawn(move || {
            let (mut stream, _) = listener.accept().expect("accept connection");
            drain_request(&mut stream);
            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len()
            );
            stream
                .write_all(response.as_bytes())
                .expect("write response");
            stream.flush().ok();
        });
        base
    }

    /// Read the request up to the end of its headers, then consume any declared
    /// body, so the client's `POST` fully completes before we reply.
    fn drain_request(stream: &mut TcpStream) {
        let mut buf = Vec::new();
        let mut chunk = [0u8; 1024];
        let header_end = loop {
            if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
                break pos + 4;
            }
            let n = stream.read(&mut chunk).expect("read request headers");
            if n == 0 {
                return;
            }
            buf.extend_from_slice(&chunk[..n]);
        };
        let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
        let content_length = head
            .split("\r\n")
            .filter_map(|line| line.split_once(':'))
            .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
            .and_then(|(_, value)| value.trim().parse::<usize>().ok())
            .unwrap_or(0);
        let mut body_read = buf.len() - header_end;
        while body_read < content_length {
            let n = stream.read(&mut chunk).expect("read request body");
            if n == 0 {
                break;
            }
            body_read += n;
        }
    }

    #[test]
    fn explain_known_topic_still_prints_topic_text() {
        // Contract 1: a known topic is looked up first and prints byte-for-byte
        // what it always did — the new file-path branch never runs.
        codelore_cmd()
            .args(["explain", "hotspots"])
            .assert()
            .success()
            .stdout(predicate::str::contains("# hotspots"))
            .stdout(predicate::str::contains("**Citation**"))
            .stdout(predicate::str::contains("**Formula**"));
    }

    #[test]
    fn explain_file_prints_dossier_without_network() {
        let fx = codelore_lib::test_support::biomarker_repo::build();
        let cache = tempfile::tempdir().expect("cache dir");
        let (target, band) = code_health_worst_row(fx.dir.path(), cache.path());

        let mut cmd = codelore_cmd();
        for var in LLM_ENV_VARS {
            cmd.env_remove(var);
        }
        cmd.args([
            "explain",
            &target,
            "--repo",
            fx.dir.path().to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("code-health"))
        .stdout(predicate::str::contains(band.as_str()))
        .stdout(predicate::str::contains(target.as_str()));
    }

    /// A syntactically valid defect-calibration artifact with a deliberately
    /// foreign `repo_identity` — proves `--allow-foreign-calibration` is what
    /// lets it apply, not merely that the flag parses. `weights` are the
    /// built-in smell defaults in canonical order, matching what
    /// `active_weights` (consulted by the dossier's code-health section)
    /// requires of a well-formed artifact.
    fn write_foreign_defect_artifact(dir: &Path) -> std::path::PathBuf {
        use codelore_lib::defect_calibration::{
            DEFECT_FORMAT_VERSION, DefectArtifact, MiningStats, OracleConfig, TuningDecision,
            ValidationMetrics, save, validate::default_weights,
        };
        let artifact = DefectArtifact {
            format_version: DEFECT_FORMAT_VERSION,
            repo_identity: "0".repeat(64),
            head_at_mining: "0".repeat(40),
            vintage: "defects-2026-07-17".to_string(),
            generated_at: "2026-07-17T00:00:00Z".to_string(),
            oracle: OracleConfig::default(),
            mining: MiningStats::default(),
            validation: ValidationMetrics {
                band_table: vec![("red".to_string(), 5, 1.0)],
                auc_default: None,
                precision_at_10: None,
                precision_at_red: None,
                implicated_files: 3,
                linked_defects: 5,
                sample_dates: vec!["2026-01-01".to_string()],
                excluded_no_data: 0,
            },
            weights: default_weights(),
            tuning: TuningDecision::DefaultsKept {
                reason: "insufficient evidence for weight tuning".to_string(),
                auc_validation_default: None,
                auc_validation_tuned: None,
            },
        };
        let path = dir.join("defects.calib.json");
        save(&artifact, &path).expect("save artifact");
        path
    }

    #[test]
    fn explain_file_defect_calibration_adds_defect_evidence_section() {
        let fx = codelore_lib::test_support::biomarker_repo::build();
        let cache = tempfile::tempdir().expect("cache dir");
        let (target, _band) = code_health_worst_row(fx.dir.path(), cache.path());
        let artifact_dir = tempfile::tempdir().expect("artifact dir");
        let artifact_path = write_foreign_defect_artifact(artifact_dir.path());

        codelore_cmd()
            .args([
                "explain",
                &target,
                "--repo",
                fx.dir.path().to_str().unwrap(),
                "--cache-dir",
                cache.path().to_str().unwrap(),
                "--defect-calibration",
                artifact_path.to_str().unwrap(),
                "--allow-foreign-calibration",
            ])
            .assert()
            .success()
            .stdout(predicate::str::contains("defect-evidence"))
            .stdout(predicate::str::contains("defects-2026-07-17"));
    }

    #[test]
    fn explain_file_without_defect_calibration_has_no_defect_evidence_section() {
        let fx = codelore_lib::test_support::biomarker_repo::build();
        let cache = tempfile::tempdir().expect("cache dir");
        let (target, _band) = code_health_worst_row(fx.dir.path(), cache.path());

        codelore_cmd()
            .args([
                "explain",
                &target,
                "--repo",
                fx.dir.path().to_str().unwrap(),
                "--cache-dir",
                cache.path().to_str().unwrap(),
            ])
            .assert()
            .success()
            .stdout(predicate::str::contains("defect-evidence").not());
    }

    #[test]
    fn explain_file_bad_defect_calibration_path_errors_naming_the_path() {
        let fx = codelore_lib::test_support::biomarker_repo::build();
        let cache = tempfile::tempdir().expect("cache dir");
        let (target, _band) = code_health_worst_row(fx.dir.path(), cache.path());
        let bad_path = cache.path().join("does-not-exist.calib.json");

        codelore_cmd()
            .args([
                "explain",
                &target,
                "--repo",
                fx.dir.path().to_str().unwrap(),
                "--cache-dir",
                cache.path().to_str().unwrap(),
                "--defect-calibration",
                bad_path.to_str().unwrap(),
            ])
            .assert()
            .failure()
            .stderr(predicate::str::contains(bad_path.to_str().unwrap()));
    }

    #[test]
    fn explain_unknown_arg_errors_naming_topics_and_files() {
        let fx = codelore_lib::test_support::biomarker_repo::build();
        codelore_cmd()
            .args([
                "explain",
                "definitely-not-a-topic-or-file",
                "--repo",
                fx.dir.path().to_str().unwrap(),
            ])
            .assert()
            .failure()
            .stderr(predicate::str::contains("topic"))
            .stderr(predicate::str::contains("file"));
    }

    #[test]
    fn explain_file_llm_prints_narrative_and_stamp() {
        let fx = codelore_lib::test_support::biomarker_repo::build();
        let cache = tempfile::tempdir().expect("cache dir");
        let (target, _band) = code_health_worst_row(fx.dir.path(), cache.path());

        let narrative = "Diagnosis: the evidence indicates this file is structurally healthy.";
        let base = serve_one_completion(narrative);

        let mut cmd = codelore_cmd();
        for var in LLM_ENV_VARS {
            cmd.env_remove(var);
        }
        // Force the OpenAI-compatible dialect at the local test server so
        // resolution is deterministic regardless of the developer's environment.
        cmd.env("CODELORE_LLM_PROVIDER", "openai-compat")
            .env("CODELORE_LLM_BASE_URL", &base)
            .env("CODELORE_LLM_MODEL", "test-model")
            .args([
                "explain",
                &target,
                "--llm",
                "--repo",
                fx.dir.path().to_str().unwrap(),
                "--cache-dir",
                cache.path().to_str().unwrap(),
            ])
            .assert()
            .success()
            .stdout(predicate::str::contains(narrative))
            .stdout(predicate::str::contains("advisory — model"))
            .stdout(predicate::str::contains("test-model"));
    }

    #[test]
    fn explain_file_llm_without_config_errors_naming_setup_vars() {
        let fx = codelore_lib::test_support::biomarker_repo::build();
        let cache = tempfile::tempdir().expect("cache dir");
        let (target, _band) = code_health_worst_row(fx.dir.path(), cache.path());

        let mut cmd = codelore_cmd();
        for var in LLM_ENV_VARS {
            cmd.env_remove(var);
        }
        cmd.args([
            "explain",
            &target,
            "--llm",
            "--repo",
            fx.dir.path().to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("CODELORE_LLM_MODEL"));
    }

    #[test]
    fn explain_file_staleness_note_is_scoped_to_the_explained_file() {
        // Regression: narrating file B must not make explaining a never-narrated
        // file A print a staleness note. The note is scoped to A's own subject,
        // and A has no narrative of its own, so no note may appear.
        let fx = codelore_lib::test_support::biomarker_repo::build();
        let cache = tempfile::tempdir().expect("cache dir");
        let paths = code_health_entity_paths(fx.dir.path(), cache.path());
        let file_b = &paths[0];
        let file_a = paths
            .iter()
            .find(|p| *p != file_b)
            .expect("fixture yields at least two distinct files");

        // Narrate file B through the local test server so a narrative is cached
        // for B's subject in this cache root.
        let base = serve_one_completion("Diagnosis: file B looks structurally healthy.");
        let mut narrate_b = codelore_cmd();
        for var in LLM_ENV_VARS {
            narrate_b.env_remove(var);
        }
        narrate_b
            .env("CODELORE_LLM_PROVIDER", "openai-compat")
            .env("CODELORE_LLM_BASE_URL", &base)
            .env("CODELORE_LLM_MODEL", "test-model")
            .args([
                "explain",
                file_b,
                "--llm",
                "--repo",
                fx.dir.path().to_str().unwrap(),
                "--cache-dir",
                cache.path().to_str().unwrap(),
            ])
            .assert()
            .success();

        // Explain file A without --llm over the same cache root: it has no
        // narrative of its own, so the staleness note must not appear.
        let mut explain_a = codelore_cmd();
        for var in LLM_ENV_VARS {
            explain_a.env_remove(var);
        }
        explain_a
            .args([
                "explain",
                file_a,
                "--repo",
                fx.dir.path().to_str().unwrap(),
                "--cache-dir",
                cache.path().to_str().unwrap(),
            ])
            .assert()
            .success()
            .stdout(predicate::str::contains("stale").not());
    }
}

/// End-to-end coverage for `diff --llm` — the opt-in, degrade-gracefully
/// advisory PR narrative. The deterministic diff output, its gate verdict, and
/// its exit code must be identical with or without the flag; the narrative is
/// appended only as a delimited advisory block. The `--llm` cases point the
/// client at the same test-local one-shot HTTP server the `explain` tests use so
/// nothing touches an external endpoint.
mod diff_llm {
    use crate::codelore_cmd;

    use crate::explain_path::{LLM_ENV_VARS, serve_one_completion};

    #[test]
    fn diff_without_llm_has_no_advisory_block() {
        let (dir, base, head) = super::delta_health_fixture();
        let mut cmd = codelore_cmd();
        for var in LLM_ENV_VARS {
            cmd.env_remove(var);
        }
        let out = cmd
            .args([
                "diff",
                "--repo",
                dir.path().to_str().unwrap(),
                "--min-revs",
                "1",
                "--format",
                "text",
                &format!("{base}..{head}"),
            ])
            .output()
            .expect("run diff without --llm");
        assert!(
            out.status.success(),
            "diff without --llm should succeed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let stdout = String::from_utf8(out.stdout).expect("utf8 diff output");
        assert!(
            !stdout.contains("LLM narrative"),
            "no advisory block without --llm: {stdout}"
        );
    }

    #[test]
    fn diff_llm_appends_advisory_block_and_preserves_exit_code() {
        let (dir, base, head) = super::delta_health_fixture();
        let repo = dir.path().to_str().unwrap().to_string();
        let range = format!("{base}..{head}");

        // Baseline: the no-flag run establishes the exit code the --llm run must
        // reproduce (the narrative is advisory and must not move it).
        let mut baseline_cmd = codelore_cmd();
        for var in LLM_ENV_VARS {
            baseline_cmd.env_remove(var);
        }
        let baseline = baseline_cmd
            .args([
                "diff",
                "--repo",
                &repo,
                "--min-revs",
                "1",
                "--format",
                "text",
                &range,
            ])
            .output()
            .expect("baseline diff");
        assert!(baseline.status.success());

        let narrative = "This change adds a large branchy function that degrades change health.";
        let base_url = serve_one_completion(narrative);

        // --llm-refresh forces the server round-trip: diff has no --cache-dir, so
        // it shares the default narrative cache; refreshing keeps the assertion
        // hermetic against any pre-existing cached narrative for this fact sheet.
        let mut cmd = codelore_cmd();
        for var in LLM_ENV_VARS {
            cmd.env_remove(var);
        }
        let out = cmd
            .env("CODELORE_LLM_PROVIDER", "openai-compat")
            .env("CODELORE_LLM_BASE_URL", &base_url)
            .env("CODELORE_LLM_MODEL", "test-model")
            .args([
                "diff",
                "--repo",
                &repo,
                "--min-revs",
                "1",
                "--format",
                "text",
                "--llm",
                "--llm-refresh",
                &range,
            ])
            .output()
            .expect("run diff --llm");
        assert!(
            out.status.success(),
            "diff --llm should succeed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert_eq!(
            out.status.code(),
            baseline.status.code(),
            "the advisory narrative must not change the exit code"
        );
        let stdout = String::from_utf8(out.stdout).expect("utf8 diff output");
        assert!(
            stdout.contains("LLM narrative (advisory)"),
            "advisory block present: {stdout}"
        );
        assert!(
            stdout.contains(narrative),
            "the served narrative is rendered: {stdout}"
        );
        assert!(
            stdout.contains("advisory — model"),
            "the citation-check stamp is rendered: {stdout}"
        );
        assert!(
            stdout.contains("test-model"),
            "the stamp names the model: {stdout}"
        );
    }

    #[test]
    fn diff_llm_without_config_warns_and_leaves_output_identical() {
        let (dir, base, head) = super::delta_health_fixture();
        let repo = dir.path().to_str().unwrap().to_string();
        let range = format!("{base}..{head}");

        let mut baseline_cmd = codelore_cmd();
        for var in LLM_ENV_VARS {
            baseline_cmd.env_remove(var);
        }
        let baseline = baseline_cmd
            .args([
                "diff",
                "--repo",
                &repo,
                "--min-revs",
                "1",
                "--format",
                "text",
                &range,
            ])
            .output()
            .expect("baseline diff");
        assert!(baseline.status.success());

        // --llm with no LLM environment: resolution fails, the failure is a
        // stderr warning, and stdout + exit code are byte-identical to the
        // no-flag run.
        let mut cmd = codelore_cmd();
        for var in LLM_ENV_VARS {
            cmd.env_remove(var);
        }
        let out = cmd
            .args([
                "diff",
                "--repo",
                &repo,
                "--min-revs",
                "1",
                "--format",
                "text",
                "--llm",
                &range,
            ])
            .output()
            .expect("run diff --llm without config");
        assert_eq!(
            out.status.code(),
            baseline.status.code(),
            "an unavailable narrative must not change the exit code"
        );
        assert_eq!(
            out.stdout, baseline.stdout,
            "an unavailable narrative must leave stdout identical to the no-flag run"
        );
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            stderr.contains("llm narrative unavailable"),
            "the degrade-gracefully warning is on stderr: {stderr}"
        );
    }
}

/// Scope guard for the advisory `--llm` flag: it exists only on the surfaces
/// that render narratives (`explain`, `diff`). The scored surfaces (`analyze`,
/// `check`) must reject it at the parser, so the flag can never even be spelled
/// on a command whose output feeds gates or CI.
mod llm_flag_scope {
    use crate::codelore_cmd;
    use predicates::prelude::*;

    #[test]
    fn analyze_rejects_the_llm_flag_at_the_parser() {
        codelore_cmd()
            .args(["analyze", "--analysis", "hotspots", "--llm", "--repo", "."])
            .assert()
            .failure()
            .stderr(predicate::str::contains("unexpected argument"))
            .stderr(predicate::str::contains("--llm"));
    }

    #[test]
    fn check_rejects_the_llm_flag_at_the_parser() {
        codelore_cmd()
            .args(["check", "--repo", ".", "--llm"])
            .assert()
            .failure()
            .stderr(predicate::str::contains("unexpected argument"))
            .stderr(predicate::str::contains("--llm"));
    }
}

/// Manual-only live check against a local ollama. Run with:
///
/// ```text
/// CODELORE_LLM_MODEL=<model from `ollama list`> \
///   cargo test -p codelore --test cli_test -- --ignored explain_file_llm_live
/// ```
///
/// Ignored by default: CI performs no live network calls, and the assertion
/// depends on a developer-local model server at the default base URL.
#[test]
#[ignore = "requires a running local ollama and CODELORE_LLM_MODEL set"]
fn explain_file_llm_live_against_local_ollama() {
    let model = std::env::var("CODELORE_LLM_MODEL")
        .expect("set CODELORE_LLM_MODEL to a model name from `ollama list` for the live check");
    let fx = codelore_lib::test_support::biomarker_repo::build();
    let cache = tempfile::tempdir().expect("cache dir");

    // Resolve a real dossier target the same way the hermetic explain tests do.
    let out = codelore_cmd()
        .args([
            "analyze",
            "--analysis",
            "code-health",
            "--repo",
            fx.dir.path().to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
            "--min-revs",
            "1",
            "--format",
            "csv",
        ])
        .output()
        .expect("run code-health");
    assert!(out.status.success());
    let stdout = String::from_utf8(out.stdout).expect("utf8 code-health output");
    let target = stdout
        .lines()
        .nth(1)
        .and_then(|row| row.split(',').next())
        .expect("code-health yields at least one row")
        .to_string();

    let mut cmd = codelore_cmd();
    for var in explain_path::LLM_ENV_VARS {
        cmd.env_remove(var);
    }
    cmd.env("CODELORE_LLM_PROVIDER", "openai-compat")
        .env("CODELORE_LLM_MODEL", &model)
        .args([
            "explain",
            &target,
            "--llm",
            "--llm-refresh",
            "--repo",
            fx.dir.path().to_str().unwrap(),
            "--cache-dir",
            cache.path().to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("advisory — model"))
        .stdout(predicate::str::contains(model.as_str()));
}