cert-x-gen 1.9.2

Advanced Multi-Language Security Scanning Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
//! Command-line interface for CERT-X-GEN

use clap::{CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use std::ffi::OsString;
use std::path::PathBuf;

/// Execution outcomes that can make a completed scan fail in CI.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum FailOnArg {
    Confirmed,
    Refuted,
    Errored,
    Skipped,
    TimedOut,
}

impl FailOnArg {
    pub fn status(self) -> cert_x_gen::types::ExecutionStatus {
        use cert_x_gen::types::ExecutionStatus;
        match self {
            Self::Confirmed => ExecutionStatus::Confirmed,
            Self::Refuted => ExecutionStatus::Refuted,
            Self::Errored => ExecutionStatus::Errored,
            Self::Skipped => ExecutionStatus::Skipped,
            Self::TimedOut => ExecutionStatus::TimedOut,
        }
    }
}

const SCAN_SCOPE_ALIASES: &[&str] = &[
    "target",
    "targets",
    "target-file",
    "domain",
    "domains",
    "domain-file",
    "cidr",
];

#[derive(Parser, Debug)]
#[command(
    name = "cxg",
    version,
    about = "Advanced Multi-Language Security Scanning Engine",
    long_about = "CERT-X-GEN is a next-generation security scanning engine that supports \
                  12 programming languages for template creation. Write security scanning \
                  templates in Python, JavaScript, Rust, Shell, YAML, C, C++, Java, Go, Ruby, \
                  Perl, or PHP - whatever works best for your use case!\n\n\
                  Local CLI binaries: cxg scan --scope cli://<binary> with CLI Security Baseline templates.\n\
                  Tauri apps: cxg pentest run --target-type tauri --codebase <repo> maps IPC commands \
                  and capability grants; --tauri-prove opts into in-process command proof.",
    after_help = "Run 'cxg <command> --help' for full details on any command.\n\
                  \n\
                  Repository:    https://github.com/Bugb-Technologies/cert-x-gen\n\
                  Documentation: https://docs.bugb.io/cxg/\n\
                  Issues:        https://github.com/Bugb-Technologies/cert-x-gen/issues",
    after_long_help = "KEY FEATURES:
  🎯 12 Programming Languages: Python, JavaScript, Rust, C, C++, Java, Go, Ruby, Perl, PHP, Shell, YAML
  🔧 Flexible Port Configuration: Add or override ports per scan
  🔍 Powerful Template Search: Full-text search, regex, content search, multiple filters
  ⚡ High Performance: Parallel execution, compilation caching for compiled languages
  📊 Multiple Output Formats: JSON, CSV, SARIF, HTML, Markdown
  🔌 Extensible: Custom templates in any supported language

EXAMPLES:
  # Local CLI binary (CLI Security Baseline from the detection-template repository)
  cxg template update
  cxg scan --scope cli:///absolute/path/to/my-tool --template-dir ~/.cert-x-gen/templates/official/templates/cli-baseline --require-instrumentation

  # Tauri source map, then optional in-process command proof (no live webview)
  cxg pentest install
  cxg pentest run --target-type tauri --codebase ./app-repo
  cxg pentest run --target-type tauri --codebase ./app-repo --tauri-prove

  # Basic scanning
  cxg scan --scope example.com
  cxg scan --scope https://api.example.com:8443 --ports 80,443,8080
  cxg scan --scope 192.168.1.0/24 --top-ports 1000

  # Bulk input
  cxg scan --scope @targets.txt
  cxg scan --scope file://scopes/internal.txt

  # Advanced scanning with filters
  cxg scan --scope example.com --template-language python,rust
  cxg scan --scope example.com --severity critical,high
  cxg scan --scope example.com --tags database,unauthenticated

  # Template search
  cxg search --query \"redis\"
  cxg search --language python --severity high
  cxg search --query \"injection\" --content --regex
  cxg search --tags \"database,unauthenticated\" --format json

  # Template management
  cxg template list
  cxg template list --language c --severity critical
  cxg template info redis-unauthenticated

  # Template search
  cxg search --query \"redis\"
  cxg search --language python --severity high
  cxg search --tags \"injection,sql\" --format json

  # Configuration
  cxg config generate --output config.yaml
  cxg scan --config config.yaml --scope example.com

  # Output formats
  cxg scan --scope example.com --output-format json,csv,sarif
  cxg scan --scope example.com --output results --output-format json

  # Performance tuning
  cxg scan --scope example.com --parallel-targets 100 --parallel-templates 20
  cxg scan --scope example.com --timeout 60s --retry 5

  # Stealth and safety
  cxg scan --scope example.com --stealth --rate-limit 10
  cxg scan --scope example.com --safe --passive

  For detailed help on any command, use: cxg <command> --help

LINKS:
  Repository:    https://github.com/Bugb-Technologies/cert-x-gen
  Documentation: https://docs.bugb.io/cxg/
  Issues:        https://github.com/Bugb-Technologies/cert-x-gen/issues"
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Commands>,

    /// Enable verbose output (-v: info+warn, -vv: +trace, -vvv: +debug)
    #[arg(short, long, action = clap::ArgAction::Count, global = true)]
    pub verbose: u8,

    /// Disable colored output
    #[arg(long, global = true)]
    pub no_color: bool,

    /// Configuration file path
    #[arg(short, long, global = true, value_name = "FILE")]
    pub config: Option<PathBuf>,

    /// Update templates (shorthand for 'cxg template update')
    #[arg(
        long = "ut",
        visible_alias = "update-templates",
        global = true,
        help = "Update templates from repository (shorthand for 'cxg template update')"
    )]
    pub update_templates: bool,

    /// Auto-update templates before running (like Nuclei's behavior)
    #[arg(
        long,
        global = true,
        help = "Automatically update templates before running scan"
    )]
    pub auto_update_templates: bool,

    /// Disable automatic template update check (like Nuclei's -duc flag)
    #[arg(
        long,
        global = true,
        help = "Disable automatic template update check on startup"
    )]
    pub disable_update_check: bool,

    /// Update templates on every startup (aggressive mode)
    #[arg(
        long,
        global = true,
        conflicts_with = "disable_update_check",
        help = "Force template update on every startup (aggressive)"
    )]
    pub update_templates_on_startup: bool,
}

impl Cli {
    pub fn parse() -> Self {
        Self::try_parse_from(std::env::args_os()).unwrap_or_else(|e| e.exit())
    }

    /// Build the pentest scan front door from the existing argument definitions.
    /// Ordinary invocations retain clap's original parser and defaults.
    pub fn try_parse_from<I, T>(args: I) -> Result<Self, clap::Error>
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
        let root = Self::command().mut_subcommand("pentest", |cmd| {
            cmd.mut_subcommand("run", |run| {
                run.mut_arg("no_author", |arg| arg.requires("template_dir"))
                    .mut_arg("codebase", |arg| {
                        arg.default_value(clap::builder::Resettable::Reset)
                            .required(true)
                    })
            })
        });
        let run_definition = root
            .find_subcommand("pentest")
            .unwrap()
            .find_subcommand("run")
            .unwrap()
            .clone();
        let replay_options: Vec<_> = run_definition
            .get_arguments()
            .filter(|arg| !authoring_option(arg.get_id().as_str()) && arg.get_id() != "target")
            .cloned()
            .collect();
        let root = root.mut_subcommand("scan", |mut scan| {
            for arg in replay_options {
                if !scan
                    .get_arguments()
                    .any(|existing| existing.get_id() == arg.get_id())
                {
                    scan =
                        scan.arg(arg.help_heading("Probe engine (scanner contracts unaffected)"));
                }
            }
            scan
        });
        if !args.iter().any(|arg| arg == "--pentest") {
            return Self::with_scan_replay_inputs(
                &root.try_get_matches_from(args)?,
                run_definition,
            );
        }
        let normal = root.clone();
        let scan = root.find_subcommand("scan").unwrap();
        let mut front = root
            .find_subcommand("pentest")
            .unwrap()
            .find_subcommand("run")
            .unwrap()
            .clone()
            .name("scan")
            .bin_name("cxg scan --pentest");
        let mut scan_only = Vec::new();
        for arg in scan.get_arguments() {
            if front
                .get_arguments()
                .any(|existing| existing.get_id() == arg.get_id())
            {
                continue;
            }
            let shared = matches!(arg.get_id().as_str(), "scope" | "templates" | "pentest");
            if !shared {
                scan_only.push((
                    arg.get_id().clone(),
                    format!("--{}", arg.get_long().unwrap()),
                ));
            }
            front = front.arg(arg.clone().hide(!shared));
        }
        // `scope`'s legacy --target alias collides with pentest's --target.
        // Keep the actual target option and the identical --scope/-s/-t spellings.
        front = front
            .mut_arg("scope", |arg| {
                arg.alias(None::<&str>).aliases(
                    SCAN_SCOPE_ALIASES
                        .iter()
                        .copied()
                        .filter(|alias| *alias != "target"),
                )
            })
            .group(clap::ArgGroup::new("supplied_templates").args(["templates", "template_dir"]))
            .mut_arg("no_author", |arg| {
                arg.requires(clap::builder::Resettable::Reset)
                    .requires("supplied_templates")
            });
        let command = root.mut_subcommand("scan", |_| front);
        // Select using clap itself so a value such as `--arg --pentest` cannot
        // switch engines. Relax validation and make help inert for this pass;
        // the selected parser performs all validation and renders its own help.
        let selection = command
            .clone()
            .ignore_errors(true)
            .mut_subcommand("scan", |cmd| {
                cmd.disable_help_flag(true).arg(
                    clap::Arg::new("scan_help")
                        .long("help")
                        .short('h')
                        .action(clap::ArgAction::SetTrue),
                )
            })
            .try_get_matches_from(args.clone())?;
        let is_pentest = selection
            .subcommand()
            .is_some_and(|(name, sub)| name == "scan" && sub.get_flag("pentest"));
        if !is_pentest {
            return Self::with_scan_replay_inputs(
                &normal.try_get_matches_from(args)?,
                run_definition,
            );
        }
        let mut matches = command.try_get_matches_from(args)?;
        let (_, sub) = matches.remove_subcommand().unwrap();
        for (id, flag) in scan_only {
            if sub.value_source(id.as_str()) == Some(clap::parser::ValueSource::CommandLine) {
                return Err(front_door_error(&format!("{flag} is a scan-only option that --pentest cannot honour; use `cxg scan --pentest --help` for pentest options")));
            }
        }
        let mut run = PentestRunArgs::from_arg_matches(&sub)?;
        let scopes = sub
            .get_many::<String>("scope")
            .map(|v| v.collect::<Vec<_>>())
            .unwrap_or_default();
        if !scopes.is_empty() {
            if scopes.len() != 1 || run.target.is_some() {
                return Err(front_door_error(
                    "--pentest requires one target; use either --scope URL or --target URL",
                ));
            }
            run.target = Some(scopes[0].clone());
        }
        if let Some(target) = &run.target {
            let url = url::Url::parse(target).ok();
            if !url.as_ref().is_some_and(|u| {
                matches!(u.scheme(), "http" | "https")
                    && u.host_str().is_some_and(|host| !host.contains(','))
            }) {
                return Err(front_door_error("--pentest requires one http:// or https:// target URL; hosts, CIDR, target lists/files and cli:// scopes are scan-only"));
            }
        }
        let templates = sub
            .get_many::<String>("templates")
            .map(|v| v.collect::<Vec<_>>())
            .unwrap_or_default();
        if !templates.is_empty() {
            if templates.len() != 1
                || run.template_dir.is_some()
                || !std::path::Path::new(templates[0]).is_dir()
            {
                return Err(front_door_error("--templates with --pentest requires one existing JS probe directory; template IDs, individual files and @lists are scan-only. Use --template-dir DIR. Convert scanner templates separately with `guardlink translate --from <template> --contract probe` using a GuardLink version that supports probe translation; --no-author never runs conversion"));
            }
            run.template_dir = Some(PathBuf::from(templates[0]));
        }
        let mut cli = Self::from_arg_matches(&matches)?;
        cli.command = Some(Commands::Pentest(PentestCommand {
            action: PentestAction::Run(run),
        }));
        Ok(cli)
    }

    fn with_scan_replay_inputs(
        matches: &clap::ArgMatches,
        definition: clap::Command,
    ) -> Result<Self, clap::Error> {
        let mut cli = Self::from_arg_matches(matches)?;
        if let Some(Commands::Scan(scan)) = &mut cli.command {
            let (_, selected) = matches.subcommand().unwrap();
            let selected_ids: std::collections::HashSet<_> =
                selected.ids().map(|id| id.as_str()).collect();
            let mut argv = vec![OsString::from("cxg-probe-inputs")];
            for arg in definition.get_arguments() {
                let id = arg.get_id().as_str();
                if authoring_option(id)
                    || !selected_ids.contains(id)
                    || selected.value_source(id) != Some(clap::parser::ValueSource::CommandLine)
                {
                    continue;
                }
                let flag = OsString::from(format!(
                    "--{}",
                    arg.get_long().expect("pentest option has a long name")
                ));
                if matches!(
                    arg.get_action(),
                    clap::ArgAction::SetTrue | clap::ArgAction::SetFalse
                ) {
                    argv.push(flag);
                } else if let Some(values) = selected.get_raw(id) {
                    for value in values {
                        argv.push(flag.clone());
                        argv.push(value.to_os_string());
                    }
                } else {
                    argv.push(flag);
                }
            }
            let parser = definition
                .mut_arg("codebase", |arg| arg.required(false).default_value("."))
                .mut_arg("no_author", |arg| {
                    arg.requires(clap::builder::Resettable::Reset)
                });
            scan.probe_run = Some(Box::new(PentestRunArgs::from_arg_matches(
                &parser.try_get_matches_from(argv)?,
            )?));
        }
        Ok(cli)
    }
}

// All other engine inputs are replay controls and reuse their original clap definitions.
fn authoring_option(id: &str) -> bool {
    matches!(
        id,
        "goal"
            | "max_templates"
            | "mutation_retries"
            | "ai_provider"
            | "ai"
            | "generation_timeout"
            | "batch_size"
            | "deterministic_templates"
            | "skills_file"
    )
}

fn front_door_error(message: &str) -> clap::Error {
    clap::Error::raw(clap::error::ErrorKind::ArgumentConflict, message)
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Run templates against network targets or local CLI binaries (cli://<binary>)
    Scan(ScanArgs),

    /// Build a target with instrumentation so a scan can earn its verdict
    ///
    /// `cxg scan` inspects a binary and refuses; it never builds the target.
    /// This is the deliberate opt-in on the other side of that line, and it is
    /// a separate verb rather than a scan flag for three reasons: building
    /// runs the project's own build system (`build.rs`, `configure`, arbitrary
    /// `Makefile` recipes) as you, which is a different trust decision from
    /// reading a file; it costs minutes and gigabytes, which is a bad surprise
    /// as a side effect and a fine one as a decision; and one instrumented
    /// build feeds many scans.
    ///
    /// It prints one JSON manifest and nothing else. There is no path from
    /// "I could not instrument this" to "here is a binary": every precondition
    /// failure is a `skipped` with a machine-readable reason, and the last
    /// check re-reads the binary that was just produced, so a build that
    /// accepted the flags and silently dropped them skips rather than passes.
    Build(BuildCommand),

    /// Manage templates
    Template(TemplateCommand),

    /// AI-powered template generation
    Ai(AiCommand),

    /// Search templates
    ///
    /// After `cxg template update`, use `cxg template search baseline --tags cli`
    /// to discover CLI Security Baseline templates from cert-x-gen-templates.
    Search(SearchArgs),

    /// Run as API server [NOT IMPLEMENTED — returns an error]
    Server(ServerArgs),

    /// Generate configuration file
    Config(ConfigCommand),

    /// Manage per-language dependency environments (does not confine execution)
    Sandbox(SandboxCommand),

    /// MCP (Model Context Protocol) server for AI agent integration
    Mcp(McpCommand),

    /// Whitebox pentests for web/Electron; Tauri source maps and optional in-process proof
    ///
    /// Web/Electron: reads `whitebox/findings.sarif` produced by guardlink, ranks threats against an
    /// operator goal, and asks your local AI CLI (claude / codex / gemini) to write
    /// JavaScript probe templates that read the target's source to craft code-aware
    /// payloads. Those templates execute in N parallel authenticated Chromium contexts,
    /// emitting confirmed/refuted/ambiguous findings to a JSON report plus a JSONL audit
    /// log of every HTTP request.
    ///
    /// Tauri instead maps IPC commands and capability grants against the threat model;
    /// --tauri-prove opts into command proof in a headless harness, without a live webview.
    ///
    /// Web/Electron capabilities:
    ///   • Interactive auth capture for SSO/MFA flows (no need to script logins)
    ///   • Chained-auth probes (IDOR cross-user) via `--auth-numbers 2+`
    ///   • Pre-flight identity inspection — landing-test based, no /me-path required
    ///   • Goal-driven LLM ranking of guardlink hypotheses
    ///   • Validator-guarded code-generation with hard 240s timeout per AI call
    ///   • Retry-with-mutation on AMBIGUOUS triage (max N retries, env-bound skip)
    ///   • Scope enforcement (URL/method allowlist, per-endpoint budget, 5xx hard-kill)
    ///   • Cookie-jar primitives in templates (HttpOnly-aware via Playwright)
    ///   • Out-of-band callbacks in two modes: inject a canary cxg cannot read
    ///     (`--oast`), or register one cxg owns and polls (`--oast-interactsh`) —
    ///     only the second yields an in-band blind-vuln confirmation
    ///   • Per-profile custom headers (WAF bypass, internal-test headers)
    ///   • Split report: confirmed_findings vs mitigation_verifications vs ambiguous
    Pentest(PentestCommand),

    /// Update cxg to the latest released build
    Update(UpdateCommand),

    /// Display version information
    Version,
}

/// `cxg build` — produce an instrumented build of a compiled target.
///
/// Cargo/Rust is the only back end today; every other recognised build system
/// skips with `build-system-not-implemented`, which is the honest answer
/// rather than a hidden limitation.
// @comment -- "CLI options for the instrumented build-assist; drives the target's own build system"
#[derive(Parser, Debug, Clone)]
pub struct BuildCommand {
    #[arg(
        long,
        help = "Build the target with sanitizer instrumentation",
        long_help = "Build the target with sanitizer instrumentation. Required: `cxg build` has \
                     no other mode, and demanding the word keeps room for one without changing \
                     what this invocation means."
    )]
    pub instrument: bool,

    #[arg(
        long,
        value_name = "DIR",
        default_value = ".",
        help = "Project directory whose build system to drive",
        long_help = "Directory holding the project to build. The build system is detected from \
                     its marker files in priority order (Cargo.toml, CMakeLists.txt, go.mod, \
                     configure, Makefile, meson.build); Cargo.toml first, so a polyglot \
                     repository such as a Tauri app instruments its Rust binary. A tree matching \
                     none of them skips with unknown-build-system rather than being guessed at."
    )]
    pub project: PathBuf,

    #[arg(
        long,
        value_name = "NAME",
        help = "Which binary target to build",
        long_help = "Which binary target to build. Inferred when the project has exactly one; a \
                     workspace with several skips with binary-target-ambiguous rather than \
                     instrumenting one nobody asked for."
    )]
    pub bin: Option<String>,

    #[arg(
        long,
        value_name = "LIST",
        default_value = "address",
        help = "Comma-separated sanitizers to build with",
        long_help = "Comma-separated sanitizers, in rustc's vocabulary: address, thread, memory. \
                     Capability is asked of rustc per target rather than guessed, so a request \
                     the target cannot serve (MSan on arm64 macOS) skips with \
                     sanitizer-unsupported-on-target. Note that Rust has NO UBSan -- \
                     -Zsanitizer=undefined does not exist on any target -- so `undefined` skips \
                     with a note naming the Rust equivalent for the integer class, \
                     -C overflow-checks=on, which cxg passes on every instrumented build anyway."
    )]
    pub sanitizer: String,

    #[arg(
        long,
        value_name = "DIR",
        help = "Where to put the instrumented build tree",
        long_help = "Where to put the instrumented build tree; defaults to \
                     <project>/target-instrumented. Never the project's own target/: RUSTFLAGS \
                     is part of cargo's fingerprint, so sharing one forces a full rebuild in \
                     both directions every time you alternate between an instrumented scan and \
                     ordinary work. Budget several gigabytes per instrumented project."
    )]
    pub out: Option<PathBuf>,

    #[arg(
        long,
        help = "Rebuild std with the sanitizer (-Zbuild-std)",
        long_help = "Rebuild std with the sanitizer. Needs the rust-src component. Mandatory for \
                     MSan, whose uninstrumented std reports uninitialised reads everywhere, and \
                     merely better for ASan, which interposes the allocator and so catches heap \
                     errors through a precompiled std. Off by default."
    )]
    pub build_std: bool,

    #[arg(
        long,
        value_name = "PATH",
        help = "Also write the manifest to this file",
        long_help = "Write the manifest to this file as well as to stdout. Hand it back to a \
                     scan with `cxg scan --instrumented-manifest <path>` so the scan trusts what \
                     cxg recorded at build time instead of re-inspecting the artefact."
    )]
    pub manifest: Option<PathBuf>,

    #[arg(
        short = 'q',
        long,
        help = "Print only the path of the instrumented binary",
        long_help = "Print only the path of the instrumented binary, and nothing at all on a \
                     skip, for `cxg scan --scope cli://$(cxg build --instrument --project . -q)`. \
                     The exit status still distinguishes the two: 0 instrumented, 3 skipped."
    )]
    pub quiet: bool,
}

/// `cxg update` — self-update the binary from the latest GitHub release.
// @comment -- "CLI options for the self-update command; downloads a release binary and replaces the running executable"
#[derive(Parser, Debug, Clone)]
pub struct UpdateCommand {
    /// Only check whether a newer version exists; don't download or install
    #[arg(long)]
    pub check: bool,

    /// Install a specific release tag (e.g. v1.2.0) instead of the latest
    #[arg(long)]
    pub version: Option<String>,

    /// Skip the confirmation prompt before replacing the binary
    #[arg(long, short = 'y')]
    pub yes: bool,

    #[arg(
        long,
        help = "Replace the binary even when a package manager owns it",
        long_help = "Replace the binary even when a package manager owns it. Without this, a cxg \
                     installed by Homebrew, by `cargo install` or inside a container is left \
                     alone: `cxg update` prints the command that upgrades it through its manager \
                     and exits with status 3, because replacing the file behind the manager's \
                     back leaves the manager believing the old version is installed."
    )]
    pub force: bool,
}

#[derive(Parser, Debug, Clone)]
#[command(after_help = "TARGETS:
  web: live browser probes; --codebase and --target required, --auth optional.
  electron: live desktop probes; also requires --app-cmd or --app-binary.
  tauri: source map of IPC commands and capability grants correlated with GuardLink.
    Requires --codebase with whitebox/findings.sarif; no --target, --auth or launch command needed.
    Default report: tauri_surface_mapped, caveat enumerated_not_live_probed.
    An empty findings list does not establish safety: no commands were invoked.
    --tauri-prove builds an app copy for headless in-process command proof, without a live webview.
  Local CLI binaries use cxg scan --scope cli://<binary>, not pentest run.

EXAMPLES:
  cxg pentest install
  guardlink sarif ./app-repo -p my-app -o ./app-repo/whitebox/findings.sarif
  cxg pentest run --target-type tauri --codebase ./app-repo
  cxg pentest run --target-type tauri --codebase ./app-repo --tauri-prove --tauri-prove-timeout 1200")]
