kingfisher-bin 2.8.0

MongoDB's blazingly fast and accurate secret scanning and validation tool
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
// ────────────────────────────────────────────────────────────
// Global allocator setup
//   * Default  - mimalloc (`use-mimalloc`)
//   * Opt-in   - jemalloc (`use-jemalloc`) for one-off debugging
//   * Explicit - system allocator on Darwin (`system-alloc`)
// ────────────────────────────────────────────────────────────

#[cfg(all(feature = "use-jemalloc", feature = "system-alloc"))]
compile_error!("`use-jemalloc` and `system-alloc` are mutually exclusive");

#[cfg(all(feature = "use-jemalloc", feature = "use-mimalloc"))]
compile_error!("`use-jemalloc` and `use-mimalloc` are mutually exclusive");

#[cfg(all(feature = "system-alloc", not(target_os = "macos")))]
compile_error!("`system-alloc` is only supported on Darwin targets");

// --- jemalloc (opt-in) ---
#[cfg(feature = "use-jemalloc")]
#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

// --- mimalloc (default) ---
#[cfg(all(
    not(feature = "use-jemalloc"),
    not(feature = "system-alloc"),
    any(feature = "use-mimalloc", target_os = "linux", target_os = "windows")
))]
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

// --- system allocator (fallback, explicit on Darwin) ---
#[cfg(any(
    feature = "system-alloc",
    all(
        not(feature = "use-jemalloc"),
        not(feature = "system-alloc"),
        not(any(feature = "use-mimalloc", target_os = "linux", target_os = "windows"))
    )
))]
use std::alloc::System;
#[cfg(any(
    feature = "system-alloc",
    all(
        not(feature = "use-jemalloc"),
        not(feature = "system-alloc"),
        not(any(feature = "use-mimalloc", target_os = "linux", target_os = "windows"))
    )
))]
#[global_allocator]
static GLOBAL: System = System;

use std::{
    io::{IsTerminal, Read, Write},
    path::PathBuf,
    sync::{Arc, Mutex},
    time::Instant,
};

use anyhow::{Context, Result};
use console::Term;
use kingfisher::{
    access_map, azure, bitbucket,
    cli::{
        self, CommandLineArgs, GlobalArgs,
        commands::{
            github::{GitCloneMode, GitHistoryMode, GitHubRepoType},
            inputs::{ContentFilteringArgs, InputSpecifierArgs},
            output::{OutputArgs, ReportOutputFormat},
            rules::{
                RuleCacheArgs, RuleCachePruneArgs, RuleSpecifierArgs, RulesCheckArgs, RulesCommand,
                RulesCompileCacheArgs, RulesListArgs, RulesListOutputFormat,
            },
        },
        global::Command,
    },
    direct_access_map, direct_revoke, direct_validate, findings_store,
    findings_store::FindingsStore,
    gitea, github, huggingface,
    reporter::{DetailsReporter, ScanAuditContext, styles::Styles},
    rule_loader::RuleLoader,
    rules_database::{RuleCacheConfig, RuleCachePruneConfig, RulesDatabase, prune_rule_cache},
    scanner::{load_and_record_rules, run_scan},
    update::{check_for_update_async, rewrite_argv_for_reexec},
    util::tokio_blocking_threads_limit,
    validation::set_user_agent_suffix,
};
use serde_json::json;
use tempfile::TempDir;
use tokio::runtime::Builder;
use tracing::{error, info, warn};
use tracing_core::metadata::LevelFilter;
use tracing_subscriber::{
    self, fmt, prelude::__tracing_subscriber_SubscriberExt, registry, util::SubscriberInitExt,
};
use url::Url;

use crate::cli::commands::{
    azure::AzureRepoType,
    bitbucket::{BitbucketAuthArgs, BitbucketRepoType},
    gitea::GiteaRepoType,
    gitlab::GitLabRepoType,
    scan::{ListRepositoriesCommand, ScanOperation},
    view,
};

fn main() -> anyhow::Result<()> {
    raise_nproc_soft_limit();
    const STACK_SIZE: usize = 32 * 1024 * 1024; // 32 MiB
    // Clap's derived parser can overflow Windows' main-thread stack in debug builds.
    // Box its result so transferring the large command enum also stays off that stack.
    let parser = std::thread::Builder::new()
        .name("kingfisher-args".to_string())
        .stack_size(STACK_SIZE)
        .spawn(|| {
            let (args, matches) = CommandLineArgs::parse_args_with_matches();
            (Box::new(args), matches)
        })
        .context("Failed to spawn argument parser thread")?;
    let (args, matches) = parser.join().unwrap_or_else(|e| std::panic::resume_unwind(e));

    // GPUI must run on the OS main thread. Keep the raw matches when handing other
    // commands to the larger-stack worker so config precedence still distinguishes
    // explicit flags from clap defaults.
    if let Command::Wizard(wizard) = &args.command {
        #[cfg(feature = "gui")]
        return kingfisher::wizard::run(
            wizard.target.clone(),
            wizard.report.clone(),
            kingfisher::wizard::global_values(&matches),
        );
        #[cfg(not(feature = "gui"))]
        {
            let _ = wizard;
            anyhow::bail!(
                "This build does not include the native wizard. Build with `cargo build --release --features gui --bin kingfisher`, then run `kingfisher wizard` (alias: `kingfisher gui`)."
            );
        }
    }
    // Run the real entry point on a thread with an explicit, larger stack so that
    // deeply-nested async state machines (validation pipeline) cannot overflow the
    // default main-thread stack.
    let builder =
        std::thread::Builder::new().name("kingfisher-main".to_string()).stack_size(STACK_SIZE);

    let handler = builder.spawn(move || run(*args, matches)).expect("failed to spawn main thread");
    let result = handler.join().unwrap_or_else(|e| std::panic::resume_unwind(e));
    if let Err(error) = &result
        && error.is::<kingfisher::scanner::NoScanInputsError>()
    {
        eprintln!("Error: {error:?}");
        std::process::exit(3);
    }
    result
}

/// Outcome of `async_main`. Used to signal that the runtime should be torn down
/// and the process should re-exec into a freshly self-updated binary.
enum AsyncMainOutcome {
    Done,
    Reexec,
}

/// Best-effort raise of the soft `RLIMIT_NPROC` (per-user thread/process cap)
/// to the current hard limit. Many users hit `pthread_create` failures
/// (`EAGAIN` / `WouldBlock`) under heavy validation because the default soft
/// limit on macOS is well below the hard limit. Failures here are intentionally
/// silent — this is a quality-of-life nudge, not a correctness requirement.
#[cfg(unix)]
fn raise_nproc_soft_limit() {
    // SAFETY: `getrlimit`/`setrlimit` are FFI calls. We pass pointers to
    // properly initialized `libc::rlimit` values with the correct layout, only
    // read `rl` after `getrlimit` reports success, and treat `setrlimit`
    // failure as best-effort by ignoring its return value.
    unsafe {
        let mut rl = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
        if libc::getrlimit(libc::RLIMIT_NPROC, &mut rl) != 0 {
            return;
        }
        if rl.rlim_cur < rl.rlim_max {
            let new = libc::rlimit { rlim_cur: rl.rlim_max, rlim_max: rl.rlim_max };
            let _ = libc::setrlimit(libc::RLIMIT_NPROC, &new);
        }
    }
}

#[cfg(not(unix))]
fn raise_nproc_soft_limit() {}

fn run(args: CommandLineArgs, matches: clap::ArgMatches) -> anyhow::Result<()> {
    // Install the AWS-LC Rustls provider before initializing any TLS clients.
    match rustls::crypto::aws_lc_rs::default_provider().install_default() {
        Ok(()) => {}
        Err(_already_installed) => {
            // Another crate already installed a provider. This is unusual for a CLI, but
            // surfacing it makes later TLS issues much easier to diagnose.
            warn!("rustls crypto provider was already installed; keeping existing provider");
        }
    }
    set_user_agent_suffix(args.global_args.user_agent_suffix.clone());

    // Determine the number of jobs, defaulting to the number of CPUs
    let num_jobs = match &args.command {
        Command::Scan(scan_args) => scan_args.scan_args.num_jobs,
        Command::SelfUpdate => 1, // Self-update doesn't need a thread pool
        Command::Rules(_) => std::thread::available_parallelism().map_or(1, |n| n.get()), // Default for Rules commands
        Command::Validate(_) => 1, // Single validation request
        Command::Revoke(_) => 1,   // Single revocation request
        Command::BlastRadius(_) => 1,
        Command::View(_) | Command::Wizard(_) => 1,
        Command::Config(_) => 1,
    };

    // Set up the Tokio runtime with the specified number of threads.
    // Worker threads need larger stacks because async state machines (validation
    // pipeline) can produce large poll stack frames. 8 MiB is sufficient now that
    // the validators are split into separate async fns.
    // Bound the blocking-thread pool. Tokio's default is 512 per runtime; the
    // helper scales with --jobs but caps each runtime below that default so the
    // main and artifact-fetcher runtimes cannot both grow huge blocking pools.
    let max_blocking = tokio_blocking_threads_limit(num_jobs);
    let runtime = Builder::new_multi_thread()
        .worker_threads(num_jobs)
        .max_blocking_threads(max_blocking)
        .thread_stack_size(8 * 1024 * 1024) // 8 MiB per worker
        .enable_all()
        .build()
        .context("Failed to create Tokio runtime")?;
    let outcome = runtime.block_on(async_main(args, matches))?;
    // Drop the Tokio runtime before re-exec so background tasks, file descriptors,
    // and signal handlers are torn down cleanly. On Unix `exec()` replaces the process
    // image regardless, but draining the runtime first avoids surprising shutdown
    // ordering when the re-exec happens to fail.
    drop(runtime);

    match outcome {
        AsyncMainOutcome::Done => Ok(()),
        AsyncMainOutcome::Reexec => {
            // On Unix, a successful exec() never returns; on Windows, reexec_with_new_binary
            // calls process::exit. We only reach here if the re-exec failed before transferring
            // control. The on-disk binary is now the updated version, so re-running the same
            // command will work — but the original command has NOT executed, so we must not
            // exit 0 and let CI think the run succeeded.
            if let Err(e) = reexec_with_new_binary() {
                error!(
                    "Binary was updated but re-exec failed: {e}. The original command did not \
                     run. Re-run the command to use the new binary."
                );
                std::process::exit(1);
            }
            Ok(())
        }
    }
}

/// Re-exec the current process into the binary at `current_exe()` so a freshly
/// self-updated binary takes over the current invocation.
///
/// Argv is rewritten via [`rewrite_argv_for_reexec`] to prevent loops and to skip the
/// next update check.
///
/// On Unix this calls `exec()` which replaces the process image — same PID, parent
/// shell sees the new binary's exit code directly.
///
/// On Windows there is no true `exec()`. Standard practice (rustup, cargo) is to spawn
/// the new binary, wait, and propagate its exit code. This adds a parent process layer
/// but preserves the parent shell's child-process tracking.
fn reexec_with_new_binary() -> std::io::Result<()> {
    use std::process::Command;

    let exe = std::env::current_exe()?;
    let argv: Vec<std::ffi::OsString> = rewrite_argv_for_reexec(std::env::args_os());

    // Defensive: rewrite_argv_for_reexec returns an empty Vec only when args_os() was empty,
    // which shouldn't happen for a real CLI invocation but would produce a child process with
    // no argv[0]. Bail rather than spawn something nonsensical.
    if argv.is_empty() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "cannot re-exec: process started with empty argv",
        ));
    }

    // Make sure prior stderr/stdout output (e.g. "Updated to version X") is committed
    // before we either replace the process image (Unix) or spawn the child (Windows). On
    // Windows the child inherits the same handles, so leftover buffered output from the
    // parent could otherwise interleave with the child's output unpredictably.
    let _ = std::io::stdout().flush();
    let _ = writeln!(std::io::stderr(), "Restarting with updated binary...");
    let _ = std::io::stderr().flush();

    // Safe by the is_empty() guard above.
    let argv0 = argv[0].clone();

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        let err = Command::new(&exe).args(argv.iter().skip(1)).arg0(&argv0).exec();
        // exec() returns only on failure.
        Err(err)
    }

    #[cfg(windows)]
    {
        // arg0 spoofing isn't available on Windows; the child sees the resolved exe path
        // as argv[0]. The user-visible difference is cosmetic.
        let _ = argv0;
        let status = Command::new(&exe).args(argv.iter().skip(1)).status()?;
        std::process::exit(status.code().unwrap_or(1));
    }

    #[cfg(not(any(unix, windows)))]
    {
        let _ = (exe, argv0);
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "re-exec is not supported on this platform",
        ))
    }
}

fn setup_logging(global_args: &GlobalArgs) {
    // Determine log level based on global verbosity
    let (level, all_targets) = if global_args.quiet {
        (LevelFilter::ERROR, false)
    } else {
        let level = match global_args.verbose {
            0 => LevelFilter::INFO,  // Default level if no `-v` is provided
            1 => LevelFilter::DEBUG, // `-v`
            2 => LevelFilter::TRACE, // `-vv`
            _ => LevelFilter::TRACE, // `-vvv` or more
        };
        let all_targets = global_args.verbose > 2; // Enable all targets for `-vvv` or more
        (level, all_targets)
    };
    // Create a filter for logging
    let filter = if all_targets {
        // Enable TRACE for all modules
        tracing_subscriber::filter::Targets::new().with_default(LevelFilter::TRACE)
    } else {
        // Per-target filtering, only TRACE for `kingfisher`
        tracing_subscriber::filter::Targets::new()
            .with_default(LevelFilter::ERROR) // Default for all modules
            .with_target("kingfisher", level) // Replace `kingfisher` with your
        // crate's name
    };
    // Configure the formatter layer
    let fmt_layer = fmt::layer()
        .with_writer(std::io::stderr) // Write logs to stderr
        .with_target(true) // Enable target filtering
        .with_ansi(std::io::stderr().is_terminal()) // Emit ANSI colours when stderr is a TTY
        .without_time(); // Remove timestamps
    // Build and initialize the registry
    registry()
        .with(fmt_layer) // Attach the formatter layer
        .with(filter) // Attach the filter
        .init();
}

