ktstr 0.5.2

Test harness for Linux process schedulers
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
//! Clap parse tests for the cargo-ktstr CLI surface.
//!
//! Lives outside the bin entry file so the entry stays focused on
//! dispatch, and mirrors the shape used elsewhere in the workspace
//! where parse-only test fixtures cluster in their own module. The
//! tests assert the user-visible spelling of every `--flag` and
//! the round-trip of clap-parsed values into the variant fields,
//! so a derive-rename or attribute drop surfaces here at compile-
//! time / test-time rather than in production.
//!
//! # Coverage shape
//!
//! Every [`KtstrCommand`] variant has at least one positive test
//! that round-trips an argument through clap into the variant's
//! fields, plus negative tests for `requires` / `conflicts_with` /
//! `value_parser` constraints clap enforces at parse time.
//!
//! Sections are separated by `// -- <theme> --` banners.
//!
//! # External pins
//!
//! The `kconfig_status_*` and `format_entry_row_*` fixtures
//! co-pin the [`ktstr::cache::CacheEntry`] /
//! [`ktstr::cache::KernelMetadata`] shape; if the cache types'
//! constructors, methods, or variants change, those tests must
//! be updated in lockstep with the production types in
//! [`ktstr::cache`].
//!
//! # Why parse-only
//!
//! These tests deliberately do not invoke any subcommand body —
//! they verify that clap parses what we expect into the type-system
//! shape the body matches against. Behaviour-level coverage of each
//! handler lives next to its production code (e.g. `kernel.rs`'s
//! `tests` module exercises label collision detection;
//! `verifier.rs` exercises profile expansion).

#![cfg(test)]

use clap::{CommandFactory, Parser};
use ktstr::cache::{CacheArtifacts, CacheDir, CacheEntry, KernelMetadata};
use ktstr::cli;
use ktstr::cli::KernelCommand;

use crate::cli::{Cargo, CargoSub, KtstrCommand, ModelCommand, StatsCommand};

// -- DRY helpers for the parse-only test surface --
//
// These helpers collapse the ~30-line boilerplate that every
// destructuring parse test repeats — build args, `try_parse_from`,
// destructure the `Cargo { CargoSub::Ktstr } -> KtstrCommand`
// outer chrome, and panic with a recognisable "expected X"
// message on a wrong-variant parse.
//
// Helpers panic on the wrong variant rather than returning
// `Result` because every call site is already in a `#[test]`
// where the panic IS the failure mode. Returning the variant
// by value (not by reference) lets the call site bind owned
// fields with a let-else destructure rather than yet another
// indirection.

/// Parse a `cargo ktstr stats compare` invocation with the given
/// trailing arguments and return the [`StatsCommand`] variant
/// guaranteed to be `Compare { .. }`. Panics if clap rejects the
/// invocation or the parsed variant is anything else.
///
/// Call sites bind the Compare fields with a `let-else`:
///
/// ```ignore
/// let StatsCommand::Compare { threshold, filter, .. } =
///     parse_compare(&["--a-kernel", "6.14", "--b-kernel", "6.15"])
/// else {
///     unreachable!()
/// };
/// ```
fn parse_compare(extra: &[&str]) -> StatsCommand {
    let mut argv: Vec<&str> = vec!["cargo", "ktstr", "stats", "compare"];
    argv.extend(extra.iter().copied());
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(argv).unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Stats {
        command: Some(sc), ..
    } = k.command
    else {
        panic!("expected Stats");
    };
    assert!(
        matches!(sc, StatsCommand::Compare { .. }),
        "expected Stats Compare",
    );
    sc
}

/// Build a `cargo ktstr <subcommand> -- <passthrough...>` invocation,
/// parse it, and assert that the trailing args round-trip verbatim
/// into the variant's `args` Vec without spuriously populating any
/// of the named flags (`--kernel`, `--no-perf-mode`, `--release`).
///
/// `subcommand` must be one of the passthrough-bearing subcommands:
/// `test`, `nextest` (alias), `coverage`, `llvm-cov`. Other
/// subcommands panic with an actionable error.
fn assert_passthrough_args(subcommand: &str, passthrough: &[&str]) {
    let mut argv: Vec<&str> = vec!["cargo", "ktstr", subcommand, "--"];
    argv.extend(passthrough.iter().copied());
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(argv).unwrap_or_else(|e| panic!("{e}"));

    let expected: Vec<String> = passthrough.iter().map(|s| s.to_string()).collect();
    match k.command {
        KtstrCommand::Test {
            kernel,
            no_perf_mode,
            no_skip_mode,
            release,
            args,
        } => {
            assert!(
                kernel.is_empty(),
                "bare `--` passthrough must not spuriously populate --kernel",
            );
            assert!(
                !no_perf_mode,
                "bare `--` passthrough must not spuriously set --no-perf-mode",
            );
            assert!(
                !no_skip_mode,
                "bare `--` passthrough must not spuriously set --no-skip-mode",
            );
            assert!(
                !release,
                "bare `--` passthrough must not spuriously set --release",
            );
            assert_eq!(args, expected);
        }
        KtstrCommand::Coverage {
            kernel,
            no_perf_mode,
            no_skip_mode,
            release,
            args,
        } => {
            assert!(
                kernel.is_empty(),
                "bare `--` passthrough must not spuriously populate --kernel",
            );
            assert!(
                !no_perf_mode,
                "bare `--` passthrough must not spuriously set --no-perf-mode",
            );
            assert!(
                !no_skip_mode,
                "bare `--` passthrough must not spuriously set --no-skip-mode",
            );
            assert!(
                !release,
                "bare `--` passthrough must not spuriously set --release",
            );
            assert_eq!(args, expected);
        }
        KtstrCommand::LlvmCov {
            kernel,
            no_perf_mode,
            no_skip_mode,
            args,
        } => {
            assert!(
                kernel.is_empty(),
                "bare `--` passthrough must not spuriously populate --kernel",
            );
            assert!(
                !no_perf_mode,
                "bare `--` passthrough must not spuriously set --no-perf-mode",
            );
            assert!(
                !no_skip_mode,
                "bare `--` passthrough must not spuriously set --no-skip-mode",
            );
            assert_eq!(args, expected);
        }
        _ => panic!("expected passthrough-bearing variant for `{subcommand}`"),
    }
}

// -- structural validation --

/// Run clap's structural self-check on the entire [`Cargo`] derive tree.
///
/// `clap::Command::debug_assert` walks every subcommand, every
/// arg, every group, and every relationship (`conflicts_with`,
/// `requires`, `default_value_if`, `value_parser`, …) and panics
/// at test time on issues that would otherwise surface as cryptic
/// runtime parse errors or silent UX bugs:
///
///   - duplicate arg / subcommand IDs
///   - dangling references in `conflicts_with` / `requires`
///   - default values that fail the arg's `value_parser`
///   - help/version conflicts with user-defined args
///   - misordered positionals (greedy followed by non-greedy)
///
/// Upstream clap recommends running this helper in a unit test for
/// every derive root; we put it FIRST in the parse-tests file so
/// any structural break stops the rest of the suite immediately
/// rather than producing a wall of less-informative downstream
/// failures from individual `try_parse_from` calls.
#[test]
fn cli_debug_assert() {
    Cargo::command().debug_assert();
}

// -- try_get_matches_from: test subcommand --

#[test]
fn parse_test_minimal() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "test"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

#[test]
fn parse_test_with_kernel() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "test", "--kernel", "6.14.2"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

/// `--release` on `test` parses to `KtstrCommand::Test { release:
/// true, .. }` so `run_test` prepends `--cargo-profile release`
/// to the cargo nextest invocation. A clap regression that
/// dropped the flag would turn the user-visible `--release` into
/// either a silent no-op (default false) or a passthrough-arg
/// typo — this test pins the clap-level wiring.
#[test]
fn parse_test_with_release_flag() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "test", "--release"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Test { release, .. } = k.command else {
        panic!("expected Test");
    };
    assert!(release, "`--release` must set `release=true`");
}

/// Pin `trailing_var_arg` args forwarded verbatim after `--`.
#[test]
fn parse_test_with_passthrough_args() {
    assert_passthrough_args("test", &["-p", "ktstr", "--no-capture"]);
}

// -- try_get_matches_from: `test` visible alias `nextest` --

/// `cargo ktstr nextest` resolves to the canonical `Test`
/// variant. `visible_alias = "nextest"` on the variant makes
/// the alias user-facing (shows in --help) and dispatch-
/// transparent (the existing `KtstrCommand::Test` arm handles
/// both spellings). A regression that dropped the attribute
/// would fail this test at runtime.
#[test]
fn parse_nextest_alias_dispatches_to_test() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "nextest"]).unwrap_or_else(|e| panic!("{e}"));
    assert!(
        matches!(k.command, KtstrCommand::Test { .. }),
        "`nextest` alias must dispatch to the Test variant",
    );
}

/// `nextest` alias carries trailing args through the same
/// `trailing_var_arg` pipeline as `test`. Pins the alias's
/// passthrough behaviour byte-exactly so a clap regression
/// that treated the alias as a distinct parse tree surfaces
/// here rather than in runtime dispatch.
#[test]
fn parse_nextest_alias_with_passthrough_args() {
    assert_passthrough_args("nextest", &["-p", "ktstr", "--no-capture"]);
}

/// Verify the `nextest` alias preserves all Test fields in a
/// single invocation: `--kernel`, `--no-perf-mode`, and empty
/// trailing `args`. A clap regression that silently dropped a
/// field on the alias path (e.g. a derive bug that re-generated
/// the subcommand without inheriting the Test variant's args)
/// would surface here.
#[test]
fn parse_nextest_alias_with_kernel_and_no_perf_mode() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "nextest",
        "--kernel",
        "6.14.2",
        "--no-perf-mode",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Test {
        kernel,
        no_perf_mode,
        no_skip_mode,
        release,
        args,
    } = k.command
    else {
        panic!("expected Test (via `nextest` alias)");
    };
    assert_eq!(kernel, vec!["6.14.2".to_string()]);
    assert!(no_perf_mode);
    assert!(!no_skip_mode);
    assert!(!release, "bare invocation must default --release to false");
    assert!(args.is_empty());
}

// -- try_get_matches_from: coverage subcommand --

#[test]
fn parse_coverage_minimal() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "coverage"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

#[test]
fn parse_coverage_with_kernel() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "coverage", "--kernel", "6.14.2"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

/// `--release` on `coverage` parses to `KtstrCommand::Coverage
/// { release: true, .. }` so `run_coverage` prepends
/// `--cargo-profile release` to the cargo llvm-cov nextest
/// invocation. Same rationale as the sibling
/// `parse_test_with_release_flag` — pins the clap-level wiring
/// against a regression that turns the flag into a no-op.
#[test]
fn parse_coverage_with_release_flag() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "coverage", "--release"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Coverage { release, .. } = k.command else {
        panic!("expected Coverage");
    };
    assert!(release, "`--release` must set `release=true`");
}

/// Pin `trailing_var_arg` args forwarded verbatim after `--`.
#[test]
fn parse_coverage_with_passthrough_args() {
    assert_passthrough_args(
        "coverage",
        &["--workspace", "--lcov", "--output-path", "lcov.info"],
    );
}

/// Combined round-trip for Coverage: `--kernel`, `--no-perf-mode`,
/// AND trailing args all populate on a single invocation. Mirrors
/// `parse_llvm_cov_with_kernel_and_no_perf_mode` — a clap
/// regression that dropped one field on the multi-flag path (or
/// mis-ordered `--` with flags) would surface here for the
/// Coverage variant.
#[test]
fn parse_coverage_with_kernel_and_no_perf_mode() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "coverage",
        "--kernel",
        "6.14.2",
        "--no-perf-mode",
        "--",
        "--workspace",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Coverage {
        kernel,
        no_perf_mode,
        no_skip_mode,
        release,
        args,
    } = k.command
    else {
        panic!("expected Coverage");
    };
    assert_eq!(kernel, vec!["6.14.2".to_string()]);
    assert!(no_perf_mode);
    assert!(!no_skip_mode);
    assert!(!release, "bare invocation must default --release to false");
    assert_eq!(args, vec!["--workspace"]);
}

// -- try_get_matches_from: llvm-cov raw passthrough subcommand --

#[test]
fn parse_llvm_cov_minimal() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "llvm-cov"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

#[test]
fn parse_llvm_cov_with_kernel() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "llvm-cov", "--kernel", "6.14.2"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::LlvmCov { kernel, .. } = k.command else {
        panic!("expected LlvmCov");
    };
    assert_eq!(kernel, vec!["6.14.2".to_string()]);
}

/// Pin `trailing_var_arg` args forwarded verbatim after `--`.
#[test]
fn parse_llvm_cov_with_passthrough_args() {
    assert_passthrough_args(
        "llvm-cov",
        &["report", "--lcov", "--output-path", "lcov.info"],
    );
}

/// Combined round-trip: `--kernel`, `--no-perf-mode`, AND
/// trailing args all populate on a single LlvmCov invocation.
/// A clap regression that dropped one field on the multi-flag
/// path (or mis-ordered `--` with flags) would surface here.
#[test]
fn parse_llvm_cov_with_kernel_and_no_perf_mode() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "llvm-cov",
        "--kernel",
        "6.14.2",
        "--no-perf-mode",
        "--",
        "report",
        "--lcov",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::LlvmCov {
        kernel,
        no_perf_mode,
        no_skip_mode,
        args,
    } = k.command
    else {
        panic!("expected LlvmCov");
    };
    assert_eq!(kernel, vec!["6.14.2".to_string()]);
    assert!(no_perf_mode);
    assert!(!no_skip_mode);
    assert_eq!(args, vec!["report", "--lcov"]);
}