pub struct PentestCommand {
    #[command(subcommand)]
    pub action: PentestAction,
}

// Keep these argument builders out of the large PentestAction builder's frame.
// Nested auth help must also fit the native Windows main-thread stack.
#[derive(clap::Args, Debug, Clone)]
pub struct PentestUpdateArgs {
    /// Print only a machine-readable result on stdout.
    #[arg(long)]
    pub json: bool,
    /// Explicitly replace a source-derived installation with the embedded bundle.
    #[arg(long)]
    pub from_embedded: bool,
}

#[derive(clap::Args, Debug, Clone)]
pub struct PentestStatusArgs {
    /// Print binary version, digests, origin, freshness and interrupted state.
    #[arg(long)]
    pub json: bool,
}

#[derive(Subcommand, Debug, Clone)]
// @comment -- "clippy::large_enum_variant, allowed deliberately. Run already carries ~35 operator flags and sat just under the lint's 200-byte spread; adding --oast-interactsh pushed it over. The lint's remedy is to box the variant's payload, which here would mean a Box around a clap-derived struct that main.rs destructures field-by-field — a churn of every pentest call site, and an allocation on a path that parses one command line and exits, to save bytes on a value that exists once per process. The size is a true statement about a subcommand with this many flags, not a defect."
#[allow(clippy::large_enum_variant)]
pub enum PentestAction {
    /// Safely install the pipeline; check (but never install) Python dependencies.
    /// Explicit development installs retain source discovery, including CXG_SOURCE.
    Install {
        /// Refresh even when current, preserving the previous tree as a backup.
        #[arg(long)]
        force: bool,
    },

    /// Refresh from this binary's embedded bundle, offline; preserve previous files.
    Update(PentestUpdateArgs),

    /// Inspect pipeline content without Python, filesystem writes, or recovery.
    Status(PentestStatusArgs),

    /// Print installed orchestrator capabilities as JSON (no target contact).
    ///
    /// Reports protocol features such as exact-threat-id, not target-type support or
    /// evidence that a target was tested. See `cxg pentest run --help` for web,
    /// Electron and Tauri targets; local CLI binaries use `cxg scan --scope cli://<binary>`.
    /// Requires `cxg pentest install` first. Example: cxg pentest capabilities
    Capabilities,

    /// Capture — or, via a subcommand, import/verify — an authenticated session profile
    ///
    /// Capture supports web and Electron only. Tauri source maps and in-process
    /// proofs need no captured profile; use `cxg pentest run --target-type tauri
    /// --codebase ./app-repo`. Local CLI scans need no browser auth profile either.
    ///
    /// With no subcommand this captures interactively: it spawns a real headed Chromium
    /// window. You log in by ANY means — username/password, SSO redirect, MFA prompt,
    /// hardware key, magic link, OAuth popup. When the app dashboard is showing, press
    /// ENTER in the terminal (or close the browser) and cxg snapshots cookies +
    /// localStorage + sessionStorage from every origin the browser touched. The profile
    /// is saved at `~/.cert-x-gen/auth/<profile>.json` plus metadata at
    /// `<profile>.meta.json`.
    ///
    /// A post-capture landing-test verifies the session works: it re-opens a fresh
    /// browser context with the saved state, navigates to --target, and checks whether
    /// the final URL/page looks like a login or the app dashboard.
    ///
    /// Use `--auth-numbers N` for chained-auth scenarios (e.g. IDOR testing needs two
    /// different identities). cxg prompts for a human-readable label for each capture.
    ///
    /// For CI, where no human can drive a browser, use the subcommands instead:
    ///   `cxg pentest auth import` replays a session captured once and exported as a
    ///   Playwright storage_state, with no browser; `cxg pentest auth verify` checks a
    ///   saved session is still alive (exit 0 alive / non-zero dead) before a run spends
    ///   any AI budget.
    ///
    /// Examples:
    ///     # Single interactive capture (no subcommand)
    ///     cxg pentest auth --target https://app.example.com --profile admin
    ///
    ///     # Two identities for chained-auth (e.g. IDOR victim + attacker)
    ///     cxg pentest auth --target https://app.example.com --profile pentest --auth-numbers 2
    ///
    ///     # Scripted login (no browser pop-up)
    ///     cxg pentest auth --target https://app.example.com --profile bot \
    ///       --creds 'user@example.com:hunter2' --login-path /api/auth/login
    ///
    ///     # Capture a profile that sends a WAF-bypass header on every request
    ///     cxg pentest auth --target https://app.example.com --profile pentest \
    ///       --header "x-test-automation:abc123xyz"
    ///
    ///     # CI: import a session captured once, then verify it before a run
    ///     cxg pentest auth import --profile pentest --target https://staging.app \
    ///       --storage-state ./pentest.storage.json
    ///     cxg pentest auth verify --profile pentest
    // @comment -- "auth carries the interactive-capture flags AND hosts the CI subcommands (import/verify). args_conflicts_with_subcommands keeps the two modes from being mixed on one line. This mirrors the Python surface, where cxg_pentest.py forwards `auth <rest>` verbatim to auth.py's own login|import|verify|list subparsers; bare `cxg pentest auth ...` maps to `auth login` exactly as before. --target/--profile are Option here rather than required-at-clap ONLY because clap's derive does not honour subcommand_negates_reqs (the builder method works, the #[command(...)] attribute is a no-op in clap 4.5), so a required --target would wrongly be demanded of `auth import`/`auth verify` too. Their required-ness for the capture path is enforced in main.rs's None branch, so the capture happy path and its errors are unchanged."
    #[command(args_conflicts_with_subcommands = true)]
    Auth {
        /// Target URL where login happens (e.g. https://app.example.com).
        /// After capture, the landing-test verifier opens this URL with the saved
        /// cookies; if it doesn't bounce to a login page, the session is alive.
        ///
        /// Required for interactive capture (no subcommand). The `import`/`verify`
        /// subcommands take their own `--target` instead.
        #[arg(long)]
        target: Option<String>,

        /// Profile name. If --auth-numbers > 1, this is the PREFIX and final profiles
        /// are named `<profile>-1`, `<profile>-2`, etc. Use a stable name so subsequent
        /// `cxg pentest run --auth <profile>` invocations can reload it.
        ///
        /// Required for interactive capture (no subcommand).
        #[arg(long)]
        profile: Option<String>,

        /// Number of profiles to capture in sequence. Each capture opens its own
        /// Chromium window and prompts for a label (e.g. "victim", "attacker", "admin").
        /// Required ≥2 for chained-auth probes like IDOR cross-user tests.
        #[arg(long, default_value = "1")]
        auth_numbers: usize,

        /// Inline credentials `email:password` for scripted login (skips browser pop-up).
        /// Only works for password-based auth — SSO/MFA flows MUST use interactive capture.
        #[arg(long)]
        creds: Option<String>,

        /// File with `profile:email:password[:label]` per line for scripted batch capture.
        /// Useful for re-auth between scans of password-only test apps.
        #[arg(long)]
        creds_file: Option<PathBuf>,

        /// Endpoint path for scripted login POST. Only used with `--creds` or `--creds-file`.
        /// The captured browser will POST {email, password} as JSON to <target><login-path>.
        #[arg(long, default_value = "/api/auth/login")]
        login_path: String,

        /// Human-readable label for the profile (e.g. "admin", "low-priv-user").
        /// Shown in scan output to make findings readable. Does not affect behavior.
        #[arg(long)]
        label: Option<String>,

        /// Authenticated API liveness endpoint checked after capture and saved with
        /// the profile for later verification. Defaults to /api/me.
        #[arg(long)]
        verify_url: Option<String>,

        /// Custom HTTP header `NAME:VALUE` sent on every outbound request from this
        /// profile's browser context — including login, every scan probe, every health
        /// check. Repeatable for multiple headers. Saved with the profile so future
        /// `cxg pentest run --auth <profile>` invocations reuse them automatically.
        ///
        /// Use case: WAF-bypass tokens granted by infra (e.g. `x-test-automation`),
        /// internal-test headers, custom forwarding hints.
        ///
        /// SECURITY: header values are stored in plaintext under
        /// `~/.cert-x-gen/auth/<profile>.meta.json`. Treat the file like a credential.
        /// `chmod 600` if your machine has multiple users. Delete the profile when
        /// the engagement ends. Header values are sent to EVERY origin the browser
        /// touches, including IDPs — keep this in mind for SSO flows.
        #[arg(long = "header", value_name = "NAME:VALUE")]
        headers: Vec<String>,

        /// Explicit privilege rank for this identity: an integer 0-100 or an alias
        /// high/medium/low (= 90/50/10). Overrides the role-based heuristic and is fed to
        /// the AI ranker so it selects the right identity per probe (lowest tier for
        /// privesc, etc.). Omit to auto-derive from the app's role. In multi-capture
        /// (--auth-numbers > 1) this pre-fills the per-identity prompt.
        #[arg(long)]
        tier: Option<String>,

        /// Semantic role hint (e.g. "billing-analyst") passed to the AI as extra context —
        /// useful when the app's /me endpoint exposes no clear role field.
        #[arg(long)]
        persona: Option<String>,

        /// Peer-group name (e.g. "analyst-team-a"). Give two SAME-permission, DIFFERENT-user
        /// sessions the same cohort so the AI treats them as peers and targets horizontal
        /// IDOR / cross-tenant access between them.
        #[arg(long)]
        cohort: Option<String>,

        /// Free-form `NAME=VALUE` context attached to the profile and shown to the AI.
        /// Repeatable.
        #[arg(long = "tag", value_name = "NAME=VALUE")]
        tags: Vec<String>,

        /// Target type to capture auth for.
        ///
        /// `web` (default): the existing authenticated-browser capture against an HTTP
        /// application. `electron`: launch the Electron desktop app and capture its
        /// session state instead of a browser's.
        ///
        /// Auth capture does not support Tauri. Its source map and optional in-process
        /// proof need no captured profile; select tauri on `cxg pentest run` instead.
        // @comment -- "selects which substrate auth capture launches against; an unknown value is rejected by clap so a typo can never silently downgrade a desktop capture to a web capture"
        // requires_if (not required_if_eq on app_cmd) is deliberate: clap's required_if_eq/
        // required_unless validation path skips the conflicts_with escape hatch, so pairing it
        // with app_cmd's conflicts_with would wrongly demand --app-cmd even when --app-binary
        // alone was supplied. requires_if instead feeds the required-arg resolution path that
        // does consult conflicts_with. See desktop_flag_tests::auth_electron_with_app_binary_alone_parses.
        #[arg(long, default_value = "web", value_parser = ["web", "electron"], requires_if("electron", "app_cmd"))]
        target_type: String,

        /// Command that launches the desktop app, e.g. "npm run electron:dev".
        ///
        /// Required with `--target-type electron` unless `--app-binary` is given.
        /// cxg appends `--remote-debugging-port` and a per-identity `--user-data-dir`.
        // @comment -- "operator-supplied launch command forwarded to the orchestrator, which splits and executes it as a child process per identity"
        // @g.source (#operator_app_cmd) -- "command string supplied by the operator on the command line"
        #[arg(long, conflicts_with = "app_binary")]
        app_cmd: Option<String>,

        /// Path to a built desktop app, e.g. /Applications/Foo.app.
        ///
        /// Alternative to `--app-cmd`; the two are mutually exclusive.
        // @comment -- "operator-supplied path to a packaged application, executed directly instead of via a launch command"
        #[arg(long, conflicts_with = "app_cmd")]
        app_binary: Option<String>,

        /// Non-interactive CI subcommand (`import` or `verify`). Absent = interactive
        /// capture using the flags above.
        // @comment -- "optional so bare `cxg pentest auth --target ... --profile ...` still means interactive capture; present it routes to the browser-free import/verify paths auth.py exposes for CI"
        #[command(subcommand)]
        auth_sub: Option<AuthSubcommand>,

        /// Auth profile directory (also honours CERT_X_GEN_HOME).
        #[arg(long)]
        auth_dir: Option<PathBuf>,
    },

    /// List saved auth profiles under ~/.cert-x-gen/auth/
    ///
    /// Shows profile name, label, target URL, and whether extra_headers are present.
    /// Useful before running `cxg pentest run --auth <name>` to confirm which profile
    /// you'll be scanning as.
    AuthList {
        /// Read saved profiles from this directory.
        #[arg(long)]
        auth_dir: Option<PathBuf>,
    },

    /// Write an example scope.yaml the operator can edit
    ///
    /// scope.yaml controls the safety rails for a scan: method allowlist (default
    /// GET/POST/HEAD/OPTIONS — DELETE/PUT/PATCH require `--destructive-ok`), URL
    /// allow/blocklist regexes, per-endpoint and total request budgets, 5xx-streak
    /// hard-kill threshold, and the `authorization_attestation` field that's recorded
    /// in the audit log header.
    ///
    /// Example:
    ///     cxg pentest scope-init -o my-engagement-scope.yaml
    ScopeInit {
        /// Output file path. Default: scope.yaml in the current directory.
        #[arg(short, long, default_value = "scope.yaml")]
        output: PathBuf,
    },

    /// Run the full end-to-end pentest pipeline against a target
    ///
    /// Targets: web and Electron use live probes. Tauri maps IPC commands and JSON
    /// capability grants from source, correlated with the GuardLink threat model.
    /// Install with `cxg pentest install` and generate `whitebox/findings.sarif`
    /// with `guardlink sarif . -p my-app -o whitebox/findings.sarif` in the app repository.
    /// Tauri requires --codebase; no --target, --auth or app launch command is needed.
    /// Keep the default --template-lang js: the legacy py pipeline rejects Tauri.
    ///
    /// A default Tauri report is tauri_surface_mapped with enumerated_not_live_probed:
    /// commands are not invoked, and empty findings do not establish safety.
    /// Opt in with --tauri-prove for headless in-process command proof; this needs
    /// a Rust toolchain and the app's build prerequisites, and does not drive a live webview.
    ///
    /// Web/Electron pipeline steps:
    ///   [1]  Load guardlink hypotheses from `<codebase>/whitebox/findings.sarif`
    ///   [1b] Inspect captured auth profiles via landing-test
    ///        (`profile_inspect.inspect_profiles_async`)
    ///   [2]  LLM-rank hypotheses against --goal + profile coverage; AI generates JS
    ///        templates that read source via Claude/Codex/Gemini's own Read/Grep tools
    ///   [3]  Load + statically validate templates (`validator.py`)
    ///   [4]  Open N parallel authenticated Chromium contexts; inject the cxg JS bridge
    ///   [5]  Run each template; triage findings (CONFIRMED / REFUTED / AMBIGUOUS);
    ///        mutate-and-retry on payload-fixable AMBIGUOUS, skip environment-bound
    ///   [6]  Write `report.json` and `audit.jsonl` to --session-dir
    ///
    /// The full set of probes available to templates is documented in
    /// `pentest/docs/TEMPLATES.md`. The runtime intelligence layer (validator, scope,
    /// session health, mutation, triage, audit) is in `pentest/docs/ARCHITECTURE.md`.
    ///
    /// Examples:
    ///     # Single-profile read-only scan with default settings
    ///     cxg pentest run --codebase ./repo --target http://localhost:8000 \
    ///       --auth admin --ai --ai-provider claude
    ///
    ///     # Two identities for IDOR/chained-auth, AI off → built-in probes only
    ///     cxg pentest run --codebase ./repo --target http://localhost:8000 \
    ///       --auth victim,attacker
    ///
    ///     # Verify mitigations only (skips unmitigated threats so you can confirm
    ///     # declared defenses hold at runtime). Useful for well-annotated codebases.
    ///     cxg pentest run --codebase ./repo --target https://staging.app \
    ///       --auth pentest --ai --ai-provider claude \
    ///       --mitigation-mode mitigated --max-templates 16
    ///
    ///     # SSRF testing against a canary cxg OWNS — it registers the interactsh
    ///     # session and polls it, so a callback becomes a confirmed finding
    ///     cxg pentest run --codebase ./repo --target https://staging.app \
    ///       --auth pentest --ai --ai-provider claude \
    ///       --oast-interactsh \
    ///       --goal "verify SSRF on /slack/proxy via OAST callback"
    ///
    ///     # Same probes, but against a canary cxg can only inject into (e.g. a Burp
    ///     # Collaborator host). Templates build the URL; YOU read the hit in
    ///     # Collaborator. Findings stay unconfirmed as far as cxg is concerned.
    ///     cxg pentest run --codebase ./repo --target https://staging.app \
    ///       --auth pentest --ai --ai-provider claude \
    ///       --oast c4ca4238a0b92.oastify.com \
    ///       --goal "test SSRF on /slack/proxy; check Collaborator for callbacks"
    ///
    /// Exit codes:
    ///   0 → no confirmed findings (clean scan)
    ///   1 → no templates available (guardlink output missing or empty, or every
    ///       template in a replayed --template-dir was withheld for carrying no
    ///       `// @attach_scheme: path` header); report.json is still written
    ///   2 → confirmed findings present
    ///   3 → scan was hard-killed (5xx streak, scope violation) OR, under
    ///       `--no-restart`, a desktop target died mid-scan and was not relaunched
    ///   4 → mis-specified run, refused at pre-flight before any probing: a
    ///       `--scope-file` cxg cannot read (missing, unreadable, invalid YAML,
    ///       not a mapping, empty file, or PyYAML absent), `--scope-file` with
    ///       `--template-lang py`, `--target-type electron` without `--app-cmd`/
    ///       `--app-binary`, `--oast` together with `--oast-interactsh`, or an auth
    ///       profile whose kind does not match the target substrate
    ///   5 → a selected auth profile or service is dead, expired, or unverified by
    ///       its configured liveness endpoint, with or without `--ci`; probes for
    ///       ready services still run, and the report is `complete: false`,
    ///       `status: incomplete`. A blocked or failed request does not change the
    ///       exit code; it is listed in `request_failures` and also makes the
    ///       report `status: incomplete`
    #[command(after_help = "SCAN FRONT DOOR:
  cxg scan --pentest accepts every option listed above through the same pentest engine.
  --scope URL aliases --target URL; --templates DIR aliases --template-dir DIR.
  Supply one HTTP(S) URL; ports, CIDR, cli:// targets and scan-only filters are refused.
  JS probes only; any-language probes are not yet supported. The legacy --template-lang py path remains available.
  Convert scanner templates separately: guardlink translate --from <template> --contract probe
    (requires a GuardLink version with probe translation; --no-author never converts).
  --no-author --template-dir DIR guarantees zero model calls (ranking, generation and mutation disabled).
  Pentest verdicts are engine-confirmed; ordinary scan findings remain template-reported.

TAURI EXAMPLES:
  # Prepare the source threat model (after cxg pentest install)
  guardlink sarif ./app-repo -p my-app -o ./app-repo/whitebox/findings.sarif
  # Source map only; no commands invoked
  cxg pentest run --target-type tauri --codebase ./app-repo
  # Opt in to headless in-process command proof
  cxg pentest run --target-type tauri --codebase ./app-repo --tauri-prove --tauri-prove-timeout 1200")]
    Run(PentestRunArgs),
}

/// Arguments shared by `pentest run` and `scan --pentest`.
#[derive(clap::Args, Debug, Clone)]
pub struct PentestRunArgs {
    #[command(flatten)]
    pub probe_inputs: ProbeInputs,