/// Resolve and read a `kingfisher.yaml` project config.
///
/// The config file is loaded **only** when the user passes `--config <PATH>`
/// explicitly. There is intentionally no auto-discovery — relying on a
/// `kingfisher.yaml` that happens to sit in the cwd (or any ancestor
/// directory) makes scan results depend on where the binary was invoked
/// from, which is too easy to get wrong in CI. If the explicit path is
/// missing or fails to parse, that is a fatal error.
fn load_project_config(
    explicit: Option<&std::path::Path>,
) -> Result<Option<kingfisher::cli::config::KingfisherConfig>> {
    let Some(p) = explicit else { return Ok(None) };
    let bytes = std::fs::read(p).with_context(|| format!("read config {}", p.display()))?;
    let yaml =
        String::from_utf8(bytes).with_context(|| format!("config {} is not UTF-8", p.display()))?;
    let cfg = kingfisher::cli::config::parse_str(&yaml)
        .with_context(|| format!("parse config {}", p.display()))?;
    info!("loaded config from {}", p.display());
    Ok(Some(cfg))
}

/// Merge config-file values into clap-parsed args.
///
/// **Lists/maps**: always concatenated onto the CLI value (additive).
///
/// **Scalars**: applied only when the user did not pass the matching CLI
/// flag, detected via [`clap::ArgMatches::value_source`]. A `Some(_)` config
/// value still loses to a CLI-supplied flag or an explicit env-var, but wins
/// over a clap `default_value_t`. This preserves precedence
/// **CLI > env > config > built-in default**.
fn apply_config(
    scan_args: &mut cli::commands::scan::ScanArgs,
    global_args: &mut GlobalArgs,
    cfg: &kingfisher::cli::config::KingfisherConfig,
    scan_matches: Option<&clap::ArgMatches>,
) {
    use clap::parser::ValueSource;

    /// True when the named arg was either absent or filled in with its clap
    /// default — i.e. the user did not pass `--<flag>` on the CLI and did
    /// not set its `env = ...`. In those cases the config value should win.
    fn config_wins(matches: Option<&clap::ArgMatches>, id: &str) -> bool {
        matches!(matches.and_then(|m| m.value_source(id)), None | Some(ValueSource::DefaultValue))
    }

    /// Like `config_wins`, but also inspects a nested provider subcommand's
    /// `--api-url` flag. The github/gitlab provider subcommands carry their
    /// own `api_url` arg (id `api_url`) that gets propagated to
    /// `scan_args.input_specifier_args.{github,gitlab}_api_url` in
    /// `into_operation()`. If that nested flag was user-supplied, the config
    /// must NOT clobber it.
    fn api_url_config_wins(
        matches: Option<&clap::ArgMatches>,
        outer_id: &str,
        subcommand: &str,
    ) -> bool {
        if !config_wins(matches, outer_id) {
            return false;
        }
        let sub = matches.and_then(|m| m.subcommand_matches(subcommand));
        config_wins(sub, "api_url")
    }

    // ---------- Filters: existing v1 list-typed merges ----------------------
    scan_args.skip_word.extend(cfg.filters.skip_words.iter().cloned());
    scan_args.skip_regex.extend(cfg.filters.skip_regex.iter().cloned());
    scan_args.content_filtering_args.exclude.extend(cfg.filters.exclude.iter().cloned());

    // ---------- scan: behavioral scalars ------------------------------------
    if let Some(c) = cfg.scan.confidence
        && config_wins(scan_matches, "confidence")
    {
        scan_args.confidence = c.into();
    }
    if let Some(e) = cfg.scan.min_entropy
        && config_wins(scan_matches, "min_entropy")
    {
        scan_args.min_entropy = Some(e);
    }
    if let Some(v) = cfg.scan.no_validate
        && config_wins(scan_matches, "no_validate")
    {
        scan_args.no_validate = v;
    }
    if let Some(v) = cfg.scan.only_valid
        && config_wins(scan_matches, "only_valid")
        && config_wins(scan_matches, "validation_filter")
    {
        scan_args.only_valid = v;
    }
    if let Some(v) = cfg.scan.validation_filter
        && config_wins(scan_matches, "validation_filter")
        && config_wins(scan_matches, "only_valid")
    {
        scan_args.validation_filter = Some(v);
    }
    if let Some(v) = cfg.scan.redact
        && config_wins(scan_matches, "redact")
    {
        scan_args.redact = v;
    }
    if let Some(v) = cfg.scan.no_dedup
        && config_wins(scan_matches, "no_dedup")
    {
        scan_args.no_dedup = v;
    }
    if let Some(v) = cfg.scan.turbo
        && config_wins(scan_matches, "turbo")
    {
        scan_args.turbo = v;
    }
    if let Some(v) = cfg.scan.no_base64
        && config_wins(scan_matches, "no_base64")
    {
        scan_args.no_base64 = v;
    }
    if let Some(v) = cfg.scan.access_map
        && config_wins(scan_matches, "access_map")
    {
        scan_args.access_map = v;
    }
    if let Some(v) = cfg.scan.rule_stats
        && config_wins(scan_matches, "rule_stats")
    {
        scan_args.rule_stats = v;
    }
    if let Some(j) = cfg.scan.jobs
        && config_wins(scan_matches, "num_jobs")
    {
        scan_args.num_jobs = j;
    }
    if let Some(t) = cfg.scan.git_repo_timeout
        && config_wins(scan_matches, "git_repo_timeout")
    {
        scan_args.git_repo_timeout = t;
    }

    // ---------- rules ------------------------------------------------------
    // `rule` and `rules_path` are list-typed; concatenate. Note: clap's default
    // for `--rule` is `["all"]`, so unconditionally appending could grow the
    // selection in surprising ways. Only append when the user did not pass
    // `--rule` (i.e. the default is in effect).
    if !cfg.rules.enabled.is_empty() {
        if config_wins(scan_matches, "rule") {
            // Replace the synthetic clap default with the config selection.
            scan_args.rules.rule = cfg.rules.enabled.clone();
        } else {
            scan_args.rules.rule.extend(cfg.rules.enabled.iter().cloned());
        }
    }
    scan_args.rules.rules_path.extend(cfg.rules.paths.iter().cloned());
    scan_args.rules.exclude_rule.extend(cfg.rules.disabled.iter().cloned());
    if let Some(v) = cfg.rules.load_builtins
        && config_wins(scan_matches, "load_builtins")
    {
        scan_args.rules.load_builtins = v;
    }
    if let Some(v) = cfg.rules.cache
        && config_wins(scan_matches, "rule_cache")
        && config_wins(scan_matches, "no_rule_cache")
    {
        scan_args.rule_cache.rule_cache = v;
        scan_args.rule_cache.no_rule_cache = !v;
    }
    if let Some(path) = &cfg.rules.cache_dir
        && config_wins(scan_matches, "rule_cache_dir")
    {
        scan_args.rule_cache.rule_cache_dir = Some(path.clone());
    }

    // ---------- validation -------------------------------------------------
    if let Some(t) = cfg.validation.timeout
        && config_wins(scan_matches, "validation_timeout")
    {
        scan_args.validation_timeout = t;
    }
    if let Some(r) = cfg.validation.retries
        && config_wins(scan_matches, "validation_retries")
    {
        scan_args.validation_retries = r;
    }
    if let Some(rps) = cfg.validation.rps
        && config_wins(scan_matches, "validation_rps")
    {
        scan_args.validation_rps = Some(rps);
    }
    for (rule, rps) in &cfg.validation.rps_per_rule {
        scan_args.validation_rps_rule.push(format!("{rule}={rps}"));
    }
    if let Some(v) = cfg.validation.full_response
        && config_wins(scan_matches, "full_validation_response")
    {
        scan_args.full_validation_response = v;
    }
    if let Some(n) = cfg.validation.max_response_length
        && config_wins(scan_matches, "max_validation_response_length")
    {
        scan_args.max_validation_response_length = n;
    }

    // ---------- filters (v2 scalars + extra additive lists) ----------------
    if let Some(mb) = cfg.filters.max_file_size_mb
        && config_wins(scan_matches, "max_file_size_mb")
    {
        scan_args.content_filtering_args.max_file_size_mb = mb;
    }
    if let Some(v) = cfg.filters.no_binary
        && config_wins(scan_matches, "no_binary")
    {
        scan_args.content_filtering_args.no_binary = v;
    }
    if let Some(v) = cfg.filters.no_extract_archives
        && config_wins(scan_matches, "no_extract_archives")
    {
        scan_args.content_filtering_args.no_extract_archives = v;
    }
    if let Some(d) = cfg.filters.extraction_depth
        && config_wins(scan_matches, "extraction_depth")
    {
        scan_args.content_filtering_args.extraction_depth = d;
    }
    if let Some(v) = cfg.filters.no_inline_ignore
        && config_wins(scan_matches, "no_inline_ignore")
    {
        scan_args.no_inline_ignore = v;
    }
    if let Some(v) = cfg.filters.no_ignore_if_contains
        && config_wins(scan_matches, "no_ignore_if_contains")
    {
        scan_args.no_ignore_if_contains = v;
    }
    scan_args.extra_ignore_comments.extend(cfg.filters.extra_ignore_comments.iter().cloned());
    scan_args.skip_aws_account.extend(cfg.filters.skip_aws_accounts.iter().cloned());
    if let Some(p) = &cfg.filters.skip_aws_account_file
        && config_wins(scan_matches, "skip_aws_account_file")
    {
        scan_args.skip_aws_account_file = Some(p.clone());
    }

    // ---------- output -----------------------------------------------------
    if let Some(f) = cfg.output.format
        && config_wins(scan_matches, "format")
    {
        scan_args.output_args.format = f.into();
    }
    if let Some(p) = &cfg.output.path
        && config_wins(scan_matches, "output")
    {
        scan_args.output_args.output = Some(p.clone());
    }

    // ---------- baseline ---------------------------------------------------
    if let Some(p) = &cfg.baseline.file
        && config_wins(scan_matches, "baseline_file")
    {
        scan_args.baseline_file = Some(p.clone());
    }
    if let Some(v) = cfg.baseline.manage
        && config_wins(scan_matches, "manage_baseline")
    {
        scan_args.manage_baseline = v;
    }

    // ---------- alerts.defaults: feed the global --alert-* fields ----------
    if let Some(f) = cfg.alerts.defaults.format
        && config_wins(scan_matches, "alert_format")
    {
        scan_args.alert_format = Some(f);
    }
    if let Some(o) = cfg.alerts.defaults.on
        && config_wins(scan_matches, "alert_on")
    {
        scan_args.alert_on = o;
    }
    if let Some(c) = cfg.alerts.defaults.min_confidence
        && config_wins(scan_matches, "alert_min_confidence")
    {
        scan_args.alert_min_confidence = c.into();
    }
    if let Some(v) = cfg.alerts.defaults.include_secret
        && config_wins(scan_matches, "alert_include_secret")
    {
        scan_args.alert_include_secret = v;
    }
    if let Some(u) = &cfg.alerts.defaults.report_url
        && config_wins(scan_matches, "alert_report_url")
    {
        scan_args.alert_report_url = Some(u.clone());
    }
    if let Some(d) = cfg.alerts.defaults.detail
        && config_wins(scan_matches, "alert_detail")
    {
        scan_args.alert_detail = d;
    }
    if let Some(f) = cfg.alerts.defaults.finding_filter
        && config_wins(scan_matches, "alert_finding_filter")
    {
        scan_args.alert_finding_filter = f;
    }
    if let Some(v) = cfg.alerts.defaults.prevent_empty
        && config_wins(scan_matches, "alert_prevent_empty")
    {
        scan_args.alert_prevent_empty = v;
    }

    // ---------- alerts.webhooks: append URLs (existing v1 behavior) --------
    for w in &cfg.alerts.webhooks {
        scan_args.alert_webhook.push(w.url.clone());
        scan_args.config_webhook_overrides.push(
            kingfisher::cli::commands::scan::ConfigWebhookOverride {
                format: w.format,
                on: w.on,
                min_confidence: w.min_confidence.map(Into::into),
                include_secret: w.include_secret,
                report_url: w.report_url.clone(),
                detail: w.detail,
                finding_filter: w.finding_filter,
                prevent_empty: w.prevent_empty,
            },
        );
    }

    // ---------- global -----------------------------------------------------
    if let Some(m) = cfg.global.tls_mode
        && config_wins(scan_matches, "tls_mode")
    {
        global_args.tls_mode = m.into();
    }
    if let Some(v) = cfg.global.allow_internal_ips
        && config_wins(scan_matches, "allow_internal_ips")
    {
        global_args.allow_internal_ips = v;
    }
    if let Some(v) = cfg.global.no_update_check
        && config_wins(scan_matches, "no_update_check")
    {
        global_args.no_update_check = v;
    }
    if let Some(s) = &cfg.global.user_agent_suffix
        && config_wins(scan_matches, "user_agent_suffix")
    {
        let trimmed = s.trim();
        if !trimmed.is_empty() {
            global_args.user_agent_suffix = Some(trimmed.to_string());
        }
    }
    global_args.endpoint.extend(cfg.global.endpoints.iter().cloned());
    if let Some(p) = &cfg.global.endpoint_config
        && config_wins(scan_matches, "endpoint_config")
    {
        global_args.endpoint_config = Some(p.clone());
    }

    // ---------- git --------------------------------------------------------
    if let Some(p) = &cfg.git.clone_dir
        && config_wins(scan_matches, "git_clone_dir")
    {
        scan_args.input_specifier_args.git_clone_dir = Some(p.clone());
    }
    if let Some(v) = cfg.git.keep_clones
        && config_wins(scan_matches, "keep_clones")
    {
        scan_args.input_specifier_args.keep_clones = v;
    }
    if let Some(n) = cfg.git.repo_clone_limit
        && config_wins(scan_matches, "repo_clone_limit")
    {
        scan_args.input_specifier_args.repo_clone_limit = Some(n);
    }
    if let Some(v) = cfg.git.include_contributors
        && config_wins(scan_matches, "include_contributors")
    {
        scan_args.input_specifier_args.include_contributors = v;
    }
    // Provider API roots for enumeration / cloning. We accept the YAML value
    // as `String` (the schema serializer keeps it stable across `Url`'s
    // trailing-slash normalization), then parse to a `Url` for the runtime
    // field. parse_str() already validated this — `unwrap_or_default()`
    // would mask a real config bug, so we re-parse and *fail loud* if the
    // string somehow does not parse here.
    //
    // The provider subcommands (`scan github`, `scan gitlab`) expose their
    // own `--api-url` flag whose value is propagated into the same runtime
    // field by `into_operation()`. `api_url_config_wins` checks both the
    // outer hidden alias and the nested subcommand flag so an explicit
    // `kingfisher scan github --api-url ...` is never overridden by the
    // config file.
    if let Some(u) = &cfg.git.github_api_url
        && api_url_config_wins(scan_matches, "github_api_url", "github")
        && let Ok(parsed) = url::Url::parse(u)
    {
        scan_args.input_specifier_args.github_api_url = parsed;
    }
    if let Some(u) = &cfg.git.gitlab_api_url
        && api_url_config_wins(scan_matches, "gitlab_api_url", "gitlab")
        && let Ok(parsed) = url::Url::parse(u)
    {
        scan_args.input_specifier_args.gitlab_api_url = parsed;
    }
}