/// Negative pin: the variant is `LlvmCov`, and clap derive's
/// default casing is kebab-case (see clap_derive
/// `DEFAULT_CASING`), so the subcommand name is `llvm-cov`,
/// NOT `llvm_cov`. A regression that switched the derive's
/// rename_all default (or silently aliased the underscore
/// form) would turn this negative pin positive. The parent-
/// level `aliases` slot is empty, so clap rejects the
/// underscore form with an unknown-subcommand error.
#[test]
fn parse_llvm_cov_underscore_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "llvm_cov"]);
    assert!(
        rejected.is_err(),
        "`llvm_cov` (underscore) must be rejected — the \
         canonical name is `llvm-cov` (kebab-case)",
    );
}

/// Positive companion to [`parse_llvm_cov_underscore_rejected`]:
/// the kebab-case form `llvm-cov` MUST resolve to
/// [`KtstrCommand::LlvmCov`] without alias indirection. The
/// existing `parse_llvm_cov_minimal` exercises the spelling but
/// only asserts `is_ok()` — this test pins the variant binding
/// so that a future rename of the derive variant or the
/// subcommand attribute (e.g. `command(name = "llvm-coverage")`)
/// surfaces here as a variant-mismatch panic instead of silently
/// breaking under a renamed-but-still-parseable form.
#[test]
fn parse_llvm_cov_kebab_accepted() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "llvm-cov"]).unwrap_or_else(|e| panic!("{e}"));
    assert!(
        matches!(k.command, KtstrCommand::LlvmCov { .. }),
        "kebab `llvm-cov` must bind to KtstrCommand::LlvmCov",
    );
}

// -- try_get_matches_from: shell subcommand --

#[test]
fn parse_shell_minimal() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "shell"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

#[test]
fn parse_shell_with_topology() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "shell", "--topology", "1,2,4,1"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell { topology, .. } = k.command else {
        panic!("expected Shell");
    };
    assert_eq!(topology, "1,2,4,1");
}

#[test]
fn parse_shell_default_topology() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "shell"]).unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell { topology, .. } = k.command else {
        panic!("expected Shell");
    };
    assert_eq!(topology, "1,1,1,1");
}

/// Pin `-i` / `--include-files` `ArgAction::Append` round-trip with ordering.
#[test]
fn parse_shell_include_files() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "shell", "-i", "/tmp/a", "-i", "/tmp/b"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell { include_files, .. } = k.command else {
        panic!("expected Shell");
    };
    assert_eq!(
        include_files,
        vec![
            std::path::PathBuf::from("/tmp/a"),
            std::path::PathBuf::from("/tmp/b"),
        ],
        "-i flag must accumulate paths in order via ArgAction::Append",
    );
}

/// `cargo ktstr shell --disk 256mib` parses; the disk arg lands as
/// `Some("256mib")` on the `Shell` variant. The string is parsed
/// into a `DiskConfig` later in `run_shell` via
/// [`ktstr::cli::parse_disk_size_mib`]; the clap stage stores the
/// raw string so a malformed input surfaces with the consistent
/// disk-size diagnostic instead of a generic clap parse error.
#[test]
fn parse_shell_disk_arg() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "shell", "--disk", "256mib"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell { disk, .. } = k.command else {
        panic!("expected Shell");
    };
    assert_eq!(disk.as_deref(), Some("256mib"));
}

/// Omitting `--disk` produces `None`, matching the no-disk default
/// in `run_shell` and `KtstrVm::builder`.
#[test]
fn parse_shell_disk_arg_omitted() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "shell"]).unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell { disk, .. } = k.command else {
        panic!("expected Shell");
    };
    assert!(disk.is_none(), "no --disk must produce None");
}

// -- try_get_matches_from: stats subcommand --

#[test]
fn parse_stats_bare() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "stats"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

#[test]
fn parse_stats_list() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "stats", "list"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

/// `cargo ktstr stats list-metrics` parses (no flags required)
/// and dispatches to the `ListMetrics` variant with `json=false`.
#[test]
fn parse_stats_list_metrics_bare() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "stats", "list-metrics"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Stats {
        command: Some(StatsCommand::ListMetrics { json }),
        ..
    } = k.command
    else {
        panic!("expected Stats ListMetrics");
    };
    assert!(
        !json,
        "bare `list-metrics` must default to text mode (json=false)",
    );
}

/// `cargo ktstr stats list-metrics --json` sets `json=true`.
/// Pins the flag name so a clap-derive-default rename
/// (kebab-case) cannot drift — `--json` is the same flag name
/// other list-style subcommands use (e.g. `kernel list --json`).
#[test]
fn parse_stats_list_metrics_json() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "stats", "list-metrics", "--json"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Stats {
        command: Some(StatsCommand::ListMetrics { json }),
        ..
    } = k.command
    else {
        panic!("expected Stats ListMetrics");
    };
    assert!(json, "--json must set the flag true");
}

/// `list-metrics` takes no positional args — a stray positional
/// must be rejected by clap so a typo like `list-metrics
/// worst_spread` doesn't silently look like success.
#[test]
fn parse_stats_list_metrics_rejects_positional() {
    let rejected =
        Cargo::try_parse_from(["cargo", "ktstr", "stats", "list-metrics", "worst_spread"]);
    assert!(
        rejected.is_err(),
        "list-metrics must reject positional arguments",
    );
}

/// `cargo ktstr stats list-values` parses with no flags and
/// dispatches to the `ListValues` variant with `json=false` and
/// `dir=None`. Pins the bare-call defaults.
#[test]
fn parse_stats_list_values_bare() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "stats", "list-values"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Stats {
        command: Some(StatsCommand::ListValues { json, dir }),
        ..
    } = k.command
    else {
        panic!("expected Stats ListValues");
    };
    assert!(!json, "bare `list-values` must default to text mode");
    assert!(
        dir.is_none(),
        "bare `list-values` must default to no --dir override"
    );
}

/// `cargo ktstr stats list-values --json` sets `json=true`.
/// Pins the flag name so the same `--json` convention used by
/// `list-metrics` and `kernel list` carries here too.
#[test]
fn parse_stats_list_values_json() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "stats", "list-values", "--json"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Stats {
        command: Some(StatsCommand::ListValues { json, .. }),
        ..
    } = k.command
    else {
        panic!("expected Stats ListValues");
    };
    assert!(json, "--json must set the flag true");
}

/// `cargo ktstr stats list-values --dir PATH` round-trips the
/// path through clap to the dispatch site. Same `--dir`
/// convention as `compare --dir` and `show-host --dir`.
#[test]
fn parse_stats_list_values_with_dir() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "stats",
        "list-values",
        "--dir",
        "/tmp/archived-runs",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Stats {
        command: Some(StatsCommand::ListValues { dir, json }),
        ..
    } = k.command
    else {
        panic!("expected Stats ListValues");
    };
    assert_eq!(
        dir.as_deref(),
        Some(std::path::Path::new("/tmp/archived-runs")),
        "--dir must round-trip to Some(PathBuf)",
    );
    assert!(!json, "bare --dir must not spuriously set --json");
}

/// `list-values` takes no positional args — clap must reject
/// strays so a typo like `list-values kernel` (intending a
/// per-dim filter) fails loudly rather than getting silently
/// dropped.
#[test]
fn parse_stats_list_values_rejects_positional() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "stats", "list-values", "kernel"]);
    assert!(
        rejected.is_err(),
        "list-values must reject positional arguments",
    );
}

#[test]
fn parse_stats_compare() {
    // Minimal partition shape: --a-kernel + --b-kernel define
    // the slicing dimension. The dispatch site rejects empty
    // slicing dims, so a bare `cargo ktstr stats compare`
    // would fail at run time — but the CLI parser accepts
    // it (validation belongs in `compare_partitions`, not
    // clap). This test pins the parse layer only.
    let m = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "stats",
        "compare",
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
    ]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

#[test]
fn parse_stats_compare_with_filter() {
    let StatsCommand::Compare {
        filter,
        threshold,
        policy,
        dir,
        a_kernel,
        b_kernel,
        ..
    } = parse_compare(&[
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
        "-E",
        "cgroup_steady",
    ])
    else {
        unreachable!()
    };
    assert_eq!(a_kernel, vec!["6.14"]);
    assert_eq!(b_kernel, vec!["6.15"]);
    assert_eq!(filter.as_deref(), Some("cgroup_steady"));
    assert!(threshold.is_none());
    assert!(policy.is_none());
    assert!(dir.is_none());
}

#[test]
fn parse_stats_compare_with_threshold() {
    let StatsCommand::Compare {
        threshold, filter, ..
    } = parse_compare(&[
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
        "--threshold",
        "5.0",
    ])
    else {
        unreachable!()
    };
    assert_eq!(threshold, Some(5.0));
    assert!(filter.is_none());
}

/// Proves the `dir: Option<PathBuf>` field is wired on
/// `StatsCommand::Compare` and round-trips through clap's arg
/// parser. A regression that removed the struct field would
/// fail this test at compile time; a regression that dropped
/// the dispatch wiring (cargo-ktstr.rs → cli.rs → stats.rs) is
/// outside parse-scope and covered by the resolver's own
/// tests. The sibling `*_with_filter` test pins the
/// `dir.is_none()` default; this one pins the `Some(PathBuf)`
/// branch byte-exactly. Uses an absolute `/tmp/...` path
/// (synthetic, not required to exist) because the parse path
/// does not touch the filesystem — clap produces the `PathBuf`
/// from the raw argument, full stop.
#[test]
fn parse_stats_compare_with_dir() {
    let StatsCommand::Compare {
        filter,
        threshold,
        policy,
        dir,
        ..
    } = parse_compare(&[
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
        "--dir",
        "/tmp/archived-runs",
    ])
    else {
        unreachable!()
    };
    assert_eq!(
        dir.as_deref(),
        Some(std::path::Path::new("/tmp/archived-runs")),
        "--dir must round-trip to Some(PathBuf); \
         parse-scope only — resolver coverage lives \
         with compare_partitions' own tests",
    );
    assert!(
        filter.is_none(),
        "bare --dir must not spuriously populate filter",
    );
    assert!(
        threshold.is_none(),
        "bare --dir must not spuriously populate threshold",
    );
    assert!(
        policy.is_none(),
        "bare --dir must not spuriously populate policy",
    );
}

/// Positive parse pin: `--policy PATH` round-trips to
/// `StatsCommand::Compare { policy: Some(PathBuf(PATH)),
/// threshold: None, ... }`. Mirrors `parse_stats_compare_with_dir`
/// for the `dir` field. Uses an obviously-synthetic path that
/// does not need to exist — the parse path never touches the
/// filesystem; policy loading happens downstream in the
/// dispatch.
#[test]
fn parse_stats_compare_with_policy() {
    let StatsCommand::Compare {
        threshold, policy, ..
    } = parse_compare(&[
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
        "--policy",
        "/tmp/policy.json",
    ])
    else {
        unreachable!()
    };
    assert_eq!(
        policy.as_deref(),
        Some(std::path::Path::new("/tmp/policy.json")),
        "--policy must round-trip to Some(PathBuf); got {policy:?}",
    );
    assert!(
        threshold.is_none(),
        "bare --policy must not populate --threshold",
    );
}

/// Conflict pin: `--threshold` and `--policy` are mutually
/// exclusive at clap parse time. A regression that dropped the
/// `conflicts_with` attribute on either field would turn the
/// dispatch-level `unreachable!()` branch into a runtime panic
/// instead of a parse-time error.
///
/// Matches on [`clap::error::ErrorKind::ArgumentConflict`] rather
/// than the generic `is_err()` so a regression that produces a
/// DIFFERENT clap error (e.g. `MissingRequiredArgument` from a
/// renamed flag, or `UnknownArgument` from a typo'd attribute)
/// surfaces here as the wrong-kind diagnostic instead of being
/// silently masked by a less-specific success-on-any-error pin.
///
/// Uses a match-on-result form rather than `expect_err`/`unwrap_err`
/// because [`Cargo`] does not derive `Debug` — the unwrap helpers
/// require `T: Debug` for their failure-render path, while a direct
/// match avoids the bound entirely.
#[test]
fn parse_stats_compare_threshold_conflicts_with_policy() {
    let result = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "stats",
        "compare",
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
        "--threshold",
        "5.0",
        "--policy",
        "/tmp/policy.json",
    ]);
    match result {
        Ok(_) => panic!("--threshold + --policy must be rejected at parse time"),
        Err(err) => assert_eq!(
            err.kind(),
            clap::error::ErrorKind::ArgumentConflict,
            "expected ArgumentConflict — a different ErrorKind would \
             signal that the conflicts_with attribute regressed in a way \
             the bare is_err() pin would silently mask. Full err: {err}",
        ),
    }
}

/// Bare `compare` defaults `--no-average` to `false` —
/// averaging is the default. `--no-average` must be opt-in
/// for "keep each sidecar distinct" semantics.
#[test]
fn parse_stats_compare_no_average_default_false() {
    let StatsCommand::Compare { no_average, .. } =
        parse_compare(&["--a-kernel", "6.14", "--b-kernel", "6.15"])
    else {
        unreachable!()
    };
    assert!(
        !no_average,
        "bare compare must default --no-average to false so \
         averaging-on remains the default — operators get \
         trial-set folding without an explicit flag.",
    );
}