    /// Running target app URL. Both `http://` and `https://` are supported.
    /// Every identity's traffic and liveness check go to this target, unless a profile
    /// was imported with `--service`, which opts it into its own saved origin.
    ///
    /// Required for `--target-type web` and `electron`; omit it for
    /// `--target-type tauri`, which maps the IPC surface from source and navigates
    /// nowhere. A web/Electron run without --target is refused at preflight (exit 4).
    // @comment -- "Optional at clap level ONLY so a tauri source-surface map can omit it. The Python preflight refuses a web/electron run with no --target, so the live-probe paths keep their 'you must say what to probe' guarantee; main.rs forwards --target only when it is present, so an absent one reaches the orchestrator as the empty default it treats as 'no live target'."
    #[arg(
        long,
        help_heading = "Target",
        display_order = 2,
        help = "Running target app URL (http:// or https://); omit for --target-type tauri"
    )]
    pub target: Option<String>,

    /// Open N headed browser windows for interactive login at scan start, then run
    /// the pipeline with the resulting fresh profiles. Each capture prompts you for
    /// a per-identity label. Use this when your captured profiles have expired or
    /// when you don't want to manage profile lifecycle separately.
    ///
    /// Profiles are saved as `<--auth-profile>-1`, `<--auth-profile>-2`, etc.
    #[arg(
        long,
        default_value = "0",
        help_heading = "Authentication",
        display_order = 13,
        help = "Capture N fresh identities interactively at start"
    )]
    pub interactive_auth: usize,

    /// Name prefix for `--interactive-auth` captures. The final profile names are
    /// `<auth_profile>-1`, `<auth_profile>-2`, etc.
    #[arg(
        long,
        default_value = "pentest",
        help_heading = "Authentication",
        display_order = 12,
        help = "Name prefix for --interactive-auth captures"
    )]
    pub auth_profile: String,

    /// Minimum auth contexts the scan requires. If you pass `--auth a,b` but
    /// `--auth-numbers 3`, chained-auth templates that need 3 contexts will be
    /// skipped with a warning. Pure usability check — engine doesn't fabricate
    /// extra contexts.
    #[arg(
        long,
        help_heading = "Authentication",
        display_order = 14,
        help = "Minimum auth contexts the scan requires"
    )]
    pub auth_numbers: Option<usize>,

    /// File of `profile:email:password[:label]` lines used to AUTO RE-AUTH a
    /// dead session mid-scan (the session-health monitor detects death via the
    /// landing test). Without this, a probe that kills its own session — e.g.
    /// session_replay's logout — leaves remaining probes unable to run.
    ///
    /// Recommended for any scan with `--mutation-retries > 0` or scans with
    /// SessionReplay / Csrf class templates.
    #[arg(
        long,
        help_heading = "Authentication",
        display_order = 15,
        help = "Creds file for auto re-auth of a dead session"
    )]
    pub creds_file: Option<PathBuf>,

    /// Template language. `js` (default): AI generates copy-paste-runnable JS
    /// templates that drive the cxg JS bridge — recommended for all interactive
    /// pentests. `py`: Python probe path (legacy) — only built-in probes in
    /// `pentest/payloads/`, no AI generation.
    #[arg(
        long,
        default_value = "js",
        help_heading = "AI Generation",
        display_order = 27,
        help = "Template language: js (default; required for Tauri/Electron) or py (legacy web)"
    )]
    pub template_lang: String,

    /// Natural-language pentest goal. Used as context for both LLM-based hypothesis
    /// ranking AND template generation. Be specific about which vuln classes,
    /// endpoints, or claims you want tested.
    ///
    /// Examples:
    ///   "test for IDOR in records and transactions APIs"
    ///   "verify each declared @mitigates actually holds at runtime"
    ///   "find unguarded admin endpoints accessible to non-admin tokens"
    #[arg(
        long,
        help_heading = "AI Generation",
        display_order = 23,
        help = "Natural-language pentest goal (ranking + generation)"
    )]
    pub goal: Option<String>,

    /// Exactly select imported hypotheses carrying this GuardLink id before ranking.
    /// Unknown ids refuse before target contact. Requires JS generation on web/electron;
    /// disables unrelated discovery, boundary and host probes. Not authorization.
    #[arg(long, help_heading = "AI Generation")]
    pub threat_id: Option<String>,

    /// Reuse JS templates from a previously-generated session directory. Skips the
    /// AI generation step entirely. Useful for re-running the same templates against
    /// different targets, or after fixing engine bugs that affected template execution.
    ///
    /// Template directories are at `~/.cert-x-gen/templates/session-<timestamp>-<pid>/`.
    /// JS probes are discovered recursively, using scan's exclusions for build
    /// artifacts, dependencies, disabled templates and skeleton directories.
    /// Scanner templates are refused: convert them separately with
    /// `guardlink translate --from <template> --contract probe` using a GuardLink
    /// version that supports probe translation. cxg never converts on replay.
    ///
    /// A template carrying no `// @attach_scheme: path` header is WITHHELD — never
    /// executed — and named in a `templates_withheld` caveat in report.json, because
    /// it may have been generated under a same-named file's intent context. See
    /// `pentest/docs/ARCHITECTURE.md` for the rule and the remedy for each case.
    #[arg(
        long,
        help_heading = "AI Generation",
        display_order = 28,
        help = "Reuse JS probes recursively (skip ranking and generation)"
    )]
    pub template_dir: Option<PathBuf>,

    /// Maximum number of templates the LLM ranker is allowed to select per scan.
    /// Each template = one AI generation call (~60-180s with claude/codex). Lower for
    /// fast feedback loops; higher for engagement-grade coverage.
    #[arg(
        long,
        default_value = "8",
        help_heading = "AI Generation",
        display_order = 24,
        help = "Max templates the LLM ranker may select"
    )]
    pub max_templates: usize,

    /// Maximum times the AI is allowed to mutate a template after AMBIGUOUS triage.
    /// Environment-bound AMBIGUOUS (missing role, missing primitive) skip mutation
    /// automatically; only payload-fixable ones consume retries.
    /// 0 disables the loop entirely.
    #[arg(
        long,
        default_value = "2",
        help_heading = "AI Generation",
        display_order = 25,
        help = "Max AI mutation retries on AMBIGUOUS triage"
    )]
    pub mutation_retries: usize,

    /// AI provider. `auto` prefers the editor bridge when $BUGB_BRIDGE_URL is set,
    /// then the first available CLI tool (claude > codex > gemini), falling back to
    /// ANTHROPIC_API_KEY / OPENAI_API_KEY HTTP APIs. Otherwise specify explicitly.
    /// CLI providers don't need API keys — they use your existing CLI auth.
    ///
    /// Options: auto | bridge | claude | codex | gemini | anthropic | openai
    ///
    /// `bridge` posts each prompt to $BUGB_BRIDGE_URL (with Authorization: Bearer
    /// $BUGB_BRIDGE_TOKEN when set) and reads the completion back — an editor/CI
    /// integration point rather than a local CLI.
    #[arg(
        long,
        default_value = "claude",
        help_heading = "AI Generation",
        display_order = 22,
        help = "AI provider: auto|bridge|claude|codex|gemini|crush|anthropic|openai"
    )]
    pub ai_provider: String,

    /// Enable AI-driven template generation. Without `--ai`, only built-in probes
    /// from `pentest/payloads/` run. With `--ai`, the orchestrator invokes the
    /// chosen `--ai-provider` to read the codebase and synthesize code-aware
    /// templates per guardlink hypothesis.
    #[arg(
        long,
        help_heading = "AI Generation",
        display_order = 21,
        help = "Enable AI-driven template generation"
    )]
    pub ai: bool,

    /// Show Chromium windows during scan instead of running headless. Useful for
    /// debugging probes, watching auth flows, or when WAF bot-detection is blocking
    /// headless requests (real Chromium has a stronger fingerprint than headless).
    #[arg(
        long,
        help_heading = "Execution",
        display_order = 43,
        help = "Show Chromium windows instead of running headless"
    )]
    pub headed: bool,

    /// Allow DELETE/PUT/PATCH methods AND paths matching destructive regexes
    /// (`/wipe`, `/delete-all`, `/factory-reset`, etc.) in scope.yaml.
    /// Default OFF. Required for templates that test destructive-action authz.
    ///
    /// USE WITH CARE on production targets. The engine emits a warning at startup
    /// and every blocked request is still recorded in the audit log.
    #[arg(
        long,
        help_heading = "Execution",
        display_order = 42,
        help = "Allow DELETE/PUT/PATCH + destructive paths (use with care)"
    )]
    pub destructive_ok: bool,

    /// Free-text written authorization statement recorded in the audit log header.
    /// Include engagement ID, operator name, change-management ticket, etc.
    ///
    /// Example: "Engagement PT-2026-003, operator J. Doe, ticket CHG-1234"
    ///
    /// Strongly recommended for any non-local scan. The audit log header is the
    /// dispute-ready record of "I had authorization to do this scan."
    #[arg(
        long,
        help_heading = "Execution",
        display_order = 47,
        help = "Written authorization statement for the audit log"
    )]
    pub attestation: Option<String>,

    /// Hypothesis filter by declared-mitigation status from guardlink:
    ///   `any`         — all HTTP-testable hypotheses (default)
    ///   `unmitigated` — only threats WITHOUT a declared @mitigates
    ///                   (find unguarded holes)
    ///   `mitigated`   — only threats WITH @mitigates declared
    ///                   (verify defenses actually hold at runtime)
    #[arg(
        long,
        default_value = "any",
        help_heading = "AI Generation",
        display_order = 29,
        help = "Hypothesis filter: any|unmitigated|mitigated"
    )]
    pub mitigation_mode: String,

    /// Authenticated API liveness endpoint. Per-profile liveness_check takes
    /// precedence; 401/403 means dead, and a configured endpoint that does not answer
    /// 2xx leaves the session unverified. When nothing is configured and the default
    /// /api/me is absent (404, an HTML page, a redirect), the landing test decides
    /// instead. The API JSON also supplies role/email/id.
    #[arg(
        long,
        default_value = "/api/me",
        help_heading = "Authentication",
        display_order = 16,
        help = "Authenticated API liveness endpoint (default /api/me; per-profile setting wins)"
    )]
    pub me_path: String,

    /// Hard wall-clock timeout per AI generation call. The whole process tree is
    /// killed if exceeded. Default 240s.
    ///
    /// Claude CLI typically takes 60-170s per template; Codex 90-220s; Gemini 30-180s.
    /// Bump to 600+ for very large codebases the AI has to grep through.
    #[arg(
        long,
        default_value = "240",
        help_heading = "AI Generation",
        display_order = 26,
        help = "Hard timeout per AI generation call, seconds (default 240)"
    )]
    pub generation_timeout: u64,

    /// Skip periodic session health checks and re-authentication. Startup API
    /// verification still runs, so a dead or expired profile still exits 5; this
    /// flag supplies no proof for denial verdicts.
    #[arg(
        long,
        help_heading = "Authentication",
        display_order = 17,
        help = "Skip periodic health checks (startup API verification still runs; a dead profile still exits 5)"
    )]
    pub skip_health_check: bool,

    /// Ignore server TLS certificate errors for web browser and raw HTTP requests
    #[arg(long)]
    pub insecure_tls: bool,

    /// Proxy server URL for web browser and raw HTTP requests
    #[arg(long)]
    pub proxy: Option<String>,

    /// PEM client certificate for the target origin
    #[arg(long, requires = "client_key")]
    pub client_cert: Option<PathBuf>,

    /// PEM private key for the client certificate
    #[arg(long, requires = "client_cert")]
    pub client_key: Option<PathBuf>,

    /// An external out-of-band callback host cxg can INJECT INTO but cannot read
    /// back (Burp Collaborator, a canary you host, an interactsh domain you
    /// generated yourself). Exposed to templates as `cxg.oast.url(label, scheme?)`
    /// so payloads carry a callback URL — but cxg never learns whether it fired,
    /// so nothing here confirms anything: blind probes (SSRF, blind SQLi, blind
    /// XXE, blind cmd-injection) still fall back to status-code heuristics and
    /// timing, and the AI prompt is instructed to mark them `confirmed=false`.
    /// Reading the callback is the operator's job, in their own tooling.
    ///
    /// Want cxg to do the confirming? Use `--oast-interactsh` instead.
    ///
    /// Example: `--oast c4ca4238a0b923820dcc.oastify.com`
    ///
    /// If the host is an interactsh domain rather than a Collaborator one, run
    /// `interactsh-client` in another terminal first and paste the hostname it
    /// prints — that terminal is the only place these callbacks become visible.
    ///
    /// (With `--oast-interactsh` there is no second terminal: cxg is the client.)
    // @comment -- "operator-supplied callback host injected into payloads; kept exactly as it was, value and all, because every existing invocation and every template calling cxg.oast.url() depends on it"
    // @comment -- "help text deliberately no longer claims 'definitive blind-vuln confirmation': cxg holds no session for a host it was merely handed, so it cannot poll it, and an operator who read the old wording would take an unconfirmed finding for a confirmed one"
    #[arg(
        long,
        value_name = "HOST",
        help_heading = "OAST",
        display_order = 31,
        help = "OAST canary cxg injects but cannot read back (unconfirmed)"
    )]
    pub oast: Option<String>,

    /// Register an interactsh session cxg OWNS and poll it — the mode that can
    /// actually confirm a blind vulnerability. Because cxg registered the session
    /// it holds the correlation id, so templates can call `cxg.oast.poll(label)`,
    /// read the interactions back in-band, and a callback becomes a genuine
    /// `confirmed=true` finding with the interaction recorded as evidence. cxg is
    /// the interactsh client here; you do not run one alongside it.
    ///
    /// The optional value is the interactsh server to register against; omit it to
    /// use interactsh's default public servers.
    ///
    /// Mutually exclusive with `--oast`. Two canaries would split payloads between
    /// a host cxg can poll and one it cannot, so "was this confirmed?" would have
    /// no single answer per finding.
    ///
    /// Examples: `--oast-interactsh` (default servers), or
    /// `--oast-interactsh https://oast.example.internal` (your own instance).
    // @comment -- "selects the OAST mode in which cxg registers and therefore can read the canary; the server URL, when given, is the interactsh instance the session is registered against"
    // @comment -- "conflicts_with rather than a runtime if-both check, matching --app-cmd/--app-binary above: clap then rejects the pair during parse with the standard usage error, before any scan work, and the constraint is visible in --help instead of hiding in main()"
    // @comment -- "num_args = 0..=1 with an empty default_missing_value keeps the value optional and distinguishes the three states the mode needs — absent (None, no session), bare (Some(\"\"), default servers), explicit (Some(url)). An Option<Option<String>> would encode the same thing while making every downstream match arm nested for no gain"
    // @g.source (#operator_oast_server) -- "interactsh server URL supplied by the operator on the command line"
    #[arg(
        long,
        value_name = "SERVER_URL",
        num_args = 0..=1,
        default_missing_value = "",
        conflicts_with = "oast",
        help_heading = "OAST",
        display_order = 32,
        help = "OAST canary cxg owns and polls (confirms blind vulns)"
    )]
    pub oast_interactsh: Option<String>,

    /// Host a built-in OAST callback cxg OWNS and poll it, bound to an interface
    /// the TARGET can reach rather than to loopback — the mode that confirms a
    /// blind vulnerability (SSRF, XXE, command injection, SSTI, NoSQL, LDAP,
    /// deserialization) against a target with no internet egress, such as an
    /// `env up` sandbox or internal staging, where `--oast-interactsh` cannot
    /// (its public servers need egress) and `--oast` cannot be read back.
    ///
    /// cxg holds the listener, so templates call `cxg.oast.poll(label)` and a
    /// callback becomes a `confirmed=true` finding with the interaction as
    /// evidence. The label rides in the URL path (`http://<host>/<label>`), not a
    /// subdomain, because the bind address has no wildcard DNS under it.
    ///
    /// The optional value selects the bind: omit it or `docker-bridge` for the
    /// docker bridge gateway (reachable from a container on the default bridge),
    /// `host-docker-internal` for a Docker Desktop container, or an
    /// address/hostname (e.g. `10.0.0.5`, or `ip:10.0.0.5`) for internal staging.
    ///
    /// Mutually exclusive with `--oast` and `--oast-interactsh`: one canary per
    /// run, or payloads split between callbacks nobody correlates per finding.
    // @comment -- "forwarded as the OAST mode, not a session: pentest/oast_listener.py binds the socket and decides reachability, so the Rust and Python CLIs cannot disagree about whether this canary is pollable; the three states (absent/bare/explicit) are carried exactly as --oast-interactsh carries them"
    #[arg(
        long,
        value_name = "BIND",
        num_args = 0..=1,
        default_missing_value = "",
        conflicts_with_all = ["oast", "oast_interactsh"],
        help_heading = "OAST",
        display_order = 33,
        help = "Built-in OAST listener cxg owns, reachable by an egress-less target"
    )]
    pub oast_listener: Option<String>,

    /// Also start a DNS listener alongside `--oast-listener`, for a target whose
    /// egress is filtered to DNS. Needs the target's resolver pointed at this host
    /// and privilege to bind udp/53; a bind failure leaves the HTTP listener
    /// working and notes the reason. No effect without `--oast-listener`.
    #[arg(
        long,
        help_heading = "OAST",
        display_order = 34,
        help = "Add a DNS leg to --oast-listener (needs udp/53)"
    )]
    pub oast_listener_dns: bool,

    /// Default Location URL for redirects staged with cxg.oast.redirect(label).
    #[arg(
        long,
        requires = "oast_listener",
        value_name = "URL",
        help_heading = "OAST"
    )]
    pub oast_redirect_location: Option<String>,

    /// Default HTTP redirect status (302 when omitted).
    #[arg(long, requires = "oast_listener", value_parser = ["302", "307"], help_heading = "OAST")]
    pub oast_redirect_status: Option<String>,

    /// First A query per name returns the listener IPv4; later queries return
    /// this IPv4, all with TTL 0. The target resolver must reach this DNS server.
    #[arg(long, requires_all = ["oast_listener", "oast_listener_dns"], value_name = "IPV4", help_heading = "OAST")]
    pub oast_dns_rebind_ip: Option<String>,

    /// Target type to pentest.
    ///
    /// `web` (default): the existing authenticated-browser pipeline against an HTTP
    /// application. `electron`: launch N isolated instances of an Electron desktop
    /// app, drive their renderers over CDP, and additionally probe IPC channels,
    /// renderer configuration, and local data at rest.
    ///
    /// `tauri`: map a Tauri app's IPC command and capability surface from source —
    /// the `#[tauri::command]` handlers, their `generate_handler!` registration, and
    /// the `capabilities/*.json` grants — and correlate it against the guardlink
    /// threat model. This is a source-surface MAP, not a live probe: a Tauri app
    /// exposes no CDP endpoint on macOS or Linux, so cxg cannot drive its webview the
    /// way it drives an Electron renderer. `--target` is not required for it, and the
    /// default report carries an `enumerated_not_live_probed` caveat. No command is
    /// confirmed or refuted unless `--tauri-prove` opts into the in-process harness.
    /// No --auth or app launch command is needed. Keep --template-lang js; py is rejected.
    ///
    /// EXAMPLES:
    ///
    ///     cxg pentest run --target-type electron --app-cmd "npm run electron:dev" \
    ///       --codebase ./app-repo --target https://api.example.com --auth desk-1,desk-2
    ///
    ///     cxg pentest run --target-type tauri --codebase ./app-repo
    // @comment -- "selects which substrate the orchestrator uses; an unknown value is rejected by clap so a typo can never silently downgrade a desktop scan to a web scan, nor a web scan to a source-only tauri map"
    // requires_if (not required_if_eq on app_cmd) is deliberate: clap's required_if_eq/
    // required_unless validation path skips the conflicts_with escape hatch, so pairing it
    // with app_cmd's conflicts_with would wrongly demand --app-cmd even when --app-binary
    // alone was supplied. requires_if instead feeds the required-arg resolution path that
    // does consult conflicts_with. See desktop_flag_tests::electron_with_app_binary_alone_parses.
    // tauri is accepted here but needs no launch mechanism (it never starts the app) and no
    // --target (it never navigates); both facts are enforced in the Python preflight, which
    // is the single place target-type-conditional requirements live.
    #[arg(
        long,
        default_value = "web",
        value_parser = ["web", "electron", "tauri"],
        requires_if("electron", "app_cmd"),
        help_heading = "Target",
        display_order = 3,
        help = "Target type: web, electron, or tauri (source map; optional --tauri-prove)"
    )]
    pub target_type: String,

    /// Command that launches the desktop app, e.g. "npm run electron:dev".
    ///
    /// Required with `--target-type electron` unless `--app-binary` is given.
    /// cxg appends `--remote-debugging-port` and a per-identity `--user-data-dir`.
    // @comment -- "operator-supplied launch command forwarded to the orchestrator, which splits and executes it as a child process per identity"
    // @g.source (#operator_app_cmd) -- "command string supplied by the operator on the command line"
    #[arg(
        long,
        conflicts_with = "app_binary",
        help_heading = "Target",
        display_order = 4,
        help = "Command that launches the desktop app (electron)"
    )]
    pub app_cmd: Option<String>,

    /// Path to a built desktop app, e.g. /Applications/Foo.app.
    ///
    /// Alternative to `--app-cmd`; the two are mutually exclusive.
    // @comment -- "operator-supplied path to a packaged application, executed directly instead of via a launch command"
    #[arg(
        long,
        conflicts_with = "app_cmd",
        help_heading = "Target",
        display_order = 5,
        help = "Path to a built desktop app (electron)"
    )]
    pub app_binary: Option<String>,

    /// Additionally scan a real installation directory for data at rest.
    ///
    /// By default host probes read only the isolated user-data directories cxg
    /// created itself. Pass this to opt in to scanning an existing install.
    // @comment -- "opt-in expansion of host-probe scan scope beyond cxg-created directories, since reading an operator's real install is host-level access"
    #[arg(
        long,
        help_heading = "Target",
        display_order = 6,
        help = "Also scan a real install dir for data at rest (electron)"
    )]
    pub host_scan_path: Option<String>,

    /// For `--target-type tauri`: after mapping the IPC surface, build an in-process
    /// proof harness against the app's own crate (Tauri's `test` feature) and drive
    /// ranked commands through `get_ipc_response` with hostile arguments, feeding
    /// confirmed / refuted / unevaluated into the findings. Needs a Rust toolchain; a
    /// command the harness cannot drive is skipped with a reason, never refuted.
    ///
    /// Copies the app to the session's tauri-harness/ and runs cargo test using
    /// a headless MockRuntime. Probes cover sentinel-based path traversal and
    /// renderer-controlled authorization arguments. A confirmation proves observed
    /// harness behavior; a refutation covers only attempted arguments. It does not
    /// test live navigation, DOM behavior or clickjacking, nor reproduce the app's
    /// full setup or capability configuration. Review caveats, ambiguous and
    /// tauri_skipped_commands; build failures do not establish safety.
    // @comment -- "opt-in because it builds the target crate (cargo test) and only applies to tauri; a plain tauri run stays a source-surface map. Forwarded to the Python orchestrator, which owns the harness."
    #[arg(
        long,
        help_heading = "Target",
        display_order = 7,
        help = "tauri: prove commands in-process via Tauri's test harness"
    )]
    pub tauri_prove: bool,

    /// Combined seconds budgeted for the `--tauri-prove` harness build and run.
    ///
    /// Used only for Tauri proof; default 1200. Example: --tauri-prove-timeout 1200
    #[arg(
        long,
        default_value = "1200",
        help_heading = "Target",
        display_order = 8,
        help = "Timeout (s) for the --tauri-prove harness build+run"
    )]
    pub tauri_prove_timeout: u64,

    /// Run cross-site probes (CSRF, CORS, clickjacking) from a loopback origin
    /// cxg controls, in the same browsing context as the identity under test.
    ///
    /// Without this, those classes are reported as NOT PROBED rather than tested
    /// from the target's own origin. A same-origin probe of them is unsound: an
    /// app defended only by an Origin check accepts cxg's own-origin request, so
    /// the probe confirms an attack a real cross-site attacker could never land.
    // @comment -- "Opt-in because it binds a listening socket on the operator's machine and performs REAL cross-site state changes against their application. Both are consequences an operator should choose rather than discover, which is why this is a flag and not a default even though it strictly improves verdict quality."
    #[arg(
        long,
        help_heading = "Probe execution",
        display_order = 7,
        help = "Probe CSRF/CORS/clickjacking from a foreign origin cxg controls"
    )]
    pub attacker_origin: bool,

    /// Generate templates for N hypotheses per AI call instead of one each.
    ///
    /// Measured: 130-220s per AI template, so 105 routes cost ~4.5 hours.
    /// Default 1 is the existing per-hypothesis path, byte-for-byte.
    // @comment -- "Clamped to 5 inside the generator rather than here, so the blast radius of one timed-out call stays bounded: a failed batch costs a re-run of that chunk individually, and at 5 the worst case is five regenerations rather than fifty. Cached and deterministically-emittable hypotheses are excluded before batching, so a fully-cached run makes zero calls whatever this is set to."
    #[arg(
        long,
        help_heading = "Hypothesis filtering",
        display_order = 10,
        default_value_t = 1,
        help = "Hypotheses per AI generation call (1 = today's behaviour)"
    )]
    pub batch_size: usize,

    /// Emit probes with no AI call at all for unambiguous shapes.
    ///
    /// Covers cross-identity IDOR reads and missing collection authorization —
    /// 47 of Juice Shop's 105 discovered routes. These probes read no source,
    /// so they cannot cite a code-level cause; breadth, not depth.
    // @comment -- "Opt-in because a deterministic probe is genuinely WEAKER than an AI-authored one: it cannot recognise an intentional design or name the guard that failed. An operator should choose that trade deliberately rather than inherit it from a default."
    #[arg(
        long,
        help_heading = "Hypothesis filtering",
        display_order = 11,
        help = "Emit known-shape probes without an AI call (fast, source-blind)"
    )]
    pub deterministic_templates: bool,

    /// Let a probe hand a fact it discovered to a later probe.
    ///
    /// Templates declare `@provides: <name>` / `@requires_artifact: <name>`; cxg
    /// orders providers before consumers and passes the value through a per-run
    /// store. Edges are also derived automatically from guardlink `@flows`.
    // @comment -- "Opt-in because it CHANGES TEMPLATE ORDER: a consumer waits for its provider, and one that declares an artifact nobody provides is skipped rather than run. With the flag off the order is the plain destructive_priority sort it has always been, so an existing run is unaffected."
    #[arg(
        long,
        help_heading = "Probe execution",
        display_order = 12,
        help = "Allow multi-step chains: one probe hands a fact to the next"
    )]
    pub enable_chaining: bool,

    /// Discover routes from source instead of requiring guardlink annotations.
    ///
    /// guardlink only parses GAL annotations, so an un-annotated codebase yields
    /// zero hypotheses and the scan exits with "no templates available" having
    /// tested nothing. Measured on OWASP Juice Shop: guardlink 0, discovery 105.
    // @comment -- "Opt-in because it changes WHAT gets tested: a discovered route is an attack SURFACE inferred from source, not a threat anybody declared, so its hypotheses are speculative in a way an annotated one is not. An annotated hypothesis always wins where both cover the same route. Default off keeps every existing run byte-identical."
    #[arg(
        long,
        help_heading = "Hypothesis filtering",
        display_order = 9,
        help = "Also derive hypotheses from routes found in source (no annotations needed)"
    )]
    pub discover_routes: bool,

    /// Do not read a code graph for this codebase.
    ///
    /// By default, when `codegraph-mcp` or `bravos graph` is installed and a graph
    /// has been built for the codebase, its route table leads `--discover-routes`
    /// and its reachable-sink ranking orders which hypotheses get templates. With
    /// no graph available the run is unchanged either way.
    // @comment -- "Forwarded only, never interpreted here: the orchestrator owns the default and the detection, and this layer restating either would give the two CLIs two definitions of when the graph is read."
    #[arg(
        long,
        help_heading = "Hypothesis filtering",
        display_order = 12,
        help = "Do not use a code graph for route discovery or ranking"
    )]
    pub no_code_graph: bool,

    /// Test only the hypotheses whose route or enclosing function is listed in FILE.
    ///
    /// Entries are `METHOD /path` (`ANY` or `*` for every method; path templates
    /// and concrete paths match each other; a trailing `*` is a prefix), `/path`,
    /// `file::Function` or `file:Function`, one per line, or JSON — including a code
    /// graph's route or attack-surface answer as written. Everything else is
    /// excluded before ranking and reported with its reason. An EMPTY list means
    /// nothing is in scope: the run exits 0 without contacting the target.
    // @comment -- "Forwarded only, never parsed here: the orchestrator owns the entry grammar, the empty-means-skip rule and the refusals, so this layer restating any of them would give the two CLIs two definitions of what the list admits."
    #[arg(
        long,
        value_name = "FILE",
        help_heading = "Hypothesis filtering",
        display_order = 13,
        help = "Test only the routes/functions listed in FILE (empty list = skip the run)"
    )]
    pub only_routes: Option<PathBuf>,

    /// One allowlist entry in the `--only-routes` line form. Repeatable.
    #[arg(
        long = "only-route",
        value_name = "ENTRY",
        help_heading = "Hypothesis filtering",
        display_order = 14,
        help = "One allowlist entry, e.g. 'GET /api/users/{id}' (repeatable)"
    )]
    pub only_route: Vec<String>,

    /// Append the operator skills in FILE to AI generation and mutation prompts.
    ///
    /// Markdown written by a caller (bravos writes the skills its operator tagged
    /// for template authoring). Appended last, under an untrusted heading: it is
    /// advice on how to write a probe and never overrides the template rules.
    // @comment -- "Forwarded only, never read here: the orchestrator owns the heading, the budget and the unreadable-file behaviour, so the two CLIs cannot disagree about what a skills file does."
    #[arg(
        long,
        value_name = "FILE",
        help_heading = "Hypothesis filtering",
        display_order = 15,
        help = "Append operator skills (untrusted guidance) to generation/mutation prompts"
    )]
    pub skills_file: Option<PathBuf>,

    /// Permit `cxg.socket`: raw TCP/TLS bytes with no HTTP client in between.
    ///
    /// Required for request smuggling, desync and header-order attacks, which no
    /// HTTP client can express — both `window.fetch` and Playwright's
    /// APIRequestContext normalise the framing that IS the payload for those
    /// classes. Can desync connections or wedge a server.
    // @comment -- "Permission, distinct from the substrate capability that says a socket is POSSIBLE. Byte-level traffic can wedge a target, and an operator must opt into that consequence rather than inherit it from their choice of --target-type. Without it, request_smuggling and http_desync hypotheses route to review_only_threats instead of consuming a template slot they could never conclude."
    #[arg(
        long,
        help_heading = "Probe execution",
        display_order = 8,
        help = "Permit raw TCP/TLS byte-level probes (smuggling, desync)"
    )]
    pub allow_raw_socket: bool,

    /// Save redacted per-template HARs and curl reproductions for web JS probes.
    #[arg(long, help_heading = "Probe execution")]
    pub capture_http: bool,

    /// Permit native gRPC over HTTP/2, for services with no gRPC-Web proxy in
    /// front of them. Requires grpcio. The call carries the identity's
    /// --header values as gRPC metadata; cxg cannot borrow the browser
    /// session on this transport.
    // @comment -- "Permission, distinct from the substrate capability that says a native gRPC call is POSSIBLE from this process. cxg.grpc dials a host:port from outside the browser where no same-origin policy contains it, so an operator opts into that reach rather than inheriting it from --target-type. Without it, hypotheses whose route is a gRPC method go to review_only_threats instead of consuming a template slot they could never conclude."
    // @comment -- "NOT the switch for gRPC-Web, which is an ordinary HTTP POST cxg.raw already sends on every run with no flag. This covers a BARE gRPC service, which nothing in cxg could reach at all before."
    #[arg(
        long,
        help_heading = "Probe execution",
        display_order = 9,
        help = "Permit native gRPC (HTTP/2) probes against bare gRPC services"
    )]
    pub allow_grpc: bool,

    /// A protoc-emitted FileDescriptorSet describing the target's gRPC
    /// services, so probes can send real typed messages and decode responses.
    /// Produce one with `protoc --descriptor_set_out=out.pb --include_imports`.
    // @comment -- "The operator's own protoc output, and the only descriptor source cxg fully trusts: a service is free to describe itself inaccurately over reflection, so the result records which source produced each decoded field. Optional — without it cxg falls back to empty or raw-byte messages, which still answer an authorization question."
    #[arg(
        long,
        value_name = "FILE",
        help_heading = "Probe execution",
        display_order = 10,
        help = "protoc FileDescriptorSet for typed gRPC messages"
    )]
    pub grpc_descriptor_set: Option<String>,

    /// Do not ask gRPC services to describe themselves over server reflection.
    /// Without reflection, typed messages need --grpc-descriptor-set.
    // @comment -- "An OFF-switch rather than an on-switch, matching the orchestrator: --allow-grpc is already the deliberate opt-in to gRPC traffic, and reflection is one cached read-only request per service of exactly the kind grpcurl makes by default. This exists for an engagement where every extra request must be accounted for."
    #[arg(
        long,
        help_heading = "Probe execution",
        display_order = 11,
        help = "Do not use gRPC server reflection to learn message types"
    )]
    pub no_grpc_reflection: bool,

    /// Absolute ceiling on one template's dispatch before it is abandoned and
    /// treated as a dead target. Default 900s. This is a BACKSTOP only —
    /// `--stall-timeout` is what actually catches a frozen app. 0 disables it,
    /// which lets a wedged app hang the scan indefinitely.
    // @comment -- "forwards the per-template ceiling to the orchestrator; without this the flag existed in Python only and was unreachable from the cxg binary, so an operator could not raise or disable the backstop at all"
    #[arg(
        long,
        help_heading = "Execution",
        display_order = 44,
        help = "Per-template dispatch ceiling, seconds (backstop; default 900)"
    )]
    pub template_timeout: Option<f64>,

    /// How long the run may go with NO completed dispatch before the surface is
    /// corroborated against the other instances and, if it alone is silent,
    /// treated as stalled. This is IDLE time, not template runtime: a probe that
    /// keeps getting answers is never killed however long it runs. Default 90s,
    /// 0 disables. Applies to `--target-type electron` only.
    // @comment -- "forwards the stall threshold to the orchestrator; the measured freeze (a native modal blocking Electron's main process) produces no exception at all, so this is the only bound that ends such a run, and it was unreachable from the binary until now"
    #[arg(
        long,
        help_heading = "Execution",
        display_order = 45,
        help = "Idle-time stall timeout, seconds (electron only; default 90)"
    )]
    pub stall_timeout: Option<f64>,

    /// Do NOT relaunch a desktop target that dies mid-scan.
    ///
    /// Default is to restart it (max 2 per instance, 3 per run), report the crash
    /// as a `denial_of_service` finding, re-probe the suspected IPC channel once
    /// and then quarantine it. With this flag a dead target ends the scan with a
    /// truncation caveat and exit 3 — the pre-recovery behaviour.
    // @comment -- "operator opt-out of crash recovery, because recovery lets cxg's own probes restart the application under test repeatedly and that side effect is an availability decision the operator owns, not cxg"
    #[arg(
        long,
        help_heading = "Execution",
        display_order = 46,
        help = "Do not relaunch a desktop target that dies mid-scan"
    )]
    pub no_restart: bool,

    /// Non-interactive CI mode: refuse a world-accessible `--auth-dir`.
    ///
    /// When credentials are in use, a world-accessible `--auth-dir` is refused
    /// (exit 4) rather than trusted. A dead or expired auth session exits 5 with or
    /// without this flag, and `--skip-health-check` does not bypass that: startup
    /// API verification still runs and a profile it cannot prove alive still fails
    /// the run.
    ///
    /// Also enabled by the environment variable CXG_CI=1, for pipelines that
    /// cannot add the flag to the invocation.
    // @comment -- "forwards the CI-mode selector as a flag when set; the hard-fail-on-dead-session and world-readable-auth-dir refusal both live in the Python orchestrator (cxg_pentest.py, auth.py), which also honours CXG_CI=1 on its own, so leaving the flag off here still lets the env var reach the orchestrator through the inherited environment"
    #[arg(
        long,
        help_heading = "Authentication",
        display_order = 19,
        help = "CI mode: refuse a world-accessible --auth-dir. Also CXG_CI=1"
    )]
    pub ci: bool,

    /// JSON report output path. Default: `report.json` under --session-dir.
    /// The report contains: target, codebase, auth_profiles, goal, scope_stats,
    /// confirmed_findings, ambiguous, mitigation_verifications, dead_profiles,
    /// rejected_templates, retried_then_resolved.
    #[arg(
        long,
        short,
        help_heading = "Output",
        display_order = 51,
        help = "JSON report output path (default report.json in session dir)"
    )]
    pub output: Option<PathBuf>,
}