/// Run `kingfisher config <subcommand>`.
fn run_config_command(
    config_args: kingfisher::cli::commands::config_command::ConfigArgs,
    global_args: &GlobalArgs,
    top_matches: &clap::ArgMatches,
) -> Result<()> {
    use kingfisher::cli::commands::config_command::ConfigSubcommand;

    match config_args.command {
        ConfigSubcommand::Init(init_args) => {
            let init_matches = top_matches
                .subcommand_matches("config")
                .and_then(|m| m.subcommand_matches("init"))
                .ok_or_else(|| anyhow::anyhow!("internal: missing `config init` matches"))?;

            let yaml = build_config_yaml(&init_args.scan_args, global_args, init_matches)?;

            match init_args.out.as_deref() {
                Some(path) => {
                    if !init_args.force && path.exists() {
                        anyhow::bail!(
                            "{} already exists. Pass --force to overwrite.",
                            path.display()
                        );
                    }
                    std::fs::write(path, &yaml)
                        .with_context(|| format!("write {}", path.display()))?;
                    info!("wrote {}", path.display());
                }
                None => {
                    let mut stdout = std::io::stdout().lock();
                    stdout.write_all(yaml.as_bytes())?;
                }
            }
        }
    }
    Ok(())
}

/// Reverse of `apply_config`: walk the user-supplied flags from `ArgMatches`
/// and emit a [`KingfisherConfig`] containing only the flags the user
/// actually passed (CLI defaults are left out so the YAML stays minimal).
fn build_config_yaml(
    scan_args: &cli::commands::scan::ScanArgs,
    global_args: &GlobalArgs,
    sub_matches: &clap::ArgMatches,
) -> Result<String> {
    use clap::parser::ValueSource;
    use kingfisher::cli::config::{
        AlertsConfig, AlertsDefaultsConfig, BaselineConfig, FiltersConfig, GitConfig, GlobalConfig,
        KingfisherConfig, OutputConfig, RulesConfig, ScanConfig, ValidationConfig, WebhookConfig,
    };
    use std::collections::BTreeMap;

    fn user_set(matches: &clap::ArgMatches, id: &str) -> bool {
        matches!(
            matches.value_source(id),
            Some(ValueSource::CommandLine | ValueSource::EnvVariable)
        )
    }

    let mut cfg = KingfisherConfig::default();

    // ---------- scan ----------------------------------------------------
    let mut scan = ScanConfig::default();
    if user_set(sub_matches, "confidence") {
        scan.confidence = Some(scan_args.confidence.into());
    }
    if user_set(sub_matches, "min_entropy")
        && let Some(e) = scan_args.min_entropy
    {
        scan.min_entropy = Some(e);
    }
    if user_set(sub_matches, "no_validate") {
        scan.no_validate = Some(scan_args.no_validate);
    }
    if user_set(sub_matches, "only_valid") {
        scan.only_valid = Some(scan_args.only_valid);
    }
    if user_set(sub_matches, "validation_filter") {
        scan.validation_filter = scan_args.validation_filter;
    }
    if user_set(sub_matches, "redact") {
        scan.redact = Some(scan_args.redact);
    }
    if user_set(sub_matches, "no_dedup") {
        scan.no_dedup = Some(scan_args.no_dedup);
    }
    if user_set(sub_matches, "turbo") {
        scan.turbo = Some(scan_args.turbo);
    }
    if user_set(sub_matches, "no_base64") {
        scan.no_base64 = Some(scan_args.no_base64);
    }
    if user_set(sub_matches, "access_map") {
        scan.access_map = Some(scan_args.access_map);
    }
    if user_set(sub_matches, "rule_stats") {
        scan.rule_stats = Some(scan_args.rule_stats);
    }
    if user_set(sub_matches, "num_jobs") {
        scan.jobs = Some(scan_args.num_jobs);
    }
    if user_set(sub_matches, "git_repo_timeout") {
        scan.git_repo_timeout = Some(scan_args.git_repo_timeout);
    }
    cfg.scan = scan;

    // ---------- rules ---------------------------------------------------
    let mut rules = RulesConfig::default();
    if user_set(sub_matches, "rule") {
        rules.enabled = scan_args.rules.rule.clone();
    }
    if user_set(sub_matches, "exclude_rule") {
        rules.disabled = scan_args.rules.exclude_rule.clone();
    }
    if !scan_args.rules.rules_path.is_empty() {
        rules.paths = scan_args.rules.rules_path.clone();
    }
    if user_set(sub_matches, "load_builtins") {
        rules.load_builtins = Some(scan_args.rules.load_builtins);
    }
    if user_set(sub_matches, "rule_cache") {
        rules.cache = Some(true);
    }
    if user_set(sub_matches, "no_rule_cache") {
        rules.cache = Some(false);
    }
    if user_set(sub_matches, "rule_cache_dir") {
        rules.cache_dir = scan_args.rule_cache.rule_cache_dir.clone();
    }
    cfg.rules = rules;

    // ---------- validation ---------------------------------------------
    let mut validation = ValidationConfig::default();
    if user_set(sub_matches, "validation_timeout") {
        validation.timeout = Some(scan_args.validation_timeout);
    }
    if user_set(sub_matches, "validation_retries") {
        validation.retries = Some(scan_args.validation_retries);
    }
    if user_set(sub_matches, "validation_rps")
        && let Some(rps) = scan_args.validation_rps
    {
        validation.rps = Some(rps);
    }
    if !scan_args.validation_rps_rule.is_empty() {
        let mut map = BTreeMap::new();
        for entry in &scan_args.validation_rps_rule {
            let (rule, rps) = entry
                .split_once('=')
                .ok_or_else(|| anyhow::anyhow!("invalid --validation-rps-rule entry: {entry:?}"))?;
            let rps: f64 = rps.parse().with_context(|| format!("invalid RPS in {entry:?}"))?;
            map.insert(rule.trim().to_string(), rps);
        }
        validation.rps_per_rule = map;
    }
    if user_set(sub_matches, "full_validation_response") {
        validation.full_response = Some(scan_args.full_validation_response);
    }
    if user_set(sub_matches, "max_validation_response_length") {
        validation.max_response_length = Some(scan_args.max_validation_response_length);
    }
    cfg.validation = validation;

    // ---------- filters --------------------------------------------------
    let mut filters = FiltersConfig::default();
    if !scan_args.skip_word.is_empty() {
        filters.skip_words = scan_args.skip_word.clone();
    }
    if !scan_args.skip_regex.is_empty() {
        filters.skip_regex = scan_args.skip_regex.clone();
    }
    if !scan_args.content_filtering_args.exclude.is_empty() {
        filters.exclude = scan_args.content_filtering_args.exclude.clone();
    }
    if user_set(sub_matches, "max_file_size_mb") {
        filters.max_file_size_mb = Some(scan_args.content_filtering_args.max_file_size_mb);
    }
    if user_set(sub_matches, "no_binary") {
        filters.no_binary = Some(scan_args.content_filtering_args.no_binary);
    }
    if user_set(sub_matches, "no_extract_archives") {
        filters.no_extract_archives = Some(scan_args.content_filtering_args.no_extract_archives);
    }
    if user_set(sub_matches, "extraction_depth") {
        filters.extraction_depth = Some(scan_args.content_filtering_args.extraction_depth);
    }
    if user_set(sub_matches, "no_inline_ignore") {
        filters.no_inline_ignore = Some(scan_args.no_inline_ignore);
    }
    if user_set(sub_matches, "no_ignore_if_contains") {
        filters.no_ignore_if_contains = Some(scan_args.no_ignore_if_contains);
    }
    if !scan_args.extra_ignore_comments.is_empty() {
        filters.extra_ignore_comments = scan_args.extra_ignore_comments.clone();
    }
    if !scan_args.skip_aws_account.is_empty() {
        filters.skip_aws_accounts = scan_args.skip_aws_account.clone();
    }
    if user_set(sub_matches, "skip_aws_account_file")
        && let Some(p) = &scan_args.skip_aws_account_file
    {
        filters.skip_aws_account_file = Some(p.clone());
    }
    cfg.filters = filters;

    // ---------- output ---------------------------------------------------
    let mut output = OutputConfig::default();
    if user_set(sub_matches, "format") {
        output.format = Some(scan_args.output_args.format.into());
    }
    if user_set(sub_matches, "output")
        && let Some(p) = &scan_args.output_args.output
    {
        output.path = Some(p.clone());
    }
    cfg.output = output;

    // ---------- baseline ------------------------------------------------
    let mut baseline = BaselineConfig::default();
    if user_set(sub_matches, "baseline_file")
        && let Some(p) = &scan_args.baseline_file
    {
        baseline.file = Some(p.clone());
    }
    if user_set(sub_matches, "manage_baseline") {
        baseline.manage = Some(scan_args.manage_baseline);
    }
    cfg.baseline = baseline;

    // ---------- alerts (defaults + webhooks via --alert-webhook) -------
    let mut alerts = AlertsConfig::default();
    let mut defaults = AlertsDefaultsConfig::default();
    if user_set(sub_matches, "alert_format") {
        defaults.format = scan_args.alert_format;
    }
    if user_set(sub_matches, "alert_on") {
        defaults.on = Some(scan_args.alert_on);
    }
    if user_set(sub_matches, "alert_min_confidence") {
        defaults.min_confidence = Some(scan_args.alert_min_confidence.into());
    }
    if user_set(sub_matches, "alert_include_secret") {
        defaults.include_secret = Some(scan_args.alert_include_secret);
    }
    if user_set(sub_matches, "alert_report_url")
        && let Some(u) = &scan_args.alert_report_url
    {
        defaults.report_url = Some(u.clone());
    }
    if user_set(sub_matches, "alert_detail") {
        defaults.detail = Some(scan_args.alert_detail);
    }
    if user_set(sub_matches, "alert_finding_filter") {
        defaults.finding_filter = Some(scan_args.alert_finding_filter);
    }
    if user_set(sub_matches, "alert_prevent_empty") {
        defaults.prevent_empty = Some(scan_args.alert_prevent_empty);
    }
    alerts.defaults = defaults;
    // Each --alert-webhook URL becomes a webhook entry. Per-webhook overrides
    // (slack vs teams, on=always, etc.) cannot be expressed as positional CLI
    // flags, so the emitted entry just carries the URL — operators can edit
    // the file to add per-sink behavior afterward.
    for url in &scan_args.alert_webhook {
        alerts.webhooks.push(WebhookConfig {
            url: url.clone(),
            format: None,
            on: None,
            min_confidence: None,
            include_secret: None,
            report_url: None,
            detail: None,
            finding_filter: None,
            prevent_empty: None,
        });
    }
    cfg.alerts = alerts;

    // ---------- global --------------------------------------------------
    let mut g = GlobalConfig::default();
    if user_set(sub_matches, "tls_mode") {
        g.tls_mode = Some(global_args.tls_mode.into());
    }
    if user_set(sub_matches, "allow_internal_ips") {
        g.allow_internal_ips = Some(global_args.allow_internal_ips);
    }
    if user_set(sub_matches, "no_update_check") {
        g.no_update_check = Some(global_args.no_update_check);
    }
    if user_set(sub_matches, "user_agent_suffix")
        && let Some(s) = &global_args.user_agent_suffix
    {
        g.user_agent_suffix = Some(s.clone());
    }
    if !global_args.endpoint.is_empty() {
        g.endpoints = global_args.endpoint.clone();
    }
    if user_set(sub_matches, "endpoint_config")
        && let Some(p) = &global_args.endpoint_config
    {
        g.endpoint_config = Some(p.clone());
    }
    cfg.global = g;

    // ---------- git ----------------------------------------------------
    let mut git = GitConfig::default();
    if user_set(sub_matches, "git_clone_dir")
        && let Some(p) = &scan_args.input_specifier_args.git_clone_dir
    {
        git.clone_dir = Some(p.clone());
    }
    if user_set(sub_matches, "keep_clones") {
        git.keep_clones = Some(scan_args.input_specifier_args.keep_clones);
    }
    if user_set(sub_matches, "repo_clone_limit")
        && let Some(n) = scan_args.input_specifier_args.repo_clone_limit
    {
        git.repo_clone_limit = Some(n);
    }
    if user_set(sub_matches, "include_contributors") {
        git.include_contributors = Some(scan_args.input_specifier_args.include_contributors);
    }
    // Provider API roots are stored as `Url` on the runtime side; the YAML
    // schema is a `String` so the emitted file matches exactly what the
    // user typed. `Url::to_string()` adds a trailing `/` on bare-host URLs
    // (e.g. `https://gitlab.example.com` → `https://gitlab.example.com/`),
    // which would silently rewrite the user's input on every `config init`
    // round-trip. Pull the raw CLI/env string from `ArgMatches` instead so
    // the emitted YAML matches what the user actually passed.
    fn raw_arg_string(matches: &clap::ArgMatches, id: &str) -> Option<String> {
        matches.get_raw(id).and_then(|mut v| v.next()).and_then(|s| s.to_str()).map(str::to_owned)
    }
    if user_set(sub_matches, "github_api_url") {
        git.github_api_url = raw_arg_string(sub_matches, "github_api_url");
    }
    if user_set(sub_matches, "gitlab_api_url") {
        git.gitlab_api_url = raw_arg_string(sub_matches, "gitlab_api_url");
    }
    cfg.git = git;

    // Serialize, then prune null/empty mappings so the YAML is concise.
    let mut value =
        serde_yaml::to_value(&cfg).context("serialize KingfisherConfig to YAML value")?;
    prune_empty(&mut value);
    let mut yaml = serde_yaml::to_string(&value).context("emit YAML")?;

    if yaml.trim() == "{}" || yaml.trim().is_empty() {
        // Avoid emitting "{}" — a no-op YAML is more confusing than empty.
        yaml = String::from("# kingfisher.yaml — no flags supplied; nothing to emit.\n");
    } else {
        let header = "# kingfisher.yaml — generated by `kingfisher config init`.\n\
                      # Edit freely; CLI flags always override config values.\n";
        yaml = format!("{header}{yaml}");
    }
    Ok(yaml)
}