/// `--no-average` parses as a bare flag (no value) and lifts
/// the `no_average: bool` field on `StatsCommand::Compare`
/// to true. Pins the clap binding so a regression that
/// dropped the derive arg, renamed the flag, or accidentally
/// made it take a value lands at parse time.
#[test]
fn parse_stats_compare_with_no_average() {
    let StatsCommand::Compare {
        no_average,
        threshold,
        policy,
        dir,
        ..
    } = parse_compare(&["--a-kernel", "6.14", "--b-kernel", "6.15", "--no-average"])
    else {
        unreachable!()
    };
    assert!(no_average, "--no-average must lift the flag to true");
    assert!(
        threshold.is_none(),
        "bare --no-average must not spuriously populate --threshold",
    );
    assert!(
        policy.is_none(),
        "bare --no-average must not spuriously populate --policy",
    );
    assert!(
        dir.is_none(),
        "bare --no-average must not spuriously populate --dir",
    );
}

/// `--project-commit V` round-trips to `Compare { project_commit:
/// vec![V], .. }`. Pins the clap binding for the shared
/// `--project-commit` filter on the stats compare subcommand; a
/// regression that removed the derive arg, renamed the flag, or
/// dropped its `ArgAction::Append` would land here at parse time.
#[test]
fn parse_stats_compare_with_project_commit_single() {
    let StatsCommand::Compare {
        project_commit,
        a_project_commit,
        b_project_commit,
        ..
    } = parse_compare(&[
        "--project-commit",
        "abc1234",
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
    ])
    else {
        unreachable!()
    };
    assert_eq!(project_commit, vec!["abc1234"]);
    assert!(
        a_project_commit.is_empty(),
        "shared --project-commit must not populate --a-project-commit",
    );
    assert!(
        b_project_commit.is_empty(),
        "shared --project-commit must not populate --b-project-commit",
    );
}

/// `--project-commit A --project-commit B` produces a Vec with two
/// entries — the flag is `ArgAction::Append`, so multiple
/// occurrences accumulate into the OR-combined filter the dispatch
/// applies. A regression that lost the Append action would
/// drop the first occurrence.
#[test]
fn parse_stats_compare_with_project_commit_repeatable() {
    let StatsCommand::Compare { project_commit, .. } = parse_compare(&[
        "--project-commit",
        "a",
        "--project-commit",
        "b",
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
    ]) else {
        unreachable!()
    };
    assert_eq!(project_commit, vec!["a", "b"]);
}

/// `--kernel-commit V` round-trips to `Compare {
/// kernel_commit: vec![V], .. }`. Pins the clap binding for
/// the shared `--kernel-commit` filter on the stats compare
/// subcommand; a regression that removed the derive arg,
/// renamed the flag, or dropped its `ArgAction::Append`
/// would land here at parse time. Mirrors
/// `parse_stats_compare_with_project_commit_single` for the
/// `kernel_commit` dimension.
#[test]
fn parse_stats_compare_with_kernel_commit_single() {
    let StatsCommand::Compare {
        kernel_commit,
        a_kernel_commit,
        b_kernel_commit,
        ..
    } = parse_compare(&[
        "--kernel-commit",
        "abc1234",
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
    ])
    else {
        unreachable!()
    };
    assert_eq!(kernel_commit, vec!["abc1234"]);
    assert!(
        a_kernel_commit.is_empty(),
        "shared --kernel-commit must not populate --a-kernel-commit",
    );
    assert!(
        b_kernel_commit.is_empty(),
        "shared --kernel-commit must not populate --b-kernel-commit",
    );
}

/// `--kernel-commit A --kernel-commit B` produces a Vec with
/// two entries via `ArgAction::Append`. Mirrors
/// `parse_stats_compare_with_project_commit_repeatable` for the
/// kernel-commit dimension.
#[test]
fn parse_stats_compare_with_kernel_commit_repeatable() {
    let StatsCommand::Compare { kernel_commit, .. } = parse_compare(&[
        "--kernel-commit",
        "a",
        "--kernel-commit",
        "b",
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
    ]) else {
        unreachable!()
    };
    assert_eq!(kernel_commit, vec!["a", "b"]);
}

/// `--scheduler A --scheduler B` produces a Vec with two
/// entries — the flag is `ArgAction::Append` (Vec, not
/// Option), so multiple occurrences accumulate into the
/// OR-combined filter the dispatch applies. Mirrors
/// `parse_stats_compare_with_project_commit_repeatable` for
/// the scheduler dimension. A regression that reverted
/// `scheduler` to `Option<String>` (the pre-conversion shape)
/// would fail this test at parse time — clap's `Option` derive
/// rejects multiple occurrences with a "supplied more than
/// once" diagnostic.
#[test]
fn parse_stats_compare_with_scheduler_repeatable() {
    let StatsCommand::Compare { scheduler, .. } = parse_compare(&[
        "--scheduler",
        "scx_alpha",
        "--scheduler",
        "scx_beta",
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
    ]) else {
        unreachable!()
    };
    assert_eq!(scheduler, vec!["scx_alpha", "scx_beta"]);
}

/// `--topology A --topology B` produces a Vec with two
/// entries via `ArgAction::Append`. Mirrors the scheduler
/// sibling above for the topology dimension. The Display form
/// of `Topology` (e.g. `1n2l4c2t`) is the operator-visible
/// label that flows verbatim through clap into this Vec.
#[test]
fn parse_stats_compare_with_topology_repeatable() {
    let StatsCommand::Compare { topology, .. } = parse_compare(&[
        "--topology",
        "1n2l4c2t",
        "--topology",
        "1n4l2c1t",
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
    ]) else {
        unreachable!()
    };
    assert_eq!(topology, vec!["1n2l4c2t", "1n4l2c1t"]);
}

/// `--work-type A --work-type B` produces a Vec with two
/// entries via `ArgAction::Append`. Mirrors the scheduler /
/// topology siblings above for the work_type dimension.
/// Hyphenated CLI flag (`--work-type`) maps to underscored
/// field name (`work_type`) per clap's default kebab-case
/// rename — pin the field-vs-flag mapping by reading from the
/// underscored field after a hyphenated invocation.
#[test]
fn parse_stats_compare_with_work_type_repeatable() {
    let StatsCommand::Compare { work_type, .. } = parse_compare(&[
        "--work-type",
        "SpinWait",
        "--work-type",
        "PageFaultChurn",
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
    ]) else {
        unreachable!()
    };
    assert_eq!(work_type, vec!["SpinWait", "PageFaultChurn"]);
}

/// `--a-kernel-commit X --b-kernel-commit Y` populates the
/// per-side fields without touching the shared
/// `kernel_commit`. Pins the clap binding for the per-side
/// kernel-commit slicers — required for the
/// `derive_slicing_dims` path to put `KernelCommit` in the
/// slicing-dim set when the operator wants to slice by
/// kernel HEAD.
#[test]
fn parse_stats_compare_with_per_side_kernel_commit() {
    let StatsCommand::Compare {
        kernel_commit,
        a_kernel_commit,
        b_kernel_commit,
        ..
    } = parse_compare(&[
        "--a-kernel-commit",
        "abc1234",
        "--b-kernel-commit",
        "def5678",
    ])
    else {
        unreachable!()
    };
    assert!(
        kernel_commit.is_empty(),
        "per-side --a-kernel-commit / --b-kernel-commit must not \
         populate the shared --kernel-commit vec",
    );
    assert_eq!(a_kernel_commit, vec!["abc1234"]);
    assert_eq!(b_kernel_commit, vec!["def5678"]);
}

/// `cargo ktstr stats show-host --run X` parses to
/// `StatsCommand::ShowHost { run: X, dir: None }`.
#[test]
fn parse_stats_show_host_with_run() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "stats", "show-host", "--run", "my-run-id"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Stats {
        command: Some(StatsCommand::ShowHost { run, dir }),
        ..
    } = k.command
    else {
        panic!("expected Stats ShowHost");
    };
    assert_eq!(run, "my-run-id");
    assert!(dir.is_none(), "bare --run must not populate --dir");
}

/// `cargo ktstr stats show-host --run X --dir PATH` carries
/// both flags through. Same --dir threading contract as
/// `compare` — parse layer preserves the PathBuf; resolution
/// against `runs_root()` is `cli::show_run_host`'s job.
#[test]
fn parse_stats_show_host_with_dir() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "stats",
        "show-host",
        "--run",
        "archive-2024-01-15",
        "--dir",
        "/tmp/archived-runs",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Stats {
        command: Some(StatsCommand::ShowHost { run, dir }),
        ..
    } = k.command
    else {
        panic!("expected Stats ShowHost");
    };
    assert_eq!(run, "archive-2024-01-15");
    assert_eq!(
        dir.as_deref(),
        Some(std::path::Path::new("/tmp/archived-runs")),
    );
}

/// `cargo ktstr stats show-host` WITHOUT `--run` must fail at
/// parse time — the flag is required and clap's default shape
/// says so. A regression that accidentally made `--run`
/// optional would silently let operators invoke the command
/// with no target, producing a no-op failure.
#[test]
fn parse_stats_show_host_missing_run_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "stats", "show-host"]);
    assert!(rejected.is_err(), "stats show-host must require --run",);
}

/// `cargo ktstr stats explain-sidecar --run X` parses to
/// `StatsCommand::ExplainSidecar { run: X, dir: None,
/// json: false }`. Mirrors `parse_stats_show_host_with_run`
/// for the explain-sidecar shape.
#[test]
fn parse_stats_explain_sidecar_with_run() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "stats",
        "explain-sidecar",
        "--run",
        "my-run-id",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Stats {
        command: Some(StatsCommand::ExplainSidecar { run, dir, json }),
        ..
    } = k.command
    else {
        panic!("expected Stats ExplainSidecar");
    };
    assert_eq!(run, "my-run-id");
    assert!(dir.is_none(), "bare --run must not populate --dir");
    assert!(!json, "default output is text, not json");
}

/// `cargo ktstr stats explain-sidecar --run X --dir PATH
/// --json` carries all three flags. Same --dir threading
/// contract as `show-host`; the `--json` flag toggles the
/// aggregate-by-field output shape.
#[test]
fn parse_stats_explain_sidecar_with_dir_and_json() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "stats",
        "explain-sidecar",
        "--run",
        "archive-2024-01-15",
        "--dir",
        "/tmp/archived-runs",
        "--json",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Stats {
        command: Some(StatsCommand::ExplainSidecar { run, dir, json }),
        ..
    } = k.command
    else {
        panic!("expected Stats ExplainSidecar");
    };
    assert_eq!(run, "archive-2024-01-15");
    assert_eq!(
        dir.as_deref(),
        Some(std::path::Path::new("/tmp/archived-runs")),
    );
    assert!(json, "--json must toggle aggregate JSON output");
}

/// `cargo ktstr stats explain-sidecar` WITHOUT `--run` must
/// fail at parse time. Same required-flag contract as
/// `show-host`; without it, an operator could invoke the
/// command with no target.
#[test]
fn parse_stats_explain_sidecar_missing_run_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "stats", "explain-sidecar"]);
    assert!(
        rejected.is_err(),
        "stats explain-sidecar must require --run",
    );
}

// -- try_get_matches_from: kernel list --

#[test]
fn parse_kernel_list() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "kernel", "list"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

#[test]
fn parse_kernel_list_json() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "kernel", "list", "--json"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

/// `kernel list --range R` round-trips to
/// `KernelCommand::List { range: Some(R), .. }` so the
/// dispatch site routes through `kernel_list_range_preview`
/// rather than the cache-walk path. Pins the clap binding
/// for the new `--range` flag — a regression that dropped
/// the `range` field from the Subcommand enum would surface
/// here as a parse rejection.
#[test]
fn parse_kernel_list_range() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "kernel", "list", "--range", "6.12..6.14"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel { command } = k.command else {
        panic!("expected Kernel");
    };
    let KernelCommand::List { json, range } = command else {
        panic!("expected KernelCommand::List, got {command:?}");
    };
    assert!(!json, "bare --range must not enable --json");
    assert_eq!(
        range.as_deref(),
        Some("6.12..6.14"),
        "--range must round-trip the literal spec for \
         dispatch to pass to `expand_kernel_range`",
    );
}

/// `kernel list --range R --json` round-trips both flags.
/// Pins the JSON-output mode is reachable on the range-preview
/// path (a regression that wired `--range` only on the text
/// path would surface here).
#[test]
fn parse_kernel_list_range_with_json() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "list",
        "--range",
        "6.12..6.14",
        "--json",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel { command } = k.command else {
        panic!("expected Kernel");
    };
    let KernelCommand::List { json, range } = command else {
        panic!("expected KernelCommand::List, got {command:?}");
    };
    assert!(json, "--json must round-trip alongside --range");
    assert_eq!(range.as_deref(), Some("6.12..6.14"));
}

/// `--run-source V` round-trips to `Compare { run_source: vec![V],
/// .. }`. Pins the clap binding for the shared `--run-source`
/// filter. Mirrors `parse_stats_compare_with_project_commit_single`
/// for the new dimension; per-side `--a-run-source` /
/// `--b-run-source` are covered by the `_per_side` sibling below.
#[test]
fn parse_stats_compare_with_run_source_single() {
    let StatsCommand::Compare {
        run_source,
        a_run_source,
        b_run_source,
        ..
    } = parse_compare(&[
        "--a-kernel",
        "6.14",
        "--b-kernel",
        "6.15",
        "--run-source",
        "ci",
    ])
    else {
        unreachable!()
    };
    assert_eq!(
        run_source,
        vec!["ci".to_string()],
        "shared --run-source must populate the shared vec",
    );
    assert!(
        a_run_source.is_empty(),
        "shared --run-source must not populate --a-run-source",
    );
    assert!(
        b_run_source.is_empty(),
        "shared --run-source must not populate --b-run-source",
    );
}