/// Inputs shared by automatic scan probes and explicit pentest runs.
#[derive(clap::Args, Debug, Clone)]
pub struct ProbeInputs {
    /// Guarantee zero model calls. Plain scan already replays selected scanner
    /// and JS probe templates without authoring. Explicit pentest runs require
    /// --template-dir and disable ranking, generation and mutation.
    #[arg(long, help_heading = "Generation")]
    pub no_author: bool,

    /// Source codebase root. Defaults to the current directory for scan;
    /// pentest run requires an explicit value. Reads whitebox/findings.sarif
    /// when present and supplies source context to the engine.
    #[arg(
        long,
        default_value = ".",
        help_heading = "Target",
        display_order = 1,
        help = "Source codebase root (contains whitebox/findings.sarif)"
    )]
    pub codebase: PathBuf,

    /// Comma-separated auth profile names previously captured via `cxg pentest auth`.
    /// Probes that need multiple identities (IDOR cross-user, session-replay-against-
    /// victim) require ≥2 profiles. The lowest-privilege identity is auto-selected as
    /// the actor for privesc-class probes.
    ///
    /// Empty means a first-class anonymous (no-login) web/Electron run, not interactive capture.
    /// Tauri source maps and in-process proofs need no --auth profile.
    #[arg(
        long,
        default_value = "",
        help_heading = "Authentication",
        display_order = 11,
        help = "Comma-separated captured auth profiles; empty = first-class anonymous (no-login) run on a clean unauthenticated surface with real anonymous probes and auth-only checks reported not-run. Empty does not imply interactive capture; use --interactive-auth"
    )]
    pub auth: String,

    /// Path to scope.yaml. Default: safe permissive defaults (any URL, GET/POST/HEAD/
    /// OPTIONS, 30 reqs/endpoint, 1500 reqs total, kill on 8-streak 5xx).
    /// Generate one with `cxg pentest scope-init`.
    ///
    /// If this flag is given and the file cannot be read — path does not exist,
    /// unreadable, invalid YAML, not a mapping, empty, or PyYAML not installed —
    /// the run is REFUSED with exit 4. It does not fall back to the defaults:
    /// a bound cxg cannot read is not the same as no bound. Omitting the flag
    /// entirely is the supported way to run on the defaults.
    ///
    /// An empty value never reaches that check and is not ignored either:
    /// `--scope-file "$SCOPE"` with `SCOPE` unset is rejected by the CLI parser
    /// as a usage error (exit 2, `a value is required for '--scope-file
    /// <SCOPE_FILE>' but none was supplied`) before the scan starts.
    ///
    /// Refused with exit 4 on `--template-lang py` as well: the legacy Python probe
    /// path enforces no scope at all, so a file accepted there would be discarded.
    #[arg(
        long,
        help_heading = "Execution",
        display_order = 41,
        help = "Path to scope.yaml (URL/method allowlist, budgets)"
    )]
    pub scope_file: Option<PathBuf>,

    /// Operator-owned configuration for IMAP and needs-you questions.
    #[arg(long, value_name = "JSON", help_heading = "Probe execution")]
    pub auth_inputs: Option<PathBuf>,

    /// Read auth profiles from this directory instead of ~/.cert-x-gen/auth.
    ///
    /// A CI pipeline restores a bundle of profiles (imported via
    /// `cxg pentest auth import --auth-dir <dir>`) into its own directory and
    /// points the run at the same directory here, so pre-flight, the engine, and
    /// the health monitor all read the restored bundle rather than the operator's
    /// home store.
    // @comment -- "forwards the auth-store redirect to the orchestrator, which reassigns auth.AUTH_DIR before any profile is loaded; every profile consumer reaches the store only through auth.load_profile, so this one flag moves all of them. Forwarded only when set, so an unset flag leaves the orchestrator's ~/.cert-x-gen/auth default in force — one default, in one place the two CLIs cannot drift apart on."
    #[arg(
        long,
        help_heading = "Authentication",
        display_order = 18,
        help = "Read auth profiles from this dir (CI profile bundle)"
    )]
    pub auth_dir: Option<PathBuf>,

    /// Session directory where this scan's artifacts (audit.jsonl, report.json,
    /// any captured screenshots) are written.
    /// Explicit pentest default: ~/.cert-x-gen/sessions/pentest-<YYYYMMDD-HHMMSS>/
    /// Plain scan groups probe inputs and per-target engine sessions under a scan-specific directory.
    #[arg(
        long,
        help_heading = "Output",
        display_order = 52,
        help = "Session artifacts directory (audit.jsonl, report.json)"
    )]
    pub session_dir: Option<PathBuf>,
}

/// Non-interactive auth subcommands for CI — mirrors `pentest/auth.py`'s
/// `import`/`verify` subparsers exactly.
// @comment -- "the CI-replay half of the auth surface: a human captures a session once (SSO/MFA and all) and exports its Playwright storage_state; import writes a profile from that state with no browser, and verify gates on whether the saved session is still alive. Both were reachable only via `python3 cxg_pentest.py auth ...` until this surface was wired into clap; the defaults here are copied from auth.py's argparse, which is the specification."
// Like PentestAction, this clap enum is parsed once per process; keep named flags inline.
#[allow(clippy::large_enum_variant)]
#[derive(Subcommand, Debug, Clone)]
pub enum AuthSubcommand {
    /// Import a saved Playwright storage_state as a profile (no browser)
    ///
    /// The CI-replay primitive: a human captures a session once locally (SSO, MFA and
    /// all), exports the Playwright storage_state, and every pipeline run injects it
    /// here without a display or a human. The written profile is byte-for-byte what an
    /// interactive capture produces, so a later `cxg pentest run --auth <profile>`
    /// cannot tell an imported profile from a captured one.
    ///
    /// Examples:
    ///     # From a file on disk
    ///     cxg pentest auth import --profile pentest --target https://staging.app \
    ///       --storage-state ./pentest.storage.json
    ///
    ///     # From stdin (a CI secret piped straight in, never written to disk in the clear)
    ///     cat "$SESSION_SECRET" | cxg pentest auth import --profile pentest \
    ///       --target https://staging.app --storage-state -
    ///
    ///     # From the base64 env var, into a restored bundle dir, CI-strict
    ///     cxg pentest auth import --profile pentest --target https://staging.app \
    ///       --auth-dir ./ci-auth --ci
    Import {
        /// Profile name. A subsequent `cxg pentest run --auth <profile>` loads it
        /// exactly like a captured one.
        #[arg(long)]
        profile: String,

        /// Target URL this session authenticates against. Recorded in the profile. A run
        /// sends this identity's traffic to its own `--scope`/`--target`; the saved
        /// origin is used instead only when `--service` is also given.
        #[arg(long)]
        target: String,

        /// Path to a Playwright storage_state JSON, or `-` to read it from stdin (a CI
        /// secret pipes straight in, never touching disk in plaintext beyond the profile
        /// dir). Omit to materialise it from the base64 env var CXG_AUTH_STATE_<NAME>
        /// instead (NAME is the profile name uppercased with non-alphanumerics folded to
        /// underscore — e.g. profile `pentest-alice` reads `CXG_AUTH_STATE_PENTEST_ALICE`).
        // @g.source (#operator_storage_state) -- "storage_state source (path, '-' for stdin, or env fallback) supplied by the operator; forwarded verbatim to auth.py which resolves and redacts it — cxg never echoes its contents"
        #[arg(long, value_name = "PATH|-")]
        storage_state: Option<String>,

        /// Human-readable label (e.g. 'admin'), shown in scan output.
        #[arg(long)]
        label: Option<String>,

        /// Explicit privilege rank: an integer 0-100 or an alias high/medium/low. Same
        /// meaning as on capture.
        #[arg(long)]
        tier: Option<String>,

        /// Semantic role hint passed to the AI as extra context.
        #[arg(long)]
        persona: Option<String>,

        /// Peer-group name for horizontal IDOR / cross-tenant tests.
        #[arg(long)]
        cohort: Option<String>,

        /// Free-form `NAME=VALUE` context attached to the profile. Repeatable.
        #[arg(long = "tag", value_name = "NAME=VALUE")]
        tags: Vec<String>,

        /// Custom HTTP header `NAME:VALUE` sent on every request from this profile
        /// (e.g. a WAF-bypass token). Repeatable. Stored as a credential; values are
        /// never echoed.
        #[arg(long = "header", value_name = "NAME:VALUE")]
        headers: Vec<String>,

        /// Authenticated API liveness path on this service (default /api/me).
        #[arg(long)]
        liveness_path: Option<String>,

        /// Expected HTTP status, repeatable (default any 2xx; 401/403 always fail).
        #[arg(long = "liveness-status")]
        liveness_status: Vec<u16>,

        /// Service name included in readiness receipts. Opts this profile into
        /// multi-service: its saved `--target` origin, not the run's target, receives
        /// its traffic and liveness check.
        #[arg(long)]
        service: Option<String>,

        /// Write into this auth directory instead of ~/.cert-x-gen/auth. A pipeline
        /// restores a bundle of profiles into one dir and points the run at it with the
        /// same flag.
        #[arg(long)]
        auth_dir: Option<PathBuf>,

        /// Non-interactive CI mode: refuse a world-accessible `--auth-dir` rather than
        /// write a credential a fellow user could read. Also enabled by CXG_CI=1.
        // @comment -- "forwards CI-strictness to auth.py, which refuses a world-readable --auth-dir before persisting a session; the refusal lives in Python (assert_auth_dir_not_world_readable), honoured here and via CXG_CI=1 in the inherited environment"
        #[arg(long)]
        ci: bool,
    },

    /// Check a saved web session is still alive (exit 0 alive / non-zero dead)
    ///
    /// An API liveness gate for a saved session, shared with scan-time pre-flight. A pipeline runs this before spending a whole run,
    /// and re-captures (or re-imports) when it fails.
    ///
    /// Example:
    ///     cxg pentest auth verify --profile pentest || echo "session expired, re-import"
    Verify {
        /// Profile name to verify.
        #[arg(long)]
        profile: String,

        /// Override the profile's saved target (a profile imported with `--service`
        /// keeps its own).
        #[arg(long)]
        target: Option<String>,

        /// Authenticated API endpoint (default /api/me); per-profile liveness_check wins.
        /// When neither is configured and /api/me is absent, the landing test decides.
        #[arg(long, default_value = "/api/me")]
        me_path: String,

        /// Read the profile from this auth directory instead of ~/.cert-x-gen/auth.
        #[arg(long)]
        auth_dir: Option<PathBuf>,
    },
}

#[derive(Parser, Debug)]
#[command(
    about = "Run a security scan against targets using vulnerability detection templates",
    long_about = "Execute comprehensive security scans against one or more targets using the multi-language \
                  template engine. CERT-X-GEN supports scanning single targets, multiple targets, CIDR ranges, \
                  and domains, or local CLI binaries via cli://<binary>, with advanced filtering and output customization.\n\n\
                  The scan command orchestrates template execution across targets, manages concurrency, \
                  filtered by language, severity, tags, and custom criteria to focus on specific \
                  vulnerability classes or compliance requirements.",
    after_help = "Run 'cxg scan --help' for the full flag reference, worked examples, and common scenarios.\n\
                  Docs: https://docs.bugb.io/cxg/",
    after_long_help = "LOCAL CLI TESTING:
  Use cli://<binary> with an absolute executable path (cli:///absolute/path/to/my-tool).
  Fetch the CLI Security Baseline pack from the detection-template repository:
  https://github.com/Bugb-Technologies/cert-x-gen-templates/tree/main/templates/cli-baseline
  With the default repository configuration:
    cxg template update
    cxg scan --scope cli:///absolute/path/to/my-tool --template-dir ~/.cert-x-gen/templates/official/templates/cli-baseline --require-instrumentation
  This repository's templates/ contains skeletons, not the detection pack.
  A skipped check provides no refutation; no findings alone does not establish safety.

  Optional probe inputs (the selected template must consume this contract):
    cxg scan --scope cli:///absolute/path/to/my-tool --templates /path/to/probe.sh --arg --format --arg json --stdin-file ./case.bin --input ./corpus --target-env ASAN_OPTIONS=abort_on_error=1 --require-instrumentation
  cxg passes argv, stdin file, seed corpus and target environment to templates; it does
  not automatically adapt every template to the target's syntax or mutate the corpus.
  Templates declare @oracles and report confirmed/refuted/skipped/errored/timed-out.
  A nonzero exit alone does not prove an unhandled exception.
  --require-instrumentation checks binary markers and oracle requirements; unsupported
  executions skip (no-instrumentation-detected, oracle-unavailable(...), target-not-found).
  Build-independent oracles (exit, signal, timeout, exception, property) can run with none.
  Interpreted scripts detect none; target-kind declarations apply even without preflight.
  Scanning does not build the target: see cxg build --help for instrumented build options,
  then use --instrumented-manifest <PATH> for provenance of the binary it names.
  Tauri IPC testing uses cxg pentest run --target-type tauri --codebase <repo>.

DETAILED USAGE GUIDE:

TARGET SPECIFICATION:
  Define scope once and let the engine figure out the rest.

  --scope <SCOPE>
    Smart selector that accepts:
      • Single host or URL (example.com, https://api.example.com:8443)
      • Comma-separated lists (example.com,test.com,192.168.1.1)
      • Files via @targets.txt or file://path/to/targets.txt (one entry per line, # for comments)
      • CIDR ranges (192.168.1.0/24, 10.0.0.0/8)
      • Domains and subdomains (example.com, api.example.com)
      • Mixed entries in a single invocation

    Legacy flags (--target, --targets, --target-file, --domain, --domains, --domain-file, --cidr) remain as aliases.
    The scanner automatically deduplicates and expands entries from files.

PORT SELECTION:
  Customize which ports to scan.

  --ports <PORT>
    Smart selector that adds ports to template defaults. Supports:
      • Single ports (8080)
      • Ranges (8000-8100)
      • Comma lists (80,443,8443)
      • Files via @ports.txt or file://ports.txt (one per line, # for comments)
      • Mixed entries in a single invocation
    Adds to template default ports; combine with --override-ports to replace defaults entirely.
    Example:
      cxg scan --scope example.com --ports 80,443,8000-8010,@extra-ports.txt
  
  --top-ports <N>
    Add the top N most common ports (based on curated frequency data).
    Example:
      cxg scan --scope example.com --top-ports 100
  
  --override-ports <PORTS>
    Replace template default ports entirely with your custom list (same formats as --ports).
    Example:
      cxg scan --scope example.com --override-ports 80,443

TEMPLATE FILTERING:
  Control which vulnerability templates are executed. Filter by ID, language, severity, or tags.
  
  --templates <TEMPLATE>
    Smart selector that understands template IDs, filenames, or file paths. Supports:
      • Direct template IDs (redis-unauthenticated)
      • File names or paths (templates/network/redis.yaml)
      • Files containing template lists via @templates.txt or file://templates.txt (one per line, # for comments)
      • Mixed entries in a single invocation
    Legacy flags (--template, --template-file) remain as aliases.
    Examples:
      cxg scan --scope example.com --templates redis-unauthenticated
      cxg scan --scope example.com --templates redis-unauthenticated,templates/network/redis.yaml
      cxg scan --scope example.com --templates @compliance-templates.txt
  
  --template-dir <DIR>
    Use templates from a custom directory instead of the default location.
    Example:
      cxg scan --scope example.com --template-dir ./custom-templates
  
  --template-language <LANGUAGES>
    Filter templates by programming language. Useful for testing specific engine types.
    Available: yaml, python, rust, shell, javascript, c, cpp, java, go, ruby, perl, php
    Example:
      cxg scan --scope example.com --template-language python --template-language rust
  
  --severity <SEVERITIES>
    Filter by severity level. Run only critical/high severity checks for quick assessments.
    Available: critical, high, medium, low, info
    Example:
      cxg scan --scope example.com --severity critical,high
  
  --tags <TAGS>
    Filter templates by tags (comma-separated). Tags categorize vulnerabilities.
    Common tags: database, injection, xss, authentication, authorization, rce, lfi, ssrf
    Example:
      cxg scan --scope example.com --tags database,unauthenticated
  
  --exclude-templates <PATTERN>
    Exclude templates matching a pattern. Supports wildcards.
    Example:
      cxg scan --scope example.com --exclude-templates test-*,experimental-*

OUTPUT AND REPORTING:
  Customize how scan results are saved and displayed.
  
  --output <BASENAME>
    Set the output file basename. Any trailing extension is REPLACED by the chosen
    format's extension — e.g. `--output report.txt --output-format json` writes report.json.
    Default: scan-results
    Example:
      cxg scan --scope example.com --output my-scan --output-format json
      # Writes: my-scan.json

  --output-format <FORMATS>
    Specify output formats (comma-separated). Multiple formats can be generated simultaneously.
    Available: json, csv, sarif, html, markdown
    - json: Machine-readable, ideal for automation and APIs
    - csv: Spreadsheet-friendly, good for reporting and analysis
    - sarif: Static Analysis Results Interchange Format (for CI/CD integration)
    - html: Human-readable report with visualizations
    - markdown: Human-readable Markdown report
    Example:
      cxg scan --scope example.com --output-format json,html,sarif

  --quiet
    Suppress the ASCII startup banner. Scan output itself is unchanged.
    Example:
      cxg scan --scope example.com --quiet

PERFORMANCE AND CONCURRENCY:
  Tune scan performance based on your resources and target infrastructure.

  --parallel-targets <N>
    How many targets to scan simultaneously. Higher = faster but may trigger rate limits.
    Default: 50
    Recommendation: Lower for production systems (10-25), higher for internal scans (50-100)
    Example:
      cxg scan --scope example.com,test.com --parallel-targets 10
  
  --parallel-templates <N>
    How many templates to run concurrently per target. Balances speed vs. target load.
    Default: 10
    Recommendation: Lower for fragile targets (5), higher for robust systems (20)
    Example:
      cxg scan --scope example.com --parallel-templates 5

TIMEOUTS AND RETRIES:
  Configure how the scanner handles slow responses and failures.
  
  --timeout <DURATION>
    Maximum time to wait for a response. Supports: s (seconds), m (minutes), h (hours)
    Default: 30s
    Recommendation: Increase for slow networks or complex checks
    Example:
      cxg scan --scope example.com --timeout 60s
      cxg scan --scope example.com --timeout 2m
  
  --retry <N>
    Number of retry attempts for failed requests. Helps with transient network issues.
    Default: 1
    Recommendation: Increase for unreliable networks, decrease for fast scans
    Example:
      cxg scan --scope example.com --retry 5
  
  --rate-limit <N>
    Maximum requests per second. Prevents overwhelming targets and triggering WAF/IPS.
    Default: None (unlimited)
    Recommendation: Use 10-50 for production, 100+ for internal testing
    Example:
      cxg scan --scope example.com --rate-limit 10

SCANNING MODES:
  Different modes for various scanning scenarios and requirements.
  
  --aggressive
    Enable aggressive scanning mode. Uses more intrusive checks and higher concurrency.
    WARNING: May trigger security alerts or cause service disruption.
    Use only with explicit permission on systems you control.
    Example:
      cxg scan --scope test-env.internal --aggressive
  
  --stealth
    Enable stealth mode. Reduces scan footprint, randomizes timing, and mimics normal traffic.
    Slower but less likely to trigger detection systems (IDS/IPS/WAF).
    Automatically reduces concurrency and adds random delays.
    Example:
      cxg scan --scope example.com --stealth
  
  --safe
    Safe mode - excludes potentially harmful checks (DoS, resource exhaustion, etc.).
    Recommended for production systems where availability is critical.
    Example:
      cxg scan --scope production.example.com --safe
  
  --passive
    Passive mode - no active probing. Only analyzes responses from normal requests.
    Safest option but limited detection capabilities. Good for initial reconnaissance.
    Example:
      cxg scan --scope example.com --passive

NETWORK CONFIGURATION:
  Configure network-level settings for scanning through proxies, with custom headers, etc.
  
  --proxy <URL>
    Route all traffic through a proxy. Supports HTTP, HTTPS, and SOCKS5 proxies.
    Useful for scanning from different geographic locations or through corporate proxies.
    Examples:
      cxg scan --scope example.com --proxy http://proxy.corp.com:8080
      cxg scan --scope example.com --proxy socks5://127.0.0.1:1080
  
  --user-agent <STRING>
    Custom User-Agent header. Useful for mimicking specific browsers or tools.
    Default: cert-x-gen/<version>
    Example:
      cxg scan --scope example.com --user-agent 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
  
  --header <KEY:VALUE>
    Add custom HTTP headers. Can be specified multiple times for multiple headers.
    Useful for authentication, API keys, or custom application headers.
    Examples:
      cxg scan --scope api.example.com --header 'Authorization: Bearer token123'
      cxg scan --scope example.com --header 'X-API-Key: abc' --header 'X-Custom: value'
  
  --cookie <KEY=VALUE>
    Add cookies to requests. Can be specified multiple times. Useful for authenticated scans.
    Example:
      cxg scan --scope example.com --cookie 'session=abc123' --cookie 'user=admin'
  
  --follow-redirects
    Follow HTTP redirects automatically. Useful for discovering redirect chains.
    Default: Disabled (redirects are not followed unless this flag is passed)
    Example:
      cxg scan --scope example.com --follow-redirects --max-redirects 10
  
  --max-redirects <N>
    Maximum number of redirects to follow. Prevents infinite redirect loops.
    Default: 5
    Example:
      cxg scan --scope example.com --max-redirects 3

CONFIGURATION FILES:
  Use configuration files for complex setups.

  --config <FILE>
    Load settings from a configuration file (YAML, TOML, or JSON).
    CLI arguments override config file settings.
    Example:
      cxg scan --config production-scan.yaml --scope example.com

COMMON SCANNING SCENARIOS:

1. Quick Vulnerability Assessment (Fast, High-Severity Only):
   cxg scan --scope example.com --severity critical,high

2. Comprehensive Security Audit (All Templates, All Severities):
   cxg scan --scope example.com --output-format json,html,sarif

3. Stealth Penetration Test (Low Detection Risk):
   cxg scan --scope example.com --stealth --rate-limit 5 --timeout 60s

4. Production System Scan (Safe, Non-Disruptive):
   cxg scan --scope production.example.com --safe --parallel-templates 3 --rate-limit 10

5. Database Security Scan (Specific Vulnerability Class):
   cxg scan --scope db.example.com --tags database,injection --severity high,critical

6. Authenticated Web Application Scan:
   cxg scan --scope app.example.com --cookie 'session=xyz' --header 'Authorization: Bearer token'

7. Large-Scale Network Scan (Multiple Targets):
   cxg scan --scope @targets.txt --parallel-targets 100 --output-format csv,json

8. API Security Testing:
   cxg scan --scope api.example.com --template-language python --tags api,authentication

9. Compliance Scan (OWASP Top 10):
   cxg scan --scope example.com --templates @owasp-top10.txt --output-format sarif

10. Internal Network Reconnaissance:
    cxg scan --scope 10.0.0.0/24 --passive --top-ports 100 --quiet

Supplied JS probe contracts run automatically through the pentest engine with zero model calls.
  Scanner templates keep their language runners; mixed packs produce one JSON report with
  template-reported and engine-adjudicated verdict sources. Missing probe inputs are refused.
  --scope supplies the target; --codebase defaults to the current directory. Use --auth,
  --auth-dir, --auth-inputs, --scope-file and --session-dir for probe execution inputs.
  All non-authoring pentest inputs are accepted for the probe engine, including CI,
  containment, protocol, chaining, capture and timeout controls. They do not change
  scanner contracts; scanner-only runs do not use these probe-engine controls.
  Profile/scope inputs require a selected probe. Plain scan always disables authoring.
  JS probes only; any-language probes are not yet supported. --pentest exposes authoring too.

For more information, visit: https://cert-x-gen.io/docs"
)]
pub struct ScanArgs {
    /// Parsed from the same engine definitions; no parallel list of option types/defaults.
    #[arg(skip)]
    pub probe_run: Option<Box<PentestRunArgs>>,

    #[command(flatten)]
    pub probe_inputs: ProbeInputs,

    /// Enable all `pentest run` options, including authoring and desktop targets.
    /// Plain scan already runs supplied JS probe contracts with zero model calls. JS probes only;
    /// any-language probes are not supported. Use --no-author --template-dir DIR
    /// for zero model calls. Engine-confirmed verdicts remain pentest verdicts;
    /// ordinary scan findings remain template-reported.
    #[arg(long, help_heading = "Engine")]
    pub pentest: bool,

    // ===== Target Selection =====
    #[arg(
        long = "scope",
        short = 's',
        short_alias = 't',
        aliases = SCAN_SCOPE_ALIASES,
        value_name = "SCOPE",
        // No `value_delimiter` here on purpose. Comma splitting for scope
        // values is done by `expand_scope_entry`, which exempts `cli:` paths
        // (a binary path may legitimately contain a comma). Letting clap split
        // first would cut such a path in half before the exemption is reached.
        help_heading = "Target Selection",
        display_order = 1,
        help = "Targets: hosts, CIDRs, URLs, @files, or local binaries cli://<binary>",
        long_help = "Smart target selector. Accepts single host, comma lists, files (@file.txt), \
                     CIDR blocks (192.168.1.0/24), domains, URLs, or local CLI binaries \
                     (cli:///absolute/path/to/my-tool). CLI scopes select a local process, not a network host; \
                     ports have no meaning for CLI targets. Binary paths preserve commas. Legacy flags \
                     (--target, --targets, --target-file, --domain, --domains, --domain-file, \
                     --cidr) remain as aliases."
    )]
    pub scope: Vec<String>,

    #[arg(
        long = "ports",
        short = 'p',
        aliases = ["port", "port-file", "add-ports"],
        value_name = "PORT",
        value_delimiter = ',',
        help_heading = "Target Selection",
        display_order = 2,
        help = "Extra ports to add: single, ranges, comma lists, @files",
        long_help = "Smart port selector. Accepts single ports, ranges (80-90), comma lists, \
                     files (@ports.txt), or mixed entries. These are ADDED to each template's \
                     default ports; use --override-ports to replace them instead."
    )]
    pub ports: Vec<String>,

    #[arg(
        long,
        help_heading = "Target Selection",
        display_order = 3,
        help = "Scan the top N most common ports",
        long_help = "Add the top N most common ports (based on curated frequency data). \
                     Example: --top-ports 1000"
    )]
    pub top_ports: Option<u16>,

    #[arg(
        long,
        help_heading = "Target Selection",
        display_order = 4,
        help = "Replace template default ports entirely",
        long_help = "Replace template default ports entirely with your own list (same formats \
                     as --ports). Use for complete control over port selection."
    )]
    pub override_ports: Option<String>,

    // ===== Template Selection =====
    #[arg(
        long = "templates",
        value_name = "TEMPLATE",
        value_delimiter = ',',
        aliases = ["template", "template-file"],
        help_heading = "Template Selection",
        display_order = 11,
        help = "Templates: IDs, file names/paths, or @files",
        long_help = "Smart template selector. Accepts template IDs, file names/paths, or @file \
                     references (one per line). Supports mixed entries. Legacy flags (--template, \
                     --template-file) remain as aliases."
    )]
    pub templates: Vec<String>,

    #[arg(
        long,
        value_enum,
        value_name = "LANG",
        help_heading = "Template Selection",
        display_order = 12,
        help = "Filter templates by language (e.g. python,rust,c)",
        long_help = "Filter templates by programming language. Available: yaml, python, rust, \
                     shell, javascript, c, cpp, java, go, ruby, perl, php."
    )]
    pub template_language: Option<Vec<LanguageArg>>,

    #[arg(
        long,
        value_enum,
        help_heading = "Template Selection",
        display_order = 13,
        help = "Filter by severity (critical,high,medium,low,info)",
        long_help = "Filter templates by severity level. Example: --severity critical,high for \
                     a quick, high-signal assessment."
    )]
    pub severity: Option<Vec<SeverityArg>>,

    #[arg(
        long,
        help_heading = "Template Selection",
        display_order = 14,
        help = "Filter by tags (database,injection,xss,rce,…)",
        long_help = "Filter templates by tags (comma-separated). Common tags: database, \
                     injection, xss, rce, lfi, ssrf, auth."
    )]
    pub tags: Option<String>,

    #[arg(
        long,
        help_heading = "Template Selection",
        display_order = 15,
        help = "Exclude templates matching a pattern (wildcards)",
        long_help = "Exclude templates matching a pattern. Supports wildcards. \
                     Example: --exclude-templates test-*,experimental-*"
    )]
    pub exclude_templates: Option<String>,

    #[arg(
        long,
        help_heading = "Template Selection",
        display_order = 16,
        help = "Use templates from a custom directory",
        long_help = "Use templates from a custom directory instead of the default discovery \
                     locations."
    )]
    pub template_dir: Option<PathBuf>,

    #[arg(
        long,
        value_name = "JSON",
        help_heading = "Template Selection",
        display_order = 17,
        help = "JSON context passed to templates (CERT_X_GEN_CONTEXT)",
        long_help = "JSON context passed to templates via the CERT_X_GEN_CONTEXT environment \
                     variable. Templates read this to receive parameterized input (target URLs, \
                     parameter names, HTTP methods, baselines, etc.) without hardcoding values. \
                     Example: '{\"param_name\":\"username\",\"method\":\"POST\"}'"
    )]
    pub context: Option<String>,

    // ===== Probe Input =====
    #[arg(
        long = "arg",
        value_name = "ARG",
        allow_hyphen_values = true,
        help_heading = "Probe Input",
        display_order = 51,
        help = "Argument to feed the target under test (repeatable)",
        long_help = "Argument passed through to the target the template drives, not to the \
                     template itself. Repeat for an argument vector; hyphen-leading values are \
                     accepted, so the target's own flags can be passed. Delivered to the \
                     template as CERT_X_GEN_ARGV (a JSON array). Example: \
                     --arg --label --arg AAAAAAAAAAAAAAAAAAAA"
    )]
    pub arg: Vec<String>,

    #[arg(
        long,
        value_name = "PATH",
        help_heading = "Probe Input",
        display_order = 52,
        help = "File whose bytes are fed to the target's stdin",
        long_help = "Path to a file whose bytes the template should feed to the target's stdin. \
                     Delivered as CERT_X_GEN_STDIN_FILE, canonicalised, so the template does not \
                     depend on its working directory."
    )]
    pub stdin_file: Option<PathBuf>,

    #[arg(
        long = "input",
        value_name = "DIR",
        help_heading = "Probe Input",
        display_order = 53,
        help = "Directory of seed inputs (corpus) for the probe",
        long_help = "Directory of seed inputs the template may iterate over. Delivered as \
                     CERT_X_GEN_INPUT_DIR. cxg does not mutate or minimise the corpus -- corpus \
                     search is discovery, and cxg verifies -- it only hands over the directory."
    )]
    pub input: Option<PathBuf>,

    #[arg(
        long,
        value_name = "K=V",
        help_heading = "Probe Input",
        display_order = 54,
        help = "Environment variable to set on the target (repeatable)",
        long_help = "Environment variable the template should set on the target process, not on \
                     itself. Delivered as CERT_X_GEN_TARGET_ENV (a JSON object). Repeatable; a \
                     repeated key takes its last value. Typical use is sanitizer runtime \
                     control, e.g. --target-env ASAN_OPTIONS=abort_on_error=1"
    )]
    pub target_env: Vec<String>,

    #[arg(
        long,
        help_heading = "Probe Input",
        display_order = 55,
        help = "Skip the templates an uninstrumented cli:// build could not have shown",
        long_help = "Instrumentation preflight. For each cli:// target, inspect the binary for \
                     sanitizer, coverage and debug-info markers before running anything against \
                     it. If none are present, record as SKIPPED with the reason \
                     no-instrumentation-detected every (template, target) execution whose \
                     oracles needed that instrumentation, instead of running the probe and \
                     reporting a 'no findings' result that looks like a refutation but is not \
                     evidence. A template declaring only oracles that work on any build (exit, \
                     signal, timeout, exception, property) still runs and reaches a real verdict. The \
                     build cxg wants is the language's instrumented one, e.g. \
                     clang -fsanitize=address -g; cxg inspects and refuses, it does not build \
                     the target -- see `cxg build --instrument` for the verb that does."
    )]
    pub require_instrumentation: bool,

    #[arg(
        long,
        value_name = "PATH",
        help_heading = "Probe Input",
        display_order = 56,
        help = "Trust this cxg build --instrument manifest over re-inspecting the binary",
        long_help = "Manifest written by `cxg build --instrument`, naming a binary and the \
                     instrumentation cxg verified in it at build time. Provenance beats \
                     inspection: cxg passed the flags and read the produced artefact back before \
                     it was willing to call the build instrumented, and that record survives \
                     stripping and a copy away from the build tree. The record applies only to \
                     the binary the manifest names; every other target is inspected exactly as \
                     before. Repeatable. Omit it and the scan behaves identically to one run \
                     before this flag existed."
    )]
    pub instrumented_manifest: Vec<PathBuf>,

    #[arg(
        long,
        value_name = "GROUP",
        help_heading = "Template Selection",
        display_order = 18,
        help = "Run only templates in this batch group",
        long_help = "Run only templates belonging to this batch group. Batch groups let you \
                     execute a cohort of templates that share the same context shape in a single \
                     invocation. Common groups: auth-context, endpoint-params, service-ports, \
                     full-surface."
    )]
    pub batch_group: Option<String>,

    // ===== Execution =====
    #[arg(
        long,
        default_value_t = 50,
        help_heading = "Execution",
        display_order = 21,
        help = "Concurrent targets scanned at once",
        long_help = "How many targets to scan simultaneously. Lower for production systems \
                     (10-25), higher for internal scans (50-100)."
    )]
    pub parallel_targets: usize,

    #[arg(
        long,
        default_value_t = 10,
        help_heading = "Execution",
        display_order = 22,
        help = "Concurrent templates per target",
        long_help = "How many templates to run concurrently per target. Balances speed against \
                     load on the target. Lower for fragile targets, higher for robust ones."
    )]
    pub parallel_templates: usize,

    #[arg(
        long,
        default_value = "30s",
        help_heading = "Execution",
        display_order = 23,
        help = "Response timeout (e.g. 30s, 2m, 1h)",
        long_help = "Maximum time to wait for a response. Supports s (seconds), m (minutes), \
                     h (hours). Increase for slow networks or complex checks."
    )]
    pub timeout: String,

    #[arg(
        long,
        default_value_t = 1,
        help_heading = "Execution",
        display_order = 24,
        help = "Retry attempts for transient failures",
        long_help = "Number of retry attempts for failed requests. Higher for unreliable \
                     networks, lower for fast scans."
    )]
    pub retry: u32,

    #[arg(
        long,
        help_heading = "Execution",
        display_order = 25,
        help = "Max requests per second (prevents WAF/IPS triggers)",
        long_help = "Maximum requests per second. Use 10-50 for production, 100+ for internal \
                     testing. Prevents overwhelming targets and triggering WAF/IPS."
    )]
    pub rate_limit: Option<u32>,

    #[arg(
        long,
        help_heading = "Execution",
        display_order = 26,
        help = "Aggressive mode: intrusive checks, higher concurrency",
        long_help = "Aggressive scanning with intrusive checks and higher concurrency. \
                     WARNING: may trigger security alerts or cause disruption. Use only with \
                     explicit permission on systems you control."
    )]
    pub aggressive: bool,

    #[arg(
        long,
        help_heading = "Execution",
        display_order = 27,
        help = "Stealth mode: randomized timing, reduced footprint",
        long_help = "Stealth mode: randomized timing and reduced footprint to evade IDS/IPS/WAF \
                     detection. Slower, but less likely to be flagged."
    )]
    pub stealth: bool,

    #[arg(
        long,
        help_heading = "Execution",
        display_order = 28,
        help = "Passive mode: analyze responses only, no active probes",
        long_help = "Passive scanning: analyze responses from normal requests only, with no \
                     active probing. Safest option, but limited detection capability."
    )]
    pub passive: bool,

    #[arg(
        long,
        help_heading = "Execution",
        display_order = 29,
        help = "Safe mode: skip DoS / resource-exhaustion checks",
        long_help = "Safe mode: excludes potentially harmful checks (DoS, resource exhaustion). \
                     Recommended for production systems where availability is critical."
    )]
    pub safe: bool,

    // ===== Network =====
    #[arg(
        long,
        help_heading = "Network",
        display_order = 31,
        help = "Route traffic through a proxy (http/https/socks5)",
        long_help = "Route all traffic through a proxy. Supports HTTP, HTTPS, and SOCKS5. \
                     Examples: http://proxy:8080, socks5://127.0.0.1:1080"
    )]
    pub proxy: Option<String>,

    #[arg(
        long,
        help_heading = "Network",
        display_order = 32,
        help = "Custom User-Agent header",
        long_help = "Custom User-Agent header, for mimicking specific browsers or tools. \
                     Default: cert-x-gen/<version>. Example: \"Mozilla/5.0 ...\""
    )]
    pub user_agent: Option<String>,

    #[arg(
        long,
        help_heading = "Network",
        display_order = 33,
        help = "Add a custom header (repeatable)",
        long_help = "Add a custom HTTP header. Repeatable for multiple headers. Useful for \
                     authentication, API keys, or custom application headers. \
                     Example: --header \"Authorization: Bearer token\""
    )]
    pub header: Option<Vec<String>>,

    #[arg(
        long,
        help_heading = "Network",
        display_order = 34,
        help = "Add a cookie (repeatable)",
        long_help = "Add a cookie to requests. Repeatable. Useful for authenticated scans. \
                     Example: --cookie \"session=abc123\""
    )]
    pub cookie: Option<Vec<String>>,

    #[arg(
        long,
        help_heading = "Network",
        display_order = 35,
        help = "Follow HTTP redirects (Default: Disabled)",
        long_help = "Follow HTTP redirects automatically, for discovering redirect chains and \
                     final destinations. Default: Disabled — redirects are not followed unless \
                     this flag is passed."
    )]
    pub follow_redirects: bool,

    #[arg(
        long,
        default_value_t = 5,
        help_heading = "Network",
        display_order = 36,
        help = "Max redirect hops to follow",
        long_help = "Maximum number of redirects to follow (when --follow-redirects is set). \
                     Prevents infinite redirect loops."
    )]
    pub max_redirects: usize,

    // ===== Output =====
    #[arg(
        short,
        long,
        default_value = "scan-results",
        help_heading = "Output",
        display_order = 41,
        help = "Output basename (extension set by --output-format)",
        long_help = "Output file basename. The trailing extension (if any) is REPLACED by the \
                     chosen format's extension — e.g. `--output report.txt --output-format json` \
                     writes report.json."
    )]
    pub output: String,

    #[arg(
        long,
        default_value = "json",
        help_heading = "Output",
        display_order = 42,
        help = "Output formats: json,csv,sarif,html,markdown",
        long_help = "Output formats (comma-separated); several can be generated at once. \
                     Available: json (automation), csv (spreadsheet), sarif (CI/CD), \
                     html (visual report), markdown (docs)."
    )]
    pub output_format: String,

    #[arg(
        long,
        value_enum,
        value_delimiter = ',',
        help_heading = "Output",
        help = "Exit 2 after writing reports if any execution has a matching status",
        long_help = "Fail CI on matching execution statuses (comma-separated or repeated). \
                     Example: --fail-on confirmed,errored,timed-out. Reports are written before \
                     exit 2. Without this flag, findings do not change the exit code."
    )]
    pub fail_on: Vec<FailOnArg>,

    #[arg(
        short,
        long,
        help_heading = "Output",
        display_order = 43,
        help = "Suppress the ASCII startup banner",
        long_help = "Suppress the ASCII startup banner. Scan output itself is unchanged."
    )]
    pub quiet: bool,

    // ===== Not Implemented (accepted and ignored) =====
    #[arg(
        long,
        help_heading = "Not Implemented",
        display_order = 91,
        help = "Protocol to use [NOT IMPLEMENTED — accepted and ignored]",
        long_help = "Specify protocol: http, https, tcp, udp, etc. \
                     [NOT IMPLEMENTED — accepted and ignored]"
    )]
    pub protocol: Option<String>,

    #[arg(
        long,
        help_heading = "Not Implemented",
        display_order = 92,
        help = "Multiple protocols [NOT IMPLEMENTED — accepted and ignored]",
        long_help = "Test multiple protocols (comma-separated). Example: http,https \
                     [NOT IMPLEMENTED — accepted and ignored]"
    )]
    pub protocols: Option<String>,

    #[arg(
        long,
        default_value_t = num_cpus::get(),
        help_heading = "Not Implemented",
        display_order = 93,
        help = "Worker threads [NOT IMPLEMENTED — accepted and ignored]",
        long_help = "Worker threads for parallel execution. Concurrency is actually controlled \
                     by --parallel-targets and --parallel-templates. \
                     [NOT IMPLEMENTED — accepted and ignored]"
    )]
    pub threads: usize,

    #[arg(
        long,
        help_heading = "Not Implemented",
        display_order = 94,
        help = "Stream results in real-time [NOT IMPLEMENTED — accepted and ignored]",
        long_help = "Stream results in real-time as they are found. \
                     [NOT IMPLEMENTED — accepted and ignored]"
    )]
    pub stream: bool,

    #[arg(
        long,
        help_heading = "Not Implemented",
        display_order = 95,
        help = "Resume an interrupted scan [NOT IMPLEMENTED — accepted and ignored]",
        long_help = "Resume a scan from where it stopped. \
                     [NOT IMPLEMENTED — accepted and ignored]"
    )]
    pub resume: Option<String>,

    #[arg(
        long,
        help_heading = "Not Implemented",
        display_order = 96,
        help = "Distributed mode [NOT IMPLEMENTED — accepted and ignored]",
        long_help = "Distributed mode: coordinate with other scanners for massive scans. \
                     [NOT IMPLEMENTED — accepted and ignored]"
    )]
    pub distributed: bool,

    #[arg(
        long,
        help_heading = "Not Implemented",
        display_order = 97,
        help = "Coordinator URL [NOT IMPLEMENTED — accepted and ignored]",
        long_help = "Coordinator URL for distributed mode. \
                     [NOT IMPLEMENTED — accepted and ignored]"
    )]
    pub coordinator: Option<String>,

    #[arg(
        long,
        help_heading = "Not Implemented",
        display_order = 98,
        help = "Worker identifier [NOT IMPLEMENTED — accepted and ignored]",
        long_help = "Worker identifier in distributed mode. \
                     [NOT IMPLEMENTED — accepted and ignored]"
    )]
    pub worker_id: Option<String>,

    #[arg(
        long,
        help_heading = "Not Implemented",
        display_order = 99,
        help = "Named config profile [NOT IMPLEMENTED — accepted and ignored]",
        long_help = "Use a named profile from the config file. \
                     [NOT IMPLEMENTED — accepted and ignored]"
    )]
    pub profile: Option<String>,
}