/// Recursively drop `null` values, empty sequences, and empty mappings from
/// a [`serde_yaml::Value`]. Used by `build_config_yaml` to keep the output
/// file as small as the user's actual flag set.
fn prune_empty(value: &mut serde_yaml::Value) {
    use serde_yaml::Value;
    match value {
        Value::Mapping(map) => {
            let keys: Vec<_> = map.keys().cloned().collect();
            for k in keys {
                if let Some(v) = map.get_mut(&k) {
                    prune_empty(v);
                    let drop = match v {
                        Value::Null => true,
                        Value::Sequence(s) => s.is_empty(),
                        Value::Mapping(m) => m.is_empty(),
                        _ => false,
                    };
                    if drop {
                        map.remove(&k);
                    }
                }
            }
        }
        Value::Sequence(s) => {
            for v in s.iter_mut() {
                prune_empty(v);
            }
        }
        _ => {}
    }
}

/// Build a human-readable description of what the scan is targeting, for use
/// in alert payloads (`Target:` header). The previous implementation looked
/// only at the first local path, so scans that used git URLs, GitHub orgs,
/// S3 buckets, etc. produced an empty target line. This walks the input
/// specifiers in priority order and returns the first one that's set.
fn describe_scan_target(args: &InputSpecifierArgs) -> Option<String> {
    fn join_brief<T: std::fmt::Display>(items: &[T], label: &str) -> String {
        match items.len() {
            0 => String::new(),
            1 => items[0].to_string(),
            n if n <= 3 => items.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", "),
            n => format!("{} {label}", n),
        }
    }

    // Local paths — the most common scan target.
    if !args.path_inputs.is_empty() {
        let s = if args.path_inputs.len() == 1 {
            args.path_inputs[0].display().to_string()
        } else if args.path_inputs.len() <= 3 {
            args.path_inputs.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(", ")
        } else {
            format!("{} paths", args.path_inputs.len())
        };
        return Some(s);
    }
    if !args.git_url.is_empty() {
        return Some(join_brief(&args.git_url, "git URLs"));
    }
    if !args.github_event_user.is_empty() {
        return Some(format!(
            "github public events: {}",
            join_brief(&args.github_event_user, "github users")
        ));
    }
    if !args.github_user.is_empty() {
        return Some(format!("github user: {}", join_brief(&args.github_user, "github users")));
    }
    if !args.github_organization.is_empty() {
        return Some(format!(
            "github org: {}",
            join_brief(&args.github_organization, "github orgs")
        ));
    }
    if args.all_github_organizations {
        return Some("all GitHub organizations".to_string());
    }
    if !args.gitlab_user.is_empty() {
        return Some(format!("gitlab user: {}", join_brief(&args.gitlab_user, "gitlab users")));
    }
    if !args.gitlab_group.is_empty() {
        return Some(format!("gitlab group: {}", join_brief(&args.gitlab_group, "gitlab groups")));
    }
    if !args.huggingface_user.is_empty()
        || !args.huggingface_organization.is_empty()
        || !args.huggingface_model.is_empty()
        || !args.huggingface_dataset.is_empty()
        || !args.huggingface_space.is_empty()
        || !args.huggingface_bucket.is_empty()
    {
        return Some("huggingface".to_string());
    }
    if !args.gitea_user.is_empty() || !args.gitea_organization.is_empty() {
        return Some("gitea".to_string());
    }
    if !args.bitbucket_user.is_empty() || !args.bitbucket_workspace.is_empty() {
        return Some("bitbucket".to_string());
    }
    if !args.azure_organization.is_empty() {
        return Some(format!("azure: {}", join_brief(&args.azure_organization, "azure orgs")));
    }
    if let Some(b) = &args.s3_bucket {
        return Some(format!("s3://{}{}", b, args.s3_prefix.as_deref().unwrap_or("")));
    }
    if let Some(b) = &args.gcs_bucket {
        return Some(format!("gs://{}{}", b, args.gcs_prefix.as_deref().unwrap_or("")));
    }
    if !args.docker_image.is_empty() || !args.docker_archive.is_empty() {
        let mut docker_targets = Vec::new();
        if !args.docker_image.is_empty() {
            docker_targets.push(join_brief(&args.docker_image, "images"));
        }
        if !args.docker_archive.is_empty() {
            let archives =
                args.docker_archive.iter().map(|p| p.display().to_string()).collect::<Vec<_>>();
            docker_targets.push(join_brief(&archives, "archives"));
        }
        return Some(format!("docker: {}", docker_targets.join(", ")));
    }
    if let Some(u) = &args.jira_url {
        return Some(format!("jira: {}", u));
    }
    if let Some(u) = &args.confluence_url {
        return Some(format!("confluence: {}", u));
    }
    if args.slack_query.is_some() {
        return Some("slack search".to_string());
    }
    if args.teams_query.is_some() {
        return Some("teams search".to_string());
    }
    if !args.postman_workspaces.is_empty()
        || !args.postman_collections.is_empty()
        || args.postman_all
    {
        return Some("postman".to_string());
    }
    None
}

/// Return whether stdin should be staged as a scan input.
///
/// `-` is the only way to ask for a stdin scan: `ScanCommandArgs::into_operation`
/// rejects an invocation that names no input at all, so an empty `path_inputs`
/// means some *other* source (a Git URL, an org, a bucket, ...) was selected and
/// must not be silently replaced by whatever happens to be on a redirected stdin.
fn should_stage_stdin(input_args: &InputSpecifierArgs, stdin_is_terminal: bool) -> bool {
    !stdin_is_terminal && input_args.path_inputs.iter().any(is_stdin_placeholder)
}

fn is_stdin_placeholder(path: impl AsRef<std::path::Path>) -> bool {
    path.as_ref().as_os_str() == "-"
}

/// Swap the `-` placeholders in `path_inputs` for the staged stdin file.
///
/// Repeated `-` arguments collapse onto the single staged file, and any sibling
/// paths (`kingfisher scan - ./src`) keep their position instead of being
/// dropped.
fn replace_stdin_placeholders(path_inputs: &mut Vec<PathBuf>, stdin_file: PathBuf) {
    let mut staged = false;
    let mut resolved = Vec::with_capacity(path_inputs.len());
    for path in path_inputs.drain(..) {
        if is_stdin_placeholder(&path) {
            if !std::mem::replace(&mut staged, true) {
                resolved.push(stdin_file.clone());
            }
        } else {
            resolved.push(path);
        }
    }
    *path_inputs = resolved;
}

/// Build the resolved list of alert sinks from CLI flags + config overrides.
/// `scan_args.config_webhook_overrides` aligns with the trailing entries of
/// `scan_args.alert_webhook` (those that came from `kingfisher.yaml`); CLI URLs
/// always come first and use the scalar CLI flags.
fn build_alert_sinks(
    scan_args: &cli::commands::scan::ScanArgs,
) -> Vec<kingfisher::alerts::AlertSink> {
    let cli_count =
        scan_args.alert_webhook.len().saturating_sub(scan_args.config_webhook_overrides.len());
    scan_args
        .alert_webhook
        .iter()
        .enumerate()
        .map(|(i, url)| {
            let override_ = if i >= cli_count {
                scan_args.config_webhook_overrides.get(i - cli_count).cloned().unwrap_or_default()
            } else {
                cli::commands::scan::ConfigWebhookOverride::default()
            };
            let format = override_
                .format
                .or(scan_args.alert_format)
                .unwrap_or_else(|| kingfisher::alerts::AlertFormat::infer_from_url(url));
            let finding_filter = override_.finding_filter.unwrap_or(scan_args.alert_finding_filter);
            kingfisher::alerts::AlertSink {
                url: url.clone(),
                format,
                on: override_.on.unwrap_or(scan_args.alert_on),
                min_confidence: override_.min_confidence.unwrap_or(scan_args.alert_min_confidence),
                include_secret: override_.include_secret.unwrap_or(scan_args.alert_include_secret),
                report_url: override_
                    .report_url
                    .clone()
                    .or_else(|| scan_args.alert_report_url.clone()),
                detail: override_.detail.unwrap_or(scan_args.alert_detail),
                finding_filter,
                prevent_empty: override_.prevent_empty.unwrap_or(scan_args.alert_prevent_empty),
            }
        })
        .collect()
}

/// Warn about alert configurations that will silently produce nothing, before
/// the scan starts.
///
/// `build_alert_sinks` runs only after the scan completes, so a check placed
/// there would tell the operator their filter was unusable only once they had
/// already paid for a full scan.
fn warn_on_alert_misconfiguration(scan_args: &cli::commands::scan::ScanArgs) {
    if scan_args.alert_webhook.is_empty() {
        return;
    }
    for sink in build_alert_sinks(scan_args) {
        if sink.finding_filter == kingfisher::alerts::AlertFindingFilter::AccessMapOnly
            && !scan_args.access_map
        {
            warn!(
                "alert sink {} uses access-map-only filtering but --blast-radius was not enabled; \
                 this sink will not include findings (use --alert-prevent-empty to suppress \
                 empty filtered alerts)",
                kingfisher::alerts::redact_webhook(&sink.url)
            );
        }
    }
}

pub fn determine_exit_code(datastore: &Arc<Mutex<findings_store::FindingsStore>>) -> i32 {
    // exit with code 200 if _any_ findings are discovered
    // exit with code 205 if VALIDATED findings are discovered
    // exit with code 0 if there are NO findings discovered
    let ds = datastore.lock().unwrap();
    // Get all matches
    // let all_matches = ds.get_matches();

    // Only consider visible matches when determining the exit code
    let all_matches = ds
        .get_matches()
        .iter()
        .filter(|msg| {
            let (_, _, match_item) = &***msg;
            match_item.visible
        })
        .collect::<Vec<_>>();

    if all_matches.is_empty() {
        // No findings discovered
        0
    } else {
        // Check if there are any validated findings
        let validated_matches = all_matches
            .iter()
            .filter(|msg| {
                let (_, _, match_item) = &****msg;
                match_item.rule.syntax().is_authoritative()
                    && match_item.validation_outcome.is_verified_active()
            })
            .count();
        if validated_matches > 0 {
            // Validated findings discovered
            205
        } else {
            // Findings discovered, but not validated
            200
        }
    }
}