/// `--a-run-source A --b-run-source B` round-trips to populated
/// per-side vecs with the shared `run_source` left empty. Pins
/// the per-side override path that
/// `BuildCompareFilters::build` consumes — a regression that
/// merged shared and per-side into one bucket would surface
/// here.
#[test]
fn parse_stats_compare_with_run_source_per_side() {
    let StatsCommand::Compare {
        run_source,
        a_run_source,
        b_run_source,
        ..
    } = parse_compare(&["--a-run-source", "ci", "--b-run-source", "local"])
    else {
        unreachable!()
    };
    assert!(
        run_source.is_empty(),
        "per-side flags must not populate the shared --run-source vec",
    );
    assert_eq!(a_run_source, vec!["ci".to_string()]);
    assert_eq!(b_run_source, vec!["local".to_string()]);
}

// -- try_get_matches_from: kernel build --

#[test]
fn parse_kernel_build_version() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "kernel", "build", "6.14.2"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

#[test]
fn parse_kernel_build_source() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "kernel", "build", "--source", "../linux"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

/// Conflict pin: `--source PATH` and the positional VERSION are
/// mutually exclusive at clap parse time. Catches a regression
/// that drops the `conflicts_with` (or its equivalent
/// `requires_ifs` shape) on the source flag and lets a contradictory
/// `--source ../linux 6.14.2` invocation flow into the dispatcher,
/// where `kernel build` would have to disambiguate a "use this
/// tree" hint from a "fetch this version" hint at runtime.
#[test]
fn parse_kernel_build_source_conflicts_with_version() {
    let result = Cargo::try_parse_from([
        "cargo", "ktstr", "kernel", "build", "--source", "../linux", "6.14.2",
    ]);
    match result {
        Ok(_) => panic!("--source + positional VERSION must be rejected at parse time"),
        Err(err) => assert_eq!(
            err.kind(),
            clap::error::ErrorKind::ArgumentConflict,
            "expected ArgumentConflict — a different ErrorKind would \
             signal that the conflicts_with attribute regressed in a way \
             the bare is_err() pin would silently mask. Full err: {err}",
        ),
    }
}

#[test]
fn parse_kernel_build_git_requires_ref() {
    let result = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "--git",
        "https://example.com/linux.git",
    ]);
    match result {
        Ok(_) => panic!("--git without --ref must be rejected at parse time"),
        Err(err) => assert_eq!(
            err.kind(),
            clap::error::ErrorKind::MissingRequiredArgument,
            "expected MissingRequiredArgument — `--git` carries \
             `requires = \"git_ref\"` (clap uses the field name, not \
             the long flag name), so a regression that dropped the \
             attribute would surface as a different ErrorKind that \
             the bare is_err() pin would silently mask. Full err: {err}",
        ),
    }
}

#[test]
fn parse_kernel_build_git_with_ref() {
    let m = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "--git",
        "https://example.com/linux.git",
        "--ref",
        "v6.14",
    ]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

/// Conflict pin: `--git URL --ref REF` and `--source PATH` are
/// mutually exclusive — git-spec triggers a clone, source-spec
/// reuses an existing tree. Both at once would either silently
/// favour one over the other or surface as an inscrutable
/// dispatcher panic; clap's `conflicts_with` pushes the
/// rejection up to parse time so the operator sees a clear
/// argument-conflict error.
#[test]
fn parse_kernel_build_git_conflicts_with_source() {
    let result = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "--git",
        "https://example.com/linux.git",
        "--ref",
        "v6.14",
        "--source",
        "../linux",
    ]);
    match result {
        Ok(_) => panic!("--git + --source must be rejected at parse time"),
        Err(err) => assert_eq!(
            err.kind(),
            clap::error::ErrorKind::ArgumentConflict,
            "expected ArgumentConflict — a different ErrorKind would \
             signal that the conflicts_with attribute regressed in a way \
             the bare is_err() pin would silently mask. Full err: {err}",
        ),
    }
}

/// `kernel build VERSION --extra-kconfig PATH` round-trips to
/// `KernelCommand::Build { version: Some(..), extra_kconfig:
/// Some(..), .. }` so the dispatch site forwards the path
/// through `kernel_build` → `kernel_build_one` →
/// `cli::kernel_build_pipeline` with `Some(content)`. Pins the
/// clap binding for the new flag — a regression that dropped
/// the field would surface here as a parse rejection or a None
/// `extra_kconfig`.
#[test]
fn parse_kernel_build_with_extra_kconfig() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "6.14.2",
        "--extra-kconfig",
        "/tmp/extra.kconfig",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel {
        command:
            KernelCommand::Build {
                version,
                extra_kconfig,
                ..
            },
    } = k.command
    else {
        panic!("expected KernelCommand::Build");
    };
    assert_eq!(version.as_deref(), Some("6.14.2"));
    assert_eq!(
        extra_kconfig,
        Some(std::path::PathBuf::from("/tmp/extra.kconfig")),
        "--extra-kconfig must round-trip the literal path",
    );
}

/// Bare `kernel build VERSION` (no `--extra-kconfig`) parses to
/// `extra_kconfig: None`. Pins that the flag is OPTIONAL — a
/// regression that made it required would fail this test.
#[test]
fn parse_kernel_build_without_extra_kconfig_is_none() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "kernel", "build", "6.14.2"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel {
        command: KernelCommand::Build { extra_kconfig, .. },
    } = k.command
    else {
        panic!("expected KernelCommand::Build");
    };
    assert!(
        extra_kconfig.is_none(),
        "no --extra-kconfig must produce None, got {extra_kconfig:?}",
    );
}

/// `kernel build VERSION --skip-sha256` round-trips to
/// `KernelCommand::Build { skip_sha256: true, .. }` so the
/// dispatch site forwards the boolean through `kernel_build` →
/// `kernel_build_one` → `fetch::download_tarball` →
/// `download_stable_tarball`. Pins the clap binding for the
/// security-sensitive bypass flag — a regression that dropped
/// the field or flipped the default would surface here.
#[test]
fn parse_kernel_build_with_skip_sha256() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "6.14.2",
        "--skip-sha256",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel {
        command:
            KernelCommand::Build {
                version,
                skip_sha256,
                ..
            },
    } = k.command
    else {
        panic!("expected KernelCommand::Build");
    };
    assert_eq!(version.as_deref(), Some("6.14.2"));
    assert!(
        skip_sha256,
        "--skip-sha256 must round-trip as true; without this the \
         download path would still verify against sha256sums.asc"
    );
}

/// Bare `kernel build VERSION` (no `--skip-sha256`) parses to
/// `skip_sha256: false`. Pins the safe default — a regression
/// that flipped the default to true would silently disable
/// checksum verification on every download.
#[test]
fn parse_kernel_build_without_skip_sha256_is_false() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "kernel", "build", "6.14.2"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel {
        command: KernelCommand::Build { skip_sha256, .. },
    } = k.command
    else {
        panic!("expected KernelCommand::Build");
    };
    assert!(
        !skip_sha256,
        "absent --skip-sha256 must produce skip_sha256: false — \
         the default must keep checksum verification enabled, \
         got skip_sha256={skip_sha256}"
    );
}

/// `--skip-sha256` works alongside `--source` (local source tree
/// path). Pins that the flag is not mutually exclusive with the
/// other source-acquire flags — skip-sha256 is documented as a
/// no-op on --source / --git, but clap must still ACCEPT the
/// combination so the help-text-promised orthogonality holds at
/// parse time.
#[test]
fn parse_kernel_build_skip_sha256_with_source() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "--source",
        "/tmp/src",
        "--skip-sha256",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel {
        command:
            KernelCommand::Build {
                source,
                skip_sha256,
                ..
            },
    } = k.command
    else {
        panic!("expected KernelCommand::Build");
    };
    assert_eq!(source, Some(std::path::PathBuf::from("/tmp/src")));
    assert!(
        skip_sha256,
        "--skip-sha256 must round-trip when combined with --source \
         (the help text promises the flag is a no-op there, but \
         clap must still accept the combination)"
    );
}

/// Underscore form `--skip_sha256` MUST be rejected by clap. The
/// canonical name is `--skip-sha256` (kebab-case). A regression
/// that added an alias for the underscore form (or changed the
/// arg-name parser to accept either) would turn this negative
/// pin positive. Mirrors `parse_llvm_cov_underscore_rejected`.
#[test]
fn parse_kernel_build_skip_sha256_underscore_rejected() {
    let rejected = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "6.14.2",
        "--skip_sha256",
    ]);
    assert!(
        rejected.is_err(),
        "`--skip_sha256` (underscore) must be rejected — the \
         canonical name is `--skip-sha256` (kebab-case)",
    );
}

/// Range expansion + --skip-sha256 composes at the parse layer.
/// A range version + the bypass flag both round-trip to their
/// fields on `KernelCommand::Build`. The dispatch then fans out
/// per version inside `kernel_build`, threading the same
/// `skip_sha256` boolean to every `kernel_build_one` call — so
/// every version in a range observes the same bypass setting.
/// Pin the parse-level composition.
#[test]
fn parse_kernel_build_skip_sha256_range_compose() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "6.14.2..6.14.4",
        "--skip-sha256",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel {
        command:
            KernelCommand::Build {
                version,
                skip_sha256,
                ..
            },
    } = k.command
    else {
        panic!("expected KernelCommand::Build");
    };
    assert_eq!(version.as_deref(), Some("6.14.2..6.14.4"));
    assert!(
        skip_sha256,
        "--skip-sha256 must round-trip on a range version so every \
         per-version `kernel_build_one` invocation sees the bypass \
         flag"
    );
}

/// Four-flag orthogonality: --skip-sha256 + --extra-kconfig +
/// --force + --clean must all coexist on a single `kernel build`
/// invocation. None pair conflicts. A regression that introduced
/// a clap `conflicts_with` between any pair (e.g. wrongly tying
/// --skip-sha256 to --force "for safety") would surface here.
/// Mirrors `parse_kernel_build_force_clean_and_extra_kconfig_compose`.
#[test]
fn parse_kernel_build_skip_sha256_with_extra_kconfig_and_force_clean() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "6.14.2",
        "--skip-sha256",
        "--extra-kconfig",
        "/tmp/k",
        "--force",
        "--clean",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel {
        command:
            KernelCommand::Build {
                force,
                clean,
                extra_kconfig,
                skip_sha256,
                ..
            },
    } = k.command
    else {
        panic!("expected KernelCommand::Build");
    };
    assert!(
        force,
        "--force must round-trip alongside --skip-sha256 + --clean + --extra-kconfig"
    );
    assert!(
        clean,
        "--clean must round-trip alongside --skip-sha256 + --force + --extra-kconfig"
    );
    assert_eq!(
        extra_kconfig,
        Some(std::path::PathBuf::from("/tmp/k")),
        "--extra-kconfig must round-trip alongside --skip-sha256 + --force + --clean"
    );
    assert!(
        skip_sha256,
        "--skip-sha256 must round-trip alongside --force + --clean + --extra-kconfig"
    );
}

/// Range expansion + --extra-kconfig composes at the parse
/// layer. A range version + an extra-kconfig path both round-
/// trip to their fields on `KernelCommand::Build`. The dispatch
/// then fans out per version inside `kernel_build`, and the
/// `extra_content` String is read ONCE up front and threaded as
/// `Option<&str>` to every `kernel_build_one` call — so every
/// version in a range observes byte-identical extras. Pin the
/// parse-level composition; the per-version threading is a
/// code-structure invariant of `kernel_build`'s shared read.
#[test]
fn parse_kernel_build_range_with_extra_kconfig() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "6.14.2..6.14.4",
        "--extra-kconfig",
        "/tmp/range-extra.kconfig",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel {
        command:
            KernelCommand::Build {
                version,
                extra_kconfig,
                ..
            },
    } = k.command
    else {
        panic!("expected KernelCommand::Build");
    };
    assert_eq!(version.as_deref(), Some("6.14.2..6.14.4"));
    assert_eq!(
        extra_kconfig,
        Some(std::path::PathBuf::from("/tmp/range-extra.kconfig")),
    );
}

/// --force + --clean + --extra-kconfig orthogonality. None of
/// these flags conflict with each other; pin that all three
/// can co-exist on a single invocation. A regression that
/// introduced a clap `conflicts_with` between any pair would
/// surface here.
#[test]
fn parse_kernel_build_force_clean_and_extra_kconfig_compose() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "--source",
        "../linux",
        "--force",
        "--clean",
        "--extra-kconfig",
        "/tmp/extra.kconfig",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel {
        command:
            KernelCommand::Build {
                force,
                clean,
                extra_kconfig,
                ..
            },
    } = k.command
    else {
        panic!("expected KernelCommand::Build");
    };
    assert!(
        force,
        "--force must round-trip alongside --clean and --extra-kconfig"
    );
    assert!(
        clean,
        "--clean must round-trip alongside --force and --extra-kconfig"
    );
    assert_eq!(
        extra_kconfig,
        Some(std::path::PathBuf::from("/tmp/extra.kconfig")),
        "--extra-kconfig must round-trip when combined with --force + --clean",
    );
}