#[derive(Parser, Debug)]
#[command(
    about = "Manage security scanning templates",
    long_about = "List, validate, update, create, and manage security scanning templates. \
                  Templates define vulnerability detection logic in 12 supported languages.",
    after_help = "TEMPLATE LANGUAGES:
  Interpreted: Python, JavaScript, Ruby, Perl, PHP, Shell
  Compiled: Rust, C, C++, Java, Go
  Declarative: YAML

EXAMPLES:
  # CLI Security Baseline from the detection-template repository (not skeletons)
  cxg template update
  cxg template list --tags cli
  cxg scan --scope cli:///absolute/path/to/my-tool --template-dir ~/.cert-x-gen/templates/official/templates/cli-baseline --require-instrumentation

  # List all templates
  cxg template list

  # Filter templates
  cxg template list --language python
  cxg template list --language c --severity critical
  cxg template list --tags database,unauthenticated

  # Search templates
  cxg template search redis
  cxg template search \"sql injection\" --language python
  cxg template search unauthenticated --detailed

  # Get template information
  cxg template info redis-unauthenticated
  cxg template info sql-injection-detection

  # Show template directories
  cxg template pwd

  # View skeleton template for a language
  cxg template skeleton python
  cxg template skeleton c

  # Add a local template to cxg
  cxg template add ./my-redis-check.py
  cxg template add ./custom-check.c custom/network

  # Validate templates
  cxg template validate ~/.cert-x-gen/templates/
  cxg template validate ./my-templates/ --recursive
  cxg template validate ./redis-check.c

  # Update templates from repository
  cxg template update
  cxg template update --force

  # Create new template from skeleton
  cxg template create --id my-check --language python --name \"My Check\"
  cxg template create --id redis-test --language c --output ./my-templates/

  # Test a template
  cxg template test --template ./my-template.c --target 192.168.1.100
  cxg template test --template redis-unauthenticated --target localhost --debug"
)]
pub struct TemplateCommand {
    #[command(subcommand)]
    pub action: TemplateAction,
}

#[derive(Subcommand, Debug)]
pub enum TemplateAction {
    /// List available templates
    ///
    /// CLI Security Baseline: run `cxg template update`, then `cxg template list --tags cli`.
    /// The pack comes from cert-x-gen-templates/templates/cli-baseline, not this
    /// repository's skeletons. Inspect a result with `cxg template info <template-id>`.
    List {
        /// Filter by programming language
        #[arg(long, value_enum, value_name = "LANG")]
        language: Option<LanguageArg>,

        /// Filter by severity level
        #[arg(long, value_enum, value_name = "LEVEL")]
        severity: Option<SeverityArg>,

        /// Filter by tags (comma-separated); use cli for local CLI templates
        #[arg(long, value_name = "TAG,TAG,...")]
        tags: Option<String>,

        /// Filter by batch group (e.g. auth-context, endpoint-params)
        #[arg(long, value_name = "GROUP")]
        batch_group: Option<String>,
    },

    /// Validate template files
    Validate {
        /// Template file or directory to validate
        path: PathBuf,

        /// Recursively validate all templates in subdirectories
        #[arg(short, long)]
        recursive: bool,

        /// Output validation results as JSON
        #[arg(long)]
        json: bool,
    },

    /// Update templates from remote repository
    ///
    /// The default repository is https://github.com/Bugb-Technologies/cert-x-gen-templates.
    /// It supplies the CLI Security Baseline under templates/cli-baseline, installed at
    /// ~/.cert-x-gen/templates/official/templates/cli-baseline with default configuration.
    /// Example: cxg template update
    Update {
        /// Force update (overwrite local changes)
        #[arg(short, long)]
        force: bool,
    },

    /// Show detailed information about a template
    Info {
        /// Template ID to show information for
        template_id: String,
    },

    /// Create a new template from skeleton/scaffold
    Create {
        /// Unique template ID
        #[arg(long, value_name = "ID")]
        id: String,

        /// Programming language for the template
        #[arg(long, value_enum, value_name = "LANG")]
        language: LanguageArg,

        /// Human-readable template name
        #[arg(long, value_name = "NAME")]
        name: String,

        /// Output directory for the new template
        #[arg(short, long, default_value = ".", value_name = "DIR")]
        output: PathBuf,
    },

    /// Test a template against a target
    Test {
        /// Path to template file or template ID
        template: PathBuf,

        /// Target to test against
        #[arg(long, value_name = "HOST")]
        target: String,

        /// Enable debug output
        #[arg(long)]
        debug: bool,
    },

    /// Search templates (shortcut for `cxg search`)
    ///
    /// Discover CLI Security Baseline templates after `cxg template update`:
    ///     cxg template search baseline --tags cli
    Search {
        /// Search query
        query: String,

        /// Filter by programming language
        #[arg(long, value_enum, value_name = "LANG")]
        language: Option<LanguageArg>,

        /// Filter by severity level
        #[arg(long, value_enum, value_name = "LEVEL")]
        severity: Option<SeverityArg>,

        /// Filter by tags (comma-separated); use cli for local CLI templates
        #[arg(long, value_name = "TAG,TAG,...")]
        tags: Option<String>,

        /// Search in template content/code
        #[arg(long)]
        content: bool,

        /// Show detailed results
        #[arg(long)]
        detailed: bool,

        /// Maximum number of results
        #[arg(long, default_value_t = 50, value_name = "N")]
        limit: usize,
    },

    /// Show the template directories used by cxg
    Pwd,

    /// Display the skeleton/scaffold template for a language.
    ///
    /// This is a starting scaffold, not a ready-to-run template. The emitted YAML skeleton
    /// in particular does not pass the engine loader as-is and must be edited before use.
    Skeleton {
        /// Programming language for the skeleton
        #[arg(value_enum, value_name = "LANG")]
        language: LanguageArg,
    },

    /// Add a local template file into the cxg template directory
    Add {
        /// Path to the template file to add
        #[arg(value_name = "FILE")]
        file: PathBuf,

        /// Destination subdirectory within the user template folder (e.g. "custom/redis")
        #[arg(value_name = "DEST")]
        dest: Option<String>,
    },
}

#[derive(Parser, Debug)]
#[command(
    about = "Search and discover security scanning templates",
    long_about = "Search through available templates using text queries, filters, and advanced options. \
                  Supports full-text search, regex patterns, content search, and multiple output formats.",
    after_help = "SEARCH CAPABILITIES:
  • Full-text search in names, descriptions, and tags
  • Regex pattern matching
  • Content search (searches inside template code)
  • Multiple filters (language, severity, tags, author, CWE)
  • Multiple output formats (table, json, yaml, csv, list, detailed)
  • Sorting and pagination

EXAMPLES:
  # Discover installed CLI Security Baseline templates
  cxg template update
  cxg search --tags cli

  # Basic text search
  cxg search --query \"redis\"
  cxg search --query \"sql injection\"
  cxg search --query \"unauthenticated access\"

  # Language-specific search
  cxg search --language python
  cxg search --language c --query \"buffer overflow\"
  cxg search --language rust --severity critical

  # Severity filtering
  cxg search --severity critical
  cxg search --severity high --language python
  cxg search --severity critical,high

  # Tag-based search
  cxg search --tags database
  cxg search --tags \"database,unauthenticated\"
  cxg search --tags injection --language c

  # Author and CWE filtering
  cxg search --author \"CERT-X-GEN\"
  cxg search --cwe \"CWE-89\"
  cxg search --cwe \"CWE-306\" --severity critical

  # Advanced search with regex
  cxg search --query \"redis|mysql|postgres\" --regex
  cxg search --query \"SQL.*injection\" --regex --case-sensitive

  # Content search (slower but comprehensive)
  cxg search --query \"curl\" --content
  cxg search --query \"SELECT.*FROM\" --content --regex

  # Output formats
  cxg search --query \"redis\" --format table        # Default
  cxg search --query \"redis\" --format json
  cxg search --query \"redis\" --format csv
  cxg search --query \"redis\" --format yaml
  cxg search --query \"redis\" --format detailed

  # Sorting and limiting
  cxg search --query \"injection\" --sort name
  cxg search --query \"injection\" --sort severity --reverse
  cxg search --query \"injection\" --limit 10

  # Get only template IDs (useful for piping to scan)
  cxg search --query \"redis\" --ids-only
  TEMPLATES=$(cxg search --query \"redis\" --ids-only | tr '\\n' ',')
  cxg scan --target example.com --templates \"$TEMPLATES\"

  # Show statistics
  cxg search --query \"redis\" --stats
  cxg search --language python --stats

  # Save results to file
  cxg search --query \"redis\" --output results.json --format json
  cxg search --language c --output c-templates.csv --format csv

  # Complex queries
  cxg search --language python --severity high --tags database --format json
  cxg search --query \"authentication\" --content --case-sensitive --regex
  cxg search --author \"CERT-X-GEN\" --severity critical --sort date --reverse"
)]
pub struct SearchArgs {
    /// Search query (searches in name, description, tags, and optionally content)
    #[arg(short, long, value_name = "TEXT")]
    pub query: Option<String>,

    /// Filter by programming language
    #[arg(long, value_enum, value_name = "LANG")]
    pub language: Option<LanguageArg>,

    /// Filter by severity level
    #[arg(long, value_enum, value_name = "LEVEL")]
    pub severity: Option<SeverityArg>,

    /// Filter by tags (comma-separated); use cli for local CLI templates
    #[arg(long, value_name = "TAG,TAG,...")]
    pub tags: Option<String>,

    /// Filter by template author
    #[arg(long, value_name = "NAME")]
    pub author: Option<String>,

    /// Filter by CWE ID (e.g., CWE-89)
    #[arg(long, value_name = "CWE-ID")]
    pub cwe: Option<String>,

    /// Search in template content/code (slower but more comprehensive)
    #[arg(long)]
    pub content: bool,

    /// Use case-sensitive search
    #[arg(long)]
    pub case_sensitive: bool,

    /// Treat query as regex pattern
    #[arg(long)]
    pub regex: bool,

    /// Maximum number of results to return
    #[arg(long, default_value_t = 50, value_name = "N")]
    pub limit: usize,

    /// Output format for search results
    #[arg(long, default_value = "table", value_enum, value_name = "FORMAT")]
    pub format: SearchFormat,

    /// Output file for results (default: print to stdout)
    #[arg(short, long, value_name = "FILE")]
    pub output: Option<PathBuf>,

    /// Show detailed information for each result
    #[arg(long)]
    pub detailed: bool,

    /// Sort results by field
    #[arg(long, default_value = "relevance", value_enum, value_name = "FIELD")]
    pub sort: SearchSort,

    /// Reverse sort order
    #[arg(long)]
    pub reverse: bool,

    /// Show only template IDs (useful for piping to other commands)
    #[arg(long)]
    pub ids_only: bool,

    /// Show search statistics and summary
    #[arg(long)]
    pub stats: bool,
}

#[derive(Parser, Debug)]
#[command(
    about = "Run as API server [NOT IMPLEMENTED — returns an error]",
    long_about = "Intended to start CERT-X-GEN as a REST API server for remote scanning.\n\n\
                  NOT IMPLEMENTED: this command currently exits with \
                  `Error: Not implemented: API server not yet implemented`. The flags below \
                  (including --tls*) are accepted but the server does not start.",
    after_help = "NOTE: `cxg server` is not implemented and exits with an error. The options \
                  below are placeholders and have no effect."
)]
pub struct ServerArgs {
    /// Server port
    #[arg(short, long, default_value_t = 8080, value_name = "PORT")]
    pub port: u16,

    /// Bind address (use 0.0.0.0 to listen on all interfaces)
    #[arg(short, long, default_value = "127.0.0.1", value_name = "ADDRESS")]
    pub bind: String,

    /// Authentication token for API requests
    #[arg(long, value_name = "TOKEN")]
    pub auth_token: Option<String>,

    /// Enable TLS/HTTPS
    #[arg(long)]
    pub tls: bool,

    /// TLS certificate file path
    #[arg(long, value_name = "FILE", requires = "tls")]
    pub tls_cert: Option<PathBuf>,

    /// TLS private key file path
    #[arg(long, value_name = "FILE", requires = "tls")]
    pub tls_key: Option<PathBuf>,
}

#[derive(Parser, Debug)]
#[command(
    about = "Generate and manage configuration files",
    long_about = "Create, validate, and manage CERT-X-GEN configuration files for reusable \
                  scan configurations and automation.",
    after_help = "EXAMPLES:
  # Generate default configuration
  cxg config generate
  cxg config generate --output config.yaml
  cxg config generate --format toml --output config.toml

  # Validate configuration
  cxg config validate config.yaml
  cxg config validate production.toml

  # Show current/default configuration
  cxg config show"
)]
pub struct ConfigCommand {
    #[command(subcommand)]
    pub action: ConfigAction,
}

#[derive(Subcommand, Debug)]
pub enum ConfigAction {
    /// Generate a default configuration file
    Generate {
        /// Output file path
        #[arg(short, long, default_value = "cert-x-gen.yaml", value_name = "FILE")]
        output: PathBuf,

        /// Configuration format
        #[arg(short, long, value_enum, default_value = "yaml", value_name = "FORMAT")]
        format: ConfigFormat,
    },

    /// Validate a configuration file
    Validate {
        /// Configuration file to validate
        config: PathBuf,
    },

    /// Show current/default configuration
    Show,
}

/// Sandbox management commands
#[derive(Parser, Debug)]
#[command(
    about = "Manage per-language dependency environments",
    long_about = "Initialize, manage, and configure per-language dependency environments for all \
                  supported programming languages: Python, JavaScript, Ruby, Perl, PHP, Rust, Go, \
                  and Java. This gives each runtime its own package directory, keeping template \
                  dependencies off the system package managers.\n\n\
                  This does NOT confine template execution. Templates execute as ordinary child \
                  processes with the invoking user's privileges and full network and filesystem \
                  access. Review templates before running them. For isolation, run cxg itself \
                  inside a container or VM, as a non-privileged user.",
    after_help = "EXAMPLES:
  # Initialize sandbox with all languages
  cxg sandbox init

  # Initialize specific languages only
  cxg sandbox init --languages python,javascript,ruby

  # Check sandbox status
  cxg sandbox status

  # Install additional packages
  cxg sandbox install python requests beautifulsoup4
  cxg sandbox install javascript axios cheerio

  # Clean sandbox environment
  cxg sandbox clean

  # Access sandbox shell
  cxg sandbox shell

  # Show sandbox location
  cxg sandbox path"
)]
pub struct SandboxCommand {
    #[command(subcommand)]
    pub action: SandboxAction,
}

/// Dependency environment management
///
/// Neither kind of environment below confines template execution. Templates execute as
/// ordinary child processes with the invoking user's privileges and full network and
/// filesystem access. Review templates before running them.
///
/// CERT-X-GEN supports two kinds of dependency environment:
///
/// 1. Docker environment:
///    - A container holding fresh Python, Ruby, Node, Go, Java, etc.
///    - Named environments (dev, test, prod)
///    - An interactive shell inside the container via 'enter' — work done in that
///      shell is contained by Docker in the ordinary way
///    - Scans launched from your host still run on your host, not in the container
///    - Commands: create, enter, delete, set-default, info
///
/// 2. Package environment:
///    - Python venv, npm node_modules, gem directories
///    - Uses host system's language runtimes
///    - Commands: init, status, install, clean
///
/// Use 'cxg sandbox info' to check Docker availability.
/// Use 'cxg sandbox create <name>' to create a Docker environment.
#[derive(Debug, Clone, Subcommand)]
pub enum SandboxAction {
    /// Initialize package-level dependency environment
    ///
    /// Creates separate package directories for Python (venv), JavaScript (node_modules),
    /// Ruby (gems), etc. This mode uses your host system's language runtimes.
    ///
    /// Note: this separates packages, not privileges. Templates still execute as ordinary
    /// child processes with your privileges and full network and filesystem access.
    ///
    /// The init command is smart:
    /// - First run: Sets up all language environments and installs packages
    /// - Subsequent runs: Only adds new languages or packages (skips existing)
    /// - Use --force to rebuild everything from scratch
    Init {
        /// Force re-initialization (rebuild everything from scratch)
        #[arg(short, long)]
        force: bool,

        /// Specific languages to initialize (comma-separated: python,node,ruby,go,etc.)
        #[arg(short, long)]
        languages: Option<String>,

        /// Custom sandbox directory (default: OS-specific data directory)
        #[arg(short, long)]
        directory: Option<PathBuf>,
    },

    /// Check sandbox status
    Status,

    /// Install packages in sandbox
    Install {
        /// Language runtime
        language: String,

        /// Packages to install
        packages: Vec<String>,
    },

    /// Clean sandbox environment
    Clean {
        /// Clean specific language only
        #[arg(short, long)]
        language: Option<String>,

        /// Force clean without confirmation
        #[arg(short, long)]
        force: bool,
    },

    /// Open sandbox shell
    Shell {
        /// Language environment to use
        #[arg(short, long, default_value = "bash")]
        language: String,
    },

    /// Show sandbox path
    Path,

    /// Update sandbox packages
    Update {
        /// Update specific language only
        #[arg(short, long)]
        language: Option<String>,
    },

    /// Export sandbox configuration
    Export {
        /// Output file
        #[arg(short, long, default_value = "sandbox-export.yaml")]
        output: PathBuf,

        /// Description
        #[arg(short, long)]
        description: Option<String>,

        /// Author
        #[arg(short, long)]
        author: Option<String>,
    },

    /// Import sandbox configuration
    Import {
        /// Import file
        file: PathBuf,

        /// Force overwrite existing sandbox
        #[arg(short, long)]
        force: bool,
    },

    /// List available sandbox templates
    Templates,