async fn async_main(args: CommandLineArgs, matches: clap::ArgMatches) -> Result<AsyncMainOutcome> {
    setup_logging(&args.global_args);
    let global_args = args.global_args.clone();

    match args.command {
        Command::SelfUpdate => {
            // The explicit `kingfisher self-update` subcommand intentionally does NOT
            // re-exec after updating: it has no further work to do, so simply exiting
            // is the correct end-of-run behavior. The re-exec path is reserved for the
            // global `--self-update` flag combined with another command (e.g. `scan`).
            let mut g = global_args;
            g.self_update = true;
            g.no_update_check = false;
            let _ = check_for_update_async(&g, None).await;
            Ok(AsyncMainOutcome::Done)
        }
        Command::View(view_args) => view::run(view_args).await.map(|_| AsyncMainOutcome::Done),
        Command::BlastRadius(blast_radius_args) => {
            if blast_radius_args.rule.is_none() {
                let view_report = blast_radius_args.view_report;
                let provider = blast_radius_args
                    .input
                    .as_deref()
                    .ok_or_else(|| {
                        anyhow::anyhow!("a provider is required for standalone mapping")
                    })?
                    .parse::<cli::commands::access_map::AccessMapProvider>()
                    .map_err(|error| anyhow::anyhow!(error))?;
                let format = match blast_radius_args.format.as_str() {
                    "json" => cli::commands::access_map::AccessMapOutputFormat::Json,
                    "html" => cli::commands::access_map::AccessMapOutputFormat::Html,
                    _ if blast_radius_args.view_report => {
                        cli::commands::access_map::AccessMapOutputFormat::Json
                    }
                    _ => anyhow::bail!(
                        "standalone blast-radius mapping supports only json and html output"
                    ),
                };
                let access_map_args = cli::commands::access_map::AccessMapArgs {
                    provider,
                    credential_path: blast_radius_args.credential_path,
                    output_args: cli::commands::access_map::AccessMapOutputArgs {
                        output: blast_radius_args.output,
                        format,
                    },
                };
                if view_report {
                    let result = access_map::map_credential(&access_map_args).await?;
                    let report_bytes = direct_access_map::build_viewer_report_bytes(&[
                        direct_access_map::DirectAccessMapResult {
                            rule_id: format!("standalone.{}", result.cloud),
                            rule_name: format!("Standalone {} credential", result.cloud),
                            result,
                        },
                    ])?;
                    view::run(view::ViewArgs {
                        reports: Vec::new(),
                        port: view::DEFAULT_PORT,
                        address: view::DEFAULT_ADDRESS.to_string(),
                        open_browser: true,
                        report_bytes: Some(report_bytes),
                    })
                    .await?;
                } else {
                    access_map::run(access_map_args).await?;
                }
                return Ok(AsyncMainOutcome::Done);
            }
            let results =
                direct_access_map::run_direct_access_map(&blast_radius_args, &global_args).await?;
            if blast_radius_args.view_report {
                let report_bytes = direct_access_map::build_viewer_report_bytes(&results)?;
                view::run(view::ViewArgs {
                    reports: Vec::new(),
                    port: view::DEFAULT_PORT,
                    address: view::DEFAULT_ADDRESS.to_string(),
                    open_browser: true,
                    report_bytes: Some(report_bytes),
                })
                .await?;
            } else {
                direct_access_map::print_results(
                    &results,
                    &blast_radius_args.format,
                    blast_radius_args.output.as_deref(),
                )?;
            }
            Ok(AsyncMainOutcome::Done)
        }
        Command::Config(config_args) => {
            run_config_command(config_args, &global_args, &matches)?;
            Ok(AsyncMainOutcome::Done)
        }
        Command::Validate(validate_args) => {
            let results =
                direct_validate::run_direct_validation(&validate_args, &global_args).await?;
            let use_color = global_args.use_color(std::io::stdout());
            direct_validate::print_results(&results, &validate_args.format, use_color);
            // Offline local derivation is a successful validation operation even though it does
            // not claim the material is an active credential.
            if direct_validate::any_actionable(&results) {
                Ok(AsyncMainOutcome::Done)
            } else {
                std::process::exit(1);
            }
        }
        Command::Revoke(revoke_args) => {
            let results = direct_revoke::run_direct_revocation(&revoke_args, &global_args).await?;
            let use_color = global_args.use_color(std::io::stdout());
            direct_revoke::print_results(&results, &revoke_args.format, use_color);
            // Exit with code 0 if any result revoked, 1 if all failed
            if direct_revoke::any_revoked(&results) {
                Ok(AsyncMainOutcome::Done)
            } else {
                std::process::exit(1);
            }
        }
        command => {
            let update_status = check_for_update_async(&global_args, None).await;
            // If the on-disk binary was just replaced by --self-update, return early so
            // fn run() can drop the runtime and re-exec into the new binary. The current
            // invocation will resume with the new code (e.g. updated rule set).
            if update_status.was_self_updated {
                return Ok(AsyncMainOutcome::Reexec);
            }
            match command {
                Command::Scan(scan_command) => match scan_command.into_operation()? {
                    ScanOperation::Scan(mut scan_args) => {
                        // Resolve and merge kingfisher.yaml. Lists are concatenated onto CLI
                        // flags; scalar fields are applied only when the user did not pass
                        // the matching CLI flag (clap `ValueSource` lookup). Errors only
                        // when --config explicitly points at a file we cannot parse.
                        // Auto-discovery failures are silent.
                        let loaded_config = load_project_config(global_args.config.as_deref())?;
                        let scan_matches = matches.subcommand_matches("scan");
                        let mut effective_global_args = global_args.clone();
                        if let Some(cfg) = &loaded_config {
                            apply_config(
                                &mut scan_args,
                                &mut effective_global_args,
                                cfg,
                                scan_matches,
                            );
                            // Re-publish the user-agent suffix in case the config supplied it
                            // — the initial set_user_agent_suffix call ran before config load.
                            set_user_agent_suffix(effective_global_args.user_agent_suffix.clone());
                        }
                        let global_args = effective_global_args;
                        // Config merging can introduce `output_args.output`
                        // (output.path) after CLI validation already ran, so
                        // re-check the effective --audit-log / --output paths
                        // against the merged values.
                        scan_args.validate_audit_log_collisions(
                            global_args.endpoint_config.as_deref(),
                            global_args.config.as_deref(),
                        )?;
                        warn_on_alert_misconfiguration(&scan_args);
                        if scan_args.view_report {
                            view::ensure_port_available(
                                scan_args.view_report_port,
                                &scan_args.view_report_address,
                                "--view-report-port",
                            )?;
                        }
                        let view_scan_started_at = chrono::Local::now();
                        let view_scan_start_time = Instant::now();
                        let temp_dir =
                            TempDir::new().context("Failed to create temporary directory")?;
                        let temp_dir_path = temp_dir.path().to_path_buf();
                        let clone_dir = if let Some(clone_dir) =
                            scan_args.input_specifier_args.git_clone_dir.as_ref()
                        {
                            std::fs::create_dir_all(clone_dir)?;
                            clone_dir.to_path_buf()
                        } else {
                            temp_dir_path.clone()
                        };
                        let keep_clones = scan_args.input_specifier_args.keep_clones
                            && scan_args.input_specifier_args.git_clone_dir.is_none();
                        // When clones go into the temp dir and the user hasn't asked to
                        // keep them, delete each clone as soon as it has been scanned so
                        // disk usage stays bounded for very large fan-outs (e.g.
                        // --include-contributors expanding to thousands of repos).
                        let auto_cleanup_clones = !scan_args.input_specifier_args.keep_clones
                            && scan_args.input_specifier_args.git_clone_dir.is_none();

                        let datastore = Arc::new(Mutex::new(FindingsStore::new(clone_dir)));
                        info!(
                            "Launching with {} concurrent scan jobs. Use --jobs to override.",
                            &scan_args.num_jobs
                        );
                        if should_stage_stdin(
                            &scan_args.input_specifier_args,
                            std::io::stdin().is_terminal(),
                        ) {
                            let mut buf = Vec::new();
                            std::io::stdin().read_to_end(&mut buf)?;
                            let stdin_file = temp_dir_path.join("stdin_input");
                            std::fs::write(&stdin_file, buf)?;
                            replace_stdin_placeholders(
                                &mut scan_args.input_specifier_args.path_inputs,
                                stdin_file,
                            );
                        }

                        let rules_db = Arc::new(load_and_record_rules(
                            &scan_args,
                            &datastore,
                            global_args.use_progress(),
                        )?);
                        run_scan(
                            &global_args,
                            &scan_args,
                            &rules_db,
                            Arc::clone(&datastore),
                            &update_status,
                            auto_cleanup_clones,
                        )
                        .await?;
                        if update_status.is_outdated
                            && let Some(styled) = &update_status.styled_message
                        {
                            let _ = writeln!(std::io::stderr(), "{}", styled);
                        }
                        let exit_code = determine_exit_code(&datastore);

                        // Dispatch alert webhooks (best-effort; failures are warned, not fatal).
                        if !scan_args.alert_webhook.is_empty() {
                            let alert_reporter = DetailsReporter {
                                datastore: Arc::clone(&datastore),
                                styles: Styles::new(global_args.use_color(std::io::stdout())),
                                validation_filter: scan_args.effective_validation_filter(),
                                audit_context: None,
                            };
                            match alert_reporter.build_finding_records(&scan_args) {
                                Ok(records) => {
                                    let target =
                                        describe_scan_target(&scan_args.input_specifier_args);
                                    let access_map =
                                        alert_reporter.build_alert_access_map_entries(&scan_args);
                                    let sinks: Vec<_> = build_alert_sinks(&scan_args)
                                        .into_iter()
                                        .filter(|sink| {
                                            match kingfisher::alerts::validate_webhook_url(
                                                &sink.url,
                                            ) {
                                                Ok(()) => true,
                                                Err(e) => {
                                                    warn!("alert dispatch: skipping sink: {}", e);
                                                    false
                                                }
                                            }
                                        })
                                        .collect();
                                    kingfisher::alerts::dispatch_with_context(
                                        &sinks,
                                        &records,
                                        &access_map,
                                        target,
                                        scan_args.alert_dry_run,
                                    )
                                    .await;
                                }
                                Err(e) => warn!("alert dispatch: failed to build findings: {}", e),
                            }
                        }

                        if scan_args.view_report {
                            let audit_context = ScanAuditContext {
                                scan_timestamp: Some(view_scan_started_at.to_rfc3339()),
                                scan_duration_seconds: Some(
                                    view_scan_start_time.elapsed().as_secs_f64(),
                                ),
                                rules_applied: Some(rules_db.num_rules()),
                                successful_validations: None,
                                failed_validations: None,
                                skipped_validations: None,
                                blobs_scanned: None,
                                bytes_scanned: None,
                                running_version: Some(update_status.running_version.clone()),
                                latest_version: update_status.latest_version.clone(),
                                update_check_status: Some(
                                    update_status.check_status.as_str().to_string(),
                                ),
                            };
                            let reporter = DetailsReporter {
                                datastore: Arc::clone(&datastore),
                                styles: Styles::new(global_args.use_color(std::io::stdout())),
                                validation_filter: scan_args.effective_validation_filter(),
                                audit_context: Some(audit_context),
                            };
                            let envelope = reporter.build_report_envelope(&scan_args)?;
                            let report_bytes = serde_json::to_vec_pretty(&envelope)?;
                            let view_args = view::ViewArgs {
                                reports: vec![],
                                port: scan_args.view_report_port,
                                address: scan_args.view_report_address.clone(),
                                open_browser: true,
                                report_bytes: Some(report_bytes),
                            };
                            view::run(view_args).await?;
                        }

                        if keep_clones {
                            let _kept_path = temp_dir.keep(); // consumes TempDir; prevents auto-delete
                        } else if let Err(e) = temp_dir.close() {
                            eprintln!("Failed to close temporary directory: {}", e);
                        }

                        std::process::exit(exit_code);
                    }
                    ScanOperation::ListRepositories(list_command) => match list_command {
                        ListRepositoriesCommand::Github { api_url, specifiers } => {
                            github::list_repositories(
                                api_url,
                                global_args.ignore_certs,
                                global_args.use_progress(),
                                &specifiers.user,
                                specifiers.include_gists,
                                &specifiers.organization,
                                specifiers.all_organizations,
                                &specifiers.exclude_repos,
                                specifiers.repo_type.into(),
                            )
                            .await?;
                        }
                        ListRepositoriesCommand::Gitlab { api_url, specifiers } => {
                            kingfisher::gitlab::list_repositories(
                                api_url,
                                global_args.ignore_certs,
                                global_args.use_progress(),
                                &specifiers.user,
                                specifiers.include_snippets,
                                &specifiers.group,
                                specifiers.all_groups,
                                specifiers.include_subgroups,
                                &specifiers.exclude_repos,
                                specifiers.repo_type.into(),
                            )
                            .await?;
                        }
                        ListRepositoriesCommand::Gitea { api_url, specifiers } => {
                            gitea::list_repositories(
                                api_url,
                                global_args.ignore_certs,
                                global_args.use_progress(),
                                &specifiers.user,
                                &specifiers.organization,
                                specifiers.all_organizations,
                                &specifiers.exclude_repos,
                                specifiers.repo_type.into(),
                            )
                            .await?;
                        }
                        ListRepositoriesCommand::Bitbucket { api_url, specifiers } => {
                            let auth_config = bitbucket::AuthConfig::from_env();
                            bitbucket::list_repositories(
                                api_url,
                                auth_config,
                                global_args.ignore_certs,
                                global_args.use_progress(),
                                &specifiers.user,
                                specifiers.include_snippets,
                                &specifiers.workspace,
                                &specifiers.project,
                                specifiers.all_workspaces,
                                &specifiers.exclude_repos,
                                specifiers.repo_type.into(),
                            )
                            .await?;
                        }
                        ListRepositoriesCommand::Azure { base_url, specifiers } => {
                            azure::list_repositories(
                                base_url,
                                global_args.ignore_certs,
                                global_args.use_progress(),
                                &specifiers.organization,
                                &specifiers.project,
                                specifiers.all_projects,
                                &specifiers.exclude_repos,
                                specifiers.repo_type.into(),
                            )
                            .await?;
                        }
                        ListRepositoriesCommand::Huggingface { specifiers } => {
                            let repo_specifiers = huggingface::RepoSpecifiers {
                                user: specifiers.user.clone(),
                                organization: specifiers.organization.clone(),
                                model: specifiers.model.clone(),
                                dataset: specifiers.dataset.clone(),
                                space: specifiers.space.clone(),
                                bucket: specifiers.bucket.clone(),
                                exclude: specifiers.exclude.clone(),
                            };
                            let auth = huggingface::AuthConfig::from_env();
                            huggingface::list_repositories(
                                &repo_specifiers,
                                &auth,
                                global_args.ignore_certs,
                                global_args.use_progress(),
                            )
                            .await?;
                        }
                    },
                },
                Command::Rules(ref rule_args) => match &rule_args.command {
                    RulesCommand::Check(check_args) => {
                        run_rules_check(check_args)?;
                    }
                    RulesCommand::CompileCache(cache_args) => {
                        run_rules_compile_cache(cache_args)?;
                    }
                    RulesCommand::PruneCache(prune_args) => {
                        run_rules_prune_cache(prune_args)?;
                    }
                    RulesCommand::List(list_args) => {
                        run_rules_list(list_args)?;
                    }
                },
                Command::View(_) | Command::Wizard(_) => {
                    anyhow::bail!("View and wizard commands should not reach this branch")
                }
                Command::BlastRadius(_) => {
                    anyhow::bail!("BlastRadius command should not reach this branch")
                }
                Command::Validate(_) => {
                    anyhow::bail!("Validate command should not reach this branch")
                }
                Command::Revoke(_) => {
                    anyhow::bail!("Revoke command should not reach this branch")
                }
                Command::SelfUpdate => {
                    anyhow::bail!("SelfUpdate command should not reach this branch")
                }
                Command::Config(_) => {
                    anyhow::bail!("Config command should not reach this branch")
                }
            }
            if let Some(message) = &update_status.message {
                info!("{}", message);
            }
            Ok(AsyncMainOutcome::Done)
        }
    }
}