/// Non-build subcommands that accept `--extra-kconfig` would
/// silently produce wrong cache lookups. The flag is `kernel
/// build`-only at the configuration layer; this test pins the
/// parse-level reject for the subcommands that have CLEAN clap
/// surfaces (no `trailing_var_arg` passthrough).
///
/// Subcommands and their behavior:
/// - `verifier`: REJECTS at parse time (no trailing_var_arg).
///   Pin via `try_parse_from` returning `Err`.
/// - `shell`: REJECTS at parse time (no trailing_var_arg).
///   Pin via `try_parse_from` returning `Err`.
/// - `test` / `coverage` / `llvm-cov`: PASSTHROUGH via
///   `args: Vec<String>` with `trailing_var_arg = true,
///   allow_hyphen_values = true`. Clap forwards `--extra-kconfig
///   ...` as positional args to `cargo nextest run` (or
///   `cargo llvm-cov`), which then rejects it as an unknown
///   cargo flag — but at the cargo subprocess layer, NOT at
///   parse time. This is a structural property of clap's
///   trailing-var-arg shape and is consistent across every
///   passthrough subcommand on `cargo ktstr`. We do NOT pin
///   these as parse errors because that's not where the
///   rejection actually happens.
#[test]
fn parse_extra_kconfig_rejected_on_verifier_subcommand() {
    let m = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "verifier",
        "--kernel",
        "../linux",
        "--extra-kconfig",
        "/tmp/x.kconfig",
    ]);
    assert!(
        m.is_err(),
        "--extra-kconfig must be rejected on `cargo ktstr verifier` \
         (verifier has no trailing_var_arg, so unknown flags fail at parse time)",
    );
}

#[test]
fn parse_extra_kconfig_rejected_on_shell_subcommand() {
    let m = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "shell",
        "--extra-kconfig",
        "/tmp/x.kconfig",
    ]);
    assert!(
        m.is_err(),
        "--extra-kconfig must be rejected on `cargo ktstr shell` \
         (shell has no trailing_var_arg, so unknown flags fail at parse time)",
    );
}

/// Documents the passthrough behavior on `test` /
/// `coverage` / `llvm-cov`: clap's `trailing_var_arg = true`
/// on `args: Vec<String>` SWALLOWS `--extra-kconfig` as a
/// positional argument forwarded to `cargo nextest run` /
/// `cargo llvm-cov`. The rejection happens later, at the
/// cargo subprocess layer, not at parse time. Pin the
/// shape so a future change to the trailing_var_arg shape
/// (e.g. removing it) surfaces here as a behavior change.
#[test]
fn parse_extra_kconfig_passes_through_test_subcommand_to_args_vec() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "test",
        "--extra-kconfig",
        "/tmp/x.kconfig",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Test { args, .. } = k.command else {
        panic!("expected KtstrCommand::Test");
    };
    assert_eq!(
        args,
        vec!["--extra-kconfig", "/tmp/x.kconfig"],
        "--extra-kconfig must passthrough into `args` Vec on test \
         subcommand (trailing_var_arg = true). The cargo nextest \
         subprocess will reject it as an unknown flag downstream."
    );
}

/// `--extra-kconfig` works alongside `--source` (local source
/// tree path). Pins that the flag is not mutually exclusive
/// with the other source-acquire flags — extra-kconfig is
/// orthogonal to where the kernel SOURCE comes from.
#[test]
fn parse_kernel_build_extra_kconfig_with_source() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "kernel",
        "build",
        "--source",
        "../linux",
        "--extra-kconfig",
        "/tmp/extra.kconfig",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel {
        command:
            KernelCommand::Build {
                source,
                extra_kconfig,
                ..
            },
    } = k.command
    else {
        panic!("expected KernelCommand::Build");
    };
    assert_eq!(source, Some(std::path::PathBuf::from("../linux")));
    assert_eq!(
        extra_kconfig,
        Some(std::path::PathBuf::from("/tmp/extra.kconfig")),
    );
}

// -- try_get_matches_from: kernel clean --

#[test]
fn parse_kernel_clean() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "kernel", "clean"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

#[test]
fn parse_kernel_clean_keep() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "kernel", "clean", "--keep", "3"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Kernel {
        command: KernelCommand::Clean { keep, .. },
    } = k.command
    else {
        panic!("expected Kernel Clean");
    };
    assert_eq!(keep, Some(3));
}

// -- try_get_matches_from: verifier --
//
// The verifier subcommand takes only --kernel (repeatable) and --raw.
// The scheduler binary set is discovered from `declare_scheduler!`
// registrations in linked test binaries, not from a CLI flag — the
// matrix is driven by the test binary's `KTSTR_SCHEDULERS`
// distributed slice.

#[test]
fn parse_verifier_bare() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "verifier"]).unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Verifier { kernel, raw } = k.command else {
        panic!("expected Verifier");
    };
    assert!(
        kernel.is_empty(),
        "bare verifier must default --kernel to empty Vec"
    );
    assert!(!raw, "bare verifier must default --raw to false");
}

#[test]
fn parse_verifier_with_kernel_single() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "verifier", "--kernel", "6.14.2"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Verifier { kernel, raw } = k.command else {
        panic!("expected Verifier");
    };
    assert_eq!(kernel, vec!["6.14.2"]);
    assert!(!raw);
}

#[test]
fn parse_verifier_with_kernel_repeatable() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo", "ktstr", "verifier", "--kernel", "6.14.2", "--kernel", "6.15.0",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Verifier { kernel, raw } = k.command else {
        panic!("expected Verifier");
    };
    assert_eq!(kernel, vec!["6.14.2", "6.15.0"]);
    assert!(!raw);
}

#[test]
fn parse_verifier_with_raw() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "verifier", "--raw"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Verifier { kernel, raw } = k.command else {
        panic!("expected Verifier");
    };
    assert!(kernel.is_empty());
    assert!(raw, "--raw must lift the flag to true");
}

/// `--scheduler` was removed when the verifier sweep moved to
/// `declare_scheduler!`-driven discovery. Pin that the flag stays
/// rejected so a future agent who reintroduces it without
/// rebuilding the sweep dispatch trips this test.
#[test]
fn parse_verifier_scheduler_flag_rejected() {
    let rejected =
        Cargo::try_parse_from(["cargo", "ktstr", "verifier", "--scheduler", "scx_rustland"]);
    assert!(
        rejected.is_err(),
        "--scheduler must be rejected — the flag was removed when the \
         verifier sweep moved to declare_scheduler!-driven discovery",
    );
}

/// `--all-profiles` was removed alongside the flag-profile sweep.
/// Pin the parse-time rejection so a future agent who re-adds the
/// argument without rebuilding the sweep surface trips this test
/// instead of silently shipping a dead flag.
#[test]
fn parse_verifier_all_profiles_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "verifier", "--all-profiles"]);
    assert!(
        rejected.is_err(),
        "--all-profiles must be rejected — the flag-profile sweep \
         was removed from the verifier subcommand",
    );
}

/// `--profiles` was removed alongside the flag-profile sweep. Pin
/// the parse-time rejection so a future agent who re-adds the
/// argument without rebuilding the sweep surface trips this test
/// instead of silently shipping a dead flag.
#[test]
fn parse_verifier_profiles_filter_rejected() {
    let rejected = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "verifier",
        "--profiles",
        "default,llc,llc+steal",
    ]);
    assert!(
        rejected.is_err(),
        "--profiles must be rejected — the flag-profile sweep \
         was removed from the verifier subcommand",
    );
}

// -- try_get_matches_from: completions --

#[test]
fn parse_completions_bash() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "completions", "bash"]);
    assert!(m.is_ok(), "{}", m.err().unwrap());
}

#[test]
fn parse_completions_invalid_shell() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "completions", "noshell"]);
    assert!(m.is_err());
}

// -- error cases --

#[test]
fn parse_missing_subcommand() {
    let m = Cargo::try_parse_from(["cargo", "ktstr"]);
    assert!(m.is_err());
}

#[test]
fn parse_unknown_subcommand() {
    let m = Cargo::try_parse_from(["cargo", "ktstr", "nonexistent"]);
    assert!(m.is_err());
}

// -- completions --

#[test]
fn completions_bash_non_empty() {
    let mut buf = Vec::new();
    let mut cmd = Cargo::command();
    clap_complete::generate(clap_complete::Shell::Bash, &mut cmd, "cargo", &mut buf);
    assert!(!buf.is_empty());
}

#[test]
fn completions_zsh_contains_subcommands() {
    let mut buf = Vec::new();
    let mut cmd = Cargo::command();
    clap_complete::generate(clap_complete::Shell::Zsh, &mut cmd, "cargo", &mut buf);
    let output = String::from_utf8(buf).expect("completions should be valid UTF-8");
    // clap_complete's zsh generator emits each subcommand as a
    // `'NAME:HELP'` describe-list entry (see `add_subcommands`
    // in clap_complete-4.6.1/src/aot/shells/zsh.rs:163). The
    // `'<name>:` prefix pin identifies an actual subcommand
    // completion, not an incidental substring match inside
    // rendered doc text.
    assert!(
        output.contains("'test:"),
        "zsh completions missing 'test:' describe-list entry"
    );
    assert!(
        output.contains("'coverage:"),
        "zsh completions missing 'coverage:' describe-list entry"
    );
    assert!(
        output.contains("'shell:"),
        "zsh completions missing 'shell:' describe-list entry"
    );
    assert!(
        output.contains("'kernel:"),
        "zsh completions missing 'kernel:' describe-list entry"
    );
    // `visible_alias = "nextest"` on the Test variant makes the
    // alias user-facing — clap_complete's zsh generator iterates
    // `get_visible_aliases` (zsh.rs:177) and emits a dedicated
    // describe entry per alias. A regression that dropped the
    // attribute (or silently switched to `alias` which is
    // NON-visible) would drop the entry and fail this assertion.
    assert!(
        output.contains("'nextest:"),
        "zsh completions missing 'nextest:' describe-list \
         entry (visible alias of `test`)"
    );
    // `LlvmCov` variant renders as the kebab-case `llvm-cov`
    // subcommand (clap derive default rename — see
    // clap_derive-4.6.0/src/item.rs:27 `DEFAULT_CASING =
    // CasingStyle::Kebab`). Pinned with the same `'name:`
    // prefix so an accidental doc-text match doesn't mask a
    // missing registration.
    assert!(
        output.contains("'llvm-cov:"),
        "zsh completions missing 'llvm-cov:' describe-list entry"
    );
}

// -- format_entry_row helpers --

fn test_metadata() -> KernelMetadata {
    KernelMetadata::new(
        ktstr::cache::KernelSource::Tarball,
        "x86_64".to_string(),
        "bzImage".to_string(),
        "2026-04-12T10:00:00Z".to_string(),
    )
    .with_version(Some("6.14.2".to_string()))
}

/// Store a fake kernel image and return the CacheEntry.
fn store_test_entry(cache: &CacheDir, key: &str, meta: &KernelMetadata) -> CacheEntry {
    let src = tempfile::TempDir::new().unwrap();
    let image = src.path().join(&meta.image_name);
    std::fs::write(&image, b"fake kernel").unwrap();
    cache
        .store(key, &CacheArtifacts::new(&image), meta)
        .unwrap()
}

// -- format_entry_row --
//
// The (Matches / Stale / Untracked) × (not-EOL / EOL) outcome
// matrix plus the `version == None` → "-" dash-render branch are
// pinned by `format_entry_row_renders_eol_kconfig_matrix` in
// `src/cli/kernel_list.rs` — see that test for the full case
// list. The test below covers a distinct corner the matrix does
// not: `KernelSource::Local` rendering through format_entry_row,
// since the matrix uses `Tarball` exclusively for determinism.

#[test]
fn format_entry_row_no_version() {
    let tmp = tempfile::TempDir::new().unwrap();
    let cache = CacheDir::with_root(tmp.path().join("cache"));
    let meta = KernelMetadata::new(
        ktstr::cache::KernelSource::Local {
            source_tree_path: None,
            git_hash: None,
        },
        "x86_64".to_string(),
        "bzImage".to_string(),
        "2026-04-12T10:00:00Z".to_string(),
    );
    let entry = store_test_entry(&cache, "local-key", &meta);
    let row = cli::format_entry_row(&entry, "hash", &[]);
    // Anchor the dash to the version COLUMN. The row format is
    // `"  {key:<48} {version:<12} {source:<8} {arch:<7} {built_at}{tags}"`
    // (see `format_entry_row` in src/cli/kernel_list.rs). A bare
    // `row.contains("-")` would also match the `-` in the timestamp
    // `2026-04-12T10:00:00Z` even if the version dash were missing.
    // Splitting on whitespace and inspecting the second token isolates
    // the version slot — token 0 is the key, token 1 is the version.
    let tokens: Vec<&str> = row.split_whitespace().collect();
    assert!(
        tokens.len() >= 2,
        "row must have at least key + version columns: {row:?}",
    );
    assert_eq!(
        tokens[1], "-",
        "missing version must render as `-` in the version column: {row:?}",
    );
}

// Corrupt-entry formatting moved inline into the caller iteration
// in cli::kernel_list, so no test on format_entry_row covers it;
// the helper itself now takes only the valid CacheEntry shape.

// -- kconfig_status (via CacheEntry method) --