    /// Use a pre-configured sandbox template
    UseTemplate {
        /// Template name (web-security, network-security, api-testing)
        template: String,
    },

    /// List installed packages
    List {
        /// Language to list packages for
        language: String,
    },

    /// Create a new Docker-based sandbox
    Create {
        /// Sandbox name
        name: String,

        /// Languages to install
        #[arg(short, long, value_delimiter = ',')]
        languages: Option<Vec<String>>,

        /// Persist container between runs
        #[arg(short, long, default_value = "true")]
        persist: bool,

        /// Auto-start on CLI launch
        #[arg(short, long, default_value = "true")]
        auto_start: bool,
    },

    /// Delete a sandbox
    Delete {
        /// Sandbox name
        name: String,

        /// Force deletion without confirmation
        #[arg(short, long)]
        force: bool,
    },

    /// Enter sandbox shell
    Enter {
        /// Sandbox name (uses default if not specified)
        name: Option<String>,
    },

    /// Set default sandbox
    SetDefault {
        /// Sandbox name (clear default if not specified)
        name: Option<String>,
    },

    /// Show Docker sandbox information
    Info,

    /// Build Docker image
    Build {
        /// Dockerfile path
        #[arg(short, long)]
        dockerfile: Option<PathBuf>,
    },
}

// ─── MCP Command ─────────────────────────────────────────────────────

#[derive(Debug, Clone, Parser)]
#[command(about = "MCP (Model Context Protocol) server for AI agent integration")]
pub struct McpCommand {
    #[command(subcommand)]
    pub action: Option<McpAction>,
}

#[derive(Debug, Clone, Subcommand)]
pub enum McpAction {
    /// Configure MCP server for AI coding agents (Claude Desktop, Claude Code, Cursor, etc.)
    Install {
        /// Specific clients to configure (comma-separated: claude-desktop,claude-code,cursor,windsurf,vscode,zed)
        #[arg(long)]
        client: Option<String>,
    },
    /// Remove MCP server configuration from AI coding agents
    Uninstall {
        /// Specific clients to unconfigure
        #[arg(long)]
        client: Option<String>,
    },
    /// Show current MCP configuration status across all detected clients
    Status,
}

#[derive(Clone, Copy, Debug, clap::ValueEnum)]
pub enum SeverityArg {
    /// Critical severity (highest priority)
    Critical,
    /// High severity
    High,
    /// Medium severity
    Medium,
    /// Low severity
    Low,
    /// Informational (lowest priority)
    Info,
}

impl From<SeverityArg> for cert_x_gen::types::Severity {
    fn from(arg: SeverityArg) -> Self {
        match arg {
            SeverityArg::Critical => cert_x_gen::types::Severity::Critical,
            SeverityArg::High => cert_x_gen::types::Severity::High,
            SeverityArg::Medium => cert_x_gen::types::Severity::Medium,
            SeverityArg::Low => cert_x_gen::types::Severity::Low,
            SeverityArg::Info => cert_x_gen::types::Severity::Info,
        }
    }
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum LanguageArg {
    /// YAML declarative templates
    Yaml,
    /// Python interpreted templates
    Python,
    /// Rust compiled templates
    Rust,
    /// Shell/Bash script templates
    Shell,
    /// JavaScript/Node.js templates
    JavaScript,
    /// C compiled templates
    C,
    /// C++ compiled templates
    Cpp,
    /// Java compiled templates
    Java,
    /// Go compiled templates
    Go,
    /// Ruby interpreted templates
    Ruby,
    /// Perl interpreted templates
    Perl,
    /// PHP interpreted templates
    Php,
}

impl From<LanguageArg> for cert_x_gen::types::TemplateLanguage {
    fn from(arg: LanguageArg) -> Self {
        match arg {
            LanguageArg::Yaml => cert_x_gen::types::TemplateLanguage::Yaml,
            LanguageArg::Python => cert_x_gen::types::TemplateLanguage::Python,
            LanguageArg::Rust => cert_x_gen::types::TemplateLanguage::Rust,
            LanguageArg::Shell => cert_x_gen::types::TemplateLanguage::Shell,
            LanguageArg::JavaScript => cert_x_gen::types::TemplateLanguage::JavaScript,
            LanguageArg::C => cert_x_gen::types::TemplateLanguage::C,
            LanguageArg::Cpp => cert_x_gen::types::TemplateLanguage::Cpp,
            LanguageArg::Java => cert_x_gen::types::TemplateLanguage::Java,
            LanguageArg::Go => cert_x_gen::types::TemplateLanguage::Go,
            LanguageArg::Ruby => cert_x_gen::types::TemplateLanguage::Ruby,
            LanguageArg::Perl => cert_x_gen::types::TemplateLanguage::Perl,
            LanguageArg::Php => cert_x_gen::types::TemplateLanguage::Php,
        }
    }
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ConfigFormat {
    /// YAML format
    Yaml,
    /// TOML format
    Toml,
    /// JSON format
    Json,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum SearchFormat {
    /// Table format (human-readable, default)
    Table,
    /// JSON format (machine-readable)
    Json,
    /// YAML format
    Yaml,
    /// CSV format (spreadsheet-compatible)
    Csv,
    /// Simple list format (template IDs only)
    List,
    /// Detailed format (all information)
    Detailed,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum SearchSort {
    /// Sort by relevance score (default)
    Relevance,
    /// Sort by template name
    Name,
    /// Sort by programming language
    Language,
    /// Sort by severity level
    Severity,
    /// Sort by author name
    Author,
    /// Sort by creation/update date
    Date,
    /// Sort by popularity/usage
    Popularity,
}

// ============================================================================
// AI COMMAND
// ============================================================================

#[derive(Parser, Debug)]
#[command(
    about = "AI-powered security template generation",
    long_about = "Generate security scanning templates using AI/LLM providers. Supports local models \
                  (Ollama) and cloud providers (OpenAI, Anthropic, DeepSeek). No API key required \
                  for local generation with Ollama.",
    after_help = "FEATURES:
  • Generate templates from natural language descriptions
  • Support for all 12 programming languages (YAML, Python, JavaScript, Rust, C, C++, Java, Go, Ruby, Perl, PHP, Shell)
  • Multiple LLM providers (Ollama, OpenAI, Anthropic, DeepSeek)
  • Local-first with Ollama (no API key needed, works offline)
  • Automatic validation before saving
  • Unlimited generations (you control your own LLM)

EXAMPLES:
  # Generate with default provider (Ollama, local)
  cxg ai generate \"detect Redis without authentication\"
  cxg ai generate \"find SQL injection in login forms\"
  cxg ai generate \"check for exposed Memcached\"

  # Specify programming language
  cxg ai generate \"detect Redis unauth\" --language python
  cxg ai generate \"find XSS vulnerabilities\" --language javascript
  cxg ai generate \"check SSL certificates\" --language rust

  # Use specific provider
  cxg ai generate \"detect RCE\" --provider openai --model gpt-4
  cxg ai generate \"find SSRF\" --provider anthropic --model claude-3-5-sonnet-20241022
  cxg ai generate \"check headers\" --provider ollama --model codellama:13b

  # Save to specific location
  cxg ai generate \"Redis check\" --language yaml --output templates/redis-test.yaml
  cxg ai generate \"MySQL scan\" --output mysql-check.py

  # List available providers
  cxg ai providers list
  cxg ai providers list --detailed

  # Test provider connection
  cxg ai providers test ollama
  cxg ai providers test openai

  # Show provider status
  cxg ai providers status

GETTING STARTED WITH OLLAMA (FREE, LOCAL):
  1. Install Ollama: curl -fsSL https://ollama.com/install.sh | sh
  2. Download model: ollama pull codellama:13b
  3. Start Ollama: ollama serve
  4. Generate: cxg ai generate \"your security check description\"

PROVIDER CONFIGURATION:
  Configure providers in ~/.cert-x-gen/ai-config.yaml or use environment variables:
  - OPENAI_API_KEY for OpenAI
  - ANTHROPIC_API_KEY for Anthropic
  - DEEPSEEK_API_KEY for DeepSeek

For more information: https://github.com/Bugb-Technologies/cert-x-gen/docs/ai-features"
)]
pub struct AiCommand {
    #[command(subcommand)]
    pub action: AiAction,
}

#[derive(Subcommand, Debug)]
pub enum AiAction {
    /// Generate a new template from natural language
    Generate {
        /// Natural language description of what to detect
        ///
        /// Examples:
        ///   "detect Redis without authentication"
        ///   "find SQL injection vulnerabilities"
        ///   "check for exposed Memcached instances"
        ///   "scan for XSS in forms"
        prompt: String,

        /// Programming language for the template
        #[arg(
            short = 'l',
            long,
            value_enum,
            default_value = "yaml",
            value_name = "LANG",
            help = "Template language (yaml, python, javascript, rust, etc.)"
        )]
        language: LanguageArg,

        /// LLM provider to use
        #[arg(
            short = 'p',
            long,
            value_name = "PROVIDER",
            help = "LLM provider (ollama, openai, anthropic, deepseek)"
        )]
        provider: Option<String>,

        /// Model name to use
        #[arg(
            short = 'm',
            long,
            value_name = "MODEL",
            help = "Model name (e.g., codellama:13b, gpt-4, claude-3-5-sonnet-20241022)"
        )]
        model: Option<String>,

        /// Output file path (auto-generated if not specified)
        #[arg(
            short = 'o',
            long,
            value_name = "FILE",
            help = "Output file path (default: ~/.cert-x-gen/templates/ai-generated/<name>.<ext>)"
        )]
        output: Option<PathBuf>,

        /// Test the generated template immediately
        #[arg(long, help = "Test the generated template after creation")]
        test: bool,

        /// Target to test against (requires --test)
        #[arg(
            long,
            requires = "test",
            value_name = "HOST",
            help = "Target host for testing (e.g., localhost, 192.168.1.1)"
        )]
        test_target: Option<String>,

        /// Force overwrite if file exists
        #[arg(short = 'f', long, help = "Overwrite output file if it already exists")]
        force: bool,

        /// Show generation cost estimate (for cloud providers)
        #[arg(
            long,
            help = "Estimate and show cost before generating (cloud providers only)"
        )]
        estimate_cost: bool,

        /// API key for the LLM provider (session-only, not persisted to config).
        /// Overrides environment variables and stored config for this invocation.
        /// Use with --provider to specify which provider the key belongs to.
        #[arg(
            long,
            value_name = "KEY",
            help = "API key for the LLM provider (not saved). E.g. --provider anthropic --api-key sk-ant-..."
        )]
        api_key: Option<String>,
    },

    /// Manage LLM providers
    #[command(after_help = "EXAMPLES:
  # List all configured providers
  cxg ai providers list
  cxg ai providers list --detailed
  
  # Test specific provider (comprehensive health check)
  cxg ai providers test ollama
  cxg ai providers test openai
  cxg ai providers test anthropic
  cxg ai providers test deepseek
  
  # Check status of all enabled providers
  cxg ai providers status

HEALTH CHECK DETAILS:
  The 'test' command performs comprehensive diagnostics:
  • Connection testing (can we reach the endpoint?)
  • Authentication verification (is the API key valid?)
  • Response time measurement (how fast is the provider?)
  • Model availability check (what models can we use?)
  • Helpful hints for common issues

  The 'status' command tests all enabled providers at once,
  giving you a quick overview of your AI setup.

TROUBLESHOOTING:
  If a provider test fails, the output will include:
  • Clear error messages explaining what went wrong
  • Helpful hints for fixing the issue
  • Setup instructions for unconfigured providers
  
  Common issues:
  • Ollama: Make sure it's running (ollama serve)
  • Cloud providers: Check your API key environment variable
  • Network: Verify your internet connection for cloud providers")]
    Providers {
        #[command(subcommand)]
        action: ProviderAction,
    },
}

#[derive(Subcommand, Debug)]
pub enum ProviderAction {
    /// List all available providers
    ///
    /// Shows which providers are configured and available.
    /// Use --detailed to see more information about each provider.
    List {
        /// Show detailed information about each provider
        #[arg(short = 'd', long, help = "Show detailed provider information")]
        detailed: bool,
    },

    /// Test connection to a specific provider
    ///
    /// Performs comprehensive health checks including:
    /// - Connection testing
    /// - Authentication verification  
    /// - Response time measurement
    /// - Model availability check
    ///
    /// Provides helpful diagnostic information if issues are found.
    Test {
        /// Provider name to test (ollama, openai, anthropic, deepseek)
        provider: String,
    },

    /// Show status of all configured providers
    ///
    /// Tests all enabled providers and displays their health status.
    /// Quick way to see which providers are ready to use.
    Status,
}

// @comment -- "unit tests for the desktop-target CLI flags (--target-type/--app-cmd/--app-binary), verifying clap's default, validation, and conflicts_with/required_if_eq resolution before wiring them into the orchestrator forwarding"
#[cfg(test)]
mod desktop_flag_tests {
    use super::*;

    fn parse(args: &[&str]) -> Result<Cli, clap::Error> {
        Cli::try_parse_from(args)
    }

    #[test]
    fn target_type_defaults_to_web() {
        let cli = parse(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "http://x",
        ])
        .expect("should parse");
        if let Some(Commands::Pentest(p)) = cli.command {
            if let PentestAction::Run(PentestRunArgs { target_type, .. }) = p.action {
                assert_eq!(target_type, "web");
                return;
            }
        }
        panic!("expected pentest run");
    }

    #[test]
    fn electron_requires_a_launch_mechanism() {
        let err = parse(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "http://x",
            "--target-type",
            "electron",
        ]);
        assert!(
            err.is_err(),
            "electron without --app-cmd/--app-binary must fail"
        );
    }

    #[test]
    fn app_cmd_and_app_binary_conflict() {
        let err = parse(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "http://x",
            "--target-type",
            "electron",
            "--app-cmd",
            "npm start",
            "--app-binary",
            "/tmp/a",
        ]);
        assert!(
            err.is_err(),
            "--app-cmd and --app-binary are mutually exclusive"
        );
    }

    #[test]
    fn electron_with_app_cmd_parses() {
        let cli = parse(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "http://x",
            "--target-type",
            "electron",
            "--app-cmd",
            "npm run electron:dev",
        ])
        .expect("should parse");
        if let Some(Commands::Pentest(p)) = cli.command {
            if let PentestAction::Run(PentestRunArgs { app_cmd, .. }) = p.action {
                assert_eq!(app_cmd.as_deref(), Some("npm run electron:dev"));
                return;
            }
        }
        panic!("expected pentest run");
    }

    // The two dispatch bounds and the recovery opt-out existed in the Python
    // orchestrator only, so they were unreachable from the `cxg` binary: an operator
    // could not raise the per-template ceiling, could not disable the stall watchdog,
    // and could not decline having their application relaunched mid-engagement. This
    // pins that all three now parse and that leaving them off yields None/false, so
    // main.rs forwards nothing and the orchestrator's own defaults stay in force.
    #[test]
    fn timeout_and_restart_flags_parse_and_default_to_unset() {
        let cli = parse(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "http://x",
            "--target-type",
            "electron",
            "--app-cmd",
            "npm start",
            "--template-timeout",
            "1200",
            "--stall-timeout",
            "45",
            "--no-restart",
        ])
        .expect("should parse");
        if let Some(Commands::Pentest(p)) = cli.command {
            if let PentestAction::Run(PentestRunArgs {
                template_timeout,
                stall_timeout,
                no_restart,
                ..
            }) = p.action
            {
                assert_eq!(template_timeout, Some(1200.0));
                assert_eq!(stall_timeout, Some(45.0));
                assert!(no_restart);
            } else {
                panic!("expected pentest run");
            }
        } else {
            panic!("expected pentest run");
        }

        let bare = parse(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "http://x",
        ])
        .expect("should parse");
        if let Some(Commands::Pentest(p)) = bare.command {
            if let PentestAction::Run(PentestRunArgs {
                template_timeout,
                stall_timeout,
                no_restart,
                ..
            }) = p.action
            {
                assert_eq!(template_timeout, None);
                assert_eq!(stall_timeout, None);
                assert!(!no_restart);
                return;
            }
        }
        panic!("expected pentest run");
    }

    #[test]
    fn rejects_unknown_target_type() {
        // Sentinel is a value that is NOT a known substrate. "tauri" used to serve
        // here and is now a valid source-surface target (see tauri_surface_map_parses),
        // so this uses "gtk" to keep testing the same thing — clap rejects an unknown
        // --target-type — rather than being quietly weakened into asserting a valid one
        // is rejected.
        assert!(parse(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "http://x",
            "--target-type",
            "gtk"
        ])
        .is_err());
    }

    #[test]
    fn tauri_prove_flag_parses() {
        let cli = parse(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target-type",
            "tauri",
            "--tauri-prove",
            "--tauri-prove-timeout",
            "600",
        ])
        .expect("tauri --tauri-prove should parse");
        if let Some(Commands::Pentest(p)) = cli.command {
            if let PentestAction::Run(PentestRunArgs {
                target_type,
                tauri_prove,
                tauri_prove_timeout,
                ..
            }) = p.action
            {
                assert_eq!(target_type, "tauri");
                assert!(tauri_prove);
                assert_eq!(tauri_prove_timeout, 600);
                return;
            }
        }
        panic!("expected pentest run");
    }

    #[test]
    fn tauri_prove_defaults_off() {
        let cli = parse(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target-type",
            "tauri",
        ])
        .expect("parse");
        if let Some(Commands::Pentest(p)) = cli.command {
            if let PentestAction::Run(PentestRunArgs {
                tauri_prove,
                tauri_prove_timeout,
                ..
            }) = p.action
            {
                assert!(!tauri_prove);
                assert_eq!(tauri_prove_timeout, 1200);
                return;
            }
        }
        panic!("expected pentest run");
    }

    #[test]
    fn tauri_surface_map_parses_without_a_target() {
        // A tauri source-surface map navigates nowhere, so --target is optional for it;
        // --target becoming Option<String> is what makes this parse. The Python preflight
        // still refuses a web/electron run with no --target.
        let cli = parse(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target-type",
            "tauri",
        ])
        .expect("tauri run should parse without --target");
        if let Some(Commands::Pentest(p)) = cli.command {
            if let PentestAction::Run(PentestRunArgs {
                target_type,
                target,
                app_cmd,
                ..
            }) = p.action
            {
                assert_eq!(target_type, "tauri");
                assert!(target.is_none(), "no --target was given");
                assert!(app_cmd.is_none(), "tauri needs no launch command");
                return;
            }
        }
        panic!("expected pentest run");
    }

    #[test]
    fn electron_with_app_binary_alone_parses() {
        // The task brief asserted clap resolves conflicts_with vs required_if_eq
        // correctly for this case. It does not: clap's r_ifs/r_unless validation path
        // (which required_if_eq feeds) never consults conflicts_with, so pairing
        // `conflicts_with = "app_binary"` with `required_if_eq("target_type", "electron")`
        // on app_cmd wrongly demanded --app-cmd even when --app-binary alone was given.
        // Fixed by moving the conditional requirement to a `requires_if("electron",
        // "app_cmd")` on `target_type`, which clap resolves through the ArgGroup-style
        // "is_missing_required_ok" path that DOES check conflicts_with of present args.
        let cli = parse(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "http://x",
            "--target-type",
            "electron",
            "--app-binary",
            "/tmp/a",
        ])
        .expect("--app-binary alone with --target-type electron should parse");
        if let Some(Commands::Pentest(p)) = cli.command {
            if let PentestAction::Run(PentestRunArgs {
                app_binary,
                app_cmd,
                ..
            }) = p.action
            {
                assert_eq!(app_binary.as_deref(), Some("/tmp/a"));
                assert_eq!(app_cmd, None);
                return;
            }
        }
        panic!("expected pentest run");
    }

    #[test]
    fn auth_electron_requires_a_launch_mechanism() {
        // Same requires_if wiring was applied to PentestAction::Auth; verify it holds there too.
        let err = parse(&[
            "cxg",
            "pentest",
            "auth",
            "--target",
            "http://x",
            "--profile",
            "p1",
            "--target-type",
            "electron",
        ]);
        assert!(
            err.is_err(),
            "electron without --app-cmd/--app-binary must fail"
        );
    }

    #[test]
    fn auth_electron_with_app_binary_alone_parses() {
        let cli = parse(&[
            "cxg",
            "pentest",
            "auth",
            "--target",
            "http://x",
            "--profile",
            "p1",
            "--target-type",
            "electron",
            "--app-binary",
            "/tmp/a",
        ])
        .expect("--app-binary alone with --target-type electron should parse for auth too");
        if let Some(Commands::Pentest(p)) = cli.command {
            if let PentestAction::Auth {
                app_binary,
                app_cmd,
                ..
            } = p.action
            {
                assert_eq!(app_binary.as_deref(), Some("/tmp/a"));
                assert_eq!(app_cmd, None);
                return;
            }
        }
        panic!("expected pentest auth");
    }

    #[test]
    fn auth_electron_with_app_cmd_parses() {
        let cli = parse(&[
            "cxg",
            "pentest",
            "auth",
            "--target",
            "http://x",
            "--profile",
            "p1",
            "--target-type",
            "electron",
            "--app-cmd",
            "npm run electron:dev",
        ])
        .expect("should parse");
        if let Some(Commands::Pentest(p)) = cli.command {
            if let PentestAction::Auth {
                app_cmd,
                app_binary,
                ..
            } = p.action
            {
                assert_eq!(app_cmd.as_deref(), Some("npm run electron:dev"));
                assert_eq!(app_binary, None);
                return;
            }
        }
        panic!("expected pentest auth");
    }

    #[test]
    fn auth_app_cmd_and_app_binary_conflict() {
        let err = parse(&[
            "cxg",
            "pentest",
            "auth",
            "--target",
            "http://x",
            "--profile",
            "p1",
            "--target-type",
            "electron",
            "--app-cmd",
            "npm start",
            "--app-binary",
            "/tmp/a",
        ]);
        assert!(
            err.is_err(),
            "--app-cmd and --app-binary are mutually exclusive for auth too"
        );
    }
}

// @comment -- "unit tests for the two OAST modes: that the pollable one parses in both its bare and explicit forms, that clap rejects the pair (a split canary), and — the one that guards backward compatibility — that a lone --oast still parses to exactly what it always did"
#[cfg(test)]
mod oast_flag_tests {
    use super::*;

    fn run_action(args: &[&str]) -> PentestAction {
        let cli = Cli::try_parse_from(args).expect("should parse");
        match cli.command {
            Some(Commands::Pentest(p)) => p.action,
            _ => panic!("expected pentest"),
        }
    }