/// Create a default ScanArgs instance for rule loading
fn create_default_scan_args() -> cli::commands::scan::ScanArgs {
    use cli::commands::scan::*;
    ScanArgs {
        num_jobs: 1,
        rules: RuleSpecifierArgs {
            rules_path: Vec::new(),
            rule: vec!["all".into()],
            exclude_rule: Vec::new(),
            load_builtins: true,
        },
        rule_cache: RuleCacheArgs::default(),
        input_specifier_args: InputSpecifierArgs {
            path_inputs: Vec::new(),
            git_url: Vec::new(),
            git_clone_dir: None,
            keep_clones: false,
            repo_clone_limit: None,
            include_contributors: false,
            github_user: Vec::new(),
            github_include_gists: false,
            github_organization: Vec::new(),
            github_exclude: Vec::new(),
            all_github_organizations: false,
            github_api_url: url::Url::parse("https://api.github.com/").unwrap(),
            github_repo_type: GitHubRepoType::Source,
            github_event_user: Vec::new(),
            github_event_lookback_hours: 24,
            // new GitLab defaults
            gitlab_user: Vec::new(),
            gitlab_include_snippets: false,
            gitlab_group: Vec::new(),
            gitlab_exclude: Vec::new(),
            all_gitlab_groups: false,
            gitlab_api_url: Url::parse("https://gitlab.com/").unwrap(),
            gitlab_repo_type: GitLabRepoType::All,
            gitlab_include_subgroups: false,

            huggingface_user: Vec::new(),
            huggingface_organization: Vec::new(),
            huggingface_model: Vec::new(),
            huggingface_dataset: Vec::new(),
            huggingface_space: Vec::new(),
            huggingface_bucket: Vec::new(),
            huggingface_exclude: Vec::new(),

            gitea_user: Vec::new(),
            gitea_organization: Vec::new(),
            gitea_exclude: Vec::new(),
            all_gitea_organizations: false,
            gitea_api_url: Url::parse("https://gitea.com/api/v1/").unwrap(),
            gitea_repo_type: GiteaRepoType::Source,

            bitbucket_user: Vec::new(),
            bitbucket_include_snippets: false,
            bitbucket_workspace: Vec::new(),
            bitbucket_project: Vec::new(),
            bitbucket_exclude: Vec::new(),
            all_bitbucket_workspaces: false,
            bitbucket_api_url: Url::parse("https://api.bitbucket.org/2.0/").unwrap(),
            bitbucket_repo_type: BitbucketRepoType::Source,
            bitbucket_auth: BitbucketAuthArgs::default(),

            azure_organization: Vec::new(),
            azure_project: Vec::new(),
            azure_exclude: Vec::new(),
            all_azure_projects: false,
            azure_base_url: Url::parse("https://dev.azure.com/").unwrap(),
            azure_repo_type: AzureRepoType::Source,

            jira_url: None,
            jql: None,
            jira_include_comments: false,
            jira_include_changelog: false,
            confluence_url: None,
            cql: None,
            max_results: 100,

            s3_bucket: None,
            s3_prefix: None,
            role_arn: None,
            aws_local_profile: None,
            gcs_bucket: None,
            gcs_prefix: None,
            gcs_service_account: None,
            // Slack query
            slack_query: None,
            slack_api_url: Url::parse("https://slack.com/api/").unwrap(),
            // Teams query
            teams_query: None,
            teams_api_url: Url::parse("https://graph.microsoft.com/").unwrap(),

            postman_workspaces: Vec::new(),
            postman_collections: Vec::new(),
            postman_environments: Vec::new(),
            postman_all: false,
            postman_include_mocks_monitors: false,
            postman_api_url: Url::parse("https://api.getpostman.com/").unwrap(),
            // Docker image scanning
            docker_image: Vec::new(),
            docker_archive: Vec::new(),

            // git clone / history options
            git_clone: GitCloneMode::Bare,
            git_history: GitHistoryMode::Full,
            commit_metadata: true,
            repo_artifacts: false,
            scan_nested_repos: true,
            since_commit: None,
            branch: None,
            branch_root: false,
            branch_root_commit: None,
            staged: false,
        },
        extra_ignore_comments: Vec::new(),
        content_filtering_args: ContentFilteringArgs {
            max_file_size_mb: 25.0,
            no_extract_archives: true,
            extraction_depth: 2,
            exclude: Vec::new(), // Exclude patterns
            no_binary: true,
        },
        confidence: ConfidenceLevel::Medium,
        disk_offload: false,
        no_validate: true,
        access_map: false,
        rule_stats: false,
        only_valid: false,
        validation_filter: None,
        include_hidden_findings: false,
        min_entropy: None,
        redact: false,
        git_repo_timeout: 1800,
        audit_log: None,
        no_dedup: false,
        view_report: false,
        baseline_file: None,
        manage_baseline: false,
        skip_regex: Vec::new(),
        skip_word: Vec::new(),
        skip_aws_account: Vec::new(),
        skip_aws_account_file: None,
        output_args: OutputArgs { output: None, format: ReportOutputFormat::Pretty },
        no_base64: false,
        turbo: false,
        no_inline_ignore: false,
        no_ignore_if_contains: false,
        view_report_port: view::DEFAULT_PORT,
        view_report_address: view::DEFAULT_ADDRESS.to_string(),
        validation_timeout: 10,
        validation_retries: 1,
        validation_rps: None,
        validation_rps_rule: Vec::new(),
        full_validation_response: false,
        max_validation_response_length: 2048,
        alert_webhook: Vec::new(),
        alert_format: None,
        alert_on: kingfisher::alerts::AlertOn::Findings,
        alert_min_confidence: kingfisher::cli::commands::scan::ConfidenceLevel::Medium,
        alert_include_secret: false,
        alert_report_url: None,
        alert_detail: kingfisher::alerts::AlertDetail::Auto,
        alert_finding_filter: kingfisher::alerts::AlertFindingFilter::All,
        alert_prevent_empty: false,
        alert_dry_run: false,
        config_webhook_overrides: Vec::new(),
    }
}
/// Run the rules compile-cache command
pub fn run_rules_compile_cache(args: &RulesCompileCacheArgs) -> Result<()> {
    let mut scan_args = create_default_scan_args();
    scan_args.confidence = args.confidence;

    let loader = RuleLoader::from_rule_specifiers(&args.rules);
    let loaded = loader.load(&scan_args).context("Failed to load rules")?;
    let resolved = loaded.resolve_enabled_rules_owned().context("Failed to resolve rules")?;
    let betterleaks_prefilter = loaded.betterleaks_prefilter_for(&resolved);
    let cache = RuleCacheConfig::from_dir_or_env(args.cache.rule_cache_dir.clone());
    info!(cache_dir = %cache.cache_dir().display(), "Using Vectorscan rule cache");
    let rules_db = RulesDatabase::from_rules_with_cache_and_betterleaks_prefilter(
        resolved,
        &cache,
        betterleaks_prefilter,
    )
    .context("Failed to compile rules with Vectorscan cache")?;

    println!("Rule cache ready: {} rules in {}", rules_db.num_rules(), cache.cache_dir().display());
    Ok(())
}

/// Run the rules prune-cache command
pub fn run_rules_prune_cache(args: &RuleCachePruneArgs) -> Result<()> {
    let cache = RuleCacheConfig::from_dir_or_env(args.cache.rule_cache_dir.clone());
    let summary = prune_rule_cache(
        &cache,
        &RuleCachePruneConfig {
            max_entries: args.max_entries,
            max_age: args.max_age,
            protected_cache_key: None,
            dry_run: args.dry_run,
        },
    );

    let action = if args.dry_run { "would remove" } else { "removed" };
    println!(
        "Rule cache prune {action} {} entries ({} bytes) from {}; scanned {} entries, {} valid, {} invalid, {} protected, {} removal errors",
        if args.dry_run { summary.candidate_entries } else { summary.removed_entries },
        if args.dry_run { summary.candidate_bytes } else { summary.removed_bytes },
        cache.cache_dir().display(),
        summary.scanned_entries,
        summary.valid_entries,
        summary.invalid_entries,
        summary.protected_entries,
        summary.removal_errors
    );
    Ok(())
}