/// Companion to the stale-kconfig case in
/// `format_entry_row_renders_eol_kconfig_matrix` (in
/// `src/cli/kernel_list.rs`): that test pins the `(stale kconfig)`
/// tag emitted by `cli::format_entry_row` for a hash-mismatch entry;
/// this test pins the enum variant
/// (`KconfigStatus::Stale { cached, current }`) returned by
/// `CacheEntry::kconfig_status` that drives the tag.
#[test]
fn kconfig_status_reports_stale_on_hash_mismatch() {
    let tmp = tempfile::TempDir::new().unwrap();
    let cache = CacheDir::with_root(tmp.path().join("cache"));
    let meta = test_metadata().with_ktstr_kconfig_hash(Some("old".to_string()));
    let entry = store_test_entry(&cache, "stale", &meta);
    assert_eq!(
        entry.kconfig_status("new"),
        ktstr::cache::KconfigStatus::Stale {
            cached: "old".to_string(),
            current: "new".to_string(),
        }
    );
}

/// Companion to the matching-kconfig case in
/// `format_entry_row_renders_eol_kconfig_matrix` (in
/// `src/cli/kernel_list.rs`): that test pins the no-tag contract
/// emitted by `cli::format_entry_row` when the hashes agree; this
/// test pins the `KconfigStatus::Matches` variant returned by
/// `CacheEntry::kconfig_status` that drives the no-tag branch.
#[test]
fn kconfig_status_reports_matches_on_hash_equality() {
    let tmp = tempfile::TempDir::new().unwrap();
    let cache = CacheDir::with_root(tmp.path().join("cache"));
    let meta = test_metadata().with_ktstr_kconfig_hash(Some("same".to_string()));
    let entry = store_test_entry(&cache, "fresh", &meta);
    assert_eq!(
        entry.kconfig_status("same"),
        ktstr::cache::KconfigStatus::Matches
    );
}

/// Companion to the untracked-kconfig case in
/// `format_entry_row_renders_eol_kconfig_matrix` (in
/// `src/cli/kernel_list.rs`): that test pins the
/// `(untracked kconfig)` tag emitted by `cli::format_entry_row`
/// when an entry has no recorded hash; this test pins the
/// `KconfigStatus::Untracked` variant returned by
/// `CacheEntry::kconfig_status` that drives the tag.
#[test]
fn kconfig_status_reports_untracked_when_entry_has_no_hash() {
    let tmp = tempfile::TempDir::new().unwrap();
    let cache = CacheDir::with_root(tmp.path().join("cache"));
    let meta = test_metadata();
    let entry = store_test_entry(&cache, "no-hash", &meta);
    assert_eq!(
        entry.kconfig_status("anything"),
        ktstr::cache::KconfigStatus::Untracked
    );
}

// Corrupt entries no longer surface as CacheEntry — they are
// ListedEntry::Corrupt with no metadata-bearing struct — so
// kconfig_status isn't reachable from that state.

/// Differential pin on the three `KconfigStatus` strings that flow
/// into the `kconfig_status` field of `cargo ktstr kernel list
/// --json`. `cli::kernel_list` emits the JSON field via
/// `entry.kconfig_status(&kconfig_hash).to_string()`, so CI scripts
/// that key off the stringified variant break if any of these
/// three words changes. This test exercises the full
/// `CacheEntry::kconfig_status(..).to_string()` chain (not just
/// `KconfigStatus::<variant>.to_string()` in isolation) to pin the
/// end-to-end JSON contract in a single test covering all three
/// variants.
#[test]
fn kconfig_status_json_string_pins_all_three_variants() {
    use ktstr::cache::KconfigStatus;
    let tmp = tempfile::TempDir::new().unwrap();
    let cache = CacheDir::with_root(tmp.path().join("cache"));

    let matches_meta = test_metadata().with_ktstr_kconfig_hash(Some("h".to_string()));
    let matches_entry = store_test_entry(&cache, "matches-key", &matches_meta);
    let matches_status = matches_entry.kconfig_status("h");
    assert!(
        matches!(matches_status, KconfigStatus::Matches),
        "hash equality must yield KconfigStatus::Matches"
    );
    assert_eq!(matches_status.to_string(), "matches");

    let stale_meta = test_metadata().with_ktstr_kconfig_hash(Some("old".to_string()));
    let stale_entry = store_test_entry(&cache, "stale-key", &stale_meta);
    let stale_status = stale_entry.kconfig_status("new");
    assert!(
        matches!(stale_status, KconfigStatus::Stale { .. }),
        "hash mismatch must yield KconfigStatus::Stale"
    );
    assert_eq!(stale_status.to_string(), "stale");

    let untracked_meta = test_metadata();
    let untracked_entry = store_test_entry(&cache, "untracked-key", &untracked_meta);
    let untracked_status = untracked_entry.kconfig_status("anything");
    assert!(
        matches!(untracked_status, KconfigStatus::Untracked),
        "entry without hash must yield KconfigStatus::Untracked"
    );
    assert_eq!(untracked_status.to_string(), "untracked");
}

// -- embedded_kconfig_hash --

#[test]
fn embedded_kconfig_hash_deterministic() {
    let h1 = cli::embedded_kconfig_hash();
    let h2 = cli::embedded_kconfig_hash();
    assert_eq!(h1, h2);
}

#[test]
fn embedded_kconfig_hash_is_hex() {
    let h = cli::embedded_kconfig_hash();
    assert_eq!(h.len(), 8, "CRC32 hex should be 8 chars");
    assert!(
        h.chars().all(|c| c.is_ascii_hexdigit()),
        "should be hex digits: {h}"
    );
}

#[test]
fn embedded_kconfig_hash_matches_manual_crc32() {
    let expected = format!("{:08x}", crc32fast::hash(cli::EMBEDDED_KCONFIG.as_bytes()));
    assert_eq!(cli::embedded_kconfig_hash(), expected);
}

// -- show-host --

/// `cargo ktstr show-host` parses with no arguments and maps to
/// the `ShowHost` variant.
#[test]
fn parse_show_host_minimal() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "show-host"]).unwrap_or_else(|e| panic!("{e}"));
    assert!(matches!(k.command, KtstrCommand::ShowHost));
}

/// A stray positional argument on `show-host` must be rejected at
/// parse time (clap default) so a typo like
/// `cargo ktstr show-host host_context` fails loudly instead of
/// silently looking like success.
#[test]
fn parse_show_host_rejects_positional() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "show-host", "stray"]);
    assert!(
        rejected.is_err(),
        "show-host must reject positional arguments",
    );
}

/// `cargo ktstr show-thresholds <test>` parses with exactly one
/// positional argument and maps to the `ShowThresholds` variant
/// carrying the test name. Missing argument rejected at parse
/// time; extra argument rejected too. Pins the arg count so a
/// future variadic refactor surfaces here.
#[test]
fn parse_show_thresholds_with_test_arg() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "show-thresholds", "my_test_fn"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::ShowThresholds { test } = k.command else {
        panic!("expected ShowThresholds");
    };
    assert_eq!(test, "my_test_fn");
}

/// `show-thresholds` without the test-name argument must fail
/// at parse time — the positional is required.
#[test]
fn parse_show_thresholds_without_arg_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "show-thresholds"]);
    assert!(
        rejected.is_err(),
        "show-thresholds requires a test-name argument",
    );
}

/// `show-thresholds <a> <b>` is rejected — variadic inputs would
/// silently drop the second arg or reinterpret it as a flag.
#[test]
fn parse_show_thresholds_extra_arg_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "show-thresholds", "a", "b"]);
    assert!(
        rejected.is_err(),
        "show-thresholds must accept exactly one positional arg",
    );
}

/// `cli::show_host` produces a non-empty report under normal
/// Linux CI conditions. Catches a regression in the underlying
/// `HostContext::format_human` (e.g. a panic in the
/// destructuring bind that surfaces every field) before the
/// ShowHost dispatch arm reaches it. Named without a
/// `dispatch_` prefix because this exercises the leaf helper
/// directly; true dispatch-path coverage lives in the parse
/// tests above + the binary's `main` call.
#[test]
fn show_host_helper_produces_non_empty_output() {
    let out = cli::show_host();
    assert!(
        !out.is_empty(),
        "show_host must return a non-empty report under normal Linux CI",
    );
    // Stronger pin: `HostContext::format_human` always includes
    // `kernel_release` even when most other fields are `None`
    // (uname is a syscall, filesystem-independent). Asserting
    // the stable field name catches a regression that returned
    // a non-empty but garbage report (e.g. only comments).
    assert!(
        out.contains("kernel_release"),
        "show_host output must include the stable `kernel_release` row: {out}",
    );
}

/// `cli::show_thresholds` returns `Err` with the actionable
/// "no registered ktstr test named" diagnostic when called with
/// an unknown test name. Named without a `dispatch_` prefix for
/// the same reason as `show_host_helper_produces_non_empty_output`
/// — this exercises the leaf helper, not the dispatch path
/// wrapping it.
#[test]
fn show_thresholds_helper_unknown_test_returns_error() {
    let err = cli::show_thresholds("definitely_not_a_registered_test_xyz").unwrap_err();
    let msg = format!("{err:#}");
    assert!(
        msg.contains("no registered ktstr test named"),
        "error path must preserve the actionable diagnostic: {msg}",
    );
}

// -- clap argument-parse pins: Shell --cpu-cap requires --no-perf-mode
//
// `#[arg(long, requires = "no_perf_mode", ...)]` on the
// Shell subcommand's `cpu_cap` field enforces the constraint
// that --cpu-cap is only meaningful in no-perf-mode (perf-mode
// already holds every LLC exclusively, so capping under
// perf-mode would double-reserve). These tests pin the
// invariant so a future refactor that drops or renames the
// `requires` attribute trips a unit-test regression instead of
// surfacing as a runtime double-reservation conflict.

/// `cargo ktstr shell --cpu-cap 4 --no-perf-mode` parses
/// successfully with both flags set. Pins the positive path of
/// the `requires = "no_perf_mode"` constraint — the happy-path
/// invocation an operator would type.
#[test]
fn parse_shell_cpu_cap_with_no_perf_mode_succeeds() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "shell",
        "--cpu-cap",
        "4",
        "--no-perf-mode",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell {
        cpu_cap,
        no_perf_mode,
        ..
    } = k.command
    else {
        panic!("expected Shell");
    };
    assert_eq!(cpu_cap, Some(4));
    assert!(no_perf_mode, "--no-perf-mode must be set");
}

/// `cargo ktstr shell --cpu-cap 4` without `--no-perf-mode`
/// must FAIL at parse time because of the `requires =
/// "no_perf_mode"` constraint. Pins the negative path: if
/// the constraint is ever dropped, this test fails so the
/// regression can't reach production where it would cause a
/// silent double-reservation under perf-mode.
#[test]
fn parse_shell_cpu_cap_without_no_perf_mode_fails() {
    // `Cargo` intentionally has no Debug derive, so unwrap
    // helpers that format the Ok variant are unavailable.
    // Match on Err directly to extract the clap error.
    let msg = match Cargo::try_parse_from(["cargo", "ktstr", "shell", "--cpu-cap", "4"]) {
        Err(e) => e.to_string(),
        Ok(_) => panic!("--cpu-cap without --no-perf-mode must fail the parse"),
    };
    // clap renders "the following required arguments were not provided"
    // or similar; lowercase + substring-match is lenient against
    // clap version-to-version message tweaks while still proving
    // the constraint fired.
    assert!(
        msg.to_ascii_lowercase().contains("no-perf-mode")
            || msg.to_ascii_lowercase().contains("no_perf_mode"),
        "clap error must name the missing --no-perf-mode flag, got: {msg}",
    );
}

/// `cargo ktstr shell --no-perf-mode` without `--cpu-cap`
/// parses successfully with `cpu_cap: None`. Pins the shape of
/// the unset sentinel (expanded to the 30%-of-allowed default by
/// the planner) — a user who wants --no-perf-mode with the
/// implicit default must still be able to invoke the shell. A
/// regression that tied --cpu-cap to --no-perf-mode
/// bidirectionally would fail here.
#[test]
fn parse_shell_no_perf_mode_without_cpu_cap_succeeds() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "shell", "--no-perf-mode"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell {
        cpu_cap,
        no_perf_mode,
        ..
    } = k.command
    else {
        panic!("expected Shell");
    };
    assert_eq!(cpu_cap, None, "no --cpu-cap must produce None");
    assert!(no_perf_mode);
}

// ---------------------------------------------------------------
// KERNEL_LIST_LONG_ABOUT — range-mode JSON schema discoverability
// ---------------------------------------------------------------
//
// `cargo ktstr kernel list --range R --json` emits a
// structurally-different JSON shape from the cache-walk mode:
// four top-level fields (`range`, `start`, `end`, `versions`)
// with no cache metadata. The help copy is the
// discoverability contract for scripted consumers — without a
// unit-test pin, a JSON emitter that adds, renames, or removes
// a range-mode field could ship without a matching help update
// and silently break dispatch-on-key consumers. The sibling
// `kernel_list_long_about_exposes_json_schema` test in
// `src/cli/kernel_cmd.rs` covers cache-walk mode; this companion
// fills the range-mode gap from the cargo-ktstr binary's
// perspective and exercises the same `pub const` re-exported
// through `ktstr::cli::KERNEL_LIST_LONG_ABOUT`.