    fn base() -> Vec<&'static str> {
        vec![
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "http://x",
        ]
    }

    // Backward compatibility is the whole point of this one: an engagement script
    // that has been passing `--oast <host>` since before the pollable mode existed
    // must still parse to Some(host) with the new flag absent, so main.rs forwards
    // the identical `--oast <host>` and nothing about that run changes.
    #[test]
    fn oast_alone_is_unchanged_and_leaves_interactsh_unset() {
        let mut argv = base();
        argv.extend(["--oast", "c4ca4238a0b92.oastify.com"]);
        if let PentestAction::Run(PentestRunArgs {
            oast,
            oast_interactsh,
            ..
        }) = run_action(&argv)
        {
            assert_eq!(oast.as_deref(), Some("c4ca4238a0b92.oastify.com"));
            assert_eq!(oast_interactsh, None);
            return;
        }
        panic!("expected pentest run");
    }

    // The bare form must be distinguishable from absence, not merely falsy: it means
    // "register against interactsh's default servers", which is a request for a
    // canary, whereas None means no canary at all. Some("") vs None is what carries
    // that difference across to the orchestrator.
    #[test]
    fn bare_interactsh_yields_empty_string_not_none() {
        let mut argv = base();
        argv.push("--oast-interactsh");
        if let PentestAction::Run(PentestRunArgs {
            oast,
            oast_interactsh,
            ..
        }) = run_action(&argv)
        {
            assert_eq!(oast_interactsh.as_deref(), Some(""));
            assert_eq!(oast, None);
            return;
        }
        panic!("expected pentest run");
    }

    #[test]
    fn interactsh_takes_an_explicit_server_url() {
        let mut argv = base();
        argv.extend(["--oast-interactsh", "https://oast.example.internal"]);
        if let PentestAction::Run(PentestRunArgs {
            oast_interactsh, ..
        }) = run_action(&argv)
        {
            assert_eq!(
                oast_interactsh.as_deref(),
                Some("https://oast.example.internal")
            );
            return;
        }
        panic!("expected pentest run");
    }

    // Two canaries would split payloads between a pollable host and an unpollable
    // one, so a blind finding could no longer be said to be confirmed or not.
    // Enforced by clap's conflicts_with, so it fails during parse rather than after
    // AI generation has already spent minutes and API budget.
    #[test]
    fn oast_and_oast_interactsh_conflict() {
        let mut argv = base();
        argv.extend([
            "--oast",
            "c4ca4238a0b92.oastify.com",
            "--oast-interactsh",
            "https://oast.example.internal",
        ]);
        assert!(
            Cli::try_parse_from(&argv).is_err(),
            "--oast and --oast-interactsh are mutually exclusive"
        );

        // Also in the bare form, where the conflict is easiest to write by accident.
        let mut bare = base();
        bare.extend(["--oast", "c4ca4238a0b92.oastify.com", "--oast-interactsh"]);
        assert!(
            Cli::try_parse_from(&bare).is_err(),
            "bare --oast-interactsh must conflict with --oast too"
        );
    }

    // An optional-value flag placed before another flag must not swallow it.
    #[test]
    fn bare_interactsh_does_not_consume_a_following_flag() {
        let mut argv = base();
        argv.extend(["--oast-interactsh", "--headed"]);
        if let PentestAction::Run(PentestRunArgs {
            oast_interactsh,
            headed,
            ..
        }) = run_action(&argv)
        {
            assert_eq!(oast_interactsh.as_deref(), Some(""));
            assert!(headed, "--headed must survive the optional-value flag");
            return;
        }
        panic!("expected pentest run");
    }

    #[test]
    fn neither_flag_leaves_both_unset() {
        if let PentestAction::Run(PentestRunArgs {
            oast,
            oast_interactsh,
            oast_listener,
            ..
        }) = run_action(&base())
        {
            assert_eq!(oast, None);
            assert_eq!(oast_interactsh, None);
            assert_eq!(oast_listener, None);
            return;
        }
        panic!("expected pentest run");
    }

    // The bare listener form means "bind the docker bridge", a request for a canary,
    // so like bare --oast-interactsh it must be Some("") and distinguishable from the
    // None that means no canary — that difference is what main.rs forwards as the flag
    // alone rather than with an empty-string value.
    #[test]
    fn bare_listener_yields_empty_string_not_none() {
        let mut argv = base();
        argv.push("--oast-listener");
        if let PentestAction::Run(PentestRunArgs { oast_listener, .. }) = run_action(&argv) {
            assert_eq!(oast_listener.as_deref(), Some(""));
            return;
        }
        panic!("expected pentest run");
    }

    #[test]
    fn listener_takes_an_explicit_bind() {
        let mut argv = base();
        argv.extend(["--oast-listener", "host-docker-internal"]);
        if let PentestAction::Run(PentestRunArgs { oast_listener, .. }) = run_action(&argv) {
            assert_eq!(oast_listener.as_deref(), Some("host-docker-internal"));
            return;
        }
        panic!("expected pentest run");
    }

    // One canary per run: the listener is a third pollable mode, and pairing it with
    // either other canary would split payloads between callbacks nobody correlates,
    // so clap rejects every pairing during parse.
    #[test]
    fn listener_conflicts_with_the_other_canaries() {
        for other in [
            vec!["--oast", "c4ca4238a0b92.oastify.com"],
            vec!["--oast-interactsh"],
            vec!["--oast-interactsh", "https://oast.example.internal"],
        ] {
            let mut argv = base();
            argv.push("--oast-listener");
            argv.extend(other.iter().copied());
            assert!(
                Cli::try_parse_from(&argv).is_err(),
                "--oast-listener must conflict with {other:?}"
            );
        }
    }

    // The DNS leg is an independent boolean that only means anything alongside the
    // listener, but it must parse on its own without consuming the listener's value.
    #[test]
    fn listener_dns_is_an_independent_boolean() {
        let mut argv = base();
        argv.extend(["--oast-listener", "127.0.0.1", "--oast-listener-dns"]);
        if let PentestAction::Run(PentestRunArgs {
            oast_listener,
            oast_listener_dns,
            ..
        }) = run_action(&argv)
        {
            assert_eq!(oast_listener.as_deref(), Some("127.0.0.1"));
            assert!(oast_listener_dns);
            return;
        }
        panic!("expected pentest run");
    }

    #[test]
    fn listener_redirect_and_rebinding_options_parse() {
        let mut argv = base();
        argv.extend([
            "--oast-listener",
            "127.0.0.1",
            "--oast-listener-dns",
            "--oast-redirect-location",
            "http://169.254.169.254/latest/meta-data/",
            "--oast-redirect-status",
            "307",
            "--oast-dns-rebind-ip",
            "169.254.169.254",
        ]);
        if let PentestAction::Run(PentestRunArgs {
            oast_redirect_location,
            oast_redirect_status,
            oast_dns_rebind_ip,
            ..
        }) = run_action(&argv)
        {
            assert_eq!(
                oast_redirect_location.as_deref(),
                Some("http://169.254.169.254/latest/meta-data/")
            );
            assert_eq!(oast_redirect_status.as_deref(), Some("307"));
            assert_eq!(oast_dns_rebind_ip.as_deref(), Some("169.254.169.254"));
            return;
        }
        panic!("expected pentest run");
    }

    #[test]
    fn redirect_and_rebinding_options_require_the_listener() {
        for options in [
            vec!["--oast-redirect-location", "http://internal.example/"],
            vec!["--oast-redirect-status", "307"],
            vec!["--oast-dns-rebind-ip", "169.254.169.254"],
            vec![
                "--oast-listener",
                "127.0.0.1",
                "--oast-dns-rebind-ip",
                "169.254.169.254",
            ],
            vec![
                "--oast-listener",
                "127.0.0.1",
                "--oast-redirect-status",
                "303",
            ],
        ] {
            let mut argv = base();
            argv.extend(options);
            assert!(Cli::try_parse_from(&argv).is_err());
        }
    }
}

// @comment -- "unit tests for the Track B CI-auth surface (auth import / auth verify subcommands, and run's --ci/--auth-dir). Track B shipped to the Python orchestrator's argparse only; src/cli.rs was never updated, so the cxg binary rejected the whole surface with 'unexpected argument'. These pin that each subcommand and flag now parses, that the auth capture path is unchanged when no subcommand is given, that the import/verify subcommands do NOT demand the capture path's --target/--profile (the reason those two are Option at the parent), and that the mutually-exclusive capture-args-vs-subcommand constraint holds."
#[cfg(test)]
mod track_b_auth_tests {
    use super::*;

    #[test]
    fn auth_capture_and_list_accept_auth_dir() {
        for args in [
            vec![
                "cxg",
                "pentest",
                "auth",
                "--target",
                "https://x",
                "--profile",
                "p",
                "--auth-dir",
                "./profiles",
            ],
            vec!["cxg", "pentest", "auth-list", "--auth-dir", "./profiles"],
        ] {
            match action(&args) {
                PentestAction::Auth { auth_dir, .. } | PentestAction::AuthList { auth_dir } => {
                    assert_eq!(auth_dir, Some(PathBuf::from("./profiles")));
                }
                _ => panic!("expected auth action"),
            }
        }
    }

    fn action(args: &[&str]) -> PentestAction {
        let cli = Cli::try_parse_from(args).expect("should parse");
        match cli.command {
            Some(Commands::Pentest(p)) => p.action,
            _ => panic!("expected pentest"),
        }
    }

    fn err(args: &[&str]) -> bool {
        Cli::try_parse_from(args).is_err()
    }

    // ---- auth import ----

    #[test]
    fn auth_import_parses_full_surface() {
        let a = action(&[
            "cxg",
            "pentest",
            "auth",
            "import",
            "--profile",
            "pentest",
            "--target",
            "https://staging.app",
            "--storage-state",
            "./s.json",
            "--label",
            "admin",
            "--tier",
            "high",
            "--persona",
            "billing",
            "--cohort",
            "team-a",
            "--tag",
            "k1=v1",
            "--tag",
            "k2=v2",
            "--header",
            "x-a:1",
            "--header",
            "x-b:2",
            "--auth-dir",
            "./ci-auth",
            "--liveness-path",
            "/session",
            "--liveness-status",
            "200",
            "--liveness-status",
            "204",
            "--service",
            "community",
            "--ci",
        ]);
        match a {
            PentestAction::Auth {
                auth_sub:
                    Some(AuthSubcommand::Import {
                        profile,
                        target,
                        storage_state,
                        label,
                        tier,
                        persona,
                        cohort,
                        tags,
                        headers,
                        auth_dir,
                        liveness_path,
                        liveness_status,
                        service,
                        ci,
                    }),
                ..
            } => {
                assert_eq!(profile, "pentest");
                assert_eq!(target, "https://staging.app");
                assert_eq!(storage_state.as_deref(), Some("./s.json"));
                assert_eq!(label.as_deref(), Some("admin"));
                assert_eq!(tier.as_deref(), Some("high"));
                assert_eq!(persona.as_deref(), Some("billing"));
                assert_eq!(cohort.as_deref(), Some("team-a"));
                assert_eq!(tags, vec!["k1=v1", "k2=v2"]);
                assert_eq!(headers, vec!["x-a:1", "x-b:2"]);
                assert_eq!(auth_dir.as_deref(), Some(std::path::Path::new("./ci-auth")));
                assert!(ci);
                assert_eq!(liveness_path.as_deref(), Some("/session"));
                assert_eq!(liveness_status, vec![200, 204]);
                assert_eq!(service.as_deref(), Some("community"));
            }
            _ => panic!("expected auth import"),
        }
    }

    // The whole point of Option-typed parent --target/--profile: `auth import`
    // must NOT inherit the capture path's requirements, only its own.
    #[test]
    fn auth_import_does_not_require_parent_target_or_profile() {
        // import supplies its own --profile/--target and nothing at the parent level.
        let a = action(&[
            "cxg",
            "pentest",
            "auth",
            "import",
            "--profile",
            "p",
            "--target",
            "https://x",
        ]);
        match a {
            PentestAction::Auth {
                target,
                profile,
                auth_sub:
                    Some(AuthSubcommand::Import {
                        storage_state, ci, ..
                    }),
                ..
            } => {
                // parent capture fields stay unset
                assert_eq!(target, None);
                assert_eq!(profile, None);
                // omitting --storage-state is valid (env-var fallback on the Python side)
                assert_eq!(storage_state, None);
                assert!(!ci);
            }
            _ => panic!("expected auth import"),
        }
    }

    #[test]
    fn auth_import_stdin_marker_is_a_value() {
        let a = action(&[
            "cxg",
            "pentest",
            "auth",
            "import",
            "--profile",
            "p",
            "--target",
            "https://x",
            "--storage-state",
            "-",
        ]);
        match a {
            PentestAction::Auth {
                auth_sub: Some(AuthSubcommand::Import { storage_state, .. }),
                ..
            } => assert_eq!(storage_state.as_deref(), Some("-")),
            _ => panic!("expected auth import"),
        }
    }

    #[test]
    fn auth_import_requires_profile_and_target() {
        assert!(
            err(&["cxg", "pentest", "auth", "import", "--target", "https://x"]),
            "import without --profile must fail"
        );
        assert!(
            err(&["cxg", "pentest", "auth", "import", "--profile", "p"]),
            "import without --target must fail"
        );
    }

    // ---- auth verify ----

    #[test]
    fn auth_verify_parses_with_defaults() {
        let a = action(&["cxg", "pentest", "auth", "verify", "--profile", "pentest"]);
        match a {
            PentestAction::Auth {
                auth_sub:
                    Some(AuthSubcommand::Verify {
                        profile,
                        target,
                        me_path,
                        auth_dir,
                    }),
                ..
            } => {
                assert_eq!(profile, "pentest");
                assert_eq!(target, None);
                assert_eq!(me_path, "/api/me"); // mirrors auth.py's default
                assert_eq!(auth_dir, None);
            }
            _ => panic!("expected auth verify"),
        }
    }

    #[test]
    fn auth_verify_accepts_overrides() {
        let a = action(&[
            "cxg",
            "pentest",
            "auth",
            "verify",
            "--profile",
            "p",
            "--target",
            "https://y",
            "--me-path",
            "/whoami",
            "--auth-dir",
            "./ci-auth",
        ]);
        match a {
            PentestAction::Auth {
                auth_sub:
                    Some(AuthSubcommand::Verify {
                        target,
                        me_path,
                        auth_dir,
                        ..
                    }),
                ..
            } => {
                assert_eq!(target.as_deref(), Some("https://y"));
                assert_eq!(me_path, "/whoami");
                assert_eq!(auth_dir.as_deref(), Some(std::path::Path::new("./ci-auth")));
            }
            _ => panic!("expected auth verify"),
        }
    }

    #[test]
    fn auth_verify_requires_profile() {
        assert!(
            err(&["cxg", "pentest", "auth", "verify"]),
            "verify without --profile must fail"
        );
    }

    // ---- interactive capture path is unchanged (no subcommand) ----

    #[test]
    fn bare_auth_capture_still_parses_and_leaves_sub_none() {
        let a = action(&[
            "cxg",
            "pentest",
            "auth",
            "--target",
            "https://x",
            "--profile",
            "p",
        ]);
        match a {
            PentestAction::Auth {
                target,
                profile,
                auth_sub,
                ..
            } => {
                assert_eq!(target.as_deref(), Some("https://x"));
                assert_eq!(profile.as_deref(), Some("p"));
                assert!(auth_sub.is_none(), "no subcommand => interactive capture");
            }
            _ => panic!("expected auth capture"),
        }
    }

    // Capture args and a subcommand are mutually exclusive on one invocation
    // (args_conflicts_with_subcommands): you either capture, or import/verify.
    #[test]
    fn capture_args_conflict_with_subcommand() {
        assert!(
            err(&[
                "cxg",
                "pentest",
                "auth",
                "--target",
                "https://x",
                "import",
                "--profile",
                "p",
                "--target",
                "https://x",
            ]),
            "parent capture args must conflict with a subcommand"
        );
    }

    // ---- run --ci / --auth-dir ----

    #[test]
    fn run_ci_and_auth_dir_parse() {
        let a = action(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "https://x",
            "--ci",
            "--auth-dir",
            "./ci-auth",
        ]);
        match a {
            PentestAction::Run(PentestRunArgs {
                ci,
                probe_inputs: ProbeInputs { auth_dir, .. },
                ..
            }) => {
                assert!(ci);
                assert_eq!(auth_dir.as_deref(), Some(std::path::Path::new("./ci-auth")));
            }
            _ => panic!("expected pentest run"),
        }
    }

    #[test]
    fn run_defaults_leave_ci_false_and_auth_dir_none() {
        let a = action(&[
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "https://x",
        ]);
        match a {
            PentestAction::Run(PentestRunArgs {
                ci,
                probe_inputs: ProbeInputs { auth_dir, .. },
                ..
            }) => {
                assert!(!ci, "--ci defaults off, so main.rs forwards nothing");
                assert_eq!(auth_dir, None);
            }
            _ => panic!("expected pentest run"),
        }
    }
}

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

    #[test]
    fn web_transport_flags_parse_and_require_a_certificate_pair() {
        let base = [
            "cxg",
            "pentest",
            "run",
            "--codebase",
            ".",
            "--target",
            "https://example.test",
        ];
        let mut argv = base.to_vec();
        argv.extend([
            "--insecure-tls",
            "--proxy",
            "http://127.0.0.1:8080",
            "--client-cert",
            "client.pem",
            "--client-key",
            "client.key",
        ]);
        let cli = Cli::try_parse_from(argv).unwrap();
        match cli.command {
            Some(Commands::Pentest(PentestCommand {
                action:
                    PentestAction::Run(PentestRunArgs {
                        insecure_tls,
                        proxy,
                        client_cert,
                        client_key,
                        ..
                    }),
            })) => {
                assert!(insecure_tls);
                assert_eq!(proxy.as_deref(), Some("http://127.0.0.1:8080"));
                assert_eq!(client_cert, Some(PathBuf::from("client.pem")));
                assert_eq!(client_key, Some(PathBuf::from("client.key")));
            }
            _ => panic!("expected pentest run"),
        }
        for flag in ["--client-cert", "--client-key"] {
            let mut argv = base.to_vec();
            argv.extend([flag, "file.pem"]);
            assert!(Cli::try_parse_from(argv).is_err());
        }
    }
}

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

    #[test]
    fn a_probe_argument_cannot_switch_engines_or_change_scan_validation() {
        let cli = Cli::try_parse_from([
            "cxg",
            "scan",
            "--scope",
            "cli:///bin/tool",
            "--arg",
            "--pentest",
            "--templates",
            "baseline",
            "--template-dir",
            "./pack",
        ])
        .unwrap();
        match cli.command {
            Some(Commands::Scan(scan)) => {
                assert_eq!(scan.arg, ["--pentest"]);
                assert_eq!(scan.templates, ["baseline"]);
                assert_eq!(scan.template_dir, Some(PathBuf::from("./pack")));
                assert!(!scan.pentest);
            }
            _ => panic!("probe argument switched engines"),
        }
        let error =
            Cli::try_parse_from(["cxg", "scan", "--arg", "--pentest", "--help"]).unwrap_err();
        assert_eq!(error.kind(), clap::error::ErrorKind::DisplayHelp);
        assert!(error.to_string().contains("--parallel-targets"));
    }

    #[test]
    fn globals_and_switch_position_are_parsed_by_clap() {
        let cli = Cli::try_parse_from([
            "cxg",
            "--config",
            "scan",
            "scan",
            "--codebase",
            ".",
            "--target-type",
            "tauri",
            "--pentest",
        ])
        .unwrap();
        assert_eq!(cli.config, Some(PathBuf::from("scan")));
        assert!(
            matches!(cli.command, Some(Commands::Pentest(PentestCommand {
            action: PentestAction::Run(PentestRunArgs { target_type, target: None, .. })
        })) if target_type == "tauri")
        );
    }

    #[test]
    fn replay_inputs_preserve_bare_optional_values_and_repeated_options() {
        let parsed = Cli::try_parse_from([
            "cxg",
            "scan",
            "--scope",
            "http://localhost",
            "--oast-listener",
            "--only-route",
            "GET /a",
            "--only-route",
            "POST /b",
        ])
        .unwrap();
        let Some(Commands::Scan(scan)) = parsed.command else {
            panic!("expected scan")
        };
        let run = scan.probe_run.unwrap();
        assert_eq!(run.oast_listener.as_deref(), Some(""));
        assert_eq!(run.only_route, ["GET /a", "POST /b"]);
    }

    #[test]
    fn plain_scan_reuses_non_authoring_engine_values_and_constraints() {
        let parsed = Cli::try_parse_from([
            "cxg",
            "scan",
            "--scope",
            "http://localhost",
            "--no-author",
            "--no-code-graph",
            "--attestation",
            "local fixture",
            "--mitigation-mode",
            "mitigated",
            "--me-path",
            "/identity",
            "--ci",
            "--enable-chaining",
            "--template-timeout",
            "1.25",
            "--stall-timeout",
            "9.5",
            "--destructive-ok",
            "--allow-grpc",
            "--grpc-descriptor-set",
            "descriptors.pb",
            "--tauri-prove",
            "--host-scan-path",
            "/fixture/install",
        ])
        .unwrap();
        let Some(Commands::Scan(scan)) = parsed.command else {
            panic!("expected scan")
        };
        let run = scan.probe_run.unwrap();
        assert!(run.probe_inputs.no_author && run.no_code_graph && run.ci && run.enable_chaining);
        assert_eq!(run.attestation.as_deref(), Some("local fixture"));
        assert_eq!(run.mitigation_mode, "mitigated");
        assert_eq!(run.me_path, "/identity");
        assert_eq!(run.template_timeout, Some(1.25));
        assert_eq!(run.stall_timeout, Some(9.5));
        assert!(run.destructive_ok && run.allow_grpc && run.tauri_prove);
        assert_eq!(run.grpc_descriptor_set.as_deref(), Some("descriptors.pb"));
        assert_eq!(run.host_scan_path.as_deref(), Some("/fixture/install"));
        assert!(Cli::try_parse_from(["cxg", "scan", "--client-cert", "cert.pem"]).is_err());
        assert!(Cli::try_parse_from(["cxg", "scan", "--ai"]).is_err());
        assert!(Cli::try_parse_from(["cxg", "scan", "--mutation-retries", "1"]).is_err());
    }

    #[test]
    fn ordinary_scan_accepts_shared_probe_inputs_and_defaults_codebase() {
        let parsed = Cli::try_parse_from([
            "cxg",
            "scan",
            "--scope",
            "https://example.test",
            "--auth",
            "attacker,victim",
            "--auth-dir",
            "profiles",
            "--auth-inputs",
            "inputs.json",
            "--scope-file",
            "scope.yaml",
            "--session-dir",
            "session",
        ])
        .unwrap();
        let Some(Commands::Scan(args)) = parsed.command else {
            panic!("expected scan")
        };
        assert_eq!(args.probe_inputs.codebase, PathBuf::from("."));
        assert_eq!(args.probe_inputs.auth, "attacker,victim");
        assert_eq!(args.probe_inputs.auth_dir, Some(PathBuf::from("profiles")));
        assert_eq!(
            args.probe_inputs.auth_inputs,
            Some(PathBuf::from("inputs.json"))
        );
        assert_eq!(
            args.probe_inputs.scope_file,
            Some(PathBuf::from("scope.yaml"))
        );
        assert_eq!(
            args.probe_inputs.session_dir,
            Some(PathBuf::from("session"))
        );
        assert!(
            Cli::try_parse_from(["cxg", "pentest", "run", "--target", "https://example.test"])
                .is_err()
        );
    }

    #[test]
    fn pentest_scan_requires_a_codebase_and_rejects_duplicate_targets() {
        let error = Cli::try_parse_from(["cxg", "scan", "--pentest"]).unwrap_err();
        assert_eq!(
            error.kind(),
            clap::error::ErrorKind::MissingRequiredArgument
        );
        assert!(error.to_string().contains("--codebase"));
        assert!(Cli::try_parse_from([
            "cxg",
            "scan",
            "--pentest",
            "--codebase",
            ".",
            "--scope",
            "https://a.test",
            "--target",
            "https://b.test",
        ])
        .unwrap_err()
        .to_string()
        .contains("one target"));
    }
}