/// Run the rules check command
pub fn run_rules_check(args: &RulesCheckArgs) -> Result<()> {
    let mut num_errors = 0;
    let mut num_warnings = 0;
    // Load and check rules
    let loader = RuleLoader::from_rule_specifiers(&args.rules);
    let loaded = loader.load(&create_default_scan_args())?;
    let resolved = loaded.resolve_enabled_rules_owned()?;
    let betterleaks_prefilter = loaded.betterleaks_prefilter_for(&resolved);
    let rules_db =
        RulesDatabase::from_rules_with_betterleaks_prefilter(resolved, betterleaks_prefilter)?;

    // Check each rule
    for (rule_index, rule) in rules_db.rules().iter().enumerate() {
        let rule_syntax = rule.syntax();
        // Basic rule validation checks
        if rule.name().len() < 3 {
            warn!("Rule '{}' has a very short name", rule.name());
            num_warnings += 1;
        }
        if rule.syntax().pattern.len() < 5 {
            warn!("Rule '{}' has a very short pattern", rule.name());
            num_warnings += 1;
        }
        if rule.syntax().examples.is_empty() {
            // Betterleaks' generated catalog does not carry example strings. The upstream
            // configuration is parsed and operation-checked by our build adapter, so retain this
            // legacy-authoring warning only for custom Kingfisher YAML rules.
            if !rule.id().starts_with("betterleaks.") {
                warn!("Rule '{}' has no examples", rule.name());
                num_warnings += 1;
            }
            continue;
        }
        // Check regex compilation
        if let Err(e) = rule.syntax().as_regex() {
            error!("Rule '{}' has invalid regex: {}", rule.name(), e);
            num_errors += 1;
            continue;
        }
        // Test each example against regex and pattern_requirements
        for (example_index, example) in rule_syntax.examples.iter().enumerate() {
            // Get the regex using the public method
            let re =
                rules_db.get_regex_by_rule_id(rule.id()).expect("Failed to get regex for rule");

            // Check if the example matches the pattern
            let example_bytes = example.as_bytes();
            let regex_matched = re.is_match(example_bytes);

            if !regex_matched {
                println!("\nTesting rule {} - {}", rule_index + 1, rule_syntax.name);
                println!("  Processing example {}", example_index + 1);
                println!("    [!] Pattern mismatch detected for example: {}", example);
                println!("    Regex match: {}", regex_matched);
                num_errors += 1;
                continue;
            }

            // If the rule has pattern_requirements, validate them against the match
            if let Some(pattern_reqs) = rule.pattern_requirements() {
                // Get the captures from the match
                if let Some(captures) = re.captures(example_bytes) {
                    // Get the full match (group 0)
                    let full_capture = captures.get(0).expect("Group 0 should always exist");
                    let full_bytes = full_capture.as_bytes();

                    // Determine which bytes to validate (same logic as in matcher.rs)
                    // Find the primary capture group for validation
                    let matching_input_for_validation = 'block: {
                        // 1. Look for a named capture "secret" (case-insensitive).
                        if let Some(secret_cap) =
                            captures.name("secret").or_else(|| captures.name("SECRET"))
                        {
                            break 'block secret_cap;
                        }

                        // 2. Look for any other named capture.
                        if let Some(named_cap) = (1..captures.len()).find_map(|i| {
                            let name_opt = re.capture_names().nth(i).and_then(|n| n);
                            name_opt.and_then(|_| captures.get(i))
                        }) {
                            break 'block named_cap;
                        }

                        // 3. Fall back to first positional capture (group 1) if it exists.
                        if let Some(pos_cap) = captures.get(1) {
                            break 'block pos_cap;
                        }

                        // 4. Finally, fall back to the full match (group 0).
                        break 'block full_capture;
                    };

                    let validation_bytes = matching_input_for_validation.as_bytes();

                    // Create context for pattern requirements validation
                    use kingfisher_rules::PatternRequirementContext;
                    let context = PatternRequirementContext {
                        regex: re,
                        captures: &captures,
                        full_match: full_bytes,
                    };

                    // Validate pattern requirements (without respect_ignore_if_contains for examples)
                    use kingfisher_rules::PatternValidationResult;
                    match pattern_reqs.validate(validation_bytes, Some(context), false) {
                        PatternValidationResult::Passed => {
                            // All requirements met
                        }
                        PatternValidationResult::Failed => {
                            println!("\nTesting rule {} - {}", rule_index + 1, rule_syntax.name);
                            println!("  Processing example {}", example_index + 1);
                            println!(
                                "    [!] Pattern requirements not met for example: {}",
                                example
                            );
                            println!(
                                "    The match does not satisfy the character requirements (min_digits, min_uppercase, etc.)"
                            );
                            num_errors += 1;
                        }
                        PatternValidationResult::FailedChecksum { actual_len, expected_len } => {
                            println!("\nTesting rule {} - {}", rule_index + 1, rule_syntax.name);
                            println!("  Processing example {}", example_index + 1);
                            println!("    [!] Checksum validation failed for example: {}", example);
                            println!(
                                "    Actual checksum length: {}, Expected checksum length: {}",
                                actual_len, expected_len
                            );
                            num_errors += 1;
                        }
                        PatternValidationResult::IgnoredBySubstring { matched_term } => {
                            // For examples, we don't want to treat this as an error in check mode
                            // since ignore_if_contains is meant for runtime filtering
                            // But we can warn about it
                            println!("\nTesting rule {} - {}", rule_index + 1, rule_syntax.name);
                            println!("  Processing example {}", example_index + 1);
                            println!(
                                "    [!] Example would be ignored due to containing term: {}",
                                matched_term
                            );
                            println!("    Example: {}", example);
                            num_warnings += 1;
                        }
                    }
                }
            }
        }
    }
    // Print summary
    if num_errors > 0 || num_warnings > 0 {
        println!("\nCheck Summary:");
        println!("  Errors: {}", num_errors);
        println!("  Warnings: {}", num_warnings);
        println!("\nError types include:");
        println!("  - Invalid regex patterns");
        println!("  - Examples that don't match their patterns");
        println!("\nWarning types include:");
        println!("  - Rules with very short names");
        println!("  - Rules with very short patterns");
        println!("  - Rules without examples");
    } else {
        println!("\nAll rules passed validation successfully!");
    }
    // Exit with error if there are errors or if warnings are treated as errors
    if num_errors > 0 || (args.warnings_as_errors && num_warnings > 0) {
        std::process::exit(1);
    }
    Ok(())
}
/// Run the rules list command
pub fn run_rules_list(args: &RulesListArgs) -> Result<()> {
    // Load rules
    let loader = RuleLoader::from_rule_specifiers(&args.rules);
    let loaded = loader.load(&create_default_scan_args())?;
    let resolved = loaded.resolve_enabled_rules()?;
    let mut writer = args.output_args.get_writer()?;
    #[cfg(debug_assertions)]
    let show_validation = args.show_validation;
    #[cfg(not(debug_assertions))]
    let show_validation = false;
    match args.output_args.format {
        RulesListOutputFormat::Pretty => {
            // Determine terminal width if possible, otherwise use default
            let term_width = usize::from(Term::stdout().size().1);
            // First pass: calculate column widths
            let max_name_width = resolved.iter().map(|r| r.name().len()).max().unwrap_or(0).max(4); // "Rule" header
            let max_id_width = resolved.iter().map(|r| r.id().len()).max().unwrap_or(0).max(2); // "ID" header
            let max_conf_width = resolved
                .iter()
                .map(|r| format!("{:?}", r.confidence()).len())
                .max()
                .unwrap_or(0)
                .max(10); // "Confidence" header
            // Calculate pattern width based on terminal width
            let reserved_width = max_name_width + max_id_width + max_conf_width + 10;
            let pattern_width = term_width.saturating_sub(reserved_width);
            // Format pattern on a single line
            let format_pattern = |pattern: &str| {
                let single_line = pattern
                    .replace(['\n', '\r'], " ")
                    .split_whitespace()
                    .collect::<Vec<_>>()
                    .join(" ");
                if single_line.len() > pattern_width {
                    format!("{}...", &single_line[..pattern_width.saturating_sub(3)])
                } else {
                    single_line
                }
            };
            // Print header
            writeln!(
                writer,
                "\n{:name_width$} │ {:id_width$} │ {:conf_width$} │ Pattern",
                "Rule",
                "ID",
                "Confidence",
                name_width = max_name_width,
                id_width = max_id_width,
                conf_width = max_conf_width
            )?;
            // Print separator
            writeln!(
                writer,
                "{0:─<name_width$} ┼ {0:─<id_width$} ┼ {0:─<conf_width$} ┼ {0:─<pattern_width$}",
                "",
                name_width = max_name_width,
                id_width = max_id_width,
                conf_width = max_conf_width,
                pattern_width = pattern_width
            )?;
            // Print each rule
            for rule in resolved {
                let formatted_pattern = format_pattern(&rule.syntax().pattern);
                writeln!(
                    writer,
                    "{:name_width$} │ {:id_width$} │ {:conf_width$} │ {}",
                    rule.name(),
                    rule.id(),
                    format!("{:?}", rule.confidence()),
                    formatted_pattern,
                    name_width = max_name_width,
                    id_width = max_id_width,
                    conf_width = max_conf_width
                )?;
                if show_validation && let Some(validation) = &rule.syntax().validation {
                    match validation {
                        kingfisher::rules::Validation::Betterleaks(validation) => {
                            #[cfg(debug_assertions)]
                            writeln!(writer, "  Validation: {}", validation.source)?;
                            writeln!(writer, "  Validation AST: {:?}", validation.expression)?;
                        }
                        validation => writeln!(writer, "  Validation: {validation:?}")?,
                    }
                }
            }
            writeln!(writer)?;
        }
        RulesListOutputFormat::Json => {
            // Create JSON format
            let rules_json: Vec<_> = resolved
                .iter()
                .map(|rule| {
                    let mut value = json!({
                        "name": rule.name(),
                        "id": rule.id(),
                        "pattern": rule.syntax().pattern,
                        "confidence": rule.confidence(),
                        "examples": rule.syntax().examples,
                        "visible": rule.visible(),
                    });
                    if show_validation {
                        value["validation"] = serde_json::to_value(&rule.syntax().validation)
                            .expect("validation serialization should succeed");
                    }
                    value
                })
                .collect();
            serde_json::to_writer_pretty(&mut writer, &rules_json)?;
            writeln!(writer)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod apply_config_tests {
    //! End-to-end precedence tests for `apply_config` — confirm that:
    //!   * a user-supplied `--flag` always wins over a config-file value, and
    //!   * a config-file value wins over the clap `default_value_t` when the
    //!     user did not pass the flag.
    //!
    //! The test parses a real `ArgMatches` via clap so the same code path
    //! `value_source` reads from is exercised.

    use std::path::PathBuf;

    use clap::{ArgMatches, CommandFactory, FromArgMatches};
    use kingfisher::cli::CommandLineArgs;
    use kingfisher::cli::commands::output::ReportOutputFormat;
    use kingfisher::cli::commands::scan::{ConfidenceLevel, ScanOperation};
    use kingfisher::cli::config::{KingfisherConfig, parse_str};
    use kingfisher::cli::global::Command;

    fn parse(argv: &[&str]) -> (CommandLineArgs, ArgMatches) {
        let matches =
            CommandLineArgs::command().try_get_matches_from(argv).expect("argv should parse");
        let args = CommandLineArgs::from_arg_matches(&matches).unwrap();
        (args, matches)
    }

    fn into_scan(args: CommandLineArgs) -> kingfisher::cli::commands::scan::ScanArgs {
        let cmd = match args.command {
            Command::Scan(c) => c,
            _ => panic!("expected scan subcommand"),
        };
        match cmd.into_operation().unwrap() {
            ScanOperation::Scan(s) => s,
            ScanOperation::ListRepositories(_) => panic!("expected scan op"),
        }
    }

    #[test]
    fn non_interactive_git_url_does_not_stage_stdin() {
        let (args, _) = parse(&["kingfisher", "scan", "github.com/octocat/Hello-World"]);
        let scan_args = into_scan(args);

        assert!(scan_args.input_specifier_args.path_inputs.is_empty());
        assert!(!scan_args.input_specifier_args.git_url.is_empty());
        assert!(!super::should_stage_stdin(&scan_args.input_specifier_args, false));
    }

    #[test]
    fn non_interactive_path_target_does_not_stage_stdin() {
        let (args, _) = parse(&["kingfisher", "scan", "."]);
        let scan_args = into_scan(args);

        assert!(!super::should_stage_stdin(&scan_args.input_specifier_args, false));
    }

    #[test]
    fn dash_stages_stdin_only_when_stdin_is_redirected() {
        let (args, _) = parse(&["kingfisher", "scan", "-"]);
        let scan_args = into_scan(args);

        assert!(super::should_stage_stdin(&scan_args.input_specifier_args, false));
        assert!(!super::should_stage_stdin(&scan_args.input_specifier_args, true));
    }

    #[test]
    fn github_event_user_file_cannot_alias_audit_log() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("users.txt");
        let path = path.to_str().unwrap();
        let (args, _) = parse(&[
            "kingfisher",
            "scan",
            "github",
            "--public-events",
            "--user-file",
            path,
            "--audit-log",
            path,
        ]);

        let command = match args.command {
            Command::Scan(command) => command,
            _ => panic!("expected scan subcommand"),
        };
        assert!(command.into_operation().is_err());
    }

    #[test]
    fn staging_stdin_keeps_sibling_paths_and_collapses_repeats() {
        let stdin_file = PathBuf::from("/tmp/kf/stdin_input");
        let mut path_inputs = vec![
            PathBuf::from("-"),
            PathBuf::from("./src"),
            PathBuf::from("-"),
            PathBuf::from("./tests"),
        ];

        super::replace_stdin_placeholders(&mut path_inputs, stdin_file.clone());

        assert_eq!(path_inputs, vec![stdin_file, PathBuf::from("./src"), PathBuf::from("./tests")]);
    }

    #[test]
    fn config_wins_when_cli_uses_default() {
        let yaml = r#"
scan:
  confidence: high
  redact: true
output:
  format: json
"#;
        let cfg: KingfisherConfig = parse_str(yaml).unwrap();
        let (args, matches) = parse(&["kingfisher", "scan", "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert_eq!(scan_args.confidence, ConfidenceLevel::High);
        assert!(scan_args.redact);
        assert_eq!(scan_args.output_args.format, ReportOutputFormat::Json);
    }

    #[test]
    fn config_output_path_colliding_with_audit_log_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("report.json");
        let path_str = path.display().to_string();
        let yaml = format!(
            r#"
output:
  path: {path_str}
"#
        );
        let cfg: KingfisherConfig = parse_str(&yaml).unwrap();
        let (args, matches) = parse(&["kingfisher", "scan", "--audit-log", &path_str, "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);

        // CLI-only validation passes: the config has not been merged yet, so
        // `output_args.output` is still unset.
        assert!(scan_args.validate_audit_log_collisions(None, None).is_ok());

        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert_eq!(scan_args.output_args.output.as_deref(), Some(path.as_path()));

        // After merging, the effective --output collides with --audit-log.
        assert!(scan_args.validate_audit_log_collisions(None, None).is_err());
    }

    #[test]
    fn audit_log_colliding_with_baseline_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("baseline-file.yaml");
        let path_str = path.display().to_string();

        // An explicit --baseline-file aliasing --audit-log is rejected during
        // CLI validation, before any file is opened.
        let (args, _) = parse(&[
            "kingfisher",
            "scan",
            "--audit-log",
            &path_str,
            "--baseline-file",
            &path_str,
            ".",
        ]);
        let cmd = match args.command {
            Command::Scan(c) => c,
            _ => panic!("expected scan subcommand"),
        };
        assert!(cmd.into_operation().is_err());

        // The managed-baseline default is protected too (resolved against the
        // working directory, so the collision is expressed relatively here).
        let (args, _) = parse(&[
            "kingfisher",
            "scan",
            "--audit-log",
            "baseline-file.yaml",
            "--manage-baseline",
            ".",
        ]);
        let cmd = match args.command {
            Command::Scan(c) => c,
            _ => panic!("expected scan subcommand"),
        };
        assert!(cmd.into_operation().is_err());

        // Without baseline operations the default path is not state.
        let (args, _) = parse(&["kingfisher", "scan", "--audit-log", &path_str, "."]);
        let scan_args = into_scan(args);
        assert!(scan_args.validate_audit_log_collisions(None, None).is_ok());
    }

    #[test]
    fn audit_log_tilde_path_is_expanded_for_collision_checks() {
        // Shells do not expand `~` in the `--flag=~/...` form; the audit-log
        // path must still collide with the same file spelled the way
        // Kingfisher expands it. The output is computed with the product's
        // own tilde expansion so the test does not depend on which of
        // HOME/USERPROFILE the platform resolves first. The scan input stays
        // outside the working directory so only the tilde expansion can
        // produce the collision.
        let expanded =
            kingfisher::util::expand_tilde(std::path::Path::new("~/kf-audit-collision.jsonl"));
        let input = tempfile::tempdir().unwrap();
        let (args, _) = parse(&[
            "kingfisher",
            "scan",
            "--audit-log=~/kf-audit-collision.jsonl",
            "--output",
            expanded.to_str().unwrap(),
            input.path().to_str().unwrap(),
        ]);
        let cmd = match args.command {
            Command::Scan(c) => c,
            _ => panic!("expected scan subcommand"),
        };
        assert!(cmd.into_operation().is_err());
    }

    #[test]
    fn audit_log_colliding_with_endpoint_config_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("endpoints.yaml");
        let path_str = path.display().to_string();
        let (args, _) = parse(&["kingfisher", "scan", "--audit-log", &path_str, "."]);
        let scan_args = into_scan(args);

        assert!(scan_args.validate_audit_log_collisions(None, None).is_ok());
        assert!(scan_args.validate_audit_log_collisions(Some(&path), None).is_err());
    }

    #[test]
    fn audit_log_colliding_with_project_config_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("kingfisher.yaml");
        let path_str = path.display().to_string();
        let (args, _) = parse(&["kingfisher", "scan", "--audit-log", &path_str, "."]);
        let scan_args = into_scan(args);

        assert!(scan_args.validate_audit_log_collisions(None, None).is_ok());
        assert!(scan_args.validate_audit_log_collisions(None, Some(&path)).is_err());
    }

    #[test]
    fn cli_beats_config_for_scalars() {
        let yaml = r#"
scan:
  confidence: high
  redact: true
output:
  format: json
"#;
        let cfg = parse_str(yaml).unwrap();
        let (args, matches) =
            parse(&["kingfisher", "scan", "--confidence", "low", "--format", "toon", "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        // CLI wins
        assert_eq!(scan_args.confidence, ConfidenceLevel::Low);
        assert_eq!(scan_args.output_args.format, ReportOutputFormat::Toon);
        // Bool with no CLI flag still picks up config
        assert!(scan_args.redact);
    }

    #[test]
    fn lists_are_concatenated_with_cli() {
        let yaml = r#"
filters:
  skip_words: ["FROM_CONFIG"]
  exclude: ["vendor/"]
"#;
        let cfg = parse_str(yaml).unwrap();
        let (args, matches) = parse(&[
            "kingfisher",
            "scan",
            "--skip-word",
            "FROM_CLI",
            "--exclude",
            "node_modules/",
            ".",
        ]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert!(scan_args.skip_word.contains(&"FROM_CLI".to_string()));
        assert!(scan_args.skip_word.contains(&"FROM_CONFIG".to_string()));
        assert!(scan_args.content_filtering_args.exclude.contains(&"vendor/".to_string()));
        assert!(scan_args.content_filtering_args.exclude.contains(&"node_modules/".to_string()));
    }

    #[test]
    fn rules_enabled_replaces_default_but_appends_to_user_selection() {
        // Case A: user passes --rule, config appends.
        let yaml = r#"
rules:
  enabled: ["custom"]
"#;
        let cfg = parse_str(yaml).unwrap();
        let (args, matches) = parse(&["kingfisher", "scan", "--rule", "default", "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert!(scan_args.rules.rule.contains(&"default".to_string()));
        assert!(scan_args.rules.rule.contains(&"custom".to_string()));

        // Case B: user did not pass --rule (CLI default `["all"]` in effect),
        // config replaces — otherwise users could never *narrow* the
        // selection from the config.
        let (args, matches) = parse(&["kingfisher", "scan", "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert_eq!(scan_args.rules.rule, vec!["custom".to_string()]);
    }

    #[test]
    fn rules_disabled_is_concatenated_with_cli_exclusions() {
        let yaml = r#"
rules:
  disabled: ["betterleaks.github-pat"]
"#;
        let cfg = parse_str(yaml).unwrap();
        let (args, matches) =
            parse(&["kingfisher", "scan", "--exclude-rule", "betterleaks.openai-api-key", "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );

        assert_eq!(
            scan_args.rules.exclude_rule,
            vec!["betterleaks.openai-api-key".to_string(), "betterleaks.github-pat".to_string()]
        );
    }

    #[test]
    fn cli_rule_and_exclude_rule_flags_are_repeated_and_preserved() {
        let (args, matches) = parse(&[
            "kingfisher",
            "scan",
            "--rule",
            "betterleaks.github-pat",
            "--rule",
            "betterleaks.github-fine-grained-pat",
            "--exclude-rule",
            "betterleaks.openai-api-key",
            "--exclude-rule",
            "custom.openai.secondary",
            ".",
        ]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &kingfisher::cli::config::KingfisherConfig::default(),
            matches.subcommand_matches("scan"),
        );

        assert_eq!(
            scan_args.rules.rule,
            vec![
                "betterleaks.github-pat".to_string(),
                "betterleaks.github-fine-grained-pat".to_string(),
            ]
        );
        assert_eq!(
            scan_args.rules.exclude_rule,
            vec!["betterleaks.openai-api-key".to_string(), "custom.openai.secondary".to_string()]
        );
    }

    #[test]
    fn rule_cache_config_and_cli_precedence_respects_opt_out() {
        let cfg = parse_str(
            r#"
rules:
  cache: false
"#,
        )
        .unwrap();
        let (args, matches) = parse(&["kingfisher", "scan", "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert!(!scan_args.rule_cache.enabled(), "config rules.cache=false should disable cache");

        let cfg = parse_str(
            r#"
rules:
  cache: true
"#,
        )
        .unwrap();
        let (args, matches) = parse(&["kingfisher", "scan", "--no-rule-cache", "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert!(!scan_args.rule_cache.enabled(), "CLI --no-rule-cache should beat config");

        let cfg = parse_str(
            r#"
rules:
  cache: false
"#,
        )
        .unwrap();
        let (args, matches) = parse(&["kingfisher", "scan", "--rule-cache", "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert!(scan_args.rule_cache.enabled(), "CLI --rule-cache should beat config");
    }

    #[test]
    fn validation_rps_per_rule_appended_as_strings() {
        let yaml = r#"
validation:
  rps_per_rule:
    betterleaks.aws: 1.5
"#;
        let cfg = parse_str(yaml).unwrap();
        let (args, matches) =
            parse(&["kingfisher", "scan", "--validation-rps-rule", "betterleaks.gcp=2.0", "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert!(scan_args.validation_rps_rule.contains(&"betterleaks.gcp=2.0".to_string()));
        assert!(scan_args.validation_rps_rule.contains(&"betterleaks.aws=1.5".to_string()));
    }

    #[test]
    fn alerts_defaults_set_alert_globals_when_cli_default() {
        let yaml = r#"
alerts:
  defaults:
    min_confidence: high
    include_secret: true
    detail: summary
    finding_filter: only-active
    prevent_empty: true
"#;
        let cfg = parse_str(yaml).unwrap();
        let (args, matches) = parse(&["kingfisher", "scan", "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert_eq!(scan_args.alert_min_confidence, ConfidenceLevel::High);
        assert!(scan_args.alert_include_secret);
        assert_eq!(scan_args.alert_detail, kingfisher::alerts::AlertDetail::Summary);
        assert_eq!(
            scan_args.alert_finding_filter,
            kingfisher::alerts::AlertFindingFilter::OnlyActive
        );
        assert!(scan_args.alert_prevent_empty);
    }

    #[test]
    fn cli_alert_flag_beats_config_default() {
        let yaml = r#"
alerts:
  defaults:
    min_confidence: high
    finding_filter: access-map-only
"#;
        let cfg = parse_str(yaml).unwrap();
        let (args, matches) = parse(&[
            "kingfisher",
            "scan",
            "--alert-min-confidence",
            "low",
            "--alert-finding-filter",
            "exclude-inactive",
            ".",
        ]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert_eq!(scan_args.alert_min_confidence, ConfidenceLevel::Low);
        assert_eq!(
            scan_args.alert_finding_filter,
            kingfisher::alerts::AlertFindingFilter::ExcludeInactive
        );
    }

    #[test]
    fn config_init_round_trips_supplied_flags_only() {
        // Take a CLI invocation, build a YAML config, parse it back, and
        // check that the resulting KingfisherConfig has *only* what we passed
        // (CLI defaults must not be reified into the config — that would
        // freeze an arbitrary moment in time as a "user choice").
        use kingfisher::cli::config::{ConfigConfidence, ConfigReportFormat, parse_str};

        let argv = &[
            "kingfisher",
            "config",
            "init",
            "--confidence",
            "high",
            "--redact",
            "--exclude",
            "vendor/",
            "--skip-word",
            "EXAMPLE",
            "--exclude-rule",
            "betterleaks.github-pat",
            "--format",
            "toon",
            "--alert-min-confidence",
            "high",
            "--alert-webhook",
            "https://hooks.slack.com/services/T0/B0/AAA",
            "--tls-mode",
            "lax",
        ];
        let matches = CommandLineArgs::command().try_get_matches_from(argv).unwrap();
        let parsed = CommandLineArgs::from_arg_matches(&matches).unwrap();
        let global_args = parsed.global_args.clone();

        let init_matches =
            matches.subcommand_matches("config").unwrap().subcommand_matches("init").unwrap();

        // Recover the ScanArgs from the parsed `Config(Init(...))` branch.
        let scan_args = match parsed.command {
            Command::Config(c) => match c.command {
                kingfisher::cli::commands::config_command::ConfigSubcommand::Init(args) => {
                    args.scan_args
                }
            },
            _ => panic!("expected config init"),
        };

        let yaml = super::build_config_yaml(&scan_args, &global_args, init_matches).unwrap();
        let cfg = parse_str(&yaml).expect("emitted YAML must round-trip");

        // Exact set of keys that should be present.
        assert!(matches!(cfg.scan.confidence, Some(ConfigConfidence::High)));
        assert_eq!(cfg.scan.redact, Some(true));
        assert!(cfg.scan.no_dedup.is_none(), "should not emit unset bools");
        assert!(cfg.scan.jobs.is_none(), "should not emit clap-default scalars");

        assert_eq!(cfg.filters.exclude, vec!["vendor/".to_string()]);
        assert_eq!(cfg.filters.skip_words, vec!["EXAMPLE".to_string()]);
        assert!(cfg.filters.max_file_size_mb.is_none(), "should not emit unset filters");
        assert_eq!(cfg.rules.disabled, vec!["betterleaks.github-pat".to_string()]);

        assert!(matches!(cfg.output.format, Some(ConfigReportFormat::Toon)));
        assert!(cfg.output.path.is_none());

        assert!(matches!(cfg.alerts.defaults.min_confidence, Some(ConfigConfidence::High)));
        assert_eq!(cfg.alerts.webhooks.len(), 1);
        assert_eq!(cfg.alerts.webhooks[0].url, "https://hooks.slack.com/services/T0/B0/AAA");

        assert!(matches!(cfg.global.tls_mode, Some(kingfisher::cli::config::ConfigTlsMode::Lax)));
    }

    /// Regression: `config init --github-api-url ... --gitlab-api-url ...`
    /// must round-trip the strings the user typed. `Url::to_string()` adds
    /// a trailing `/` to bare-host URLs, so re-serializing the parsed `Url`
    /// would silently rewrite `https://gitlab.example.com` →
    /// `https://gitlab.example.com/` on every `config init` run.
    #[test]
    fn config_init_preserves_raw_api_url_strings() {
        use kingfisher::cli::config::parse_str;

        let argv = &[
            "kingfisher",
            "config",
            "init",
            // Bare host (no trailing slash) — `Url::to_string()` would add one.
            "--github-api-url",
            "https://ghe.corp.example.com/api/v3",
            "--gitlab-api-url",
            "https://gitlab.corp.example.com",
        ];
        let matches = CommandLineArgs::command().try_get_matches_from(argv).unwrap();
        let parsed = CommandLineArgs::from_arg_matches(&matches).unwrap();
        let global_args = parsed.global_args.clone();
        let init_matches =
            matches.subcommand_matches("config").unwrap().subcommand_matches("init").unwrap();
        let scan_args = match parsed.command {
            Command::Config(c) => match c.command {
                kingfisher::cli::commands::config_command::ConfigSubcommand::Init(args) => {
                    args.scan_args
                }
            },
            _ => panic!("expected config init"),
        };

        let yaml = super::build_config_yaml(&scan_args, &global_args, init_matches).unwrap();
        let cfg = parse_str(&yaml).expect("emitted YAML must round-trip");

        assert_eq!(
            cfg.git.github_api_url.as_deref(),
            Some("https://ghe.corp.example.com/api/v3"),
            "github_api_url must preserve user input verbatim, no trailing-slash rewrite",
        );
        assert_eq!(
            cfg.git.gitlab_api_url.as_deref(),
            Some("https://gitlab.corp.example.com"),
            "gitlab_api_url must preserve user input verbatim, no trailing-slash rewrite",
        );

        // Sanity: when the user *does* pass a trailing slash, that's preserved too.
        let argv = &[
            "kingfisher",
            "config",
            "init",
            "--github-api-url",
            "https://ghe.corp.example.com/api/v3/",
        ];
        let matches = CommandLineArgs::command().try_get_matches_from(argv).unwrap();
        let parsed = CommandLineArgs::from_arg_matches(&matches).unwrap();
        let global_args = parsed.global_args.clone();
        let init_matches =
            matches.subcommand_matches("config").unwrap().subcommand_matches("init").unwrap();
        let scan_args = match parsed.command {
            Command::Config(c) => match c.command {
                kingfisher::cli::commands::config_command::ConfigSubcommand::Init(args) => {
                    args.scan_args
                }
            },
            _ => panic!("expected config init"),
        };
        let yaml = super::build_config_yaml(&scan_args, &global_args, init_matches).unwrap();
        let cfg = parse_str(&yaml).expect("emitted YAML must round-trip");
        assert_eq!(
            cfg.git.github_api_url.as_deref(),
            Some("https://ghe.corp.example.com/api/v3/"),
            "github_api_url must preserve a user-supplied trailing slash",
        );
    }

    #[test]
    fn config_init_with_no_flags_emits_placeholder_comment() {
        // Edge case: user runs `kingfisher config init` with no flags. The
        // emitted file should still be valid YAML / a clear no-op rather
        // than a bare `{}`.
        let argv = &["kingfisher", "config", "init"];
        let matches = CommandLineArgs::command().try_get_matches_from(argv).unwrap();
        let parsed = CommandLineArgs::from_arg_matches(&matches).unwrap();
        let global_args = parsed.global_args.clone();

        let init_matches =
            matches.subcommand_matches("config").unwrap().subcommand_matches("init").unwrap();

        let scan_args = match parsed.command {
            Command::Config(c) => match c.command {
                kingfisher::cli::commands::config_command::ConfigSubcommand::Init(args) => {
                    args.scan_args
                }
            },
            _ => panic!("expected config init"),
        };

        let yaml = super::build_config_yaml(&scan_args, &global_args, init_matches).unwrap();
        assert!(yaml.contains("no flags supplied"), "expected no-op header, got:\n{yaml}");
        assert!(!yaml.trim().ends_with("{}"));
    }

    #[test]
    fn global_section_updates_global_args_when_cli_default() {
        let yaml = r#"
global:
  tls_mode: lax
  allow_internal_ips: true
  endpoints:
    - github=https://ghe.example.com/api/v3/
"#;
        let cfg = parse_str(yaml).unwrap();
        let (args, matches) = parse(&["kingfisher", "scan", "."]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert_eq!(global_args.tls_mode, kingfisher::cli::global::TlsMode::Lax);
        assert!(global_args.allow_internal_ips);
        assert_eq!(global_args.endpoint.len(), 1);
    }

    /// Regression test: an explicit `--api-url` on the `scan github`
    /// subcommand must beat `git.github_api_url` from the config file. The
    /// flag lives on `GithubScanArgs` (id `api_url`), not on the outer scan
    /// command — checking only the outer matches misses it and the config
    /// silently overrode the CLI value.
    #[test]
    fn github_subcommand_api_url_beats_config() {
        let yaml = r#"
git:
  github_api_url: https://ghe-from-config.example.com/api/v3/
"#;
        let cfg = parse_str(yaml).unwrap();
        let (args, matches) = parse(&[
            "kingfisher",
            "scan",
            "github",
            "--organization",
            "my-org",
            "--api-url",
            "https://ghe-from-cli.example.com/api/v3/",
        ]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert_eq!(
            scan_args.input_specifier_args.github_api_url.as_str(),
            "https://ghe-from-cli.example.com/api/v3/",
        );
    }

    /// And the inverse: when the user did NOT pass `--api-url` at all,
    /// `git.github_api_url` from the config should still win over the
    /// built-in default `https://api.github.com/`.
    #[test]
    fn github_config_wins_when_subcommand_api_url_default() {
        let yaml = r#"
git:
  github_api_url: https://ghe-from-config.example.com/api/v3/
"#;
        let cfg = parse_str(yaml).unwrap();
        let (args, matches) = parse(&["kingfisher", "scan", "github", "--organization", "my-org"]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert_eq!(
            scan_args.input_specifier_args.github_api_url.as_str(),
            "https://ghe-from-config.example.com/api/v3/",
        );
    }

    /// Same precedence story for `scan gitlab --api-url`.
    #[test]
    fn gitlab_subcommand_api_url_beats_config() {
        let yaml = r#"
git:
  gitlab_api_url: https://gitlab-from-config.example.com/
"#;
        let cfg = parse_str(yaml).unwrap();
        let (args, matches) = parse(&[
            "kingfisher",
            "scan",
            "gitlab",
            "--group",
            "my-group",
            "--api-url",
            "https://gitlab-from-cli.example.com/",
        ]);
        let mut global_args = args.global_args.clone();
        let mut scan_args = into_scan(args);
        super::apply_config(
            &mut scan_args,
            &mut global_args,
            &cfg,
            matches.subcommand_matches("scan"),
        );
        assert_eq!(
            scan_args.input_specifier_args.gitlab_api_url.as_str(),
            "https://gitlab-from-cli.example.com/",
        );
    }
}