/// Pins that every range-mode JSON top-level field name appears
/// in the help copy by its column-aligned row. Range-mode emits
/// `{ range, start, end, versions }` per the schema block in
/// `KERNEL_LIST_LONG_ABOUT` (`src/cli/kernel_cmd.rs`). Each field
/// is pinned against its column-aligned row prefix (e.g.
/// `  range     literal`) rather than the bare word, since
/// `start` / `end` / `range` appear elsewhere in the help copy
/// (e.g. "parsed start endpoint", "the inclusive range") and a
/// bare-word substring would match the prose, masking a regression
/// that dropped the actual schema row.
///
/// Co-update contract: when the JSON schema changes (field
/// added, renamed, removed, or its emission site moves), three
/// updates land in the same commit:
///   1. the JSON emitter — `cli::kernel_list` /
///      `kernel_list_range_preview` in `src/cli/kernel_list.rs`,
///   2. the help-copy schema block — `KERNEL_LIST_LONG_ABOUT`
///      in `src/cli/kernel_cmd.rs` (the column-aligned table
///      this test reads), and
///   3. this test's column-aligned assertions.
///
/// Updating any one without the others either silently breaks
/// scripted consumers (1 without 2) or surfaces a misleading
/// stale assertion (2 without 3).
#[test]
fn kernel_list_long_about_exposes_range_mode_json_keys() {
    let about = ktstr::cli::KERNEL_LIST_LONG_ABOUT;
    // Column-aligned rows from kernel_cmd.rs's range-mode schema
    // block — each begins with two spaces, the field name, and
    // padding to the description column. Pinning against this
    // exact prefix shape rejects matches inside surrounding prose.
    assert!(
        about.contains("  range     literal"),
        "KERNEL_LIST_LONG_ABOUT must carry the `range` row from the \
         range-mode schema block: got: {about:?}",
    );
    assert!(
        about.contains("  start     parsed start endpoint"),
        "KERNEL_LIST_LONG_ABOUT must carry the `start` row from the \
         range-mode schema block: got: {about:?}",
    );
    assert!(
        about.contains("  end       parsed end endpoint"),
        "KERNEL_LIST_LONG_ABOUT must carry the `end` row from the \
         range-mode schema block: got: {about:?}",
    );
    assert!(
        about.contains("  versions  array of resolved version strings"),
        "KERNEL_LIST_LONG_ABOUT must carry the `versions` row from the \
         range-mode schema block: got: {about:?}",
    );
    // The help copy must explicitly distinguish range-mode from
    // cache-walk-mode by mentioning that the range-mode shape
    // "never carries cache metadata" (the dispatch-on-key contract).
    assert!(
        about.contains("Range-mode output never carries cache metadata"),
        "KERNEL_LIST_LONG_ABOUT must call out the `Range-mode output \
         never carries cache metadata` contract so scripted consumers \
         know to dispatch on the presence of the `range` key versus \
         the `entries` key: got: {about:?}",
    );
    assert!(
        about.contains("--range"),
        "KERNEL_LIST_LONG_ABOUT must reference the `--range` flag \
         so a `kernel list --help` reader sees the range-mode \
         entry point: got: {about:?}",
    );
    // The exact phrase from kernel_cmd.rs:416 splits across a
    // line break (`...range-preview\nmode...`), so pin the
    // unambiguous hyphenated token directly. Plain "range mode"
    // also appears in surrounding prose (e.g. help text — see
    // `the `range` key (range mode) versus `entries` key (list mode)`
    // at kernel_cmd.rs:437) so a disjunction would re-introduce
    // false-positive risk.
    assert!(
        about.contains("range-preview"),
        "KERNEL_LIST_LONG_ABOUT must use the `range-preview` term so \
         scripted consumers know to dispatch on the presence of the \
         `range` key: got: {about:?}",
    );
}

// -- try_get_matches_from: model subcommand --
//
// `cargo ktstr model <fetch|status|clean>` pins each
// `ModelCommand` variant — a regression that renamed a subcommand
// or restructured the enum surfaces here at parse time.

/// `cargo ktstr model fetch` resolves to `ModelCommand::Fetch`.
#[test]
fn parse_model_fetch() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "model", "fetch"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Model { command } = k.command else {
        panic!("expected Model");
    };
    assert!(matches!(command, ModelCommand::Fetch));
}

/// `cargo ktstr model status` resolves to `ModelCommand::Status`.
#[test]
fn parse_model_status() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "model", "status"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Model { command } = k.command else {
        panic!("expected Model");
    };
    assert!(matches!(command, ModelCommand::Status));
}

/// `cargo ktstr model clean` resolves to `ModelCommand::Clean`.
#[test]
fn parse_model_clean() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "model", "clean"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Model { command } = k.command else {
        panic!("expected Model");
    };
    assert!(matches!(command, ModelCommand::Clean));
}

/// `cargo ktstr model` without a subcommand must fail at parse
/// time — the enum carries no Option<ModelCommand>, so clap
/// requires one of the three.
#[test]
fn parse_model_missing_subcommand_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "model"]);
    assert!(
        rejected.is_err(),
        "model must require a subcommand (fetch/status/clean)",
    );
}

/// `cargo ktstr model unknown` rejects unknown subcommand names —
/// pins the closed enum shape so a typo doesn't fall through to
/// a different code path.
#[test]
fn parse_model_unknown_subcommand_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "model", "wat"]);
    assert!(rejected.is_err(), "model must reject unknown subcommands",);
}

// -- try_get_matches_from: funify subcommand --
//
// `cargo ktstr funify` (alias `costume`) reads JSON from stdin
// or a file and emits a deterministic petname-substituted
// transformation. Tests pin the input/seed/pretty fields plus
// the `costume` visible alias dispatch.

/// `cargo ktstr funify` parses bare with all fields default.
#[test]
fn parse_funify_bare() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "funify"]).unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Funify {
        input,
        seed,
        pretty,
    } = k.command
    else {
        panic!("expected Funify");
    };
    assert!(input.is_none(), "bare funify must default --input to None");
    assert!(seed.is_none(), "bare funify must default --seed to None");
    assert!(!pretty, "bare funify must default --pretty to false");
}

/// `cargo ktstr funify <PATH>` round-trips the positional input
/// path into `Funify { input: Some(PathBuf), .. }`.
#[test]
fn parse_funify_with_input_path() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "funify", "/tmp/dump.json"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Funify { input, .. } = k.command else {
        panic!("expected Funify");
    };
    assert_eq!(
        input,
        Some(std::path::PathBuf::from("/tmp/dump.json")),
        "positional INPUT must round-trip to Some(PathBuf)",
    );
}

/// `cargo ktstr funify --seed S --pretty` round-trips both flags.
#[test]
fn parse_funify_with_seed_and_pretty() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "funify", "--seed", "demo", "--pretty"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Funify {
        input,
        seed,
        pretty,
    } = k.command
    else {
        panic!("expected Funify");
    };
    assert!(input.is_none(), "no positional INPUT must produce None");
    assert_eq!(seed.as_deref(), Some("demo"));
    assert!(pretty, "--pretty must lift the flag to true");
}

/// The `costume` visible alias dispatches to the same `Funify`
/// variant. `visible_alias = "costume"` on the variant makes the
/// alias user-facing; a regression that dropped or renamed it
/// surfaces here as an unknown-subcommand parse error.
#[test]
fn parse_funify_costume_alias_dispatches_to_funify() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "costume"]).unwrap_or_else(|e| panic!("{e}"));
    assert!(
        matches!(k.command, KtstrCommand::Funify { .. }),
        "`costume` alias must dispatch to the Funify variant",
    );
}

/// Sibling pin to [`parse_funify_costume_alias_dispatches_to_funify`]:
/// the `costume` alias inherits the canonical `Funify` variant's full
/// arg surface (positional INPUT, `--seed`, `--pretty`). Mirrors the
/// `nextest` alias coverage — the alias path must NOT regress to a
/// distinct parse tree that silently drops fields. A clap regression
/// that re-generated the costume subcommand without inheriting the
/// Funify variant's args would surface here at parse time.
#[test]
fn parse_funify_costume_alias_with_seed_and_pretty() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "costume",
        "/tmp/dump.json",
        "--seed",
        "demo",
        "--pretty",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Funify {
        input,
        seed,
        pretty,
    } = k.command
    else {
        panic!("expected Funify (via `costume` alias)");
    };
    assert_eq!(
        input,
        Some(std::path::PathBuf::from("/tmp/dump.json")),
        "costume alias must round-trip the positional INPUT",
    );
    assert_eq!(seed.as_deref(), Some("demo"));
    assert!(
        pretty,
        "--pretty must lift the flag to true on costume alias"
    );
}

/// `cargo ktstr funify -` round-trips the dash sentinel into
/// `Funify { input: Some(PathBuf("-")), .. }`. The dispatch site
/// (`funify.rs`) keys on this exact form for stdin mode — without a
/// pin here, a future `value_parser` mapping `-` to `None` would
/// silently dead-code the stdin path while the help text still
/// promised `Pass `-` (or omit) to read from stdin`.
#[test]
fn parse_funify_with_dash_input() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "funify", "-"]).unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Funify { input, .. } = k.command else {
        panic!("expected Funify");
    };
    assert_eq!(
        input,
        Some(std::path::PathBuf::from("-")),
        "the `-` stdin sentinel must round-trip as Some(PathBuf(\"-\")), \
         NOT collapse to None — the dispatch path keys on this exact form",
    );
}

// -- try_get_matches_from: export subcommand --
//
// `cargo ktstr export <test>` produces a self-extracting `.run`
// reproducer for a registered test. Tests pin the positional
// test name plus the `--output`, `--package`, and `--release`
// flags.

/// `cargo ktstr export <test>` round-trips the bare positional
/// test name with all option fields defaulting to None/false.
#[test]
fn parse_export_with_test_arg() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "export",
        "preempt_regression_fault_under_load",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Export {
        test,
        output,
        package,
        release,
    } = k.command
    else {
        panic!("expected Export");
    };
    assert_eq!(test, "preempt_regression_fault_under_load");
    assert!(
        output.is_none(),
        "bare export must default --output to None"
    );
    assert!(
        package.is_none(),
        "bare export must default --package to None"
    );
    assert!(!release, "bare export must default --release to false");
}

/// `cargo ktstr export <test> -o PATH --package P --release`
/// round-trips every flag plus the positional argument.
#[test]
fn parse_export_with_all_flags() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "export",
        "my_test_fn",
        "-o",
        "/tmp/out.run",
        "--package",
        "scx_rusty",
        "--release",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Export {
        test,
        output,
        package,
        release,
    } = k.command
    else {
        panic!("expected Export");
    };
    assert_eq!(test, "my_test_fn");
    assert_eq!(
        output,
        Some(std::path::PathBuf::from("/tmp/out.run")),
        "-o must round-trip to Some(PathBuf)",
    );
    assert_eq!(package.as_deref(), Some("scx_rusty"));
    assert!(release, "--release must lift the flag to true");
}

/// `cargo ktstr export --output PATH ...` (long form of `-o`)
/// must work identically. Pins the long-form spelling so a
/// regression that dropped the long-form attribute surfaces here.
#[test]
fn parse_export_with_output_long_form() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo",
        "ktstr",
        "export",
        "test_fn",
        "--output",
        "/tmp/long.run",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Export { output, .. } = k.command else {
        panic!("expected Export");
    };
    assert_eq!(output, Some(std::path::PathBuf::from("/tmp/long.run")));
}

/// `cargo ktstr export -p PKG ...` (short form of `--package`)
/// must work identically.
#[test]
fn parse_export_with_package_short_form() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "export", "test_fn", "-p", "ktstr"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Export { package, .. } = k.command else {
        panic!("expected Export");
    };
    assert_eq!(package.as_deref(), Some("ktstr"));
}

/// `cargo ktstr export` without a positional test name must fail
/// at parse time — the test name is required.
#[test]
fn parse_export_missing_test_arg_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "export"]);
    assert!(
        rejected.is_err(),
        "export must require a positional test-name argument",
    );
}

/// `cargo ktstr export <a> <b>` is rejected — `export` accepts
/// exactly one positional test name. A variadic regression would
/// silently drop the second arg (or reinterpret it as a flag value
/// like `--package b`), masking the operator's typo. Mirrors
/// `parse_show_thresholds_extra_arg_rejected` for the export
/// subcommand.
#[test]
fn parse_export_extra_arg_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "export", "a", "b"]);
    assert!(
        rejected.is_err(),
        "export must accept exactly one positional arg",
    );
}

// -- try_get_matches_from: locks subcommand --
//
// `cargo ktstr locks` snapshots ktstr flock state under
// `/tmp/ktstr-*.lock` and `{cache_root}/.locks/*.lock` for
// `--cpu-cap` contention diagnosis. Tests pin the `--json` and
// `--watch` flags plus the `humantime` value parser on `--watch`.

/// `cargo ktstr locks` parses bare with both fields default.
#[test]
fn parse_locks_bare() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "locks"]).unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Locks { json, watch } = k.command else {
        panic!("expected Locks");
    };
    assert!(!json, "bare locks must default --json to false");
    assert!(watch.is_none(), "bare locks must default --watch to None");
}

/// `cargo ktstr locks --json` lifts the json field to true.
#[test]
fn parse_locks_with_json() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "locks", "--json"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Locks { json, watch } = k.command else {
        panic!("expected Locks");
    };
    assert!(json, "--json must lift the flag to true");
    assert!(watch.is_none(), "bare --json must not populate --watch");
}

/// `cargo ktstr locks --watch <DURATION>` round-trips a humantime
/// duration through the `value_parser =
/// humantime::parse_duration` attribute.
#[test]
fn parse_locks_with_watch_duration() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "locks", "--watch", "500ms"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Locks { json, watch } = k.command else {
        panic!("expected Locks");
    };
    assert!(!json, "bare --watch must not populate --json");
    assert_eq!(
        watch,
        Some(std::time::Duration::from_millis(500)),
        "--watch 500ms must round-trip to Duration::from_millis(500)",
    );
}

/// `cargo ktstr locks --watch 5s --json` round-trips both flags
/// in combination — the `--watch` redraw mode emits ndjson when
/// `--json` is also set.
#[test]
fn parse_locks_with_watch_and_json() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "locks", "--watch", "5s", "--json"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Locks { json, watch } = k.command else {
        panic!("expected Locks");
    };
    assert!(json, "--json must lift the flag to true alongside --watch");
    assert_eq!(
        watch,
        Some(std::time::Duration::from_secs(5)),
        "--watch 5s must round-trip to Duration::from_secs(5)",
    );
}

/// `cargo ktstr locks --watch <BAD>` rejects malformed duration
/// strings at parse time via humantime's `parse_duration`. Catches
/// a regression that dropped the `value_parser` attribute and
/// turned the field into a raw String / unbounded text input.
#[test]
fn parse_locks_watch_rejects_malformed_duration() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "locks", "--watch", "not-a-duration"]);
    assert!(
        rejected.is_err(),
        "--watch must reject malformed humantime input via the \
         value_parser = humantime::parse_duration attribute",
    );
}

// -- try_get_matches_from: shell --memory-mb / --exec / --dmesg --

/// `cargo ktstr shell --memory-mb 256` round-trips the value
/// through clap's `value_parser!(u32).range(128..)` attribute.
#[test]
fn parse_shell_memory_mb_valid() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "shell", "--memory-mb", "256"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell { memory_mb, .. } = k.command else {
        panic!("expected Shell");
    };
    assert_eq!(memory_mb, Some(256), "--memory-mb 256 must round-trip");
}

/// `cargo ktstr shell --memory-mb 128` accepts the range floor —
/// the clap range is `128..` (inclusive).
#[test]
fn parse_shell_memory_mb_at_range_floor() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "shell", "--memory-mb", "128"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell { memory_mb, .. } = k.command else {
        panic!("expected Shell");
    };
    assert_eq!(
        memory_mb,
        Some(128),
        "--memory-mb 128 must succeed at the inclusive range floor",
    );
}

/// `cargo ktstr shell --memory-mb 64` is rejected — below the
/// `value_parser!(u32).range(128..)` floor. Pins the constraint:
/// a regression that dropped the range or relaxed the lower
/// bound surfaces here.
#[test]
fn parse_shell_memory_mb_below_range_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "shell", "--memory-mb", "64"]);
    assert!(
        rejected.is_err(),
        "--memory-mb 64 must be rejected — value_parser range floor is 128",
    );
}

/// `cargo ktstr shell --memory-mb -1` is rejected at parse time —
/// the field is `u32`, so a signed value cannot satisfy the
/// type-level value parser. Pins the unsigned-integer
/// constraint.
#[test]
fn parse_shell_memory_mb_negative_rejected() {
    let rejected = Cargo::try_parse_from(["cargo", "ktstr", "shell", "--memory-mb", "-1"]);
    assert!(
        rejected.is_err(),
        "--memory-mb -1 must be rejected — the field is u32",
    );
}

/// `cargo ktstr shell --exec "uname -a"` round-trips the command
/// string through clap into `Shell { exec: Some(..), .. }`. The
/// dispatch site forwards the string into the VM's init line.
#[test]
fn parse_shell_with_exec() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "shell", "--exec", "uname -a"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell { exec, .. } = k.command else {
        panic!("expected Shell");
    };
    assert_eq!(exec.as_deref(), Some("uname -a"));
}

/// `cargo ktstr shell --dmesg` lifts the dmesg field to true.
#[test]
fn parse_shell_with_dmesg() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "shell", "--dmesg"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell { dmesg, .. } = k.command else {
        panic!("expected Shell");
    };
    assert!(dmesg, "--dmesg must lift the flag to true");
}

/// Bare `cargo ktstr shell` defaults `--dmesg` to false and
/// `--exec` to None. Pins that neither flag is implicitly set.
#[test]
fn parse_shell_dmesg_and_exec_default_unset() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "shell"]).unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Shell { dmesg, exec, .. } = k.command else {
        panic!("expected Shell");
    };
    assert!(!dmesg, "bare shell must default --dmesg to false");
    assert!(exec.is_none(), "bare shell must default --exec to None");
}

// -- try_get_matches_from: --kernel ArgAction::Append on every
// `Vec<String> kernel` subcommand. Repeats fan out the gauntlet
// across kernels at the dispatch layer; a regression that lost
// `ArgAction::Append` would either reject the second occurrence
// outright (`Vec<String>` derive without the action would fail
// "the argument was supplied more than once") or silently keep
// only the last value.

/// `cargo ktstr test --kernel A --kernel B` accumulates both
/// values into the `kernel` Vec via `ArgAction::Append`.
#[test]
fn parse_test_kernel_repeatable() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo", "ktstr", "test", "--kernel", "6.14.2", "--kernel", "6.15-rc3",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Test { kernel, .. } = k.command else {
        panic!("expected Test");
    };
    assert_eq!(
        kernel,
        vec!["6.14.2".to_string(), "6.15-rc3".to_string()],
        "test --kernel must accumulate via ArgAction::Append",
    );
}

/// `cargo ktstr coverage --kernel A --kernel B` accumulates both
/// values via `ArgAction::Append`.
#[test]
fn parse_coverage_kernel_repeatable() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo", "ktstr", "coverage", "--kernel", "6.14.2", "--kernel", "6.15-rc3",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Coverage { kernel, .. } = k.command else {
        panic!("expected Coverage");
    };
    assert_eq!(
        kernel,
        vec!["6.14.2".to_string(), "6.15-rc3".to_string()],
        "coverage --kernel must accumulate via ArgAction::Append",
    );
}

/// `cargo ktstr llvm-cov --kernel A --kernel B` accumulates both
/// values via `ArgAction::Append`.
#[test]
fn parse_llvm_cov_kernel_repeatable() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo", "ktstr", "llvm-cov", "--kernel", "6.14.2", "--kernel", "6.15-rc3",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::LlvmCov { kernel, .. } = k.command else {
        panic!("expected LlvmCov");
    };
    assert_eq!(
        kernel,
        vec!["6.14.2".to_string(), "6.15-rc3".to_string()],
        "llvm-cov --kernel must accumulate via ArgAction::Append",
    );
}

/// `cargo ktstr verifier --kernel A --kernel B` accumulates both
/// values via `ArgAction::Append`. Mirrors
/// `parse_test_kernel_repeatable` for the verifier subcommand —
/// the verifier surface is `--kernel` + `--raw` only (no
/// `--scheduler`).
#[test]
fn parse_verifier_kernel_repeatable() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from([
        "cargo", "ktstr", "verifier", "--kernel", "6.14.2", "--kernel", "6.15-rc3",
    ])
    .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Verifier { kernel, .. } = k.command else {
        panic!("expected Verifier");
    };
    assert_eq!(
        kernel,
        vec!["6.14.2".to_string(), "6.15-rc3".to_string()],
        "verifier --kernel must accumulate via ArgAction::Append",
    );
}

// -- try_get_matches_from: kernel build --ref/--git symmetry --

/// Symmetric pin to [`parse_kernel_build_git_requires_ref`]:
/// `--ref REF` without `--git URL` must also fail at parse time.
/// `git_ref` carries `requires = "git"`, so a regression that
/// dropped that attribute would let `--ref` be set without a
/// matching git URL — ambiguous at the dispatch layer.
#[test]
fn parse_kernel_build_ref_requires_git() {
    let result = Cargo::try_parse_from(["cargo", "ktstr", "kernel", "build", "--ref", "v6.14"]);
    match result {
        Ok(_) => panic!("--ref without --git must be rejected at parse time"),
        Err(err) => assert_eq!(
            err.kind(),
            clap::error::ErrorKind::MissingRequiredArgument,
            "expected MissingRequiredArgument — `--ref` carries \
             `requires = \"git\"` (clap uses the field name, not \
             the long flag name), so a regression that dropped the \
             attribute would surface as a different ErrorKind that \
             the bare is_err() pin would silently mask. Full err: {err}",
        ),
    }
}

// -- try_get_matches_from: completions --binary default --

/// `cargo ktstr completions bash` defaults `--binary` to `cargo`
/// per the `default_value = "cargo"` attribute on the field.
/// A regression that dropped or changed the default surfaces
/// here.
#[test]
fn parse_completions_binary_default_is_cargo() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "completions", "bash"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Completions { binary, .. } = k.command else {
        panic!("expected Completions");
    };
    assert_eq!(binary, "cargo", "default --binary must be `cargo`",);
}

/// `cargo ktstr completions bash --binary X` overrides the
/// default. Pins the override path.
#[test]
fn parse_completions_binary_override() {
    let Cargo {
        command: CargoSub::Ktstr(k),
    } = Cargo::try_parse_from(["cargo", "ktstr", "completions", "bash", "--binary", "ktstr"])
        .unwrap_or_else(|e| panic!("{e}"));
    let KtstrCommand::Completions { binary, .. } = k.command else {
        panic!("expected Completions");
    };
    assert_eq!(binary, "ktstr");
}

// -- try_get_matches_from: per-side compare flags coverage --
//
// The shared/per-side `--X` / `--a-X` / `--b-X` shape on `stats
// compare` is exercised for `kernel`, `kernel_commit`,
// `project_commit`, and `run_source` above. The siblings below
// pin the SAME shape for the remaining slicing dimensions —
// `topology`, `scheduler`, `work_type`, and `flag` — so a
// regression that lost the per-side derive on any one of them
// surfaces here at parse time rather than at the dispatch layer
// where "more-specific replaces" semantics fold per-side into
// the BuildCompareFilters bundle.

/// `--a-topology A --b-topology B` round-trips into the per-side
/// vecs without touching the shared `topology` vec.
#[test]
fn parse_stats_compare_with_per_side_topology() {
    let StatsCommand::Compare {
        topology,
        a_topology,
        b_topology,
        ..
    } = parse_compare(&["--a-topology", "1n2l4c2t", "--b-topology", "1n4l2c1t"])
    else {
        unreachable!()
    };
    assert!(
        topology.is_empty(),
        "per-side --a-topology / --b-topology must not populate the shared --topology vec",
    );
    assert_eq!(a_topology, vec!["1n2l4c2t".to_string()]);
    assert_eq!(b_topology, vec!["1n4l2c1t".to_string()]);
}

/// `--a-scheduler A --b-scheduler B` round-trips into the per-side
/// vecs without touching the shared `scheduler` vec.
#[test]
fn parse_stats_compare_with_per_side_scheduler() {
    let StatsCommand::Compare {
        scheduler,
        a_scheduler,
        b_scheduler,
        ..
    } = parse_compare(&["--a-scheduler", "scx_alpha", "--b-scheduler", "scx_beta"])
    else {
        unreachable!()
    };
    assert!(
        scheduler.is_empty(),
        "per-side --a-scheduler / --b-scheduler must not populate the shared --scheduler vec",
    );
    assert_eq!(a_scheduler, vec!["scx_alpha".to_string()]);
    assert_eq!(b_scheduler, vec!["scx_beta".to_string()]);
}

/// `--a-work-type A --b-work-type B` round-trips into the per-side
/// vecs without touching the shared `work_type` vec.
#[test]
fn parse_stats_compare_with_per_side_work_type() {
    let StatsCommand::Compare {
        work_type,
        a_work_type,
        b_work_type,
        ..
    } = parse_compare(&[
        "--a-work-type",
        "SpinWait",
        "--b-work-type",
        "PageFaultChurn",
    ])
    else {
        unreachable!()
    };
    assert!(
        work_type.is_empty(),
        "per-side --a-work-type / --b-work-type must not populate the shared --work-type vec",
    );
    assert_eq!(a_work_type, vec!["SpinWait".to_string()]);
    assert_eq!(b_work_type, vec!["PageFaultChurn".to_string()]);
}

/// `--a-project-commit A --b-project-commit B` round-trips into
/// the per-side vecs without touching the shared `project_commit`
/// vec.
#[test]
fn parse_stats_compare_with_per_side_project_commit() {
    let StatsCommand::Compare {
        project_commit,
        a_project_commit,
        b_project_commit,
        ..
    } = parse_compare(&[
        "--a-project-commit",
        "abc1234",
        "--b-project-commit",
        "def5678",
    ])
    else {
        unreachable!()
    };
    assert!(
        project_commit.is_empty(),
        "per-side --a-project-commit / --b-project-commit must not \
         populate the shared --project-commit vec",
    );
    assert_eq!(a_project_commit, vec!["abc1234".to_string()]);
    assert_eq!(b_project_commit, vec!["def5678".to_string()]);
}

/// `--flag F --a-flag G --b-flag H` are rejected by clap — the
/// flag-profile filter surface was removed alongside the flag
/// infrastructure. A future re-add without rebuilding the
/// underlying `RowFilter.flags` plumbing would fail this test.
#[test]
fn parse_stats_compare_flag_filters_rejected() {
    let outcome = std::panic::catch_unwind(|| {
        parse_compare(&[
            "--flag",
            "shared_flag",
            "--a-flag",
            "a_only_flag",
            "--b-flag",
            "b_only_flag",
        ])
    });
    assert!(
        outcome.is_err(),
        "--flag / --a-flag / --b-flag must be rejected — the flag-profile \
         filter was removed when the flag infrastructure went away",
    );
}