ktstr 0.4.9

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
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;

use clap::{ArgAction, CommandFactory, Parser, Subcommand};
use ktstr::cache::{CacheDir, CacheEntry};
use ktstr::cli;
use ktstr::cli::KernelCommand;
use ktstr::cli::{KERNEL_HELP_NO_RAW, KERNEL_HELP_RAW_OK};
use ktstr::fetch;

#[derive(Parser)]
#[command(name = "cargo-ktstr", bin_name = "cargo")]
struct Cargo {
    #[command(subcommand)]
    command: CargoSub,
}

#[derive(Subcommand)]
enum CargoSub {
    /// ktstr dev workflow: build kernel + run tests.
    Ktstr(Ktstr),
}

#[derive(Parser)]
struct Ktstr {
    #[command(subcommand)]
    command: KtstrCommand,
}

// Same rationale as `StatsCommand`'s sibling `#[allow]` — clap's
// derive expands every variant into a struct of `Option<T>` /
// `Vec<T>` per CLI flag, which after #117's per-side slicing
// flags pushes the Stats-via-Compare variant past clippy's
// large-variant heuristic. The enum is constructed once per CLI
// invocation and dispatched immediately; boxing every variant
// would distort the match ergonomics without measurable benefit.
#[allow(clippy::large_enum_variant)]
#[derive(Subcommand)]
enum KtstrCommand {
    /// Build the kernel (if needed) and run tests via cargo nextest.
    #[command(visible_alias = "nextest")]
    Test {
        /// Repeatable. See [`KERNEL_HELP_NO_RAW`] for accepted shapes
        /// (path, version, cache key, range `START..END`, git source
        /// `git+URL#REF`). Multiple `--kernel` flags fan out the
        /// gauntlet across kernels: each `(test × scenario × topology
        /// × flags × kernel)` tuple becomes a distinct nextest test
        /// case so nextest's parallelism, retries, and `-E`
        /// filtering all apply natively.
        #[arg(long, action = ArgAction::Append, help = KERNEL_HELP_NO_RAW)]
        kernel: Vec<String>,
        /// Disable all performance mode features (flock, pinning, RT
        /// scheduling, hugepages, NUMA mbind, KVM exit suppression).
        /// For shared runners or unprivileged containers.
        /// Also settable via KTSTR_NO_PERF_MODE env var.
        #[arg(long)]
        no_perf_mode: bool,
        /// Build and run tests with the release profile
        /// (`--cargo-profile release` to nextest).
        ///
        /// Release mode uses STRICTER assertion thresholds
        /// (`gap_threshold_ms` 2000 vs debug's 3000, `spread_threshold_pct`
        /// 15% vs debug's 35%) — tests that barely pass in debug may
        /// fail under `--release`. `catch_unwind`-based tests are
        /// skipped because release sets `panic = "abort"` (see
        /// `Cargo.toml [profile.release]`). Tests gated on
        /// `#[cfg(debug_assertions)]` also skip.
        #[arg(long)]
        release: bool,
        /// Arguments passed through to cargo nextest run.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Build the kernel (if needed) and run tests with coverage via
    /// cargo llvm-cov nextest. For other llvm-cov subcommands
    /// (`report`, `clean`, `show-env`), use `cargo ktstr llvm-cov`.
    Coverage {
        /// Repeatable. Same shapes and multi-kernel semantics as
        /// `cargo ktstr test --kernel`: each (test × kernel) variant
        /// runs as its own nextest subprocess so cargo-llvm-cov
        /// merges every variant's profraw automatically.
        #[arg(long, action = ArgAction::Append, help = KERNEL_HELP_NO_RAW)]
        kernel: Vec<String>,
        /// Disable all performance mode features (flock, pinning, RT
        /// scheduling, hugepages, NUMA mbind, KVM exit suppression).
        /// For shared runners or unprivileged containers.
        /// Also settable via KTSTR_NO_PERF_MODE env var.
        #[arg(long)]
        no_perf_mode: bool,
        /// Build and collect coverage with the release profile
        /// (`--cargo-profile release` to llvm-cov nextest).
        ///
        /// Release mode uses STRICTER assertion thresholds
        /// (`gap_threshold_ms` 2000 vs debug's 3000, `spread_threshold_pct`
        /// 15% vs debug's 35%) — tests that barely pass in debug may
        /// fail under `--release`. `catch_unwind`-based tests are
        /// skipped because release sets `panic = "abort"`.
        #[arg(long)]
        release: bool,
        /// Arguments passed through to cargo llvm-cov nextest.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Run `cargo llvm-cov` with arbitrary arguments.
    ///
    /// When you want `cargo llvm-cov nextest`, prefer `cargo ktstr
    /// coverage` — this subcommand is the raw passthrough for
    /// `llvm-cov` invocations that don't fit the coverage flow
    /// (e.g. `report`, `clean`, `show-env`).
    ///
    /// Note: bare `cargo ktstr llvm-cov` (no subcommand) dispatches
    /// to `cargo llvm-cov` which runs `cargo test` — not useful for
    /// ktstr tests. Always pass a subcommand.
    LlvmCov {
        /// Repeatable. Same shapes and multi-kernel semantics as
        /// `cargo ktstr test --kernel`. Profraw aggregation across
        /// kernel variants happens inside cargo-llvm-cov; this raw-
        /// passthrough hands every other argument to the user's
        /// chosen llvm-cov subcommand.
        #[arg(long, action = ArgAction::Append, help = KERNEL_HELP_NO_RAW)]
        kernel: Vec<String>,
        /// Disable all performance mode features (flock, pinning, RT
        /// scheduling, hugepages, NUMA mbind, KVM exit suppression).
        /// For shared runners or unprivileged containers.
        /// Also settable via KTSTR_NO_PERF_MODE env var.
        #[arg(long)]
        no_perf_mode: bool,
        /// Arguments passed through to cargo llvm-cov.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Print sidecar analysis from the most recent test run.
    ///
    /// Reads sidecar JSON files from the newest subdirectory under
    /// `{CARGO_TARGET_DIR or "target"}/ktstr/` (overridable with
    /// `KTSTR_SIDECAR_DIR`) and prints gauntlet analysis, BPF
    /// verifier stats, callback profile, and KVM stats. Test runs
    /// are partitioned into `{kernel}-{project_commit}` subdirectories,
    /// where `{project_commit}` is the project HEAD short hex with
    /// `-dirty` when the worktree differs; each subdirectory is
    /// the baseline snapshot of the most recent run at that
    /// (kernel, project commit) pair (re-running at the same key
    /// pre-clears prior sidecars before writing the new run).
    ///
    /// Use `list` to see runs; `compare <a> <b>` to diff two.
    Stats {
        #[command(subcommand)]
        command: Option<StatsCommand>,
    },
    /// Manage cached kernel images.
    Kernel {
        #[command(subcommand)]
        command: KernelCommand,
    },
    /// Manage the LLM model cache used by `OutputFormat::LlmExtract`
    /// payloads. `fetch` downloads the default pinned model to
    /// `~/.cache/ktstr/models/` (respecting `KTSTR_CACHE_DIR` /
    /// `XDG_CACHE_HOME`); `status` reports whether a SHA-checked copy
    /// is already cached; `clean` deletes the cached artifact and
    /// its `.mtime-size` warm-cache sidecar.
    Model {
        #[command(subcommand)]
        command: ModelCommand,
    },
    /// Collect BPF verifier statistics for a scheduler.
    ///
    /// Builds the scheduler (or uses a pre-built binary), boots a VM,
    /// loads the scheduler's BPF programs, and reports per-program
    /// verified instruction counts from host-side memory introspection.
    Verifier {
        /// Scheduler package name to build and analyze.
        #[arg(long)]
        scheduler: Option<String>,
        /// Path to pre-built scheduler binary (alternative to --scheduler).
        #[arg(long, conflicts_with = "scheduler")]
        scheduler_bin: Option<PathBuf>,
        /// Repeatable. See [`KERNEL_HELP_NO_RAW`] for accepted shapes
        /// (path / version / cache key / range / git source). When
        /// the resolved set has 2+ entries, the verifier collects
        /// stats per kernel sequentially and outputs per-kernel
        /// blocks separated by a header line — there is no
        /// cross-kernel summary table. Single-kernel runs are
        /// unchanged. Raw image files are rejected here for the
        /// same reason as `cargo ktstr test`/`coverage`/`llvm-cov`:
        /// the verifier needs the cached `vmlinux` and kconfig
        /// fragment alongside the image, which a bare `bzImage`
        /// path does not carry.
        #[arg(long, action = ArgAction::Append, help = KERNEL_HELP_NO_RAW)]
        kernel: Vec<String>,
        /// Print raw verifier output without formatting.
        #[arg(long)]
        raw: bool,
        /// Run verifier for all flag profiles. Discovers flags via
        /// `--ktstr-list-flags`, constructs profiles (power set
        /// respecting requires dependencies), and collects verifier
        /// stats per profile.
        #[arg(long)]
        all_profiles: bool,
        /// Run verifier for specific profiles only (comma-separated
        /// names, e.g. `default,llc,llc+steal`). Implies --all-profiles
        /// for flag discovery.
        #[arg(long, value_delimiter = ',')]
        profiles: Vec<String>,
    },
    /// Generate shell completions for cargo-ktstr.
    Completions {
        /// Shell to generate completions for.
        shell: clap_complete::Shell,
        /// Binary name for completions.
        #[arg(long, default_value = "cargo")]
        binary: String,
    },
    /// Print the current host context used by sidecar collection:
    /// CPU identity, memory/hugepage config, transparent-hugepage
    /// policy, NUMA node count, kernel uname triple
    /// (sysname/release/machine), kernel cmdline, and every
    /// `/proc/sys/kernel/sched_*` tunable. Useful for diagnosing
    /// cross-run regressions that trace back to host-context drift
    /// (sysctl change, THP policy flip, hugepage reservation).
    ///
    /// For historical drift between archived runs, use
    /// `cargo ktstr stats compare` — its host-delta section
    /// reports which host-context fields changed between run A
    /// and run B using the same [`HostContext::diff`] logic.
    ShowHost,
    /// Print the resolved assertion thresholds for the named test.
    ///
    /// Dumps the merged `Assert` produced by the runtime merge chain
    /// `Assert::default_checks().merge(entry.scheduler.assert()).merge(&entry.assert)`
    /// — the same value `run_ktstr_test_inner` evaluates against
    /// worker reports. Surfaces every threshold field (or `none`
    /// when inherited / unset) so an operator can see what the test
    /// will actually check against without reading source or
    /// guessing which layer contributed each bound.
    ///
    /// Fails with an actionable message when no registered test
    /// matches the given name. Use `cargo nextest list` to
    /// enumerate test names — then pass just the FUNCTION-NAME
    /// component to `show-thresholds`, not the `<binary>::`
    /// prefix that nextest prepends to each line. The
    /// `#[ktstr_test]` registry keys on the bare function name,
    /// so `ktstr::preempt_regression_fault_under_load` (as
    /// printed by nextest) must be trimmed to
    /// `preempt_regression_fault_under_load` before it resolves.
    ShowThresholds {
        /// Function-name-only test identifier as registered in
        /// `#[ktstr_test]` (e.g. `preempt_regression_fault_under_load`).
        /// Do NOT include the `<binary>::` prefix that
        /// `cargo nextest list` prepends — strip it before
        /// invoking this command.
        test: String,
    },
    /// Clean up leftover ktstr cgroups.
    ///
    /// Without `--parent-cgroup`, scans `/sys/fs/cgroup` for the default
    /// ktstr parents (`ktstr` and `ktstr-<pid>`, the paths that `ktstr
    /// run` and the in-process test harness create) and rmdirs each.
    /// `ktstr-<pid>` directories whose pid is still a running ktstr or
    /// cargo-ktstr process are skipped, so a concurrent cleanup run
    /// doesn't yank an active run's cgroup.
    Cleanup {
        /// Parent cgroup path. When set, cleans only this path and
        /// leaves the parent directory in place; when omitted, scans
        /// `/sys/fs/cgroup` for the default ktstr parents
        /// (`ktstr/` and `ktstr-<pid>/`) and rmdirs each.
        #[arg(long)]
        parent_cgroup: Option<String>,
    },
    /// Enumerate every ktstr flock held on this host.
    ///
    /// Troubleshooting companion for `--cpu-cap` contention. Scans
    /// `/tmp/ktstr-llc-*.lock`, `/tmp/ktstr-cpu-*.lock`, and
    /// `{cache_root}/.locks/*.lock`, cross-referenced against
    /// `/proc/locks` via [`ktstr::cli::list_locks`] to name the holder
    /// process (PID + cmdline) for each held lock. Read-only — does
    /// NOT attempt any flock acquire.
    Locks {
        /// Emit the snapshot as JSON (compact object under --watch,
        /// pretty-printed otherwise). Stable field names; schema
        /// documented at [`ktstr::cli::list_locks`].
        #[arg(long)]
        json: bool,
        /// Redraw the snapshot on the given interval until SIGINT.
        /// Value is parsed by `humantime`: `100ms`, `1s`, `5m`, `1h`.
        /// Human output clears and redraws in place; `--json` emits
        /// one line-terminated object per interval (ndjson-style).
        #[arg(long, value_parser = humantime::parse_duration)]
        watch: Option<std::time::Duration>,
    },
    /// Boot an interactive shell in a KVM virtual machine.
    ///
    /// Launches a VM with busybox and drops into a shell. Files and
    /// directories passed via -i are available at /include-files/<name>
    /// inside the guest. Directories are walked recursively, preserving
    /// structure. Dynamically-linked ELF binaries get automatic shared
    /// library resolution via ELF DT_NEEDED parsing.
    Shell {
        #[arg(long, help = KERNEL_HELP_RAW_OK)]
        kernel: Option<String>,
        /// Virtual topology as "numa_nodes,llcs,cores,threads".
        #[arg(long, default_value = "1,1,1,1")]
        topology: String,
        /// Files or directories to include in the guest. Repeatable.
        #[arg(short = 'i', long = "include-files", action = ArgAction::Append)]
        include_files: Vec<PathBuf>,
        /// Guest memory in MB (minimum 128). When absent, estimated
        /// from payload and include file sizes.
        #[arg(long = "memory-mb", value_parser = clap::value_parser!(u32).range(128..))]
        memory_mb: Option<u32>,
        /// Forward kernel console (COM1/dmesg) to stderr in real-time.
        /// Sets loglevel=7 for verbose kernel output.
        #[arg(long)]
        dmesg: bool,
        /// Run a command in the VM instead of an interactive shell.
        /// The VM exits after the command completes.
        #[arg(long)]
        exec: Option<String>,

        /// Disable all performance mode features (flock, pinning, RT
        /// scheduling, hugepages, NUMA mbind, KVM exit suppression).
        /// For shared runners or unprivileged containers.
        /// Also settable via KTSTR_NO_PERF_MODE env var.
        #[arg(long)]
        no_perf_mode: bool,

        /// Reserve only N host CPUs for the shell VM. Requires
        /// `--no-perf-mode` — perf-mode already holds every LLC
        /// exclusively, so capping under perf-mode would
        /// double-reserve. See `ktstr::cli::CPU_CAP_HELP` for the
        /// full contract.
        #[arg(long, requires = "no_perf_mode", help = ktstr::cli::CPU_CAP_HELP)]
        cpu_cap: Option<usize>,
    },
}

#[derive(Subcommand)]
enum ModelCommand {
    /// Download the default pinned model and check its SHA-256.
    /// No-op when the cache already holds a SHA-checked copy.
    /// Respects `KTSTR_MODEL_OFFLINE` — set to `1` to refuse network
    /// fetches.
    Fetch,
    /// Print the cache path for the default model and whether a
    /// SHA-checked copy is already present.
    Status,
    /// Delete the cached GGUF artifact and its `.mtime-size`
    /// warm-cache sidecar. Subsequent `model fetch` re-downloads
    /// the pin from scratch. No-op when nothing is cached.
    Clean,
}

// `clippy::large_enum_variant` triggers because clap's argument
// derives produce variant-sized cells of `Option<String>` /
// `Option<PathBuf>` per CLI flag. Boxing each variant would
// distort every match arm's pattern shape (`Some(StatsCommand::
// Compare { .. })` becomes `Some(StatsCommand::Compare(box))`)
// and force every dispatch site through an extra deref. The enum
// is constructed once per CLI invocation and immediately
// pattern-matched into a single subcommand call — no allocation
// hot path, no cache pressure. Suppress at the enum level rather
// than wrapping each variant in `Box`.
#[allow(clippy::large_enum_variant)]
#[derive(Subcommand)]
enum StatsCommand {
    /// List test runs under `{CARGO_TARGET_DIR or "target"}/ktstr/`.
    List,
    /// List the registered regression metrics and their default
    /// thresholds.
    ///
    /// Enumerates the `ktstr::stats::METRICS` registry: metric name,
    /// polarity (higher/lower better), default absolute-delta gate,
    /// default relative-delta gate, display unit, and a one-line
    /// description. Use this to see which metric names
    /// `ComparisonPolicy.per_metric_percent` keys can reference, and
    /// what each default_abs / default_rel gate starts at before an
    /// override.
    ///
    /// Default output is a human-readable table; `--json` emits a
    /// JSON array with the same fields (the row accessor function is
    /// omitted — `#[serde(skip)]` in the registry).
    ListMetrics {
        /// Emit JSON instead of a table.
        #[arg(long)]
        json: bool,
    },
    /// List the distinct values present per filterable dimension in
    /// the sidecar pool.
    ///
    /// Walks every run directory under `runs_root()` (or `--dir`),
    /// pools the sidecars, and reports the set of distinct values
    /// found across all eight filterable dimensions: `kernel`,
    /// `commit`, `kernel_commit`, `source`, `scheduler`,
    /// `topology`, `work_type`, and `flags` (individual flag
    /// names). The JSON keys `commit` and `source` map to the
    /// internal `SidecarResult::project_commit` /
    /// `SidecarResult::run_source` fields; the per-side filter
    /// flags spell `--project-commit` / `--run-source` on the
    /// `compare` subcommand. Use this before crafting a
    /// `cargo ktstr stats compare` invocation to discover what
    /// `--a-X` / `--b-X` values the pool actually carries — a
    /// `--a-kernel 6.20` against an empty pool fails downstream
    /// with "no rows match filter A", and `list-values` is the
    /// upstream answer to "what kernels do I have?".
    ///
    /// Default output renders one block per dimension with values
    /// one per line; `--json` emits a single JSON object keyed by
    /// dimension name. The four optional dimensions (`kernel`,
    /// `commit`, `kernel_commit`, `source`) surface absent values
    /// as the textual sentinel `unknown` in the table shape and as
    /// JSON `null` in the JSON shape.
    ListValues {
        /// Emit JSON instead of a per-dimension text block.
        #[arg(long)]
        json: bool,
        /// Alternate run root to walk. Defaults to
        /// `test_support::runs_root()` (typically `target/ktstr/`).
        /// Same semantics as `cargo ktstr stats compare --dir` and
        /// `cargo ktstr stats show-host --dir`: useful when
        /// inspecting archived sidecar trees copied off a CI host.
        #[arg(long)]
        dir: Option<std::path::PathBuf>,
    },
    /// Print the archived host context for a specific run.
    ///
    /// Resolves `--run <id>` against `test_support::runs_root()`
    /// (or `--dir` when set), loads any sidecar file under that
    /// run directory, and renders the `host` field via
    /// `HostContext::format_human`. Useful for inspecting the
    /// CPU model, memory config, THP policy, and sched_* tunables
    /// captured at archive time — the same fingerprint
    /// `compare_partitions` uses for its host-delta section, now
    /// available on a single run.
    ///
    /// Scans sidecars in iteration order and returns the FIRST
    /// sidecar with a populated host field. Every sidecar in a
    /// single run captures the same host, but older pre-
    /// enrichment sidecars may have `host: None`; the forward
    /// scan tolerates those without false-failing as long as at
    /// least one sidecar carries the data. If NO sidecar has a
    /// populated host field, the command fails with an actionable
    /// error naming the likely cause (pre-enrichment run) rather
    /// than silently returning empty output.
    ShowHost {
        /// Run key (e.g. `6.14-abc1234` or `6.14-abc1234-dirty`;
        /// from `cargo ktstr stats list`).
        #[arg(long)]
        run: String,
        /// Alternate run root to resolve `--run` against. Defaults
        /// to `test_support::runs_root()` (typically
        /// `target/ktstr/`). Same semantics as
        /// `cargo ktstr stats compare --dir`.
        #[arg(long)]
        dir: Option<std::path::PathBuf>,
    },
    /// Diagnose missing optional fields across a run's sidecars.
    ///
    /// Loads every `*.ktstr.json` under `--run <id>` and reports,
    /// per sidecar, which optional fields landed as null along
    /// with the documented reasons each one can be missing. Every
    /// such field carries a classification:
    ///
    /// - `expected` — null is the steady-state shape; no operator
    ///   action recovers it (e.g. payload metadata for a
    ///   scheduler-only test).
    /// - `actionable` — null indicates a recoverable gap;
    ///   re-running in a different environment (in-repo cwd,
    ///   non-tarball kernel, non-host-only test) would populate
    ///   the field.
    ///
    /// Different gauntlet variants on the same run legitimately
    /// differ on which fields populate (host-only vs VM-backed,
    /// scheduler-only vs payload-bearing), so the report is
    /// per-sidecar rather than aggregate.
    ///
    /// Sidecars are loaded verbatim. Diverges intentionally from
    /// `stats compare` / `stats list-values` (which rewrite the
    /// `run_source` field to `"archive"` when `--dir` is set):
    /// the override would erase the only signal that surfaces a
    /// pre-rename archive whose `run_source` field was lost on
    /// load. Matches `stats show-host` semantics.
    ///
    /// Default output is per-sidecar text blocks with a header
    /// line reporting walked / parsed counts (so a corrupt
    /// `.ktstr.json` file surfaces as a parse-failure delta
    /// against the file count). Each `None` cause carries an
    /// optional `fix:` line with an operator-actionable
    /// remediation when one applies (e.g. "set KTSTR_KERNEL to
    /// a local kernel source tree" recovers `kernel_commit =
    /// None` for env-unset cases). When the walk encounters
    /// parse failures, the text output appends a trailing
    /// `corrupt sidecars (N):` block listing each corrupt path
    /// with the raw serde error message and (when applicable)
    /// an `enriched:` line with operator-facing remediation
    /// prose for known schema-drift cases. All-corrupt runs
    /// render the header + corrupt-block alone (no per-sidecar
    /// breakdown to render), preserving per-file diagnostic
    /// detail rather than collapsing to a single error line.
    ///
    /// `--json` emits a single object with three top-level
    /// keys: `_schema_version` (string version stamp —
    /// currently `"1"` — that consumers can gate on for
    /// incompatible shape changes), `_walk` (carrying the same
    /// walked / valid counts plus an `errors` array of
    /// `{path, error, enriched_message}` entries covering every
    /// parse failure; `enriched_message` is a JSON string
    /// when a known schema-drift remediation applies, JSON null
    /// otherwise), and `fields` (one entry per optional field
    /// with run-wide `none_count` + `some_count` summing to
    /// `_walk.valid`, plus the static `classification` /
    /// `causes` / `fix` catalog entry; `fix` is a JSON string
    /// when a remediation applies, JSON null otherwise). All-
    /// corrupt runs render the same shape with `valid = 0` and
    /// per-field counts at zero — never bail.
    ///
    /// Exit code is 0 even for all-corrupt runs — the
    /// diagnostic surface is the structured `_walk.errors`
    /// array (or the trailing `corrupt sidecars` text block),
    /// not the process exit code. CI scripts that need to fail
    /// on parse failures must gate on `_walk.valid > 0` or
    /// `_walk.errors.len() == 0` rather than the exit status.
    /// The only non-zero exits are missing-run-directory and
    /// empty-run (zero `.ktstr.json` files).
    ExplainSidecar {
        /// Run key (e.g. `6.14-abc1234` or `6.14-abc1234-dirty`;
        /// from `cargo ktstr stats list`).
        #[arg(long)]
        run: String,
        /// Alternate run root to resolve `--run` against.
        /// Defaults to `target/ktstr/`. Same semantics as
        /// `cargo ktstr stats compare --dir`.
        #[arg(long)]
        dir: Option<std::path::PathBuf>,
        /// Emit aggregate JSON instead of per-sidecar text. The
        /// text shape is per-sidecar (different gauntlet variants
        /// have different None patterns); the JSON shape is
        /// across-the-run aggregate by field, suitable for
        /// dashboards and CI ingestion.
        #[arg(long)]
        json: bool,
    },
    /// Compare two filter-defined partitions of the sidecar pool
    /// and report regressions across slicing dimensions.
    ///
    /// Each `--a-X` / `--b-X` pair pins a different value on
    /// dimension `X` for the A and B sides; the dimensions on
    /// which A and B differ are the SLICING dimensions, the
    /// dimensions on which they agree are the PAIRING dimensions
    /// the comparison joins on. Shared `--X` flags pin BOTH sides
    /// to the same value (sugar that narrows pre-slicing scope).
    /// Per-side `--a-X` / `--b-X` flags REPLACE the corresponding
    /// shared `--X` value for that side — "more-specific replaces."
    Compare {
        /// Substring filter. Matches against scenario, topology,
        /// scheduler, work_type.
        #[arg(short = 'E', long)]
        filter: Option<String>,
        /// Uniform relative significance threshold in percent
        /// (e.g. 10 for 10%). When set, overrides the per-metric
        /// default threshold for ALL metrics — intentionally, so
        /// callers can loosen a tight default or tighten a loose
        /// one from the CLI without per-metric knobs. Omit to use
        /// each metric's built-in default.
        ///
        /// Sugar for `--policy` with `{default_percent: N}` and an
        /// empty per-metric map. Mutually exclusive with `--policy`
        /// — if you need per-metric overrides, spell them out in a
        /// policy file and pass `--policy`.
        #[arg(long, conflicts_with = "policy")]
        threshold: Option<f64>,
        /// Path to a JSON-persisted `ktstr::cli::ComparisonPolicy`
        /// file with per-metric thresholds. Mutually exclusive
        /// with `--threshold`. Use `--threshold` as sugar for a
        /// uniform default; use `--policy` for the per-metric
        /// override map.
        ///
        /// Priority: per-metric override → `default_percent` →
        /// each metric's registry `default_rel`.
        ///
        /// Schema (every field optional; empty object produces
        /// the "registry defaults everywhere" policy):
        ///
        ///   {
        ///     "default_percent": 10.0,
        ///     "per_metric_percent": {
        ///       "worst_spread": 5.0,
        ///       "worst_p99_wake_latency_us": 20.0,
        ///       "worst_mean_run_delay_us": 15.0
        ///     }
        ///   }
        ///
        /// Values are PERCENT (e.g. `10.0` → 10%). Negative
        /// values are rejected. Per-metric keys must match a
        /// metric name in the `METRICS` registry — a typo
        /// (e.g. `wrost_spread`) is rejected at load time so it
        /// does not silently fall through to `default_percent`.
        /// Use `cargo ktstr stats list-metrics` to discover
        /// available metric names and their default thresholds.
        #[arg(long, conflicts_with = "threshold")]
        policy: Option<std::path::PathBuf>,
        /// Alternate run root to resolve `a` / `b` against. Defaults
        /// to `test_support::runs_root()` (typically `target/ktstr/`).
        /// Useful when comparing archived sidecar trees copied off a
        /// CI host.
        #[arg(long)]
        dir: Option<std::path::PathBuf>,
        /// Match against the sidecar's `kernel_version` field
        /// (e.g. `--kernel 6.14.2`). **Match shape depends on
        /// segment count**: a two-segment value (`--kernel 6.12`)
        /// is a major.minor PREFIX — it matches `6.12`, `6.12.0`,
        /// `6.12.5`, etc., letting the operator narrow on a stable
        /// series without naming every patch release. A
        /// three-or-more-segment value (`--kernel 6.14.2`,
        /// `--kernel 6.15-rc3`) is STRICT EQUALITY — `6.14.2` does
        /// NOT match `6.14.20`. See [`kernel_filter_matches`] in
        /// stats.rs for the cutoff implementation.
        ///
        /// Repeatable: `--kernel A --kernel B` keeps rows whose
        /// `kernel_version` equals A OR B (each value applies its
        /// own match shape per the segment-count rule). Rows whose
        /// `kernel_version` is `None` (sidecar writer could not
        /// extract a version) NEVER match a populated filter —
        /// passing `--kernel` is an opt-in that demands a
        /// known-version row. Same flag name as on `cargo ktstr
        /// test`/`coverage`/`llvm-cov` for consistency: every
        /// subcommand that accepts a kernel filter spells it
        /// `--kernel`. The per-side overrides `--a-kernel` /
        /// `--b-kernel` carry the same match-shape rule.
        #[arg(long, action = ArgAction::Append)]
        kernel: Vec<String>,
        /// Repeatable OR-combined filter on the sidecar's
        /// `project_commit` field (e.g. `--project-commit abcdef1`
        /// or `--project-commit abcdef1-dirty`).
        /// `--project-commit A --project-commit B` keeps rows
        /// whose `project_commit` equals A OR B; each entry uses
        /// strict equality (no prefix matching — `abcdef1` does
        /// not match `abcdef10`). Rows whose `project_commit` is
        /// `None` (sidecar writer's gix probe failed, or cwd was
        /// outside any git repo at write time) NEVER match a
        /// populated filter — same opt-in policy as `--kernel`.
        ///
        /// Also accepts git revspecs (`HEAD`, `HEAD~N`, branch
        /// names, tags, `A..B` ranges) resolved against the
        /// project repo (`gix::discover` from cwd) into the same
        /// 7-char short hashes the sidecar writer records. A range
        /// expands to every commit reachable from `B` but not from
        /// `A`, each treated as an OR-combined exact-match
        /// filter. Example: `--project-commit HEAD~3..HEAD` keeps
        /// rows whose `project_commit` matches every commit
        /// reachable from `HEAD` but not from `HEAD~3` (the walk
        /// is breadth-first across the full commit DAG, so for
        /// linear histories this is "the last 3 commits"; for
        /// histories with merges it includes every commit on every
        /// branch joined since `HEAD~3`).
        /// Unrecognized inputs and `<hash>-dirty` forms (which
        /// revspec parsing rejects) pass through as literal
        /// exact-match filters, preserving compatibility with
        /// hand-typed dirty entries. When run outside any git tree,
        /// every input passes through as a literal — revspec
        /// resolution requires the cwd to be inside a project repo.
        ///
        /// Filters on the ktstr framework commit
        /// (`SidecarResult::project_commit`); the scheduler
        /// binary's commit (`SidecarResult::scheduler_commit`,
        /// currently always `None`) is a separate concept and is
        /// not currently exposed as a filter.
        ///
        /// The recorded commit is whatever
        /// `detect_project_commit` reads from `gix::discover`
        /// walking up from the test process's cwd at sidecar-write
        /// time; the `-dirty` suffix lands when HEAD-vs-index or
        /// index-vs-worktree changes are detected, so a clean run
        /// and a dirty run of the same HEAD bucket separately
        /// under this filter.
        ///
        /// Symmetric with `--kernel-commit` (which filters on the
        /// kernel SOURCE TREE commit). Together the pair lets the
        /// operator narrow on either or both commit dimensions.
        #[arg(long = "project-commit", action = ArgAction::Append)]
        project_commit: Vec<String>,
        /// Repeatable OR-combined filter on the sidecar's
        /// `kernel_commit` field (e.g. `--kernel-commit abcdef1`
        /// or `--kernel-commit abcdef1-dirty`).
        /// `--kernel-commit A --kernel-commit B` keeps rows whose
        /// `kernel_commit` equals A OR B; each entry uses strict
        /// equality (no prefix matching — `abcdef1` does not
        /// match `abcdef10`). Rows whose `kernel_commit` is
        /// `None` (KTSTR_KERNEL pointed at a non-git path, the
        /// underlying source was Tarball / Git rather than a
        /// `Local` tree, or `detect_kernel_commit`'s gix probe
        /// failed) NEVER match a populated filter — same opt-in
        /// policy as `--project-commit` / `--kernel`.
        ///
        /// Also accepts git revspecs (`HEAD`, `HEAD~N`, branch
        /// names, tags, `A..B` ranges) resolved against the
        /// kernel repo (`gix::open` against `KTSTR_KERNEL`'s
        /// path) into the same 7-char short hashes the sidecar
        /// writer records. A range expands to every commit
        /// reachable from `B` but not from `A`, each treated as
        /// an OR-combined exact-match filter. Example:
        /// `--kernel-commit v6.14..v6.15` keeps rows whose
        /// `kernel_commit` falls in that release window.
        /// Unrecognized inputs and `<hash>-dirty` forms (which
        /// revspec parsing rejects) pass through as literal
        /// exact-match filters, preserving compatibility with
        /// hand-typed dirty entries. When `KTSTR_KERNEL` is unset
        /// or points outside any git tree, every input passes
        /// through as a literal — revspec resolution requires the
        /// repo to be available.
        ///
        /// Filters on the kernel SOURCE TREE commit
        /// (`SidecarResult::kernel_commit`), NOT on the kernel
        /// release version (`SidecarResult::kernel_version` —
        /// filter that with `--kernel`). Two runs of the same
        /// `kernel_version` with different `kernel_commit` values
        /// represent the same release rebuilt from different
        /// trees (e.g. WIP patches on top of a tagged release);
        /// `--kernel-commit` distinguishes them, `--kernel` does
        /// not.
        ///
        /// The recorded value is whatever
        /// `detect_kernel_commit` reads via
        /// `gix::open(<kernel-dir>)` (NOT `discover` — the
        /// kernel directory is explicit, not walked-up); the
        /// `-dirty` suffix lands when HEAD-vs-index or
        /// index-vs-worktree changes are detected, so a clean
        /// kernel tree and a dirty one at the same HEAD bucket
        /// separately under this filter.
        #[arg(long, action = ArgAction::Append)]
        kernel_commit: Vec<String>,
        /// Repeatable OR-combined filter on the sidecar's
        /// `scheduler` field (e.g. `--scheduler scx_rusty`).
        /// `--scheduler A --scheduler B` keeps rows whose
        /// `scheduler` equals A OR B; each entry uses strict
        /// equality (no prefix matching).
        /// Distinct from `-E`, which matches a substring across
        /// the joined fields. Use this when the operator wants to
        /// pin specific schedulers rather than narrow on a
        /// fragment. Empty (no `--scheduler` flag) is the no-op
        /// default and matches every row's scheduler.
        #[arg(long, action = ArgAction::Append)]
        scheduler: Vec<String>,
        /// Repeatable OR-combined filter on the rendered topology
        /// label (e.g. `--topology 1n2l4c2t`). The label is what
        /// `Topology::Display` produces; `cargo ktstr stats list`
        /// shows the form per-row. `--topology A --topology B`
        /// keeps rows whose `topology` equals A OR B; each entry
        /// uses strict equality (no prefix matching). Empty is
        /// the no-op default.
        #[arg(long, action = ArgAction::Append)]
        topology: Vec<String>,
        /// Repeatable OR-combined filter on the sidecar's
        /// `work_type` field (e.g. `--work-type CpuSpin`). Valid
        /// names are the PascalCase variants of `WorkType`. See
        /// `WorkType::ALL_NAMES` for the canonical variant list, or
        /// `doc/guide/src/concepts/work-types.md`. `--work-type A
        /// --work-type B` keeps rows whose `work_type` equals A OR
        /// B; each entry uses strict equality (no prefix
        /// matching). Empty is the no-op default.
        #[arg(long = "work-type", action = ArgAction::Append)]
        work_type: Vec<String>,
        /// Repeatable OR-combined filter on the sidecar's
        /// `run_source` field (e.g. `--run-source local`,
        /// `--run-source ci`, `--run-source archive`).
        /// `--run-source A --run-source B` keeps rows whose
        /// `run_source` equals A OR B; each entry uses strict
        /// equality (case-sensitive, no prefix matching). Rows
        /// whose `run_source` is `None` (sidecar pre-dates the
        /// field) NEVER match a populated filter — same opt-in
        /// policy as `--kernel` / `--project-commit` /
        /// `--kernel-commit`.
        ///
        /// Filters on the run-environment provenance recorded by
        /// `detect_run_source` at sidecar-write time (`"local"`
        /// for developer runs, `"ci"` when `KTSTR_CI` was set),
        /// or rewritten to `"archive"` at load time when this
        /// command's `--dir` flag points at a non-default pool
        /// root. Combine with `--a-run-source` / `--b-run-source`
        /// to contrast across run environments (e.g.
        /// `--a-run-source ci --b-run-source local` to diff CI
        /// runs against developer runs of the same scenarios).
        ///
        /// Named `--run-source` (rather than `--source`) to
        /// disambiguate from `KernelSource` — every other
        /// `source`-shaped CLI surface in the workspace
        /// (`kernel build --source`, `KernelMetadata.source`)
        /// refers to a kernel-source kind, not a run-environment
        /// tag.
        #[arg(long = "run-source", action = ArgAction::Append)]
        run_source: Vec<String>,
        /// Repeatable AND-combined flag filter (e.g.
        /// `--flag llc --flag rusty_balance`). Every flag listed
        /// must be present in the sidecar's `active_flags`; the row
        /// may carry additional flags beyond the filter set. Empty
        /// repeats are rejected by clap (zero-width match).
        #[arg(long = "flag")]
        flags: Vec<String>,
        /// A-side overrides: replace the corresponding shared
        /// `--X` value for the A side only. See the per-side
        /// semantics on each `--X` flag's doc.
        ///
        /// `--a-kernel` carries the same match-shape rule as the
        /// shared `--kernel`: a two-segment value (e.g.
        /// `--a-kernel 6.12`) is a major.minor PREFIX matching
        /// every patch release in that series; a three-or-more-
        /// segment value (`6.14.2`, `6.15-rc3`) is strict
        /// equality. NOT strict equality across the board — see
        /// [`kernel_filter_matches`] for the cutoff implementation.
        #[arg(long = "a-kernel", action = ArgAction::Append)]
        a_kernel: Vec<String>,
        #[arg(long = "a-project-commit", action = ArgAction::Append)]
        a_project_commit: Vec<String>,
        #[arg(long = "a-kernel-commit", action = ArgAction::Append)]
        a_kernel_commit: Vec<String>,
        #[arg(long = "a-run-source", action = ArgAction::Append)]
        a_run_source: Vec<String>,
        #[arg(long = "a-scheduler", action = ArgAction::Append)]
        a_scheduler: Vec<String>,
        #[arg(long = "a-topology", action = ArgAction::Append)]
        a_topology: Vec<String>,
        #[arg(long = "a-work-type", action = ArgAction::Append)]
        a_work_type: Vec<String>,
        #[arg(long = "a-flag")]
        a_flags: Vec<String>,

        /// B-side overrides: replace the corresponding shared
        /// `--X` value for the B side only. See the per-side
        /// semantics on each `--X` flag's doc.
        ///
        /// `--b-kernel` carries the same match-shape rule as the
        /// shared `--kernel`: a two-segment value (e.g.
        /// `--b-kernel 6.12`) is a major.minor PREFIX matching
        /// every patch release in that series; a three-or-more-
        /// segment value (`6.14.2`, `6.15-rc3`) is strict
        /// equality. NOT strict equality across the board — see
        /// [`kernel_filter_matches`] for the cutoff implementation.
        #[arg(long = "b-kernel", action = ArgAction::Append)]
        b_kernel: Vec<String>,
        #[arg(long = "b-project-commit", action = ArgAction::Append)]
        b_project_commit: Vec<String>,
        #[arg(long = "b-kernel-commit", action = ArgAction::Append)]
        b_kernel_commit: Vec<String>,
        #[arg(long = "b-run-source", action = ArgAction::Append)]
        b_run_source: Vec<String>,
        #[arg(long = "b-scheduler", action = ArgAction::Append)]
        b_scheduler: Vec<String>,
        #[arg(long = "b-topology", action = ArgAction::Append)]
        b_topology: Vec<String>,
        #[arg(long = "b-work-type", action = ArgAction::Append)]
        b_work_type: Vec<String>,
        #[arg(long = "b-flag")]
        b_flags: Vec<String>,

        /// Disable averaging. By default the comparison folds
        /// every matching sidecar within each side into a single
        /// arithmetic-mean row per pairing key; `--no-average`
        /// keeps each sidecar distinct and bails with an
        /// actionable diagnostic if multiple sidecars on the
        /// same side share the same pairing key (otherwise
        /// pairing across A/B sides is ambiguous).
        ///
        /// Aggregation rules under the default (averaging-on)
        /// path: failing/skipped contributors are excluded from
        /// the metric mean (they carry failure-mode telemetry,
        /// not scheduler behaviour); the aggregated row's
        /// `passed` is the AND across every contributor (a
        /// single failure flips the aggregate to `failed`,
        /// which routes the pair through `compare_rows`'
        /// `skipped_failed` gate).
        #[arg(long = "no-average")]
        no_average: bool,
    },
}

/// Resolve a `KernelId::Path` to a directory suitable for export
/// via [`ktstr::KTSTR_KERNEL_ENV`] plus the dirty-tree flag the
/// caller uses to decorate the kernel label.
///
/// Routes Path specs through [`cli::resolve_kernel_dir_to_entry`]
/// so they share the same cache pipeline as Version / CacheKey /
/// Git specs:
///   - Clean source tree, cache miss → build, store at
///     `local-{hash7}-{arch}-kc{suffix}`, return cache entry dir
///     with `is_dirty=false`.
///   - Clean source tree, cache hit → skip build, emit a stderr
///     line referencing the user's raw input path, the resolved
///     cache key, and the build age, then return cache entry dir
///     with `is_dirty=false`.
///   - Dirty source tree → build in source, skip cache store,
///     return canonical source dir with `is_dirty=true`. The
///     caller appends `_dirty` to the kernel label so the test
///     report distinguishes the non-reproducible run from a
///     subsequent clean rebuild of the same tree.
///
/// Both directory shapes are valid inputs to
/// [`crate::kernel_path::find_image_in_dir`]'s child consumers;
/// the cache-entry layout (`<dir>/<image_name>`) and source-tree
/// layout (`<dir>/arch/<arch>/boot/<image_name>`) are both probed.
///
/// `raw_input` is the verbatim user-supplied `--kernel` argument
/// before canonicalization — used in the cache-hit stderr line so
/// the operator sees the path they actually typed (e.g.
/// `../linux`) rather than the resolved canonical form, and in
/// the resolve-failure error so a typo names whatever the user
/// supplied.
///
/// On canonicalize / source-tree-validation failure, the inner
/// error is re-wrapped with the user's raw input + the standard
/// `KTSTR_KERNEL_HINT` so the diagnostic shape matches the
/// behaviour the previous inline `canonicalize` call provided.
/// The single canonicalize then lives inside
/// [`crate::fetch::local_source`] (called via
/// [`cli::resolve_kernel_dir_to_entry`]); doing it twice in this
/// function and again in `local_source` produced redundant
/// syscalls without changing the resulting path.
fn resolve_path_kernel(p: &Path, raw_input: &str) -> Result<(PathBuf, bool), String> {
    // Boundary bridge: `cli::resolve_kernel_dir_to_entry` returns
    // `anyhow::Result<KernelDirOutcome>` while this function
    // returns `Result<_, String>`, so we stringify at the call
    // site. A broader anyhow migration across cargo-ktstr.rs is
    // pending and would drop this last bridge.
    let outcome = cli::resolve_kernel_dir_to_entry(p, "cargo ktstr", None).map_err(|e| {
        format!(
            "--kernel {raw_input}: {e:#}. {hint}",
            hint = ktstr::KTSTR_KERNEL_HINT,
        )
    })?;
    if let Some(hit) = outcome.cache_hit {
        eprintln!(
            "cargo ktstr: cache hit for {raw_input} ({key}{age})",
            key = hit.cache_key,
            age = format_built_age(&hit.built_at),
        );
    }
    Ok((outcome.dir, outcome.is_dirty))
}

/// Format a cache entry's `built_at` ISO-8601 timestamp as a
/// human-readable age suffix for the cache-hit log line.
///
/// Returns `, built {age} ago` (with the leading comma+space) on
/// successful parse + elapsed-since-now computation, so the call
/// site can splice it directly into the parenthesised message:
/// `(local-..., built 2h 15m ago)`. Returns the empty string when
/// either the timestamp can't be parsed (malformed metadata) or
/// the build moment is in the future relative to local clock
/// (clock skew on a shared cache); callers see `(local-...)` with
/// no age suffix in those degenerate cases.
fn format_built_age(built_at: &str) -> String {
    let Ok(parsed) = humantime::parse_rfc3339(built_at) else {
        return String::new();
    };
    let Ok(elapsed) = std::time::SystemTime::now().duration_since(parsed) else {
        return String::new();
    };
    // Truncate to whole-second granularity. `format_duration` on
    // sub-second remainders renders nanos that aren't useful
    // ("2h 15m 32s 184ms 7us 12ns") and clutter the cache-hit
    // line.
    let elapsed = std::time::Duration::from_secs(elapsed.as_secs());
    format!(", built {} ago", humantime::format_duration(elapsed))
}

/// Canonicalize a cache-entry directory before exporting it via
/// [`ktstr::KTSTR_KERNEL_ENV`] / [`ktstr::KTSTR_KERNEL_LIST_ENV`].
/// `CacheDir` roots at the XDG cache home (or `KTSTR_CACHE_DIR`),
/// both typically absolute — but an operator-supplied
/// `KTSTR_CACHE_DIR=./cache` would produce a relative path here and
/// reach the same cwd-divergence bug the `Path` branch defends
/// against. `canonicalize` resolves that from the parent's cwd; a
/// failure means the cache dir was removed between lookup and
/// export (rare race), in which case we fall back to the original
/// path rather than bailing — the child will re-enter its own cache
/// lookup and surface the real missing-entry error.
fn canonicalize_cache_dir(cache_dir: PathBuf) -> PathBuf {
    std::fs::canonicalize(&cache_dir).unwrap_or(cache_dir)
}

/// Resolve every `--kernel` spec to a flat list of `(kernel_label,
/// kernel_dir)` pairs. Each Range expands to one entry per release
/// in the interval; each Path / Version / CacheKey / Git produces
/// exactly one entry.
///
/// The flat list is what `cargo ktstr test` (and `coverage` /
/// `llvm-cov`) hand to the test binary as the kernel dimension of
/// the gauntlet expansion: every (test × scenario × topology ×
/// flags × kernel) tuple becomes a distinct nextest test case so
/// nextest's parallelism, retries, and `-E` filtering apply
/// natively. A single `cargo nextest run` (or `cargo llvm-cov
/// nextest`) invocation services every variant; profraw lands per-
/// child so cargo-llvm-cov merges all of them automatically.
///
/// Build / download / clone failures abort the resolution before
/// any test runs — there's no useful state to continue from
/// (a missing kernel can't be tested, and continuing would mask
/// which kernel was requested-but-unavailable in the operator-
/// visible error stream).
///
/// `kernel_label` for each entry is a semantic, operator-readable
/// identity:
/// - Path → `path_{basename}_{hash6}` (basename + 6-char hash of the
///   canonical path so two distinct directories with the same name
///   don't collide).
/// - Version / Range expansion → the version string verbatim
///   (e.g. `6.14.2`, `6.15-rc3`).
/// - CacheKey → the version prefix (everything before the first
///   `-tarball-` / `-git-` / `-local-` component).
/// - Git → `git_{owner}_{repo}_{ref}` extracted from the URL +
///   git ref.
///
/// The downstream `sanitize_kernel_label` in
/// [`crate::test_support::dispatch`] applies the `kernel_` prefix
/// and `[a-z0-9_]+` normalisation; this label is the human-meaningful
/// payload it operates on.
/// Resolve one already-validated [`KernelId`] (NOT `Range` — the
/// caller fans Range out to per-version `Version` ids before
/// calling here) to a `(label, dir)` tuple.
///
/// Extracted from `resolve_kernel_set`'s rayon body so the per-
/// spec match arm is one function call rather than five inline
/// arms duplicated across the parallel and sequential paths.
/// Each non-Range arm here mirrors what the original sequential
/// loop did.
///
/// Range fan-out lives on the caller because the
/// `expand_kernel_range` step yields a `Vec<String>` that has to
/// be expanded into the same parallel pool — `flat_map_iter` is
/// the wrong shape for "fan out N items into the parent
/// iterator." See the parallel comment block in
/// [`resolve_kernel_set`] for the full strategy.
fn resolve_one(id: ktstr::kernel_path::KernelId) -> Result<(String, PathBuf), String> {
    use ktstr::kernel_path::KernelId;
    match id {
        KernelId::Path(p) => {
            // Capture the user's raw input string before any
            // canonicalization so cache-hit diagnostics inside
            // `resolve_path_kernel` can name the path they
            // actually typed (`../linux`) instead of the
            // resolved canonical form.
            let raw_input = p.display().to_string();
            // Compute the BASE label from the CANONICAL SOURCE TREE
            // path, NOT the directory `resolve_path_kernel`
            // returns. The returned dir may be a cache entry
            // (`<cache>/local-{hash7}-{arch}-kc{suffix}`); a
            // basename-derived label off that would render as
            // `path_local-{hash7}-{arch}-kc{suffix}_{hash6}` and
            // change between cache-miss runs (when
            // `path_kernel_label` would have observed the source
            // tree dir) and cache-hit runs (when it would have
            // observed the cache entry dir). Pinning the label
            // to the canonical SOURCE path keeps the operator-
            // facing identifier stable across cache states for
            // the same `--kernel /path/to/linux` invocation.
            //
            // The dirty-tree flag from `resolve_path_kernel`
            // appends a `_dirty` suffix when `local_source`
            // observed uncommitted modifications. The dirty-tree
            // build skips the cache store, so a `path_linux_a3b1c2`
            // row in the test report is not interchangeable with
            // a `path_linux_a3b1c2_dirty` row — the former is
            // reproducible from the recorded git hash, the latter
            // is not. Surfacing the divergence in the label keeps
            // the gauntlet output honest about which runs the
            // operator can re-run from cache.
            let canon_input = std::fs::canonicalize(&p).map_err(|e| {
                format!(
                    "--kernel {}: path does not exist or cannot be \
                     canonicalized ({e:#}). {hint}",
                    p.display(),
                    hint = ktstr::KTSTR_KERNEL_HINT,
                )
            })?;
            let base_label = path_kernel_label(&canon_input);
            let (dir, is_dirty) = resolve_path_kernel(&p, &raw_input)?;
            let label = decorate_path_label_for_dirty(&base_label, is_dirty);
            Ok((label, dir))
        }
        KernelId::Version(ref ver) => {
            let cache_dir = ktstr::cli::resolve_cached_kernel(&id, "cargo ktstr")
                .map_err(|e| format!("{e:#}"))?;
            let dir = canonicalize_cache_dir(cache_dir);
            Ok((ver.clone(), dir))
        }
        KernelId::CacheKey(ref key) => {
            let cache_dir = ktstr::cli::resolve_cached_kernel(&id, "cargo ktstr")
                .map_err(|e| format!("{e:#}"))?;
            let dir = canonicalize_cache_dir(cache_dir);
            // Extract a discriminating label from the cache key —
            // tarball keys yield the version prefix
            // (`6.14.2-tarball-…` → `6.14.2`), git keys yield the
            // ref (`for-next-git-…` → `for-next`), local keys yield
            // `local_{hash6}` (or `local_unknown` for non-git
            // trees). See [`cache_key_to_version_label`] for the
            // full per-shape contract and fallback behavior.
            let label = cache_key_to_version_label(key).to_string();
            Ok((label, dir))
        }
        KernelId::Git {
            ref url,
            ref git_ref,
        } => {
            let cache_dir = ktstr::cli::resolve_git_kernel(url, git_ref, "cargo ktstr")
                .map_err(|e| format!("resolve git+{url}#{git_ref}: {e:#}"))?;
            let dir = canonicalize_cache_dir(cache_dir);
            let label = git_kernel_label(url, git_ref);
            Ok((label, dir))
        }
        KernelId::Range { start, end } => {
            // Defensive: the caller fans Range out to per-version
            // Version ids before calling here. This arm exists
            // only so the compiler accepts the exhaustive match;
            // hitting it indicates a programming error in the
            // caller's flat-map shape rather than a user-visible
            // condition, so the diagnostic is descriptive enough
            // to point a developer at the wrong call site.
            Err(format!(
                "internal: resolve_one called with Range {start}..{end}; \
                 caller must expand Range via `expand_kernel_range` and \
                 call `resolve_one` per version"
            ))
        }
    }
}

fn resolve_kernel_set(specs: &[String]) -> Result<Vec<(String, PathBuf)>, String> {
    use ktstr::kernel_path::KernelId;
    use rayon::iter::{IntoParallelIterator, ParallelIterator};

    preflight_collision_check(specs)?;

    // Each spec resolves independently:
    //   - Path → cache lookup → maybe build (no network).
    //     Clean source trees hit the local-source cache key
    //     `local-{hash7}-{arch}-kc{suffix}`; cache miss reaches
    //     the same `kernel_build_pipeline` Version/CacheKey/Git
    //     specs use, with the result stored back at the same key.
    //     Dirty trees skip the cache store and build in place.
    //   - Version / CacheKey → cache lookup → maybe download +
    //     build.
    //   - Range → fetch releases.json once, then per-version
    //     cache lookup → maybe download + build for each
    //     expanded version.
    //   - Git → shallow clone → cache lookup → maybe build.
    //
    // Two phases of work happen behind the per-spec resolvers:
    // (1) network I/O — kernel.org tarball download or
    //     `git_clone` shallow fetch — which is independent
    //     across specs and overlaps freely.
    // (2) build — `make -j$(nproc)` invoked under an LLC flock
    //     plus a cgroup v2 sandbox (`acquire_build_reservation`
    //     in `kernel_build_pipeline`). The flock serializes
    //     concurrent builders against each other, so parallel
    //     resolvers queue at the LLC level even when their
    //     downloads overlapped.
    //
    // Net effect: parallelizing `resolve_kernel_set` overlaps
    // every download / clone phase, while the build phase
    // remains serialized via the LLC flock the build pipeline
    // already holds. `make -j$(nproc)` inside a single build
    // saturates CPU on its own — running multiple builds
    // concurrently would only contend with the active build's
    // reserved LLCs, so the flock-driven serialization is the
    // correct ceiling. The cache-store path is also flock-
    // protected (`store_succeeds_under_internal_exclusive_lock`
    // in `cache.rs`) so concurrent stores against different
    // cache keys are safe.
    //
    // Concurrent resolves of the SAME spec (e.g. a duplicated
    // `--kernel 6.14.2` flag) racing on the same cache key are
    // also safe — the cache's exclusive store lock means the
    // second resolver re-checks the cache after acquiring its
    // own lock and finds the just-written entry, skipping the
    // redundant build.
    //
    // `flat_map_iter` flattens Range expansion under one rayon
    // worker: the closure resolves every version of a single
    // Range spec sequentially via `.map(...).collect::<Vec<_>>()`
    // before yielding the iterator, so a 5-version range
    // serializes its five resolves against itself within one
    // worker. Peer specs (other top-level `--kernel` arguments)
    // still parallelize across workers — only versions WITHIN
    // one Range are serial. The serialization is acceptable
    // because the per-version build phase is already serialized
    // at the LLC-flock layer (see comment above), so the lost
    // intra-range download overlap is a small fraction of total
    // wall time on multi-version Range invocations.
    //
    // Result-collecting fail-fast: rayon's `collect` on
    // `Result<_, _>` short-circuits on the first error, so a
    // single failed spec aborts the rest. This matches the
    // pre-parallel loop's `?` propagation; the operator sees
    // the first failure even though peers may still be in
    // flight (their cleanup is owned by their tempdirs going
    // out of scope, see `download_and_cache_version` /
    // `resolve_git_kernel` for the `tempfile::TempDir`-driven
    // teardown).
    // Cap rayon parallelism via a bounded ThreadPool installed
    // ONLY for this resolve pipeline. Without the cap, an
    // operator passing `--kernel A --kernel B ... --kernel Z`
    // (10+ specs) would saturate the global rayon pool with
    // simultaneous git_clone + tarball downloads. Each download
    // / clone is network-bound and largely cooperative on local
    // CPU, but the spawn cost (rayon worker steal-and-park,
    // tempdir creation, gix or reqwest init) compounds in
    // proportion to spec count, and a contended local network
    // (the kernel.org CDN's per-IP throttle, a developer's home
    // ISP, a CI runner's shared NIC) degrades when too many
    // streams overlap.
    //
    // The cap defaults to `available_parallelism()` — the host's
    // logical CPU count, std-lib provided so no extra dependency
    // is pulled in. Saturating local parallelism is the right
    // ceiling: download streams shouldn't outnumber the threads
    // the host can drive without thrashing, and the build phase
    // is already serialized at the LLC-flock layer (see comment
    // above) so additional download fan-out wouldn't accelerate
    // builds anyway.
    //
    // Operators can override the cap via the
    // `KTSTR_KERNEL_PARALLELISM` env var (see
    // [`ktstr::KTSTR_KERNEL_PARALLELISM_ENV`]) — useful when the
    // default is wrong for the host: a fast NIC + slow CPU
    // benefits from more in-flight downloads; a contended CI
    // runner with concurrent jobs benefits from a lower cap to
    // leave bandwidth for siblings. Parsing rules and fallback
    // behavior live in [`ktstr::cli::resolve_kernel_parallelism`]
    // so a typoed export (`=abc`, `=0`) silently degrades to the
    // host-CPU default rather than disabling parallelism.
    //
    // Bounded ThreadPool via `pool.install(|| ...)` scopes the
    // cap to this pipeline only — the global rayon pool is
    // unaffected, so any other rayon-using code in the same
    // process (test parallelism in nextest's harness, polars'
    // groupby, etc.) keeps its own width. Falls back to the
    // global pool if `ThreadPoolBuilder::build` fails (e.g. on
    // a host that's already maxed its thread limits) — better
    // to run the resolve under the default global pool than
    // bail with a cap-construction error that has nothing to
    // do with the user's `--kernel` input.
    let max_threads = ktstr::cli::resolve_kernel_parallelism();
    let bounded_pool = rayon::ThreadPoolBuilder::new()
        .num_threads(max_threads)
        .build()
        .ok();

    // Per-resolve progress feedback. A user passing `--kernel
    // 6.10..6.20` (10+ versions) sees `cargo ktstr: resolved
    // kernel "6.10"` lines as each version finishes its
    // download+build cycle, instead of staring at silence for
    // the multi-minute resolve. Emitted at the Ok-arm of each
    // `resolve_one` call so failures still propagate via the
    // existing fail-fast `collect::<Result<_, _>>?` chain
    // upstream — only successful resolves print. Single-kernel
    // runs emit ONE line; that's negligible noise versus the
    // multi-kernel UX gain. Output is `eprintln!` (stderr) so
    // it doesn't pollute stdout pipelines that consume the
    // tool's other output (e.g. shell scripts piping through
    // jq).
    //
    // `tracing::info!` would respect `RUST_LOG`, but the
    // command spends most of its wall time in
    // `resolve_kernel_set` and operators expect progress
    // visibility by default — gating it behind a verbosity
    // flag would defeat the point. Keep it as unconditional
    // `eprintln!` matching the pattern other long-running
    // helpers (`expand_kernel_range`, `kernel_build_pipeline`)
    // already use.
    let resolve_one_with_progress = |id: KernelId| -> Result<(String, PathBuf), String> {
        let result = resolve_one(id);
        if let Ok((label, _)) = &result {
            eprintln!("cargo ktstr: resolved kernel {label:?}");
        }
        result
    };

    let resolve_in_pool = || -> Result<Vec<(String, PathBuf)>, String> {
        specs
            .into_par_iter()
            .filter_map(|raw| {
                let trimmed = raw.trim();
                if trimmed.is_empty() {
                    None
                } else {
                    Some(trimmed.to_string())
                }
            })
            .flat_map_iter(|trimmed| {
                // `flat_map_iter` returns an iterator per input. The
                // Range arm below pre-collects every version's
                // `resolve_one` result into a Vec before yielding,
                // so versions WITHIN a single Range spec resolve
                // sequentially under one rayon worker; only PEER
                // specs (other top-level `--kernel` args) parallelize
                // across workers. Each yielded item is an opaque
                // `Result<(String, PathBuf), String>` driven by the
                // shared `resolve_one` helper; rayon's `collect` on
                // `Result` short-circuits on the first error.
                //
                // Validation runs first so an inverted Range bails
                // before any I/O — same diagnostic timing the
                // sequential loop preserved.
                let id = KernelId::parse(&trimmed);
                if let Err(e) = id.validate() {
                    return vec![Err(format!("--kernel {id}: {e}"))].into_iter();
                }
                match id {
                    KernelId::Range { start, end } => {
                        match ktstr::cli::expand_kernel_range(&start, &end, "cargo ktstr") {
                            Ok(versions) => versions
                                .into_iter()
                                .map(|ver| {
                                    resolve_one_with_progress(KernelId::Version(ver.clone()))
                                        .map_err(|e| format!("resolve kernel {ver}: {e}"))
                                })
                                .collect::<Vec<_>>()
                                .into_iter(),
                            Err(e) => vec![Err(format!("{e:#}"))].into_iter(),
                        }
                    }
                    other => vec![resolve_one_with_progress(other)].into_iter(),
                }
            })
            .collect::<Result<Vec<_>, _>>()
    };
    let resolved: Vec<(String, PathBuf)> = match bounded_pool {
        Some(pool) => pool.install(resolve_in_pool)?,
        None => resolve_in_pool()?,
    };

    let resolved = dedupe_resolved(resolved);

    detect_label_collisions(&resolved)?;
    Ok(resolved)
}

/// Pre-flight collision detection on cheap-to-label kernel specs
/// (Version / CacheKey / Git refs). Returns `Err(message)` when
/// two distinct producer-side labels sanitize to the same nextest
/// identifier; `Ok(())` otherwise.
///
/// Versions, CacheKeys, and Git refs all yield labels through
/// pure string manipulation (`ver.clone()`,
/// `cache_key_to_version_label(key)`, `git_kernel_label(url,
/// ref)`) — no I/O. We can compute and compare the sanitized
/// forms of those labels BEFORE the parallel resolve fires any
/// downloads, builds, or git clones. That moves the collision
/// diagnostic from a multi-minute build cost ("downloaded 6.14.2,
/// downloaded git+...#main, both rebuilt their kernel, NOW we
/// tell you they collide") to a sub-millisecond pre-flight.
///
/// Path and Range specs are intentionally EXCLUDED:
/// - Path: `path_kernel_label(dir)` requires `dir` to be
///   canonicalized first (its hash6 component is over the
///   canonical path's UTF-8 bytes). Canonicalization is real
///   filesystem I/O — admissible at resolve time but not here,
///   where the goal is "fast pre-flight". Path specs that
///   collide still surface via the post-resolve
///   `detect_label_collisions` call after their canonical labels
///   are known.
/// - Range: expanding a range to its per-version label set
///   requires a `releases.json` fetch — admissible at resolve
///   time but not pre-flight (and the resolve pipeline already
///   does it once; doing it twice is waste). Range-vs-Range or
///   Range-vs-Version collisions surface post-resolve.
///
/// Identical labels appearing twice are NOT a collision under
/// this check (the `prior != label` guard on the same-label
/// case). Two `--kernel 6.14.2` specs resolve to the same
/// `(label, path)` post-resolve, get folded by `dedupe_resolved`,
/// and reach `detect_label_collisions` as a single entry.
///
/// Inverted ranges and other malformed inputs fail validation
/// here, BEFORE the network fetch the rayon resolve would
/// otherwise run — preserves the same diagnostic timing the
/// parallel path would produce on its own.
///
/// Extracted from `resolve_kernel_set` so the pre-flight
/// algorithm is unit-testable on contrived inputs without driving
/// the rayon resolve pipeline (every `resolve_one` arm performs
/// real I/O — canonicalize+build for Path, cache lookup+download
/// for Version/CacheKey, shallow git clone for Git).
fn preflight_collision_check(specs: &[String]) -> Result<(), String> {
    use ktstr::kernel_path::KernelId;
    let mut preflight: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    for raw in specs {
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            continue;
        }
        let id = KernelId::parse(trimmed);
        if let Err(e) = id.validate() {
            return Err(format!("--kernel {id}: {e}"));
        }
        let label: Option<String> = match &id {
            KernelId::Version(v) => Some(v.clone()),
            KernelId::CacheKey(k) => Some(cache_key_to_version_label(k).to_string()),
            KernelId::Git { url, git_ref } => Some(git_kernel_label(url, git_ref)),
            // Path / Range deferred to post-resolve check.
            KernelId::Path(_) | KernelId::Range { .. } => None,
        };
        if let Some(label) = label {
            let sanitized = ktstr::test_support::sanitize_kernel_label(&label);
            if let Some(prior) = preflight.insert(sanitized.clone(), label.clone())
                && prior != label
            {
                return Err(format!(
                    "--kernel: pre-flight check found collision before any \
                     download or build started — labels {prior:?} and {label:?} \
                     both sanitize to {sanitized:?}, which the nextest \
                     test-name suffix cannot disambiguate. Spell each \
                     --kernel value distinctly so its sanitized form is \
                     unique. (Path and Range specs are checked post-resolve.)"
                ));
            }
        }
    }
    Ok(())
}

/// Dedupe identical `(label, path)` tuples before
/// `detect_label_collisions` fires.
///
/// Two `--kernel 6.14.2` specs (or a Range that overlaps a
/// separate Version spec) resolve to the same `(label, path)`
/// pair by construction — `resolve_one` is deterministic per
/// spec, so identical inputs produce identical outputs. Letting
/// the duplicate flow into `detect_label_collisions` would trip
/// its same-label diagnostic on a fundamentally benign input.
/// Tuple-level dedup keeps the intent ("dedupe identical
/// specs") narrow: two specs that produce the SAME label but
/// DIFFERENT paths represent a real cache-key collision that
/// `detect_label_collisions` must still catch — those rows
/// survive dedup because their tuples differ on the path.
///
/// Order-preserving dedup via a sequential first-seen pass: the
/// rayon pipeline upstream may have shuffled the input order, so
/// we honor whatever order arrived (the downstream wire format
/// is `;`-separated and order-insensitive at the dispatch layer;
/// preserving order keeps stderr diagnostics operator-readable).
/// HashSet membership check + Vec push is O(n) — acceptable on
/// the ~10s-of-kernels scale this function targets.
///
/// Extracted from `resolve_kernel_set` so the dedupe algorithm
/// is unit-testable on contrived inputs without driving the
/// rayon resolve pipeline.
fn dedupe_resolved(resolved: Vec<(String, PathBuf)>) -> Vec<(String, PathBuf)> {
    let mut seen: std::collections::HashSet<(String, PathBuf)> =
        std::collections::HashSet::with_capacity(resolved.len());
    let mut deduped: Vec<(String, PathBuf)> = Vec::with_capacity(resolved.len());
    for entry in resolved {
        if seen.insert(entry.clone()) {
            deduped.push(entry);
        }
    }
    deduped
}

/// Detect two distinct producer-side labels that normalize to the
/// same nextest identifier via [`ktstr::test_support::sanitize_kernel_label`].
/// A collision would shatter two cache directories under one test-
/// name suffix, so the dispatch-side label-to-dir map in
/// `parse_kernel_list` would silently retain only the last entry
/// and every prior collision would route to the wrong kernel.
///
/// On collision: returns `Err(message)` naming both labels and the
/// shared sanitized form so the operator can disambiguate the
/// inputs (e.g. spell `6.14.2` and `git+...#6.14.2` distinctly
/// rather than relying on suffix-encoded identity).
///
/// Identical (label, path) tuples are deduped UPSTREAM in
/// `resolve_kernel_set` before this helper runs, so two identical
/// `--kernel 6.14.2` specs resolving to the same (label, path)
/// pair never reach this check. What CAN reach this check is two
/// distinct producer-side labels that sanitize to the same nextest
/// suffix — that IS a real collision (different kernel content,
/// same routing identity), and surfaces here. Same-label-different-
/// path inputs (e.g. a hypothetical future producer that emits a
/// label with cache-collision shape) also reach here because the
/// upstream tuple-level dedup leaves them distinct, and
/// `seen.insert` then finds the prior label and surfaces the
/// `labels "X" and "X"` diagnostic. This helper is the last line
/// of defense against the silent-routing class of bug.
///
/// Extracted from `resolve_kernel_set` so the collision-detection
/// algorithm is unit-testable on contrived inputs without driving
/// the rayon resolve pipeline (every `resolve_one` arm performs
/// real I/O — canonicalize+build for Path, cache lookup+download
/// for Version/CacheKey, shallow git clone for Git).
fn detect_label_collisions(resolved: &[(String, PathBuf)]) -> Result<(), String> {
    let mut seen: std::collections::HashMap<String, &str> =
        std::collections::HashMap::with_capacity(resolved.len());
    for (label, _) in resolved {
        let sanitized = ktstr::test_support::sanitize_kernel_label(label);
        if let Some(prior) = seen.insert(sanitized.clone(), label.as_str()) {
            return Err(format!(
                "--kernel: labels {prior:?} and {label:?} both sanitize to {sanitized:?}\
                 the nextest test-name suffix cannot disambiguate them. \
                 Spell each --kernel value distinctly so its sanitized form is unique."
            ));
        }
    }
    Ok(())
}

/// Build the `path_{basename}_{hash6}` label for a `Path`-resolved
/// kernel. The basename keeps the label operator-readable; the 6-char
/// hex hash of the canonical path's UTF-8 bytes disambiguates two
/// `linux` directories under different parents. `crc32fast` is
/// already a workspace dep (see `cli::kernel_build_pipeline` for the
/// existing consumer), so re-using it costs nothing extra.
fn path_kernel_label(dir: &Path) -> String {
    let basename = dir.file_name().and_then(|n| n.to_str()).unwrap_or("kernel");
    let hash = crc32fast::hash(dir.display().to_string().as_bytes());
    // `{:08x}` would emit 8 hex digits; ruling specifies a 6-char
    // hash prefix. Truncating to the leading 6 is sufficient
    // disambiguation for the operator's purpose (collision risk is
    // only a UI nuisance, not a correctness issue — the kernel_dir
    // path itself is the actual identity).
    format!("path_{basename}_{:06x}", hash & 0x00ff_ffff)
}

/// Append a `_dirty` suffix to a Path-spec kernel label when the
/// build skipped the cache store because the source tree carried
/// uncommitted modifications. Returns the label unchanged when the
/// tree was clean.
///
/// Test reports key on the (sanitized) kernel label as the
/// per-kernel column header; without the suffix, a dirty-tree run
/// and a clean-tree run on the same path render identically and
/// the operator cannot tell which row came from a non-reproducible
/// build. With the suffix:
///   - clean tree: `path_linux_a3b1c2`
///   - dirty tree: `path_linux_a3b1c2_dirty`
///
/// Downstream [`ktstr::test_support::sanitize_kernel_label`]
/// preserves alphanumerics and converts `-` / `.` to `_`, so the
/// `_dirty` suffix passes through verbatim and surfaces in the
/// nextest test-name suffix as `kernel_path_linux_a3b1c2_dirty`.
fn decorate_path_label_for_dirty(base_label: &str, is_dirty: bool) -> String {
    if is_dirty {
        format!("{base_label}_dirty")
    } else {
        base_label.to_string()
    }
}

/// Extract a discriminating label from a cache-entry key.
///
/// Cache keys follow three shapes:
/// - tarball: `{version}-tarball-{arch}-kc{hash}` — version is a
///   PROPER PREFIX, e.g. `6.14.2-tarball-x86_64-kcabc` → `6.14.2`.
/// - git: `{ref}-git-{short_hash}-{arch}-kc{hash}` — ref is a
///   PROPER PREFIX, e.g. `for-next-git-deadbee-x86_64-kcabc` →
///   `for-next`.
/// - local: `local-{discriminator}-{arch}-kc{hash}` — the `local-`
///   PREFIX is the source tag, with `{discriminator}` being the
///   git short_hash of the source tree (or the literal `unknown`
///   when the tree is not a git repo, see
///   `crate::fetch::local_source`). Label is `local_{hash6}`,
///   where `{hash6}` is the 6-char prefix of the discriminator —
///   collapsing every local entry to bare `"local"` would erase
///   distinct local trees from the operator-visible label and
///   cause two different `--kernel /path/A` and `--kernel /path/B`
///   builds to render identically in `kernel list` /
///   `--a-kernel` / `--b-kernel` outputs. The hash6 disambiguates
///   without leaking the full short_hash (which is meaningful at
///   the git layer but redundant in the operator-facing label).
///   For `local-unknown-...` (non-git tree), the label is
///   `local_unknown` — a single shared bucket is the correct
///   render because non-git trees lack a discriminator entirely.
///
/// Returns `Cow<str>` because the local arm builds an owned label
/// (`local_{hash6}` requires a fresh allocation), while the
/// tarball/git arms return a borrow into the input.
///
/// Falls back to the full key (borrowed) if no recognised tag is
/// present — a future cache-key shape with an unknown tag still
/// produces a non-empty label rather than a panic.
fn cache_key_to_version_label(key: &str) -> std::borrow::Cow<'_, str> {
    use std::borrow::Cow;
    // Local prefix has no preceding version segment — the source
    // tag is the leading token. Match the prefix shape and pull
    // the discriminator (git short_hash or `unknown`) for
    // labelling.
    if key == "local" {
        return Cow::Borrowed("local");
    }
    if let Some(rest) = key.strip_prefix("local-") {
        // `rest` shape: `{discriminator}-{arch}-kc{hash}`. Take the
        // first segment as the discriminator. Empty discriminator
        // (e.g. `local--x86_64-...`, malformed) collapses to bare
        // `local` — defensive, never produced by `fetch::local_source`.
        let discriminator = rest.split('-').next().unwrap_or("");
        if discriminator.is_empty() {
            return Cow::Borrowed("local");
        }
        // Truncate to 6 chars. `unknown` (7 chars) collapses to
        // `unknow` if truncated mid-word, which is unhelpful — keep
        // the special-case literal that `fetch::local_source` emits
        // at full length so non-git trees render as
        // `local_unknown`.
        let suffix: String = if discriminator == "unknown" {
            "unknown".to_string()
        } else {
            // Truncate to 6 chars via `chars().take(6)` to avoid
            // panicking on a non-UTF-8-aligned byte slice. Today's
            // `fetch::local_source` only emits ASCII hex
            // discriminators, but a future producer that synthesizes
            // a non-ASCII discriminator (or a malformed cache key
            // hand-typed via `KTSTR_KERNEL=local-…`) would crash
            // under `&discriminator[..6]` byte-slicing if the 6th
            // byte fell mid-char. `chars().take(6)` is UTF-8 safe by
            // construction.
            discriminator.chars().take(6).collect::<String>()
        };
        return Cow::Owned(format!("local_{suffix}"));
    }
    for tag in &["-tarball-", "-git-"] {
        if let Some(prefix_end) = key.find(tag) {
            return Cow::Borrowed(&key[..prefix_end]);
        }
    }
    Cow::Borrowed(key)
}

/// Build the `git_{owner}_{repo}_{ref}` label for a `Git`-resolved
/// kernel. Extracts the `owner` and `repo` segments from the URL's
/// path component, drops the scheme/host, strips a trailing `.git`,
/// and pairs them with the operator-supplied git ref.
///
/// Examples:
/// - `git+https://github.com/tj/sched_ext#for-next` →
///   `git_tj_sched_ext_for-next`
/// - `git+https://gitlab.com/foo/bar.git#v6.14` →
///   `git_foo_bar_v6.14`
/// - URL without a recognisable owner/repo (path with only one
///   segment, e.g. a local mirror `/srv/linux.git`) → `git_<first
///   non-empty segment>_<ref>` (defensively avoids producing an
///   ambiguous `git_` prefix on its own).
fn git_kernel_label(url: &str, git_ref: &str) -> String {
    // Strip scheme: everything up to and including `://`.
    let after_scheme = url.split_once("://").map(|(_, rest)| rest).unwrap_or(url);
    // Strip user@host: split off the leading host segment by
    // dropping everything before the FIRST `/` in the post-scheme
    // remainder, leaving the path component.
    let path = after_scheme
        .split_once('/')
        .map(|(_, rest)| rest)
        .unwrap_or(after_scheme);
    // Trim leading `/`, drop trailing `.git`, then pull the last
    // two non-empty segments as `(owner, repo)`. A single-segment
    // path (e.g. local mirror) gives `(segment, "")` which we
    // collapse to `git_{segment}_{ref}`.
    let trimmed = path.trim_start_matches('/').trim_end_matches('/');
    let trimmed = trimmed.strip_suffix(".git").unwrap_or(trimmed);
    let mut segments: Vec<&str> = trimmed.split('/').filter(|s| !s.is_empty()).collect();
    let repo = segments.pop().unwrap_or("repo");
    let owner = segments.pop().unwrap_or("");
    if owner.is_empty() {
        format!("git_{repo}_{git_ref}")
    } else {
        format!("git_{owner}_{repo}_{git_ref}")
    }
}

/// Encode a flat `(label, kernel_dir)` list into the wire format that
/// the test binary's [`ktstr::KTSTR_KERNEL_LIST_ENV`] reader parses:
/// `label1=path1;label2=path2;...`. Semicolon is the entry separator
/// (paths can contain `:` on POSIX); `=` separates the label from the
/// path. Empty input returns an empty string so the env var is
/// idempotent — an empty value means "no list, single-kernel mode."
///
/// The label is encoded verbatim — sanitization into nextest-safe
/// `[a-z0-9_]+` identifiers happens on the test-binary side via
/// `dispatch::sanitize_kernel_label`. The producer-side label is
/// already a semantic, operator-readable identifier (a version
/// string like `6.14.2`, `git_owner_repo_ref`, `path_basename_hash6`,
/// or `local`), so the env var inspected directly via `printenv
/// KTSTR_KERNEL_LIST` reads as a meaningful kernel→path map rather
/// than as raw cache-key plumbing.
fn encode_kernel_list(resolved: &[(String, PathBuf)]) -> Result<String, String> {
    // KTSTR_KERNEL_LIST wire format is
    // `label1=path1;label2=path2;...`. Both metacharacters MUST be
    // rejected on the label side: `;` would split the label into
    // two pseudo-entries (the parser's `split(';')` upstream of
    // `split_once('=')`); `=` would split label/path
    // pathologically (the parser's `split_once('=')` consumes the
    // FIRST `=`, so a label `a=b` paired with path `/x` would
    // emit `a=b=/x` — the parser would treat `a` as the label
    // and `b=/x` as the path). Rejecting at encode time bails
    // with an actionable error rather than silently producing a
    // malformed env var that the test-binary parser would split
    // into garbage.
    //
    // Producers feeding this helper today (the encoder family
    // around `path_kernel_label` / `git_kernel_label` /
    // `version_kernel_label`) never emit either character in
    // practice — basenames are `[a-zA-Z0-9._-]+`, version
    // strings have `[0-9.-]`, and git labels are
    // `git_{owner}_{repo}_{ref}` with hash-stripped refs. The
    // checks here guard against a future producer change OR a
    // direct caller of `encode_kernel_list` (e.g. a unit test
    // injecting synthetic input) that violates the wire-format
    // invariant.
    for (label, _) in resolved {
        if label.contains(';') {
            return Err(format!(
                "kernel label {label:?} contains a `;`; \
                 KTSTR_KERNEL_LIST uses `;` as the entry separator. \
                 The label-emission path must produce `;`-free identifiers — \
                 if a producer is emitting this label, fix the producer to \
                 sanitize/strip `;` from its output."
            ));
        }
        if label.contains('=') {
            return Err(format!(
                "kernel label {label:?} contains a `=`; \
                 KTSTR_KERNEL_LIST uses `=` to separate label from path within an entry. \
                 The label-emission path must produce `=`-free identifiers — \
                 if a producer is emitting this label, fix the producer to \
                 sanitize/strip `=` from its output."
            ));
        }
    }
    // POSIX permits `;` in paths but the wire format uses it as
    // entry separator. Bail with an actionable error rather than
    // silently producing a malformed env var that the test-binary
    // parser would split into garbage. `=` in paths is fine — the
    // parser's `split_once('=')` only consumes the first `=`,
    // which sits inside the label↔path boundary; subsequent `=`s
    // become part of the path payload verbatim.
    for (label, dir) in resolved {
        let path = dir.display().to_string();
        if path.contains(';') {
            return Err(format!(
                "kernel directory path for {label:?} contains a `;` ({path:?}); \
                 KTSTR_KERNEL_LIST uses `;` as the entry separator and cannot encode \
                 such paths. Move or symlink the kernel cache to a path without `;`."
            ));
        }
    }
    let mut out = String::new();
    for (i, (label, dir)) in resolved.iter().enumerate() {
        if i > 0 {
            out.push(';');
        }
        out.push_str(label);
        out.push('=');
        out.push_str(&dir.display().to_string());
    }
    Ok(out)
}

/// Shared runner for `cargo ktstr test`, `cargo ktstr coverage`, and
/// `cargo ktstr llvm-cov`.
///
/// All three subcommands share the same plumbing: resolve `--kernel`
/// to a flat `(label, kernel_dir)` set, propagate `--no-perf-mode`
/// via an env var, optionally prepend `--cargo-profile release`,
/// append the user's trailing args, and `cmd.exec()` once. The
/// cargo subcommand name (`["nextest","run"]` vs `["llvm-cov",
/// "nextest"]` vs `["llvm-cov"]`) and the log / error-message
/// prefix are the only static differences.
///
/// Multi-kernel fan-out lives entirely in the test binary's
/// gauntlet expansion (`src/test_support/dispatch.rs`): when the
/// resolved set has more than one entry, the test binary's
/// `--list` handler prints `gauntlet/{name}/{preset}/{profile}/
/// {kernel_label}` for every kernel and the `--exact` handler
/// strips the kernel suffix and re-exports `KTSTR_KERNEL` to that
/// kernel's directory before booting the VM. `cargo nextest`
/// already handles parallelism, retries, and `-E` filtering;
/// cargo-ktstr never spawns its own loop.
///
/// Empty `--kernel` (the default): no `KTSTR_KERNEL` /
/// `KTSTR_KERNEL_LIST` export — the test binary resolves its own
/// kernel via the existing `find_kernel` chain.
///
/// Single-entry `--kernel` (one Path / Version / CacheKey / Git, OR a
/// Range that expanded to exactly one release): export
/// `KTSTR_KERNEL` only. Test names stay backward-compatible — no
/// kernel suffix is appended in `--list` output.
///
/// Multi-entry `--kernel` (≥ 2 entries after expansion): export
/// `KTSTR_KERNEL_LIST` AND set `KTSTR_KERNEL` to the first entry so
/// downstream code that reads `KTSTR_KERNEL` directly (e.g. budget
/// listing in dispatch.rs that needs ANY kernel for vmlinux probe)
/// still gets a valid path. The test binary's `--list` / `--exact`
/// handlers prefer `KTSTR_KERNEL_LIST` when set.
///
/// Decide whether to inject `LLVM_PROFILE_FILE` for a given cargo
/// sub-invocation, returning the pattern to set or `None` to leave
/// the env untouched.
///
/// When the user invokes `cargo ktstr test` from inside a kernel
/// source tree, every link in the spawn chain (cargo-ktstr ->
/// cargo nextest -> test binary) inherits the shell's cwd. A
/// coverage-instrumented test binary would then drop
/// `default.profraw` directly in the kernel tree at exit because
/// the LLVM runtime defaults to writing in cwd when
/// `LLVM_PROFILE_FILE` is unset. Injecting a workspace-local
/// pattern here keeps the host's profraw next to the build output
/// regardless of cwd. `%p` (process id) and `%m` (binary hash) are
/// LLVM runtime expansions that keep parallel-test output files
/// distinct.
///
/// Returns `Some(pattern)` only when both:
///   - `sub_argv` selects the bare `nextest` path (the `test`
///     subcommand). The `coverage` path execs `cargo llvm-cov
///     nextest`, which manages `LLVM_PROFILE_FILE` itself for its
///     profraw collection pipeline; pre-setting the env here would
///     race that pipeline. The `llvm-cov` raw-passthrough path is
///     user-controlled by contract and must not be touched.
///   - `existing_env` is `None`. An operator who has already
///     exported `LLVM_PROFILE_FILE` keeps that value — we only set
///     when the env is currently absent, so an explicit override
///     stays authoritative. Operators who want a different
///     workspace-local target without touching `LLVM_PROFILE_FILE`
///     can set `LLVM_COV_TARGET_DIR` instead, which
///     [`ktstr::test_support::profraw_target_dir`] honors as the
///     highest-precedence entry in its cascade.
///
/// Pure with respect to its arguments — does no env read of its
/// own — so callers can drive the gate from a unit test by
/// supplying the env probe explicitly.
fn profraw_inject_for(
    sub_argv: &[&str],
    existing_env: Option<std::ffi::OsString>,
) -> Option<PathBuf> {
    if sub_argv != TEST_SUB_ARGV || existing_env.is_some() {
        return None;
    }
    let dir = ktstr::test_support::profraw_target_dir();
    Some(dir.join("default-%p-%m.profraw"))
}

/// `release` is always `false` for the raw `llvm-cov` passthrough —
/// that subcommand hands every argument to the user, so the profile
/// is set via the user's trailing args (or not at all). `test` and
/// `coverage` wire their `--release` flag through to this argument.
fn run_cargo_sub(
    sub_argv: &[&str],
    label: &str,
    kernel: Vec<String>,
    no_perf_mode: bool,
    release: bool,
    args: Vec<String>,
) -> Result<(), String> {
    let mut cmd = Command::new("cargo");
    cmd.args(sub_argv);
    if release {
        // Prepend `--cargo-profile release` BEFORE the user's
        // trailing args so the profile selection applies to the
        // whole invocation. nextest reads `--cargo-profile` directly;
        // `cargo llvm-cov nextest` forwards it to its inner nextest
        // invocation. For `cargo llvm-cov <sub>` (the raw-passthrough
        // binding), the release arg is never passed here — the raw
        // path relies on user-supplied `--release` / `--profile`.
        cmd.args(["--cargo-profile", "release"]);
    }
    cmd.args(&args);
    if no_perf_mode {
        cmd.env("KTSTR_NO_PERF_MODE", "1");
    }

    if let Some(pat) = profraw_inject_for(sub_argv, std::env::var_os("LLVM_PROFILE_FILE")) {
        cmd.env("LLVM_PROFILE_FILE", pat);
    }

    if !kernel.is_empty() {
        let resolved = resolve_kernel_set(&kernel)?;
        if resolved.is_empty() {
            // `resolve_kernel_set` skips arguments that trim to
            // empty, so `--kernel ""` or `--kernel "  "` reach
            // here without ever entering the per-spec resolve
            // branch. Bail with an actionable error rather than
            // letting the child reach for `find_kernel` as if
            // `--kernel` had never been passed (which would mask
            // the operator's intent).
            return Err(
                "--kernel: every supplied value parsed to empty / whitespace; \
                 omit the flag for auto-discovery, or supply a kernel \
                 identifier"
                    .to_string(),
            );
        }
        // `KTSTR_KERNEL` always points at the first resolved entry
        // so downstream code that inspects the env directly (e.g.
        // budget listing's vmlinux probe in `dispatch.rs`) sees a
        // valid kernel even when running under multi-kernel.
        let first_dir = &resolved[0].1;
        eprintln!("cargo ktstr: using kernel {}", first_dir.display());
        cmd.env(ktstr::KTSTR_KERNEL_ENV, first_dir);

        if resolved.len() > 1 {
            let encoded = encode_kernel_list(&resolved)?;
            eprintln!(
                "cargo ktstr: fanning gauntlet across {n} kernels",
                n = resolved.len(),
            );
            cmd.env(ktstr::KTSTR_KERNEL_LIST_ENV, encoded);
        }
    }

    eprintln!("cargo ktstr: running {label}");
    let err = cmd.exec();
    Err(format!("exec cargo {}: {err}", sub_argv.join(" ")))
}

/// Cargo sub-argv that `run_test` passes to `run_cargo_sub`. Named
/// constant so the dispatch wiring is pinnable from a test — see
/// `cargo_sub_argv_constants_are_pinned`.
const TEST_SUB_ARGV: &[&str] = &["nextest", "run"];
/// Cargo sub-argv for the `coverage` subcommand (cargo llvm-cov
/// nextest).
const COVERAGE_SUB_ARGV: &[&str] = &["llvm-cov", "nextest"];
/// Cargo sub-argv for the `llvm-cov` raw-passthrough subcommand.
/// Single element — the user's trailing args supply the llvm-cov
/// subcommand (`report`, `clean`, `show-env`, ...).
const LLVM_COV_SUB_ARGV: &[&str] = &["llvm-cov"];

fn run_test(
    kernel: Vec<String>,
    no_perf_mode: bool,
    release: bool,
    args: Vec<String>,
) -> Result<(), String> {
    run_cargo_sub(TEST_SUB_ARGV, "tests", kernel, no_perf_mode, release, args)
}

fn run_coverage(
    kernel: Vec<String>,
    no_perf_mode: bool,
    release: bool,
    args: Vec<String>,
) -> Result<(), String> {
    run_cargo_sub(
        COVERAGE_SUB_ARGV,
        "coverage",
        kernel,
        no_perf_mode,
        release,
        args,
    )
}

fn run_llvm_cov(kernel: Vec<String>, no_perf_mode: bool, args: Vec<String>) -> Result<(), String> {
    // `llvm-cov` is raw passthrough — the user supplies every
    // argument after the subcommand name, including any profile
    // selection. `release: false` here means "don't inject a profile
    // ourselves"; the user decides.
    run_cargo_sub(
        LLVM_COV_SUB_ARGV,
        "llvm-cov",
        kernel,
        no_perf_mode,
        false,
        args,
    )
}

fn run_stats(command: &Option<StatsCommand>) -> Result<(), String> {
    match command {
        None => {
            if let Some(output) = cli::print_stats_report() {
                print!("{output}");
            }
            Ok(())
        }
        Some(StatsCommand::List) => cli::list_runs().map_err(|e| format!("{e:#}")),
        Some(StatsCommand::ListMetrics { json }) => match cli::list_metrics(*json) {
            Ok(s) => {
                print!("{s}");
                Ok(())
            }
            Err(e) => Err(format!("{e:#}")),
        },
        Some(StatsCommand::ListValues { json, dir }) => {
            match cli::list_values(*json, dir.as_deref()) {
                Ok(s) => {
                    print!("{s}");
                    Ok(())
                }
                Err(e) => Err(format!("{e:#}")),
            }
        }
        Some(StatsCommand::ShowHost { run, dir }) => {
            match cli::show_run_host(run, dir.as_deref()) {
                Ok(s) => {
                    print!("{s}");
                    Ok(())
                }
                Err(e) => Err(format!("{e:#}")),
            }
        }
        Some(StatsCommand::ExplainSidecar { run, dir, json }) => {
            match cli::explain_sidecar(run, dir.as_deref(), *json) {
                Ok(s) => {
                    print!("{s}");
                    Ok(())
                }
                Err(e) => Err(format!("{e:#}")),
            }
        }
        Some(StatsCommand::Compare {
            filter,
            threshold,
            policy,
            dir,
            kernel,
            project_commit,
            kernel_commit,
            run_source,
            scheduler,
            topology,
            work_type,
            flags,
            a_kernel,
            a_project_commit,
            a_kernel_commit,
            a_run_source,
            a_scheduler,
            a_topology,
            a_work_type,
            a_flags,
            b_kernel,
            b_project_commit,
            b_kernel_commit,
            b_run_source,
            b_scheduler,
            b_topology,
            b_work_type,
            b_flags,
            no_average,
        }) => {
            // Resolve `--threshold N` / `--policy PATH` / neither
            // into a single `ComparisonPolicy`. Clap's
            // `conflicts_with` guarantees at most one of
            // (threshold, policy) is set, so the three branches
            // are exhaustive on user-visible input.
            let resolved_policy = match (threshold, policy.as_ref()) {
                (Some(t), None) => {
                    let p = ktstr::cli::ComparisonPolicy::uniform(*t);
                    // `uniform` is infallible, but the user-supplied
                    // percent still needs a sign check. `validate`
                    // rejects negatives before they reach
                    // `compare_rows`' dual-gate math.
                    p.validate().map_err(|e| format!("{e:#}"))?;
                    p
                }
                (None, Some(path)) => {
                    ktstr::cli::ComparisonPolicy::load_json(path).map_err(|e| format!("{e:#}"))?
                }
                (None, None) => ktstr::cli::ComparisonPolicy::default(),
                (Some(_), Some(_)) => {
                    // Defence-in-depth: clap's `conflicts_with` is
                    // load-bearing here, but a regression that
                    // dropped either attribute would silently pick
                    // one path and ignore the other. Panic loudly.
                    unreachable!(
                        "clap `conflicts_with` on --threshold / --policy \
                         must enforce mutual exclusion at parse time",
                    );
                }
            };
            // Resolve git revspecs in `--project-commit` /
            // `--kernel-commit` flags (HEAD~1, tags, branch names,
            // `A..B` ranges) into 7-char short hashes BEFORE
            // constructing BuildCompareFilters. The shared and
            // per-side vecs each go through `resolve_commit_specs`
            // independently so a per-side override that uses a
            // revspec ("--a-project-commit HEAD~1") expands the
            // same way a shared one would.
            //
            // Project-side repo: `gix::discover` from cwd, mirroring
            // `detect_project_commit`'s open mode at sidecar-write
            // time. `gix::discover` walks parents until it finds a
            // `.git` marker so the operator can run `cargo ktstr
            // stats compare` from anywhere inside the project tree;
            // failure (cwd outside any repo) collapses to `None`
            // and every input passes through as a literal — matching
            // the documented "literal fallback" contract.
            //
            // Kernel-side repo: `gix::open` against the path in
            // `KTSTR_KERNEL`, mirroring `detect_kernel_commit`'s
            // open mode. `KTSTR_KERNEL` unset / empty / non-git
            // collapses to `None` — every input passes through as
            // a literal. `KTSTR_KERNEL` may carry a Version /
            // CacheKey (not a path) on the test/coverage paths;
            // here on the stats path the caller is doing post-hoc
            // analysis, so a path is the relevant interpretation.
            // A non-path value falls through to literal too.
            let project_repo = std::env::current_dir()
                .ok()
                .and_then(|cwd| gix::discover(cwd).ok());
            // Probe `KTSTR_KERNEL` for the kernel-side git repo.
            // Path-spec resolution in cargo-ktstr now exports the
            // CACHE ENTRY directory for clean source trees (see
            // [`ktstr::cli::resolve_kernel_dir_to_entry`]); a
            // direct `gix::open` against that dir would fail
            // because the cache entry is not a git repo. The
            // shared `recover_local_source_tree` helper reads
            // `metadata.json` and returns the recorded
            // `source_tree_path` when present; when absent (the
            // env value is itself a source tree — the dirty
            // build-every-time path), fall back to opening the
            // env value verbatim.
            let kernel_repo = ktstr::ktstr_kernel_env()
                .map(std::path::PathBuf::from)
                .and_then(|p| {
                    let target = ktstr::cache::recover_local_source_tree(&p).unwrap_or(p);
                    gix::open(target).ok()
                });
            let project_commit =
                resolve_commit_specs(project_repo.as_ref(), project_commit, "project-commit");
            let kernel_commit =
                resolve_commit_specs(kernel_repo.as_ref(), kernel_commit, "kernel-commit");
            let a_project_commit =
                resolve_commit_specs(project_repo.as_ref(), a_project_commit, "a-project-commit");
            let a_kernel_commit =
                resolve_commit_specs(kernel_repo.as_ref(), a_kernel_commit, "a-kernel-commit");
            let b_project_commit =
                resolve_commit_specs(project_repo.as_ref(), b_project_commit, "b-project-commit");
            let b_kernel_commit =
                resolve_commit_specs(kernel_repo.as_ref(), b_kernel_commit, "b-kernel-commit");
            // Construct the BuildCompareFilters from the raw CLI
            // inputs. Sugar logic (shared `--X` pins both sides;
            // per-side `--a-X` / `--b-X` REPLACES the shared value
            // for that side) lives inside `build()` so it's
            // unit-testable in isolation. The dispatch site stays
            // a dumb data carrier.
            let build = BuildCompareFilters {
                shared_kernel: kernel.clone(),
                shared_project_commit: project_commit,
                shared_kernel_commit: kernel_commit,
                shared_run_source: run_source.clone(),
                shared_scheduler: scheduler.clone(),
                shared_topology: topology.clone(),
                shared_work_type: work_type.clone(),
                shared_flags: flags.clone(),
                a_kernel: a_kernel.clone(),
                a_project_commit,
                a_kernel_commit,
                a_run_source: a_run_source.clone(),
                a_scheduler: a_scheduler.clone(),
                a_topology: a_topology.clone(),
                a_work_type: a_work_type.clone(),
                a_flags: a_flags.clone(),
                b_kernel: b_kernel.clone(),
                b_project_commit,
                b_kernel_commit,
                b_run_source: b_run_source.clone(),
                b_scheduler: b_scheduler.clone(),
                b_topology: b_topology.clone(),
                b_work_type: b_work_type.clone(),
                b_flags: b_flags.clone(),
            };
            let (filter_a, filter_b) = build.build();
            let exit = cli::compare_partitions(
                &filter_a,
                &filter_b,
                filter.as_deref(),
                &resolved_policy,
                dir.as_deref(),
                *no_average,
            )
            .map_err(|e| format!("{e:#}"))?;
            if exit != 0 {
                std::process::exit(exit);
            }
            Ok(())
        }
    }
}

/// Match the on-disk `project_commit` / `kernel_commit` shape:
/// `^[0-9a-f]{7,40}(-dirty)?$`. Used to gate the rev_parse-Err
/// warning in [`resolve_commit_specs`] so legitimate literal
/// hashes (the common case for `--project-commit abc1234`) do
/// not produce noisy "did not resolve as a revspec" lines.
///
/// SHAPE rationale: `detect_project_commit` /
/// `detect_kernel_commit` write `to_hex_with_len(7)` (7-char
/// short hash) optionally followed by `-dirty`. A 40-char
/// upper bound matches the SHA-1 width gix uses. Anything
/// outside this shape — `HEAD`, `HEAD~1`, branch/tag names,
/// `..`-ranges, mixed-case, longer than 40 chars — is
/// considered an attempted revspec and warrants the warning.
///
/// Case-insensitive hex: `detect_*_commit`'s `to_hex_with_len`
/// produces lowercase and the sidecar pool stores lowercase, so
/// an uppercase input like `ABC1234` will not match a stored row
/// — but it is still recognizably a hash, not a revspec, and
/// silently emitting "did not resolve as a revspec" on it is
/// noise. Pasted-from-elsewhere uppercase / mixed-case hex
/// strings pass the predicate; the suppressed warning means the
/// downstream filter sees the literal verbatim and the
/// (lowercase) pool simply produces an empty match — the same
/// outcome as a legitimate-but-unknown short hash.
fn looks_like_literal_hash(input: &str) -> bool {
    let core = input.strip_suffix("-dirty").unwrap_or(input);
    let len = core.len();
    if !(7..=40).contains(&len) {
        return false;
    }
    core.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Resolve git revspecs (HEAD~1, tags, branch names, ranges
/// `A..B`) in `--project-commit` / `--kernel-commit` filter
/// inputs into the 7-char short hashes the sidecar's
/// `project_commit` / `kernel_commit` fields are written with.
///
/// Each entry in `raw` is treated independently. `repo` is the
/// repository against which to resolve (cwd-discovered for
/// project commits, opened from `KTSTR_KERNEL` for kernel
/// commits); when `None` (no repo available — cwd outside any
/// git tree, or `KTSTR_KERNEL` unset) every input passes
/// through verbatim as a literal. `flag_name` is the
/// user-visible CLI flag (e.g. `"project-commit"`,
/// `"a-kernel-commit"`) included in stderr warnings for
/// fall-through arms so the operator can identify which input
/// did not resolve as expected.
///
/// Per-input resolution:
/// - `repo.rev_parse(input)` succeeds with `Spec::Include(id)`
///   or `Spec::ExcludeParents(id)` (single-commit revspec):
///   push the commit's 7-char short hex. When the resolved OID
///   equals current HEAD AND the worktree is dirty, append
///   `-dirty` to the short hex so the filter matches the
///   suffixed entries `detect_project_commit` /
///   `detect_kernel_commit` write at sidecar-write time.
///   Historical commits (Include / ExcludeParents resolving to
///   non-HEAD OIDs) never get the suffix — the operator named
///   that specific commit and current worktree state has no
///   bearing on its identity in the recorded pool.
/// - `repo.rev_parse(input)` succeeds with `Spec::Range { from,
///   to }` (an `A..B` revspec): walk via `repo.rev_walk([to])
///   .with_hidden([from]).all()` and push each yielded
///   commit's 7-char short hex. Range commits never get the
///   `-dirty` suffix even if the walk includes HEAD — `A..B`
///   is a content-set query, not a current-state query. A
///   walk-init failure prints a stderr warning naming the
///   input and the gix error, then falls through to literal.
/// - `repo.rev_parse(input)` succeeds with another spec kind
///   (`Exclude`, `Merge`, `IncludeOnlyParents`): push the input
///   unchanged. Those forms have no useful single-side
///   expansion for an OR-combined exact-match filter, and a
///   stderr warning is emitted so the operator notices that the
///   input was not expanded.
/// - `repo.rev_parse(input)` returns `Err`: push the input
///   unchanged (literal fallback). This preserves the existing
///   exact-match contract for hand-typed short hashes — a
///   `--project-commit abc1234-dirty` argument never resolves
///   as a revspec (revspec parsing rejects the `-dirty`
///   suffix) and lands as a literal, matching the `-dirty`-
///   suffixed entries in the sidecar pool. The warning fires
///   only when [`looks_like_literal_hash`] returns false —
///   legitimate `<hex>` and `<hex>-dirty` shapes pass through
///   silently, while revspec-shaped inputs that failed
///   resolution surface a diagnostic.
///
/// Resolution happens BEFORE [`BuildCompareFilters`]
/// construction so the sugar logic in `build()` operates on
/// already-expanded vecs and stays free of repo I/O. The
/// expansion is order-preserving on the input, with each
/// range entry yielding its commits in walk order; downstream
/// `RowFilter::matches` is OR-combined so order does not affect
/// the matched set.
fn resolve_commit_specs(
    repo: Option<&gix::Repository>,
    raw: &[String],
    flag_name: &str,
) -> Vec<String> {
    let Some(repo) = repo else {
        return raw.to_vec();
    };
    // Resolve once: the `-dirty` suffix only applies when the
    // resolved OID equals current HEAD AND the worktree is
    // dirty. Both are repo-global properties, so compute them
    // upfront and reuse across every input. Either probe
    // failing (no HEAD, no readable tree) collapses
    // `head_dirty` to false — the documented "treat as clean
    // on probe failure" policy that the canonical
    // [`ktstr::test_support::repo_is_dirty`] already encodes,
    // matching what the sidecar writer applies at sidecar-write
    // time so the filter shape lines up with pool entries.
    let head_oid: Option<gix::ObjectId> = repo.head_id().ok().map(|id| id.detach());
    let head_dirty: bool = head_oid
        .as_ref()
        .and_then(|_| ktstr::test_support::repo_is_dirty(repo))
        .unwrap_or(false);
    let format_short = |id: gix::ObjectId| -> String {
        let short = id.to_hex_with_len(7).to_string();
        // Dirty-suffix only when (a) the worktree is dirty and
        // (b) the resolved OID is current HEAD. A historical
        // commit that happens to be referenced via Include /
        // ExcludeParents (e.g. an explicit short-hash that
        // resolves to a non-HEAD object) does NOT get -dirty,
        // because the operator named that specific commit and
        // the current worktree state has no bearing on its
        // identity in the recorded sidecar pool.
        if head_dirty && head_oid == Some(id) {
            format!("{short}-dirty")
        } else {
            short
        }
    };
    let mut out: Vec<String> = Vec::with_capacity(raw.len());
    for input in raw {
        match repo.rev_parse(input.as_str()) {
            Ok(spec) => match spec.detach() {
                gix::revision::plumbing::Spec::Include(id)
                | gix::revision::plumbing::Spec::ExcludeParents(id) => {
                    out.push(format_short(id));
                }
                gix::revision::plumbing::Spec::Range { from, to } => {
                    match repo.rev_walk([to]).with_hidden([from]).all() {
                        Ok(walk) => {
                            // `walk.flatten()` silently drops any
                            // per-element traversal `Err` (a single
                            // unreadable commit object inside the
                            // range walk). The cost is one filter
                            // entry per failure; the alternative —
                            // bailing on the whole range — would
                            // discard every successfully-yielded
                            // sibling commit. Since the filter is
                            // OR-combined, a missing entry only
                            // narrows the match set rather than
                            // producing wrong rows, so silent drop
                            // is the safe degradation.
                            //
                            // Range commits are historical — they
                            // never get the -dirty suffix even when
                            // the walk happens to include HEAD,
                            // because the operator's intent in
                            // `A..B` is "match every commit in this
                            // range" which is a content-set, not a
                            // current-state query. Use raw
                            // `to_hex_with_len` here (bypass the
                            // `format_short` closure) to skip the
                            // dirty-suffix decision.
                            for info in walk.flatten() {
                                out.push(info.id.to_hex_with_len(7).to_string());
                            }
                        }
                        Err(err) => {
                            eprintln!(
                                "cargo ktstr: --{flag_name} range '{input}' could \
                                 not be expanded: {err}; using as literal filter",
                            );
                            out.push(input.clone());
                        }
                    }
                }
                gix::revision::plumbing::Spec::Exclude(_)
                | gix::revision::plumbing::Spec::Merge { .. }
                | gix::revision::plumbing::Spec::IncludeOnlyParents(_) => {
                    eprintln!(
                        "cargo ktstr: --{flag_name} '{input}' uses an unsupported \
                         revspec form (Exclude/Merge/IncludeOnlyParents); using \
                         as literal filter",
                    );
                    out.push(input.clone());
                }
            },
            Err(_) => {
                // Suppress the warning when `input` already looks
                // like a literal hash (`^[0-9a-fA-F]{7,40}(-dirty)?$`).
                // Lowercase is the SHAPE the sidecar writer produces;
                // uppercase / mixed-case is what an operator pastes
                // from `git log` output or another tool's UI. Both
                // are recognizably hashes and the operator typing
                // them at the CLI is the common case — emitting
                // "did not resolve as a revspec" on every legitimate
                // `--project-commit abc1234` invocation is pure
                // noise. Only warn for inputs that look like an
                // attempted revspec (alpha beyond hex, ~, .., ^,
                // longer than 40 chars, or other non-hash shapes)
                // so a typo'd revspec ("HEAD~XYZ", "main") still
                // surfaces a diagnostic.
                if !looks_like_literal_hash(input) {
                    eprintln!(
                        "cargo ktstr: --{flag_name} '{input}' did not resolve as \
                         a revspec; using as literal filter",
                    );
                }
                out.push(input.clone());
            }
        }
    }
    out
}

/// Symmetric-sugar resolver for `cargo ktstr stats compare`'s
/// shared `--X` and per-side `--a-X` / `--b-X` filter flags.
///
/// CLI flag semantics:
/// - Shared `--X` pins BOTH sides to the same value(s). E.g.
///   `--kernel 6.14` is equivalent to
///   `--a-kernel 6.14 --b-kernel 6.14`.
/// - Per-side `--a-X` REPLACES the shared `--X` value for the A
///   side only (and `--b-X` replaces for B only). "More-specific
///   replaces" — the per-side flag takes precedence over the
///   shared default for that side, but does not affect the
///   other side.
///
/// Constructed from the raw clap-parsed values; `build()` does
/// the sugar resolution and returns `(filter_a, filter_b)`. The
/// struct is unit-testable in isolation so the sugar logic does
/// not require booting a real comparison.
///
/// Project- and kernel-commit fields hold ALREADY-EXPANDED
/// commit lists: any git revspecs (HEAD~1, tags, branch names,
/// `A..B` ranges) the user typed are resolved to 7-char short
/// hashes by [`resolve_commit_specs`] BEFORE construction so
/// `build()` stays a pure data-shuffler with no repo I/O.
#[derive(Debug, Clone, Default)]
struct BuildCompareFilters {
    shared_kernel: Vec<String>,
    shared_project_commit: Vec<String>,
    shared_kernel_commit: Vec<String>,
    shared_run_source: Vec<String>,
    shared_scheduler: Vec<String>,
    shared_topology: Vec<String>,
    shared_work_type: Vec<String>,
    shared_flags: Vec<String>,
    a_kernel: Vec<String>,
    a_project_commit: Vec<String>,
    a_kernel_commit: Vec<String>,
    a_run_source: Vec<String>,
    a_scheduler: Vec<String>,
    a_topology: Vec<String>,
    a_work_type: Vec<String>,
    a_flags: Vec<String>,
    b_kernel: Vec<String>,
    b_project_commit: Vec<String>,
    b_kernel_commit: Vec<String>,
    b_run_source: Vec<String>,
    b_scheduler: Vec<String>,
    b_topology: Vec<String>,
    b_work_type: Vec<String>,
    b_flags: Vec<String>,
}

impl BuildCompareFilters {
    /// Resolve sugar into per-side `RowFilter` instances.
    /// "More-specific replaces": a per-side Vec is applied
    /// verbatim when non-empty, otherwise the shared Vec is
    /// used. Every dimension on `RowFilter` is now a `Vec<String>`
    /// (after the #13 conversion from `Option<String>` to repeatable
    /// Vec for scheduler/topology/work_type), so a single `pick_vec`
    /// helper handles every dim uniformly — the prior `pick_opt`
    /// branch is no longer reachable.
    fn build(&self) -> (ktstr::cli::RowFilter, ktstr::cli::RowFilter) {
        let pick_vec = |a: &[String], shared: &[String]| -> Vec<String> {
            if a.is_empty() {
                shared.to_vec()
            } else {
                a.to_vec()
            }
        };
        let filter_a = ktstr::cli::RowFilter {
            kernels: pick_vec(&self.a_kernel, &self.shared_kernel),
            project_commits: pick_vec(&self.a_project_commit, &self.shared_project_commit),
            kernel_commits: pick_vec(&self.a_kernel_commit, &self.shared_kernel_commit),
            run_sources: pick_vec(&self.a_run_source, &self.shared_run_source),
            schedulers: pick_vec(&self.a_scheduler, &self.shared_scheduler),
            topologies: pick_vec(&self.a_topology, &self.shared_topology),
            work_types: pick_vec(&self.a_work_type, &self.shared_work_type),
            flags: pick_vec(&self.a_flags, &self.shared_flags),
        };
        let filter_b = ktstr::cli::RowFilter {
            kernels: pick_vec(&self.b_kernel, &self.shared_kernel),
            project_commits: pick_vec(&self.b_project_commit, &self.shared_project_commit),
            kernel_commits: pick_vec(&self.b_kernel_commit, &self.shared_kernel_commit),
            run_sources: pick_vec(&self.b_run_source, &self.shared_run_source),
            schedulers: pick_vec(&self.b_scheduler, &self.shared_scheduler),
            topologies: pick_vec(&self.b_topology, &self.shared_topology),
            work_types: pick_vec(&self.b_work_type, &self.shared_work_type),
            flags: pick_vec(&self.b_flags, &self.shared_flags),
        };
        (filter_a, filter_b)
    }
}

/// Acquire source, configure, build, and cache a kernel image.
///
/// `version` accepts `MAJOR.MINOR[.PATCH][-rcN]` for a single tarball,
/// `MAJOR.MINOR` (a major.minor prefix that resolves to the latest
/// patch in that series), or `START..END` for a range that expands
/// against kernel.org's `releases.json` to every `stable` /
/// `longterm` release inside the inclusive interval. A range is
/// detected via [`KernelId::parse`] and dispatched here to
/// [`kernel_build_one`] per resolved version, sharing the
/// download / cache-lookup / build pipeline that single-version
/// invocations use. Range mode collects per-version errors as a
/// best-effort summary: a build failure on one version is reported
/// and the iteration continues to the next, so a stale endpoint
/// doesn't block the rest of the range from caching.
///
/// `--git` and `--source` paths bypass range expansion (range
/// applies to tarball downloads only) and forward unchanged to
/// [`kernel_build_one`].
fn kernel_build(
    version: Option<String>,
    source: Option<PathBuf>,
    git: Option<String>,
    git_ref: Option<String>,
    force: bool,
    clean: bool,
    cpu_cap: Option<usize>,
) -> Result<(), String> {
    // Range dispatch only applies to tarball mode. `--source` and
    // `--git` carry their own source-of-truth that ranges don't
    // overlap with: a path identifies one tree, a git ref names one
    // commit. A range argument alongside either is undefined input;
    // clap's existing `conflicts_with` already rejects
    // `version + source` and `version + git` combinations, so the
    // range branch only fires when neither --source nor --git is
    // present.
    if source.is_none()
        && git.is_none()
        && let Some(ref v) = version
    {
        use ktstr::kernel_path::KernelId;
        let id = KernelId::parse(v);
        // Validate before any I/O: an inverted range surfaces the
        // "swap the endpoints" diagnostic ahead of any download.
        id.validate().map_err(|e| format!("--kernel {id}: {e}"))?;
        if let KernelId::Range { start, end } = id {
            let versions = ktstr::cli::expand_kernel_range(&start, &end, "cargo ktstr")
                .map_err(|e| format!("{e:#}"))?;
            let total = versions.len();
            let mut failures: Vec<(String, String)> = Vec::new();
            for (i, ver) in versions.iter().enumerate() {
                eprintln!("cargo ktstr: [{}/{total}] kernel build {ver}", i + 1);
                if let Err(e) =
                    kernel_build_one(Some(ver.clone()), None, None, None, force, clean, cpu_cap)
                {
                    eprintln!("cargo ktstr: {ver}: {e}");
                    failures.push((ver.clone(), e));
                }
            }
            if failures.is_empty() {
                Ok(())
            } else {
                // Surface the failure summary on the way out so an
                // automated invocation can scrape one log line per
                // failing version. Continue-on-error is the right
                // default for ranges (a stale endpoint shouldn't
                // gate the rest of the build cohort), but a
                // non-zero exit still flags the cohort as
                // partial.
                Err(format!(
                    "kernel build range {start}..{end}: {failed}/{total} \
                     version(s) failed: {names}",
                    start = start,
                    end = end,
                    failed = failures.len(),
                    names = failures
                        .iter()
                        .map(|(v, _)| v.as_str())
                        .collect::<Vec<_>>()
                        .join(", "),
                ))
            }
        } else {
            kernel_build_one(version, source, git, git_ref, force, clean, cpu_cap)
        }
    } else {
        kernel_build_one(version, source, git, git_ref, force, clean, cpu_cap)
    }
}

/// Single-version variant of [`kernel_build`]: handles one tarball,
/// `--source`, or `--git` invocation. Carries the `kernel_build`
/// implementation as it stood before range dispatch was wired in;
/// extracted into a helper so the range loop in `kernel_build` can
/// reuse the same download + cache + build pipeline per resolved
/// version without duplicating it.
fn kernel_build_one(
    version: Option<String>,
    source: Option<PathBuf>,
    git: Option<String>,
    git_ref: Option<String>,
    force: bool,
    clean: bool,
    cpu_cap: Option<usize>,
) -> Result<(), String> {
    // Resolve the CLI --cpu-cap flag against KTSTR_CPU_CAP env
    // and the implicit "no cap" default. Conflict with
    // KTSTR_BYPASS_LLC_LOCKS=1 surfaces here so operators see
    // the parse-time error, not an opaque pipeline bail later.
    if cpu_cap.is_some()
        && std::env::var("KTSTR_BYPASS_LLC_LOCKS")
            .ok()
            .is_some_and(|v| !v.is_empty())
    {
        return Err(
            "--cpu-cap conflicts with KTSTR_BYPASS_LLC_LOCKS=1; unset one of them. \
             --cpu-cap is a resource contract; bypass disables the contract entirely."
                .to_string(),
        );
    }
    let resolved_cap = cli::CpuCap::resolve(cpu_cap).map_err(|e| format!("{e:#}"))?;

    let cache = CacheDir::new().map_err(|e| format!("open cache: {e:#}"))?;

    // Temporary directory for tarball/git source extraction.
    let tmp_dir = tempfile::TempDir::new().map_err(|e| format!("create temp dir: {e:#}"))?;

    // Acquire source.
    let client = fetch::shared_client();
    let acquired = if let Some(ref src_path) = source {
        fetch::local_source(src_path).map_err(|e| format!("{e:#}"))?
    } else if let Some(ref url) = git {
        let ref_name = git_ref.as_deref().expect("clap requires --ref with --git");
        fetch::git_clone(url, ref_name, tmp_dir.path(), "cargo ktstr")
            .map_err(|e| format!("{e:#}"))?
    } else {
        // Tarball download: explicit version, prefix, or latest stable.
        let ver = match version {
            Some(v) if fetch::is_major_minor_prefix(&v) => {
                // Major.minor prefix (e.g., "6.12") — resolve latest patch.
                fetch::fetch_version_for_prefix(client, &v, "cargo ktstr")
                    .map_err(|e| format!("{e:#}"))?
            }
            Some(v) => v,
            None => fetch::fetch_latest_stable_version(client, "cargo ktstr")
                .map_err(|e| format!("{e:#}"))?,
        };
        // Check cache before downloading.
        let (arch, _) = fetch::arch_info();
        let cache_key = format!("{ver}-tarball-{arch}-kc{}", ktstr::cache_key_suffix());
        if !force && let Some(entry) = cache_lookup(&cache, &cache_key) {
            eprintln!("cargo ktstr: cached kernel found: {}", entry.path.display());
            eprintln!("cargo ktstr: use --force to rebuild");
            return Ok(());
        }
        let sp = cli::Spinner::start("Downloading kernel...");
        let result = fetch::download_tarball(client, &ver, tmp_dir.path(), "cargo ktstr");
        drop(sp);
        result.map_err(|e| format!("{e:#}"))?
    };

    // Check cache for --source and --git (tarball already checked
    // pre-download above).
    if !force
        && (source.is_some() || git.is_some())
        && !acquired.is_dirty
        && let Some(entry) = cache_lookup(&cache, &acquired.cache_key)
    {
        eprintln!("cargo ktstr: cached kernel found: {}", entry.path.display());
        eprintln!("cargo ktstr: use --force to rebuild");
        return Ok(());
    }

    // `--force` fail-fast pre-check: if tests are actively holding
    // the cache-entry lock, bail with the PID list rather than
    // silently waiting to stomp the in-use entry. The guard drops
    // at the end of this `if` before `kernel_build_pipeline` runs.
    if force {
        let _force_check = cache
            .try_acquire_exclusive_lock(&acquired.cache_key)
            .map_err(|e| format!("{e:#}"))?;
    }

    cli::kernel_build_pipeline(
        &acquired,
        &cache,
        "cargo ktstr",
        clean,
        source.is_some(),
        resolved_cap,
    )
    .map_err(|e| format!("{e:#}"))?;

    Ok(())
}

/// Look up a cache key, checking local first, then remote (if enabled).
fn cache_lookup(cache: &CacheDir, cache_key: &str) -> Option<CacheEntry> {
    cli::cache_lookup(cache, cache_key, "cargo ktstr")
}

/// Policy for cargo-ktstr's shell + verifier kernel resolution:
/// accept raw image files, use "cargo ktstr" as the CLI label.
const KERNEL_POLICY: ktstr::cli::KernelResolvePolicy<'static> = ktstr::cli::KernelResolvePolicy {
    accept_raw_image: true,
    cli_label: "cargo ktstr",
};

/// Resolve a kernel identifier to a bootable image path via the
/// shared `ktstr::cli::resolve_kernel_image` helper with cargo-ktstr's
/// policy.
fn resolve_kernel_image(kernel: Option<&str>) -> Result<PathBuf, String> {
    ktstr::cli::resolve_kernel_image(kernel, &KERNEL_POLICY).map_err(|e| format!("{e:#}"))
}

#[allow(clippy::too_many_arguments)]
fn run_shell(
    kernel: Option<String>,
    topology: String,
    include_files: Vec<PathBuf>,
    memory_mb: Option<u32>,
    dmesg: bool,
    exec: Option<String>,
    no_perf_mode: bool,
    cpu_cap: Option<usize>,
) -> Result<(), String> {
    if no_perf_mode {
        // SAFETY: single-threaded at this point — no concurrent env readers.
        unsafe { std::env::set_var("KTSTR_NO_PERF_MODE", "1") };
    }
    if let Some(cap) = cpu_cap {
        // Parse-time conflict with KTSTR_BYPASS_LLC_LOCKS — see
        // ktstr.rs Shell dispatch for the same check.
        if std::env::var("KTSTR_BYPASS_LLC_LOCKS")
            .ok()
            .is_some_and(|v| !v.is_empty())
        {
            return Err(
                "--cpu-cap conflicts with KTSTR_BYPASS_LLC_LOCKS=1; unset one of them. \
                 --cpu-cap is a resource contract; bypass disables the contract entirely."
                    .to_string(),
            );
        }
        // Validate early so a bad cap surfaces at CLI-parse time.
        cli::CpuCap::new(cap).map_err(|e| format!("{e:#}"))?;
        // SAFETY: single-threaded at this point — no concurrent env readers.
        unsafe { std::env::set_var("KTSTR_CPU_CAP", cap.to_string()) };
    }
    cli::check_kvm().map_err(|e| format!("{e:#}"))?;
    let kernel_path = resolve_kernel_image(kernel.as_deref())?;

    let (numa_nodes, llcs, cores, threads) =
        cli::parse_topology_string(&topology).map_err(|e| format!("{e:#}"))?;

    let resolved_includes =
        cli::resolve_include_files(&include_files).map_err(|e| format!("{e:#}"))?;

    let include_refs: Vec<(&str, &Path)> = resolved_includes
        .iter()
        .map(|(a, p)| (a.as_str(), p.as_path()))
        .collect();

    ktstr::run_shell(
        kernel_path,
        numa_nodes,
        llcs,
        cores,
        threads,
        &include_refs,
        memory_mb,
        dmesg,
        exec.as_deref(),
    )
    .map_err(|e| format!("{e:#}"))
}

/// Query a scheduler binary's flag declarations via `--ktstr-list-flags`.
///
/// Runs the binary with `--ktstr-list-flags` and parses its stdout as
/// JSON. Returns an empty vec if the binary doesn't support the flag
/// (exits non-zero or produces no output).
fn query_scheduler_flags(
    sched_bin: &Path,
) -> Result<Vec<ktstr::scenario::flags::FlagDeclJson>, String> {
    let output = Command::new(sched_bin)
        .arg("--ktstr-list-flags")
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output()
        .map_err(|e| format!("run scheduler --ktstr-list-flags: {e:#}"))?;

    if !output.status.success() {
        return Ok(Vec::new());
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let trimmed = stdout.trim();
    if trimmed.is_empty() {
        return Ok(Vec::new());
    }

    serde_json::from_str(trimmed).map_err(|e| format!("parse --ktstr-list-flags output: {e:#}"))
}

/// Generate flag profiles from flag declarations.
///
/// Produces the power set of flags, filtered by requires constraints,
/// via the shared [`ktstr::scenario::compute_flag_profiles`] generator.
/// Each profile's flags are sorted in declaration order. The profile
/// name is the flags joined with `+`, or `"default"` when empty.
fn generate_flag_profiles(
    flags: &[ktstr::scenario::flags::FlagDeclJson],
) -> Vec<(String, Vec<String>)> {
    let n = flags.len();
    if n > 31 {
        eprintln!(
            "cargo ktstr: error: scheduler has {n} flags, power set too large (2^{n}). \
             Use --profiles to select specific profiles."
        );
        return Vec::new();
    }

    let all: Vec<String> = flags.iter().map(|f| f.name.clone()).collect();
    let requires_fn = |name: &String| -> Vec<String> {
        flags
            .iter()
            .find(|f| f.name == *name)
            .map(|f| f.requires.clone())
            .unwrap_or_default()
    };

    ktstr::scenario::compute_flag_profiles(&all, requires_fn, &[], &[])
        .into_iter()
        .map(|flag_names| {
            let name = if flag_names.is_empty() {
                "default".to_string()
            } else {
                flag_names.join("+")
            };
            (name, flag_names)
        })
        .collect()
}

/// Collect the extra scheduler args for a set of active flags.
///
/// Returns `Err` if any flag in `active_flags` is not declared in
/// `all_flags`. Silently dropping unknown flags masked typos in
/// CLI `--profiles` lists and version-drift in cached nextest args —
/// the caller would see "flag applied" in the profile name but the
/// scheduler was actually invoked without the corresponding CLI arg.
fn profile_sched_args(
    active_flags: &[String],
    all_flags: &[ktstr::scenario::flags::FlagDeclJson],
) -> Result<Vec<String>, String> {
    let mut args = Vec::new();
    for flag_name in active_flags {
        match all_flags.iter().find(|f| f.name == *flag_name) {
            Some(decl) => args.extend(decl.args.iter().cloned()),
            None => {
                let known: Vec<&str> = all_flags.iter().map(|f| f.name.as_str()).collect();
                return Err(format!(
                    "unknown flag {flag_name:?} (known: {})",
                    known.join(", ")
                ));
            }
        }
    }
    Ok(args)
}

fn run_verifier(
    scheduler: Option<String>,
    scheduler_bin: Option<PathBuf>,
    kernel: Vec<String>,
    raw: bool,
    all_profiles: bool,
    profiles_filter: Vec<String>,
) -> Result<(), String> {
    cli::check_kvm().map_err(|e| format!("{e:#}"))?;

    // Resolve scheduler binary.
    let sched_bin = match (scheduler, scheduler_bin) {
        (Some(package), None) => {
            ktstr::build_and_find_binary(&package).map_err(|e| format!("build scheduler: {e:#}"))?
        }
        (None, Some(path)) => {
            if !path.exists() {
                return Err(format!("scheduler binary not found: {}", path.display()));
            }
            path
        }
        (None, None) => {
            return Err("either --scheduler or --scheduler-bin is required".to_string());
        }
        // clap conflicts_with prevents this.
        (Some(_), Some(_)) => unreachable!(),
    };

    // Resolve --kernel into a flat (label, kernel_dir) list. Empty
    // input falls through to the single-kernel auto-discovery path
    // below (`resolve_kernel_image(None)` → `find_kernel`'s
    // fallback chain), preserving the no-flag behaviour. A
    // single-entry list is treated identically to the historical
    // single-kernel path: one verifier run, no kernel-prefixed
    // output. Two or more entries (multiple `--kernel` flags, OR
    // a single `--kernel` Range that expanded to multiple
    // releases) iterate sequentially with per-kernel header lines.
    let kernel_paths: Vec<(String, PathBuf)> = if kernel.is_empty() {
        // Auto-discovery: route through `resolve_kernel_image(None)`
        // so the existing `find_kernel` cascade applies, then label
        // the result `"auto"` for diagnostic visibility on the rare
        // path where the user neither passed `--kernel` nor exported
        // `KTSTR_KERNEL`.
        let path = resolve_kernel_image(None)?;
        vec![("auto".to_string(), path)]
    } else {
        // Multi-kernel resolution shares its plumbing with the test
        // path (`run_cargo_sub`'s `resolve_kernel_set` call),
        // including Range expansion and Git fetch. Each resolved
        // entry is a built / cached kernel directory; convert it to
        // a bootable image via `find_image_in_dir` since the
        // verifier collects stats from a loaded image rather than
        // a directory.
        let resolved = resolve_kernel_set(&kernel)?;
        if resolved.is_empty() {
            return Err(
                "--kernel: every supplied value parsed to empty / whitespace; \
                 omit the flag for auto-discovery, or supply a kernel \
                 identifier"
                    .to_string(),
            );
        }
        let mut out: Vec<(String, PathBuf)> = Vec::with_capacity(resolved.len());
        for (label, dir) in resolved {
            let image = ktstr::kernel_path::find_image_in_dir(&dir).ok_or_else(|| {
                format!(
                    "no kernel image found in {} (resolved from --kernel {label})",
                    dir.display()
                )
            })?;
            out.push((label, image));
        }
        out
    };

    // Build the ktstr init binary.
    let ktstr_bin =
        ktstr::build_and_find_binary("ktstr").map_err(|e| format!("build ktstr: {e:#}"))?;

    let multi_kernel = kernel_paths.len() > 1;
    for (i, (label, kernel_path)) in kernel_paths.iter().enumerate() {
        if multi_kernel {
            eprintln!(
                "cargo ktstr: [kernel {}/{}] {label}",
                i + 1,
                kernel_paths.len(),
            );
            // Header on stdout so a redirected `>` capture
            // separates kernels even when stderr isn't pulled.
            println!("\n=== kernel: {label} ===");
        }

        if all_profiles || !profiles_filter.is_empty() {
            run_verifier_all_profiles(&sched_bin, &ktstr_bin, kernel_path, raw, &profiles_filter)?;
            continue;
        }

        eprintln!("cargo ktstr: collecting verifier stats");
        let result =
            ktstr::verifier::collect_verifier_output(&sched_bin, &ktstr_bin, kernel_path, &[])
                .map_err(|e| format!("collect verifier output: {e:#}"))?;

        let output = ktstr::verifier::format_verifier_output("verifier", &result, raw);
        print!("{output}");
    }

    Ok(())
}

fn run_verifier_all_profiles(
    sched_bin: &Path,
    ktstr_bin: &Path,
    kernel_path: &Path,
    raw: bool,
    profiles_filter: &[String],
) -> Result<(), String> {
    let flags = query_scheduler_flags(sched_bin)?;
    if flags.is_empty() {
        eprintln!(
            "cargo ktstr: scheduler does not support --ktstr-list-flags, \
             running with default profile only"
        );
        let result =
            ktstr::verifier::collect_verifier_output(sched_bin, ktstr_bin, kernel_path, &[])
                .map_err(|e| format!("collect verifier output: {e:#}"))?;
        let output = ktstr::verifier::format_verifier_output("default", &result, raw);
        print!("{output}");
        return Ok(());
    }

    let all_profiles = generate_flag_profiles(&flags);

    // Filter profiles if --profiles was specified.
    let profiles: Vec<&(String, Vec<String>)> = if profiles_filter.is_empty() {
        all_profiles.iter().collect()
    } else {
        let filtered: Vec<_> = all_profiles
            .iter()
            .filter(|(name, _)| profiles_filter.iter().any(|f| f == name))
            .collect();
        if filtered.is_empty() {
            return Err(format!(
                "no matching profiles found. Available: {}",
                all_profiles
                    .iter()
                    .map(|(n, _)| n.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
        filtered
    };

    let total = profiles.len();
    if total == 0 {
        // Differentiate the empty-profile cases so the user gets an
        // actionable error rather than a generic "0 profiles" message.
        return Err(if flags.len() > 31 {
            format!(
                "no profiles to verify: power-set generation is capped at \
                 31 flags (found {}); use --profiles to select a subset",
                flags.len(),
            )
        } else {
            format!(
                "no profiles to verify: {} flag(s) advertised but profile \
                 generation produced 0 profiles — check `requires` \
                 dependencies and exclusions for cycles or conflicts",
                flags.len(),
            )
        });
    }
    if total > 32 {
        eprintln!(
            "cargo ktstr: warning: {total} profiles to verify (>32). \
             Use --profiles to select a subset."
        );
    }

    eprintln!(
        "cargo ktstr: verifying {total} profile{}",
        if total == 1 { "" } else { "s" }
    );

    // Per-profile summary table: (profile_name, Vec<(prog_name, verified_insns)>).
    let mut summary: Vec<(String, Vec<(String, u32)>)> = Vec::new();

    for (i, (profile_name, active_flags)) in profiles.iter().enumerate() {
        eprintln!(
            "cargo ktstr: [{}/{}] profile: {}",
            i + 1,
            total,
            profile_name
        );

        let extra_args = profile_sched_args(active_flags, &flags)
            .map_err(|e| format!("profile {profile_name}: {e}"))?;
        let result = ktstr::verifier::collect_verifier_output(
            sched_bin,
            ktstr_bin,
            kernel_path,
            &extra_args,
        )
        .map_err(|e| format!("profile {profile_name}: {e:#}"))?;

        let output = ktstr::verifier::format_verifier_output(profile_name, &result, raw);
        print!("{output}");

        let prog_stats: Vec<(String, u32)> = result
            .stats
            .iter()
            .map(|ps| (ps.name.clone(), ps.verified_insns))
            .collect();
        summary.push((profile_name.clone(), prog_stats));
    }

    // Print per-profile summary table.
    if summary.len() > 1 {
        print_profile_summary(&summary);
    }

    Ok(())
}

/// Print a summary table comparing verified_insns across profiles.
fn print_profile_summary(summary: &[(String, Vec<(String, u32)>)]) {
    // Collect all unique program names in insertion order.
    let mut prog_names: Vec<String> = Vec::new();
    for (_, progs) in summary {
        for (name, _) in progs {
            if !prog_names.contains(name) {
                prog_names.push(name.clone());
            }
        }
    }

    println!("\n--- profile summary ---");

    let profile_names: Vec<&str> = summary.iter().map(|(n, _)| n.as_str()).collect();
    let mut table = ktstr::cli::new_table();
    let mut header: Vec<&str> = Vec::with_capacity(1 + profile_names.len());
    header.push("program");
    header.extend(profile_names.iter().copied());
    table.set_header(header);

    for prog in &prog_names {
        let mut row: Vec<String> = Vec::with_capacity(1 + profile_names.len());
        row.push(prog.clone());
        for (_, progs) in summary {
            let insns = progs
                .iter()
                .find(|(n, _)| n == prog)
                .map(|(_, v)| *v)
                .unwrap_or(0);
            row.push(insns.to_string());
        }
        table.add_row(row);
    }

    println!("{table}");
}

fn run_completions(shell: clap_complete::Shell, binary: &str) {
    let mut cmd = Cargo::command();
    clap_complete::generate(shell, &mut cmd, binary, &mut std::io::stdout());
}

/// `cargo ktstr model fetch` — download + SHA-check the default model
/// into the user's cache. Wraps `ktstr::test_support::ensure` with a
/// human-readable progress line; the status is printed after so
/// users can see the final cache path regardless of whether the
/// fetch did any work.
fn run_model_fetch() -> Result<(), String> {
    let spec = ktstr::test_support::DEFAULT_MODEL;
    match ktstr::test_support::ensure(&spec) {
        Ok(path) => {
            println!(
                "ktstr: model '{}' ready at {}",
                spec.file_name,
                path.display()
            );
            Ok(())
        }
        Err(e) => Err(format!("fetch model '{}': {e:#}", spec.file_name)),
    }
}

/// `cargo ktstr model status` — report the cache path and whether a
/// SHA-checked copy of the default model is already present.
fn run_model_status() -> Result<(), String> {
    let spec = ktstr::test_support::DEFAULT_MODEL;
    let status = ktstr::test_support::status(&spec).map_err(|e| format!("{e:#}"))?;
    println!("model:    {}", status.spec.file_name);
    println!("path:     {}", status.path.display());
    println!("cached:   {}", status.sha_verdict.is_cached());
    println!("checked:  {}", status.sha_verdict.is_match());
    // Distinguish the four verdict variants so each gets a
    // remediation-specific line: absent cache, I/O failure during
    // the SHA check, successful hash that didn't match, and the
    // all-clear case (no annotation needed). An I/O failure points
    // at the filesystem entry (permissions, truncation); a mismatch
    // points at the bytes themselves.
    // "Re-fetch to replace it" is the shared remediation tail for
    // every non-Matches cached-file branch (both CheckFailed and
    // Mismatches land on the same operator action — the cause
    // differs but the fix does not). Factoring the tail into one
    // string keeps the two arms in lock-step so a wording change
    // lands in both places by construction.
    const RE_FETCH_TAIL: &str = "re-fetch to replace it";
    match &status.sha_verdict {
        ktstr::test_support::ShaVerdict::NotCached => println!(
            "(no cached copy — run `cargo ktstr model fetch` to download {} MiB)",
            status.spec.size_bytes / 1024 / 1024,
        ),
        ktstr::test_support::ShaVerdict::CheckFailed(err) => {
            // Defensively collapse any embedded `\n` into `; `
            // before placing `err` inside the "(single
            // parenthesized note)" wrapper. The alternate
            // anyhow format (`{e:#}`) that produced `err` joins
            // causes with `: ` and is single-line in practice;
            // this replace is a guard against a future error
            // source whose Display impl injects its own
            // newlines (std::io errors wrapping multi-line OS
            // messages, third-party crates formatting
            // call-chain trees). Keeping the output on one
            // line preserves the visual grouping the other
            // match arms use.
            let single_line = err.replace('\n', "; ");
            println!(
                "(cached file could not be checked: {single_line}; \
                 inspect the cache entry or {RE_FETCH_TAIL})",
            );
        }
        ktstr::test_support::ShaVerdict::Mismatches => {
            println!("(cached file failed SHA-256 check; {RE_FETCH_TAIL})",);
        }
        ktstr::test_support::ShaVerdict::Matches => {}
    }
    Ok(())
}

/// `cargo ktstr model clean` — remove the cached GGUF artifact and
/// its `.mtime-size` sidecar. Wraps
/// `ktstr::test_support::clean` and renders the resulting
/// [`ktstr::test_support::CleanReport`] as a per-file deletion
/// log plus a total-freed summary line. Sizes pass through
/// `indicatif::HumanBytes` for IEC-prefixed rendering ("2.34 GiB",
/// "52 B") consistent with the rest of the model surface.
///
/// Empty-cache case (neither file present) prints a single
/// "no cached model found" line so an idempotent re-run after a
/// successful clean produces a clear "nothing to do" outcome
/// rather than two "(absent)" lines.
fn run_model_clean() -> Result<(), String> {
    let spec = ktstr::test_support::DEFAULT_MODEL;
    let report =
        ktstr::test_support::clean(&spec).map_err(|e| format!("clean model cache: {e:#}"))?;
    if report.is_empty() {
        println!(
            "no cached model found at {}",
            report.artifact_path.display()
        );
        return Ok(());
    }
    if let Some(bytes) = report.artifact_freed_bytes {
        println!(
            "removed {} ({})",
            report.artifact_path.display(),
            indicatif::HumanBytes(bytes),
        );
    }
    if let Some(bytes) = report.sidecar_freed_bytes {
        println!(
            "removed {} ({})",
            report.sidecar_path.display(),
            indicatif::HumanBytes(bytes),
        );
    }
    println!(
        "freed {} total",
        indicatif::HumanBytes(report.total_freed_bytes()),
    );
    Ok(())
}

fn main() {
    // Restore SIGPIPE so piping `cargo ktstr ... | head` doesn't
    // panic inside `print!`. See `ktstr::cli::restore_sigpipe_default`
    // for the full rationale; shared across all three ktstr bins so
    // the rationale + SAFETY text lives in one place.
    ktstr::cli::restore_sigpipe_default();
    // Mirror `ktstr`'s tracing init (src/bin/ktstr.rs main()) so
    // `tracing::warn!` calls inside `cli::` / `test_support::` surface
    // on stderr instead of being silently dropped. Default to `warn`
    // so normal CLI invocations (kernel build, model fetch, etc.) stay
    // quiet; users who want finer detail set `RUST_LOG=info,debug,...`.
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")),
        )
        .with_writer(std::io::stderr)
        .init();

    let Cargo {
        command: CargoSub::Ktstr(ktstr),
    } = Cargo::parse();

    // Match-arm order mirrors the `KtstrCommand` enum declaration at
    // the top of this file. Keeping the two orderings in lockstep lets
    // a reviewer eyeball "every variant is dispatched" in one linear
    // scan instead of cross-referencing two different orders; a future
    // variant addition then lands in the matching enum position and
    // here without requiring the reader to rebuild the mapping.
    let result = match ktstr.command {
        KtstrCommand::Test {
            kernel,
            no_perf_mode,
            release,
            args,
        } => run_test(kernel, no_perf_mode, release, args),
        KtstrCommand::Coverage {
            kernel,
            no_perf_mode,
            release,
            args,
        } => run_coverage(kernel, no_perf_mode, release, args),
        KtstrCommand::LlvmCov {
            kernel,
            no_perf_mode,
            args,
        } => run_llvm_cov(kernel, no_perf_mode, args),
        KtstrCommand::Stats { ref command } => run_stats(command),
        KtstrCommand::Kernel { command } => match command {
            KernelCommand::List { json, range } => match range {
                Some(r) => cli::kernel_list_range_preview(json, &r).map_err(|e| format!("{e:#}")),
                None => cli::kernel_list(json).map_err(|e| format!("{e:#}")),
            },
            KernelCommand::Build {
                version,
                source,
                git,
                git_ref,
                force,
                clean,
                cpu_cap,
            } => kernel_build(version, source, git, git_ref, force, clean, cpu_cap),
            KernelCommand::Clean {
                keep,
                force,
                corrupt_only,
            } => cli::kernel_clean(keep, force, corrupt_only).map_err(|e| format!("{e:#}")),
        },
        KtstrCommand::Model { command } => match command {
            ModelCommand::Fetch => run_model_fetch(),
            ModelCommand::Status => run_model_status(),
            ModelCommand::Clean => run_model_clean(),
        },
        KtstrCommand::Verifier {
            scheduler,
            scheduler_bin,
            kernel,
            raw,
            all_profiles,
            profiles,
        } => run_verifier(
            scheduler,
            scheduler_bin,
            kernel,
            raw,
            all_profiles,
            profiles,
        ),
        KtstrCommand::Completions { shell, binary } => {
            run_completions(shell, &binary);
            Ok(())
        }
        KtstrCommand::ShowHost => {
            print!("{}", cli::show_host());
            Ok(())
        }
        KtstrCommand::ShowThresholds { test } => match cli::show_thresholds(&test) {
            Ok(s) => {
                print!("{s}");
                Ok(())
            }
            Err(e) => Err(format!("{e:#}")),
        },
        KtstrCommand::Cleanup { parent_cgroup } => {
            cli::cleanup(parent_cgroup).map_err(|e| format!("{e:#}"))
        }
        KtstrCommand::Locks { json, watch } => {
            cli::list_locks(json, watch).map_err(|e| format!("{e:#}"))
        }
        KtstrCommand::Shell {
            kernel,
            topology,
            include_files,
            memory_mb,
            dmesg,
            exec,
            no_perf_mode,
            cpu_cap,
        } => run_shell(
            kernel,
            topology,
            include_files,
            memory_mb,
            dmesg,
            exec,
            no_perf_mode,
            cpu_cap,
        ),
    };

    if let Err(e) = result {
        eprintln!("error: {e:#}");
        std::process::exit(1);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;
    use ktstr::cache::KernelMetadata;

    // -- structural validation --

    #[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}"));
        match k.command {
            KtstrCommand::Test { release, .. } => {
                assert!(release, "`--release` must set `release=true`");
            }
            _ => panic!("expected Test"),
        }
    }

    #[test]
    fn parse_test_with_passthrough_args() {
        let Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "test",
            "--",
            "-p",
            "ktstr",
            "--no-capture",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Test { args, .. } => {
                assert_eq!(args, vec!["-p", "ktstr", "--no-capture"]);
            }
            _ => panic!("expected Test"),
        }
    }

    // -- 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() {
        let Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "nextest",
            "--",
            "-p",
            "ktstr",
            "--no-capture",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Test { args, .. } => {
                assert_eq!(args, vec!["-p", "ktstr", "--no-capture"]);
            }
            _ => panic!("expected Test (via `nextest` alias)"),
        }
    }

    /// 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}"));
        match k.command {
            KtstrCommand::Test {
                kernel,
                no_perf_mode,
                release,
                args,
            } => {
                assert_eq!(kernel, vec!["6.14.2".to_string()]);
                assert!(no_perf_mode);
                assert!(!release, "bare invocation must default --release to false");
                assert!(args.is_empty());
            }
            _ => panic!("expected Test (via `nextest` alias)"),
        }
    }

    // -- 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}"));
        match k.command {
            KtstrCommand::Coverage { release, .. } => {
                assert!(release, "`--release` must set `release=true`");
            }
            _ => panic!("expected Coverage"),
        }
    }

    #[test]
    fn parse_coverage_with_passthrough_args() {
        let Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "coverage",
            "--",
            "--workspace",
            "--lcov",
            "--output-path",
            "lcov.info",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Coverage { args, .. } => {
                assert_eq!(
                    args,
                    vec!["--workspace", "--lcov", "--output-path", "lcov.info"]
                );
            }
            _ => panic!("expected Coverage"),
        }
    }

    /// 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}"));
        match k.command {
            KtstrCommand::Coverage {
                kernel,
                no_perf_mode,
                release,
                args,
            } => {
                assert_eq!(kernel, vec!["6.14.2".to_string()]);
                assert!(no_perf_mode);
                assert!(!release, "bare invocation must default --release to false");
                assert_eq!(args, vec!["--workspace"]);
            }
            _ => panic!("expected Coverage"),
        }
    }

    // -- 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}"));
        match k.command {
            KtstrCommand::LlvmCov { kernel, .. } => {
                assert_eq!(kernel, vec!["6.14.2".to_string()]);
            }
            _ => panic!("expected LlvmCov"),
        }
    }

    #[test]
    fn parse_llvm_cov_with_passthrough_args() {
        let Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "llvm-cov",
            "--",
            "report",
            "--lcov",
            "--output-path",
            "lcov.info",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::LlvmCov { args, .. } => {
                assert_eq!(args, vec!["report", "--lcov", "--output-path", "lcov.info"]);
            }
            _ => panic!("expected LlvmCov"),
        }
    }

    /// 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}"));
        match k.command {
            KtstrCommand::LlvmCov {
                kernel,
                no_perf_mode,
                args,
            } => {
                assert_eq!(kernel, vec!["6.14.2".to_string()]);
                assert!(no_perf_mode);
                assert_eq!(args, vec!["report", "--lcov"]);
            }
            _ => panic!("expected LlvmCov"),
        }
    }

    /// 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)",
        );
    }

    // -- 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}"));
        match k.command {
            KtstrCommand::Shell { topology, .. } => {
                assert_eq!(topology, "1,2,4,1");
            }
            _ => panic!("expected Shell"),
        }
    }

    #[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}"));
        match k.command {
            KtstrCommand::Shell { topology, .. } => {
                assert_eq!(topology, "1,1,1,1");
            }
            _ => panic!("expected Shell"),
        }
    }

    #[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}"));
        match k.command {
            KtstrCommand::Shell { include_files, .. } => {
                assert_eq!(include_files.len(), 2);
            }
            _ => panic!("expected Shell"),
        }
    }

    // -- 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}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::ListMetrics { json }),
                ..
            } => {
                assert!(
                    !json,
                    "bare `list-metrics` must default to text mode (json=false)",
                );
            }
            _ => panic!("expected Stats ListMetrics"),
        }
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::ListMetrics { json }),
                ..
            } => {
                assert!(json, "--json must set the flag true");
            }
            _ => panic!("expected Stats ListMetrics"),
        }
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::ListValues { json, dir }),
                ..
            } => {
                assert!(!json, "bare `list-values` must default to text mode");
                assert!(
                    dir.is_none(),
                    "bare `list-values` must default to no --dir override"
                );
            }
            _ => panic!("expected Stats ListValues"),
        }
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::ListValues { json, .. }),
                ..
            } => {
                assert!(json, "--json must set the flag true");
            }
            _ => panic!("expected Stats ListValues"),
        }
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::ListValues { dir, json }),
                ..
            } => {
                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");
            }
            _ => panic!("expected Stats ListValues"),
        }
    }

    /// `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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
            "-E",
            "cgroup_steady",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command:
                    Some(StatsCommand::Compare {
                        filter,
                        threshold,
                        policy,
                        dir,
                        a_kernel,
                        b_kernel,
                        ..
                    }),
                ..
            } => {
                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());
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    #[test]
    fn parse_stats_compare_with_threshold() {
        let Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
            "--threshold",
            "5.0",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command:
                    Some(StatsCommand::Compare {
                        threshold, filter, ..
                    }),
                ..
            } => {
                assert_eq!(threshold, Some(5.0));
                assert!(filter.is_none());
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// 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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
            "--dir",
            "/tmp/archived-runs",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command:
                    Some(StatsCommand::Compare {
                        filter,
                        threshold,
                        policy,
                        dir,
                        ..
                    }),
                ..
            } => {
                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",
                );
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// 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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
            "--policy",
            "/tmp/policy.json",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command:
                    Some(StatsCommand::Compare {
                        threshold, policy, ..
                    }),
                ..
            } => {
                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",
                );
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// `--threshold` and `--policy` are mutually exclusive via
    /// clap `conflicts_with`. Passing both must be rejected at
    /// parse time, NOT reach the dispatch-level `unreachable!()`
    /// branch. A regression that dropped the `conflicts_with`
    /// attribute on either field would turn the `unreachable!()`
    /// into a panic at runtime instead of a parse error at parse
    /// time — this test catches that at compile-time parse
    /// behaviour.
    #[test]
    fn parse_stats_compare_rejects_both_threshold_and_policy() {
        // Avoid `expect_err` / `unwrap_err` because they require
        // the `Ok` type (`Cargo`) to implement `Debug`, which the
        // clap `Parser` derive does not add. A direct `match`
        // sidesteps the bound and keeps the test compiling
        // independently of whether `Cargo` gains `#[derive(Debug)]`
        // elsewhere.
        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",
        ]);
        let err = match result {
            Err(e) => e,
            Ok(_) => panic!(
                "clap conflicts_with must reject both --threshold \
                 and --policy being set together"
            ),
        };
        let rendered = err.to_string();
        assert!(
            rendered
                .to_ascii_lowercase()
                .contains("cannot be used with")
                || rendered.to_ascii_lowercase().contains("conflict"),
            "clap error must surface the conflict between \
             --threshold and --policy; got: {rendered}",
        );
    }

    /// Bare `compare` defaults `--no-average` to `false` —
    /// averaging is the default since #117. `--no-average`
    /// must be opt-in for "keep each sidecar distinct"
    /// semantics.
    #[test]
    fn parse_stats_compare_no_average_default_false() {
        let Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::Compare { no_average, .. }),
                ..
            } => {
                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.",
                );
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// `--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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
            "--no-average",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command:
                    Some(StatsCommand::Compare {
                        no_average,
                        threshold,
                        policy,
                        dir,
                        ..
                    }),
                ..
            } => {
                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",
                );
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// `--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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--project-commit",
            "abc1234",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command:
                    Some(StatsCommand::Compare {
                        project_commit,
                        a_project_commit,
                        b_project_commit,
                        ..
                    }),
                ..
            } => {
                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",
                );
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// `--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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--project-commit",
            "a",
            "--project-commit",
            "b",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::Compare { project_commit, .. }),
                ..
            } => {
                assert_eq!(project_commit, vec!["a", "b"]);
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// `--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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--kernel-commit",
            "abc1234",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command:
                    Some(StatsCommand::Compare {
                        kernel_commit,
                        a_kernel_commit,
                        b_kernel_commit,
                        ..
                    }),
                ..
            } => {
                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",
                );
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// `--kernel-commit A --kernel-commit B` produces a Vec with
    /// two entries via `ArgAction::Append`. Mirrors
    /// `parse_stats_compare_with_commit_repeatable` for the
    /// kernel-commit dimension.
    #[test]
    fn parse_stats_compare_with_kernel_commit_repeatable() {
        let Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--kernel-commit",
            "a",
            "--kernel-commit",
            "b",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::Compare { kernel_commit, .. }),
                ..
            } => {
                assert_eq!(kernel_commit, vec!["a", "b"]);
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// `--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-#13 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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--scheduler",
            "scx_alpha",
            "--scheduler",
            "scx_beta",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::Compare { scheduler, .. }),
                ..
            } => {
                assert_eq!(scheduler, vec!["scx_alpha", "scx_beta"]);
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// `--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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--topology",
            "1n2l4c2t",
            "--topology",
            "1n4l2c1t",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::Compare { topology, .. }),
                ..
            } => {
                assert_eq!(topology, vec!["1n2l4c2t", "1n4l2c1t"]);
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// `--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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--work-type",
            "CpuSpin",
            "--work-type",
            "PageFaultChurn",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::Compare { work_type, .. }),
                ..
            } => {
                assert_eq!(work_type, vec!["CpuSpin", "PageFaultChurn"]);
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// `--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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--a-kernel-commit",
            "abc1234",
            "--b-kernel-commit",
            "def5678",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command:
                    Some(StatsCommand::Compare {
                        kernel_commit,
                        a_kernel_commit,
                        b_kernel_commit,
                        ..
                    }),
                ..
            } => {
                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"]);
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    // -- BuildCompareFilters: symmetric sugar resolution --

    /// Empty input → both sides default. No filters populated
    /// anywhere; the dispatch site rejects this with the
    /// "specify at least one --a-X" error, but the builder
    /// itself just returns two empty filters.
    #[test]
    fn build_compare_filters_empty_yields_default_default() {
        let b = BuildCompareFilters::default();
        let (fa, fb) = b.build();
        assert!(fa.kernels.is_empty());
        assert!(fa.project_commits.is_empty());
        assert!(fa.kernel_commits.is_empty());
        assert!(fa.run_sources.is_empty());
        assert!(fa.schedulers.is_empty());
        assert!(fa.topologies.is_empty());
        assert!(fa.work_types.is_empty());
        assert!(fa.flags.is_empty());
        assert_eq!(fa.kernels, fb.kernels);
        assert_eq!(fa.project_commits, fb.project_commits);
        assert_eq!(fa.kernel_commits, fb.kernel_commits);
        assert_eq!(fa.run_sources, fb.run_sources);
        assert_eq!(fa.schedulers, fb.schedulers);
        assert_eq!(fa.topologies, fb.topologies);
        assert_eq!(fa.work_types, fb.work_types);
    }

    /// Per-side `--a-kernel-commit` overrides shared
    /// `--kernel-commit` for A only; B retains the shared value.
    /// Same "more-specific replaces" semantics as `--a-kernel`.
    /// The per-side override path is what populates the slicing
    /// dim on `KernelCommit` — without it, two sides with
    /// different live kernel HEADs cannot be contrasted in one
    /// `compare` invocation.
    #[test]
    fn build_compare_filters_per_side_kernel_commit_overrides_shared() {
        let b = BuildCompareFilters {
            shared_kernel_commit: vec!["abcdef1".to_string(), "fedcba2".to_string()],
            a_kernel_commit: vec!["111aaaa".to_string()],
            ..BuildCompareFilters::default()
        };
        let (fa, fb) = b.build();
        assert_eq!(
            fa.kernel_commits,
            vec!["111aaaa"],
            "A overrides shared kernel-commit",
        );
        assert_eq!(
            fb.kernel_commits,
            vec!["abcdef1", "fedcba2"],
            "B retains shared kernel-commit default",
        );
    }

    /// `--a-kernel-commit X --b-kernel-commit Y` slices on the
    /// `KernelCommit` dimension. Pins the slicing-dim derivation
    /// for the kernel-commit axis so a regression that dropped
    /// the dim from `derive_slicing_dims` lands here.
    #[test]
    fn build_compare_filters_disjoint_per_side_kernel_commit_slices() {
        let b = BuildCompareFilters {
            a_kernel_commit: vec!["abcdef1".to_string()],
            b_kernel_commit: vec!["fedcba2".to_string()],
            ..BuildCompareFilters::default()
        };
        let (fa, fb) = b.build();
        assert_eq!(fa.kernel_commits, vec!["abcdef1"]);
        assert_eq!(fb.kernel_commits, vec!["fedcba2"]);
        let slicing = ktstr::cli::derive_slicing_dims(&fa, &fb);
        assert_eq!(
            slicing,
            vec![ktstr::cli::Dimension::KernelCommit],
            "differing per-side kernel-commit must derive as a single \
             KernelCommit slicing dim",
        );
    }

    /// Shared `--kernel V` pins BOTH sides to the same vec.
    /// Sugar for `--a-kernel V --b-kernel V`.
    #[test]
    fn build_compare_filters_shared_kernel_pins_both_sides() {
        let b = BuildCompareFilters {
            shared_kernel: vec!["6.14".to_string()],
            ..BuildCompareFilters::default()
        };
        let (fa, fb) = b.build();
        assert_eq!(fa.kernels, vec!["6.14"]);
        assert_eq!(fb.kernels, vec!["6.14"]);
    }

    /// Per-side `--a-kernel` overrides shared `--kernel` for A
    /// only; B retains the shared value. "More-specific
    /// replaces" semantics.
    #[test]
    fn build_compare_filters_per_side_overrides_shared_for_that_side_only() {
        let b = BuildCompareFilters {
            shared_kernel: vec!["6.14".to_string(), "6.15".to_string()],
            a_kernel: vec!["6.13".to_string()],
            ..BuildCompareFilters::default()
        };
        let (fa, fb) = b.build();
        assert_eq!(fa.kernels, vec!["6.13"], "A overrides shared");
        assert_eq!(fb.kernels, vec!["6.14", "6.15"], "B retains shared default",);
    }

    /// Per-side overrides on the SAME dimension on BOTH sides
    /// produce the disjoint per-side filters the dispatch
    /// expects. This is the typical "slice on kernel" call shape:
    /// `--a-kernel A --b-kernel B`.
    #[test]
    fn build_compare_filters_disjoint_per_side_kernel_yields_two_filters() {
        let b = BuildCompareFilters {
            a_kernel: vec!["6.14".to_string()],
            b_kernel: vec!["6.15".to_string()],
            ..BuildCompareFilters::default()
        };
        let (fa, fb) = b.build();
        assert_eq!(fa.kernels, vec!["6.14"]);
        assert_eq!(fb.kernels, vec!["6.15"]);
    }

    /// Per-side `--a-scheduler` overrides shared `--scheduler` for
    /// A only. Sibling test for the scheduler dimension after the
    /// #13 conversion from `Option<String>` to repeatable
    /// `Vec<String>` — the override semantics now mirror every
    /// other Vec dim ("non-empty per-side replaces shared
    /// verbatim"), so this test pins the same shape every other
    /// override-test pins for kernel / commit / source / etc.
    #[test]
    fn build_compare_filters_per_side_scheduler_overrides_shared() {
        let b = BuildCompareFilters {
            shared_scheduler: vec!["scx_default".to_string()],
            a_scheduler: vec!["scx_alpha".to_string()],
            ..BuildCompareFilters::default()
        };
        let (fa, fb) = b.build();
        assert_eq!(
            fa.schedulers,
            vec!["scx_alpha".to_string()],
            "A overrides shared scheduler",
        );
        assert_eq!(
            fb.schedulers,
            vec!["scx_default".to_string()],
            "B retains shared scheduler when only --a-scheduler overrides",
        );
    }

    /// Multi-dim sugar: shared `--kernel` pins both sides AND
    /// per-side `--a-scheduler` / `--b-scheduler` slice on
    /// scheduler. The resulting filters share kernel but slice
    /// on scheduler — exactly what the
    /// "narrow scope, slice on one axis" workflow needs.
    #[test]
    fn build_compare_filters_shared_pin_plus_per_side_slice() {
        let b = BuildCompareFilters {
            shared_kernel: vec!["6.14".to_string()],
            a_scheduler: vec!["scx_alpha".to_string()],
            b_scheduler: vec!["scx_beta".to_string()],
            ..BuildCompareFilters::default()
        };
        let (fa, fb) = b.build();
        assert_eq!(fa.kernels, vec!["6.14"]);
        assert_eq!(fb.kernels, vec!["6.14"]);
        assert_eq!(fa.schedulers, vec!["scx_alpha".to_string()]);
        assert_eq!(fb.schedulers, vec!["scx_beta".to_string()]);
        // The slicing-dim derivation for these two filters
        // returns just [Scheduler] — kernel pins both sides
        // so the comparison joins on kernel and contrasts on
        // scheduler.
        let slicing = ktstr::cli::derive_slicing_dims(&fa, &fb);
        assert_eq!(slicing, vec![ktstr::cli::Dimension::Scheduler]);
    }

    /// `--a-flag` / `--b-flag` (AND-combined Vec) compose the
    /// same way as `--a-kernel` / `--b-kernel` (OR-combined
    /// Vec) — per-side empty defers to shared, per-side non-
    /// empty replaces. Pin the shape for the AND-combined dim
    /// to ensure no accidental special-case for OR-vs-AND.
    #[test]
    fn build_compare_filters_per_side_flag_overrides_shared() {
        let b = BuildCompareFilters {
            shared_flags: vec!["llc".to_string()],
            a_flags: vec!["steal".to_string(), "borrow".to_string()],
            ..BuildCompareFilters::default()
        };
        let (fa, fb) = b.build();
        assert_eq!(fa.flags, vec!["steal", "borrow"]);
        assert_eq!(fb.flags, vec!["llc"]);
    }

    /// Sibling of `build_compare_filters_empty_yields_default_default`
    /// for the `run_sources` field. The existing empty-default test
    /// asserts on `run_sources` already (see line ~3499) — this
    /// companion adds the cross-side equality check that ensures
    /// `fa.run_sources == fb.run_sources` under the empty default,
    /// matching the same pattern other dimensions have. A regression
    /// that diverged the per-side `run_sources` defaults (e.g. by
    /// forgetting to thread `shared_run_source` into BOTH
    /// constructors in `BuildCompareFilters::build`) would surface
    /// here.
    #[test]
    fn build_compare_filters_empty_run_sources_field_equal_on_both_sides() {
        let b = BuildCompareFilters::default();
        let (fa, fb) = b.build();
        assert!(
            fa.run_sources.is_empty(),
            "empty BuildCompareFilters must produce A-side filter with empty run_sources",
        );
        assert!(
            fb.run_sources.is_empty(),
            "empty BuildCompareFilters must produce B-side filter with empty run_sources",
        );
        assert_eq!(
            fa.run_sources, fb.run_sources,
            "both sides must agree on empty run_sources",
        );
    }

    /// Per-side `--a-run-source` / `--b-run-source` produce
    /// disjoint per-side filters with the shared `run_sources`
    /// left empty. Mirrors
    /// `build_compare_filters_disjoint_per_side_kernel_yields_two_filters`
    /// for the run-source dimension. Pins the wiring of the
    /// `run_sources` field through `build()` so a regression that
    /// dropped it from the per-side branch — silently leaving
    /// `fa.run_sources` / `fb.run_sources` empty under per-side
    /// input — surfaces here.
    #[test]
    fn build_compare_filters_disjoint_per_side_source_yields_two_filters() {
        let b = BuildCompareFilters {
            a_run_source: vec!["ci".to_string()],
            b_run_source: vec!["local".to_string()],
            ..BuildCompareFilters::default()
        };
        let (fa, fb) = b.build();
        assert_eq!(fa.run_sources, vec!["ci".to_string()]);
        assert_eq!(fb.run_sources, vec!["local".to_string()]);
    }

    /// Shared `--run-source` pins BOTH sides to the same vec.
    /// Sugar for `--a-run-source V --b-run-source V`. Mirrors
    /// `build_compare_filters_shared_kernel_pins_both_sides` for
    /// the run-source dimension.
    #[test]
    fn build_compare_filters_shared_source_pins_both_sides() {
        let b = BuildCompareFilters {
            shared_run_source: vec!["ci".to_string()],
            ..BuildCompareFilters::default()
        };
        let (fa, fb) = b.build();
        assert_eq!(fa.run_sources, vec!["ci".to_string()]);
        assert_eq!(fb.run_sources, vec!["ci".to_string()]);
    }

    /// Per-side `--a-run-source` overrides shared `--run-source`
    /// for A only; B retains the shared value. "More-specific
    /// replaces" semantics — same shape as the existing
    /// `per_side_overrides_shared_for_that_side_only` for kernels.
    /// Pins the override resolution path for the run-source
    /// dimension.
    #[test]
    fn build_compare_filters_per_side_source_overrides_shared_for_that_side_only() {
        let b = BuildCompareFilters {
            shared_run_source: vec!["local".to_string(), "archive".to_string()],
            a_run_source: vec!["ci".to_string()],
            ..BuildCompareFilters::default()
        };
        let (fa, fb) = b.build();
        assert_eq!(fa.run_sources, vec!["ci".to_string()], "A overrides shared");
        assert_eq!(
            fb.run_sources,
            vec!["local".to_string(), "archive".to_string()],
            "B retains shared default",
        );
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::ShowHost { run, dir }),
                ..
            } => {
                assert_eq!(run, "my-run-id");
                assert!(dir.is_none(), "bare --run must not populate --dir");
            }
            _ => panic!("expected Stats ShowHost"),
        }
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::ShowHost { run, dir }),
                ..
            } => {
                assert_eq!(run, "archive-2024-01-15");
                assert_eq!(
                    dir.as_deref(),
                    Some(std::path::Path::new("/tmp/archived-runs")),
                );
            }
            _ => panic!("expected Stats ShowHost"),
        }
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::ExplainSidecar { run, dir, json }),
                ..
            } => {
                assert_eq!(run, "my-run-id");
                assert!(dir.is_none(), "bare --run must not populate --dir");
                assert!(!json, "default output is text, not json");
            }
            _ => panic!("expected Stats ExplainSidecar"),
        }
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Stats {
                command: Some(StatsCommand::ExplainSidecar { run, dir, json }),
                ..
            } => {
                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");
            }
            _ => panic!("expected Stats ExplainSidecar"),
        }
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Kernel { command } => match command {
                KernelCommand::List { json, range } => {
                    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`",
                    );
                }
                other => panic!("expected KernelCommand::List, got {other:?}"),
            },
            _ => panic!("expected Kernel"),
        }
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Kernel { command } => match command {
                KernelCommand::List { json, range } => {
                    assert!(json, "--json must round-trip alongside --range");
                    assert_eq!(range.as_deref(), Some("6.12..6.14"));
                }
                other => panic!("expected KernelCommand::List, got {other:?}"),
            },
            _ => panic!("expected Kernel"),
        }
    }

    /// `--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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--a-kernel",
            "6.14",
            "--b-kernel",
            "6.15",
            "--run-source",
            "ci",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command:
                    Some(StatsCommand::Compare {
                        run_source,
                        a_run_source,
                        b_run_source,
                        ..
                    }),
                ..
            } => {
                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",
                );
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    /// `--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 Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "stats",
            "compare",
            "--a-run-source",
            "ci",
            "--b-run-source",
            "local",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Stats {
                command:
                    Some(StatsCommand::Compare {
                        run_source,
                        a_run_source,
                        b_run_source,
                        ..
                    }),
                ..
            } => {
                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()]);
            }
            _ => panic!("expected Stats Compare"),
        }
    }

    // -- 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());
    }

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

    #[test]
    fn parse_kernel_build_git_requires_ref() {
        let m = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "kernel",
            "build",
            "--git",
            "https://example.com/linux.git",
        ]);
        assert!(m.is_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());
    }

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

    // -- 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}"));
        match k.command {
            KtstrCommand::Kernel {
                command: KernelCommand::Clean { keep, .. },
            } => {
                assert_eq!(keep, Some(3));
            }
            _ => panic!("expected Kernel Clean"),
        }
    }

    // -- try_get_matches_from: verifier --

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

    #[test]
    fn parse_verifier_with_scheduler_bin() {
        let m = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "verifier",
            "--scheduler-bin",
            "/tmp/sched",
        ]);
        assert!(m.is_ok(), "{}", m.err().unwrap());
    }

    #[test]
    fn parse_verifier_scheduler_conflicts_with_scheduler_bin() {
        let m = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "verifier",
            "--scheduler",
            "scx_rustland",
            "--scheduler-bin",
            "/tmp/sched",
        ]);
        assert!(m.is_err());
    }

    #[test]
    fn parse_verifier_all_profiles() {
        let m = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "verifier",
            "--scheduler",
            "scx_rustland",
            "--all-profiles",
        ]);
        assert!(m.is_ok(), "{}", m.err().unwrap());
    }

    #[test]
    fn parse_verifier_profiles_filter() {
        let Cargo {
            command: CargoSub::Ktstr(k),
        } = Cargo::try_parse_from([
            "cargo",
            "ktstr",
            "verifier",
            "--scheduler",
            "scx_rustland",
            "--profiles",
            "default,llc,llc+steal",
        ])
        .unwrap_or_else(|e| panic!("{e}"));
        match k.command {
            KtstrCommand::Verifier { profiles, .. } => {
                assert_eq!(profiles, vec!["default", "llc", "llc+steal"]);
            }
            _ => panic!("expected Verifier"),
        }
    }

    // -- 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());
    }

    // -- topology parsing --

    #[test]
    fn topology_valid() {
        let parts: Vec<&str> = "1,2,4,1".split(',').collect();
        assert_eq!(parts.len(), 4);
        assert!(parts[0].parse::<u32>().is_ok());
        assert!(parts[1].parse::<u32>().is_ok());
        assert!(parts[2].parse::<u32>().is_ok());
        assert!(parts[3].parse::<u32>().is_ok());
    }

    #[test]
    fn topology_invalid_one_component() {
        let parts: Vec<&str> = "abc".split(',').collect();
        assert_ne!(parts.len(), 4);
    }

    #[test]
    fn topology_invalid_non_numeric() {
        let parts: Vec<&str> = "a,b,c,d".split(',').collect();
        assert_eq!(parts.len(), 4);
        assert!(parts[0].parse::<u32>().is_err());
    }

    #[test]
    fn topology_invalid_three_components() {
        let parts: Vec<&str> = "1,2,1".split(',').collect();
        assert_ne!(parts.len(), 4);
    }

    #[test]
    fn topology_invalid_zero_component() {
        // run_shell rejects zero values.
        let parts: Vec<&str> = "0,1,1,1".split(',').collect();
        assert_eq!(parts.len(), 4);
        let val: u32 = parts[0].parse().unwrap();
        assert_eq!(val, 0);
    }

    // -- 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"
        );
    }

    // -- dispatch wiring: sub_argv constants --

    /// Byte-exact pin on the three `*_SUB_ARGV` constants that drive
    /// `run_test`, `run_coverage`, and `run_llvm_cov` into
    /// `run_cargo_sub`. A regression that re-ordered the Coverage
    /// tokens (e.g. swapped `["llvm-cov","nextest"]` → `["nextest",
    /// "llvm-cov"]`) would exec `cargo nextest llvm-cov` which is
    /// not a valid cargo subcommand, silently failing coverage
    /// runs. A regression that added a second token to
    /// `LLVM_COV_SUB_ARGV` (e.g. `["llvm-cov","test"]`) would
    /// prepend an implicit subcommand and override the user's
    /// trailing args. Both are caught here.
    #[test]
    fn cargo_sub_argv_constants_are_pinned() {
        assert_eq!(TEST_SUB_ARGV, &["nextest", "run"]);
        assert_eq!(COVERAGE_SUB_ARGV, &["llvm-cov", "nextest"]);
        assert_eq!(LLVM_COV_SUB_ARGV, &["llvm-cov"]);
    }

    // -- profraw_inject_for --
    //
    // The injection must fire for `test` (so an instrumented test
    // binary cannot drop `default.profraw` in cwd), and must NOT
    // fire for `coverage` (cargo-llvm-cov manages
    // `LLVM_PROFILE_FILE` itself) or `llvm-cov` (raw passthrough,
    // user-controlled). An operator-supplied `LLVM_PROFILE_FILE`
    // must always win.

    /// `test` path with no operator override: returns a workspace-
    /// relative pattern ending in the `default-%p-%m.profraw`
    /// expansion tokens.
    #[test]
    fn profraw_inject_for_test_path_returns_pattern() {
        let pat = profraw_inject_for(TEST_SUB_ARGV, None)
            .expect("test path without LLVM_PROFILE_FILE must inject");
        assert!(
            pat.ends_with("default-%p-%m.profraw"),
            "injected pattern must end with default-%%p-%%m.profraw, got {}",
            pat.display(),
        );
        assert_ne!(
            pat.as_os_str(),
            "default-%p-%m.profraw",
            "pattern must be absolute (carry a target dir prefix), \
             not bare so the LLVM runtime never falls back to cwd",
        );
    }

    /// `coverage` path: cargo-llvm-cov manages the env itself.
    #[test]
    fn profraw_inject_for_coverage_path_skips() {
        assert!(
            profraw_inject_for(COVERAGE_SUB_ARGV, None).is_none(),
            "coverage path must not inject — cargo-llvm-cov owns LLVM_PROFILE_FILE",
        );
    }

    /// `llvm-cov` raw passthrough: user-controlled by contract.
    #[test]
    fn profraw_inject_for_llvm_cov_path_skips() {
        assert!(
            profraw_inject_for(LLVM_COV_SUB_ARGV, None).is_none(),
            "llvm-cov passthrough path must not inject — user owns env decisions",
        );
    }

    /// Operator already exported `LLVM_PROFILE_FILE` — explicit
    /// override stays authoritative even on the `test` path.
    #[test]
    fn profraw_inject_for_respects_operator_override() {
        let existing = std::ffi::OsString::from("/tmp/operator-pinned-%p.profraw");
        assert!(
            profraw_inject_for(TEST_SUB_ARGV, Some(existing)).is_none(),
            "an operator-set LLVM_PROFILE_FILE must not be overridden",
        );
    }

    // -- generate_flag_profiles --

    #[test]
    fn generate_flag_profiles_empty() {
        let profiles = generate_flag_profiles(&[]);
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].0, "default");
        assert!(profiles[0].1.is_empty());
    }

    #[test]
    fn generate_flag_profiles_single_flag() {
        let flags = vec![ktstr::scenario::flags::FlagDeclJson {
            name: "llc".to_string(),
            args: vec!["--llc".to_string()],
            requires: vec![],
        }];
        let profiles = generate_flag_profiles(&flags);
        assert_eq!(profiles.len(), 2);
        assert_eq!(profiles[0].0, "default");
        assert_eq!(profiles[1].0, "llc");
    }

    #[test]
    fn generate_flag_profiles_requires_constraint() {
        let flags = vec![
            ktstr::scenario::flags::FlagDeclJson {
                name: "llc".to_string(),
                args: vec!["--llc".to_string()],
                requires: vec![],
            },
            ktstr::scenario::flags::FlagDeclJson {
                name: "steal".to_string(),
                args: vec!["--steal".to_string()],
                requires: vec!["llc".to_string()],
            },
        ];
        let profiles = generate_flag_profiles(&flags);
        // Valid: default, llc, llc+steal. Invalid: steal alone.
        let names: Vec<&str> = profiles.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(profiles.len(), 3);
        assert!(names.contains(&"default"));
        assert!(names.contains(&"llc"));
        assert!(names.contains(&"llc+steal"));
        assert!(!names.contains(&"steal"));
    }

    // -- profile_sched_args --

    #[test]
    fn profile_sched_args_collects_args() {
        let flags = vec![
            ktstr::scenario::flags::FlagDeclJson {
                name: "llc".to_string(),
                args: vec!["--llc".to_string()],
                requires: vec![],
            },
            ktstr::scenario::flags::FlagDeclJson {
                name: "steal".to_string(),
                args: vec!["--steal".to_string(), "--aggressive".to_string()],
                requires: vec![],
            },
        ];
        let active = vec!["llc".to_string(), "steal".to_string()];
        let args = profile_sched_args(&active, &flags).unwrap();
        assert_eq!(args, vec!["--llc", "--steal", "--aggressive"]);
    }

    #[test]
    fn profile_sched_args_empty() {
        let flags = vec![ktstr::scenario::flags::FlagDeclJson {
            name: "llc".to_string(),
            args: vec!["--llc".to_string()],
            requires: vec![],
        }];
        let active: Vec<String> = vec![];
        let args = profile_sched_args(&active, &flags).unwrap();
        assert!(args.is_empty());
    }

    #[test]
    fn profile_sched_args_unknown_flag_errors() {
        // Silently dropping unknown flag names would mask typos in
        // --profiles CLI lists and version-drift in cached nextest
        // args — the profile NAME would still say "foo+bar" while
        // the scheduler was invoked without the corresponding CLI
        // switches.
        let flags = vec![ktstr::scenario::flags::FlagDeclJson {
            name: "llc".to_string(),
            args: vec!["--llc".to_string()],
            requires: vec![],
        }];
        let active = vec!["llc".to_string(), "unknown_flag".to_string()];
        let err = profile_sched_args(&active, &flags).unwrap_err();
        assert!(
            err.contains("unknown_flag"),
            "error should cite flag: {err}"
        );
        assert!(err.contains("llc"), "error should list known flags: {err}");
    }

    // -- 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, &ktstr::cache::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.rs` tests (cases c1-c7). 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", &[]);
        assert!(row.contains("-"), "missing version should show dash");
    }

    // 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) --

    /// Sibling of `format_entry_row_stale_kconfig`: 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(),
            }
        );
    }

    /// Sibling of `format_entry_row_matching_kconfig`: 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
        );
    }

    /// Sibling of
    /// `format_entry_row_untracked_kconfig_tagged_distinctly_from_stale`:
    /// 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. A stray positional argument must be
    /// rejected (clap default) so a typo like
    /// `cargo ktstr show-host host_context` is caught at parse time.
    #[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));

        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}"));
        match k.command {
            KtstrCommand::ShowThresholds { test } => {
                assert_eq!(test, "my_test_fn");
            }
            _ => panic!("expected ShowThresholds"),
        }
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Shell {
                cpu_cap,
                no_perf_mode,
                ..
            } => {
                assert_eq!(cpu_cap, Some(4));
                assert!(no_perf_mode, "--no-perf-mode must be set");
            }
            _ => panic!("expected Shell"),
        }
    }

    /// `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}"));
        match k.command {
            KtstrCommand::Shell {
                cpu_cap,
                no_perf_mode,
                ..
            } => {
                assert_eq!(cpu_cap, None, "no --cpu-cap must produce None");
                assert!(no_perf_mode);
            }
            _ => panic!("expected Shell"),
        }
    }

    // ---------------------------------------------------------------
    // Kernel label encoding for the multi-kernel test-name suffix
    // ---------------------------------------------------------------

    #[test]
    fn cache_key_to_version_label_tarball() {
        assert_eq!(
            cache_key_to_version_label("6.14.2-tarball-x86_64-kcabc1234"),
            "6.14.2",
        );
    }

    #[test]
    fn cache_key_to_version_label_rc_tarball() {
        assert_eq!(
            cache_key_to_version_label("6.15-rc3-tarball-x86_64-kcabc"),
            "6.15-rc3",
        );
    }

    #[test]
    fn cache_key_to_version_label_git() {
        // Git keys carry the git ref as the prefix; the label
        // captures the ref, not the post-`-git-` short hash.
        assert_eq!(
            cache_key_to_version_label("for-next-git-deadbee-x86_64-kcabc"),
            "for-next",
        );
    }

    #[test]
    fn cache_key_to_version_label_local_emits_hash6_disambiguator() {
        // Local cache keys carry the source tree's git short_hash
        // as the discriminator after `local-`. The label preserves
        // the first 6 chars so two distinct local builds (different
        // source trees, different short_hashes) render with
        // distinct labels in `kernel list` / per-side filter
        // outputs. Truncating to 6 keeps the label compact while
        // still disambiguating against the typical 7-char git
        // short_hash space.
        assert_eq!(
            cache_key_to_version_label("local-deadbee-x86_64-kcabc"),
            "local_deadbe",
            "must emit `local_{{first 6 chars of discriminator}}` so \
             distinct local trees do not collide on label",
        );
    }

    #[test]
    fn cache_key_to_version_label_local_distinct_hashes_render_distinct_labels() {
        // Anti-collision pin: two local cache keys with different
        // discriminators must produce different labels. Bare
        // `"local"` for both would erase the distinction in the
        // operator UI.
        let a = cache_key_to_version_label("local-aaaaaa1-x86_64-kcabc");
        let b = cache_key_to_version_label("local-bbbbbb2-x86_64-kcabc");
        assert_ne!(
            a, b,
            "distinct local discriminators must render distinct labels"
        );
        assert_eq!(a, "local_aaaaaa");
        assert_eq!(b, "local_bbbbbb");
    }

    #[test]
    fn cache_key_to_version_label_local_unknown_renders_local_unknown() {
        // `local-unknown-...` is the literal `fetch::local_source`
        // emits when the source tree is not a git repo (no commit
        // hash to discriminate on). The label uses the full
        // `unknown` literal rather than truncating to `unknow`.
        assert_eq!(
            cache_key_to_version_label("local-unknown-x86_64-kcabc"),
            "local_unknown",
        );
    }

    #[test]
    fn cache_key_to_version_label_local_bare_yields_bare_local() {
        // Defensive: bare `local` (no trailing segments) yields
        // bare `"local"`. Not produced by `fetch::local_source`,
        // but the function must not panic on it.
        assert_eq!(cache_key_to_version_label("local"), "local");
    }

    #[test]
    fn cache_key_to_version_label_unknown_tag_falls_through() {
        // A future cache-key shape with an unrecognised source
        // tag must still produce a non-empty label rather than
        // panicking. Operator can read the raw key in the test
        // name and infer.
        assert_eq!(
            cache_key_to_version_label("6.14.2-novel-tag-kcabc"),
            "6.14.2-novel-tag-kcabc",
        );
    }

    #[test]
    fn git_kernel_label_github_https() {
        assert_eq!(
            git_kernel_label("https://github.com/tj/sched_ext", "for-next"),
            "git_tj_sched_ext_for-next",
        );
    }

    #[test]
    fn git_kernel_label_github_https_with_dot_git() {
        assert_eq!(
            git_kernel_label("https://github.com/tj/sched_ext.git", "for-next"),
            "git_tj_sched_ext_for-next",
        );
    }

    #[test]
    fn git_kernel_label_gitlab_with_ref_tag() {
        assert_eq!(
            git_kernel_label("https://gitlab.com/foo/bar.git", "v6.14"),
            "git_foo_bar_v6.14",
        );
    }

    #[test]
    fn git_kernel_label_local_mirror_two_segment_path() {
        // Two-segment path (`/srv/linux.git`) renders as
        // `git_{owner}_{repo}_{ref}` even when the "owner" is just
        // a parent directory — the helper does not heuristically
        // distinguish "meaningful" ownership from filesystem
        // hierarchy. Deterministic and unique-per-URL is good
        // enough; over-cleverness would risk silently colliding
        // labels across distinct mirrors.
        assert_eq!(
            git_kernel_label("file:///srv/linux.git", "v6.14"),
            "git_srv_linux_v6.14",
        );
    }

    #[test]
    fn git_kernel_label_truly_single_segment_path() {
        // True single-segment path (just one component after the
        // host strip) — e.g. a bare hostname-rooted URL like
        // `file://linux.git` (no `/` after the scheme). The
        // helper's host-strip splits on `://` and takes everything
        // after the first `/` post-scheme; with no `/` to split
        // on, the entire post-scheme string IS the path. After
        // `.git` strip we have one segment, owner pops empty, and
        // the helper falls back to `git_{repo}_{ref}` to avoid
        // emitting `git__{ref}`.
        assert_eq!(
            git_kernel_label("file://linux.git", "v6.14"),
            "git_linux_v6.14",
        );
    }

    #[test]
    fn git_kernel_label_ssh_style_url() {
        // `git+ssh://git@github.com/tj/sched_ext` — the helper's
        // scheme-strip splits on `://`, then the first `/` after
        // the host, yielding the same `tj/sched_ext` path
        // component as the https variant.
        assert_eq!(
            git_kernel_label("ssh://git@github.com/tj/sched_ext", "main"),
            "git_tj_sched_ext_main",
        );
    }

    #[test]
    fn path_kernel_label_includes_basename_and_hash() {
        // `path_kernel_label` builds `path_{basename}_{hash6}`.
        // We don't pin the exact hash (it's a CRC32 of the path)
        // but assert the shape: prefix + basename + 6 hex chars.
        let p = std::path::Path::new("/tmp/somewhere/linux");
        let label = path_kernel_label(p);
        assert!(
            label.starts_with("path_linux_"),
            "label must start with `path_<basename>_`, got: {label}"
        );
        let hash_part = label.strip_prefix("path_linux_").unwrap();
        assert_eq!(hash_part.len(), 6, "hash suffix must be 6 chars: {label}");
        assert!(
            hash_part.chars().all(|c| c.is_ascii_hexdigit()),
            "hash suffix must be hex: {label}"
        );
    }

    #[test]
    fn path_kernel_label_distinguishes_paths_sharing_basename() {
        // Two different parent directories with the same `linux`
        // basename must produce DIFFERENT labels (the hash
        // disambiguates them). Pins the "collision risk is only a
        // UI nuisance" claim in the doc.
        let a = std::path::Path::new("/srv/a/linux");
        let b = std::path::Path::new("/srv/b/linux");
        assert_ne!(
            path_kernel_label(a),
            path_kernel_label(b),
            "distinct path parents must produce distinct labels",
        );
    }

    /// `decorate_path_label_for_dirty` is the seam where a
    /// dirty-tree Path resolve attaches its `_dirty` suffix to
    /// the operator-readable kernel label. Clean trees pass
    /// through unchanged so the cache-stored vs in-tree label
    /// shapes remain stable for the same canonical path.
    #[test]
    fn decorate_path_label_for_dirty_clean_tree_passthrough() {
        let base = "path_linux_a3b1c2";
        assert_eq!(
            decorate_path_label_for_dirty(base, false),
            base,
            "clean trees must not append a `_dirty` suffix",
        );
    }

    /// Dirty trees must append `_dirty` so the test report shows
    /// a non-reproducible run as distinct from the same path's
    /// clean rebuild. The suffix is deliberately placed after
    /// the hash6 segment (rather than between basename and
    /// hash6) so the `path_{basename}_{hash6}` invariant
    /// `path_kernel_label` relies on still parses cleanly.
    #[test]
    fn decorate_path_label_for_dirty_dirty_tree_appends_suffix() {
        let base = "path_linux_a3b1c2";
        assert_eq!(
            decorate_path_label_for_dirty(base, true),
            "path_linux_a3b1c2_dirty",
            "dirty trees must append `_dirty` to the base label",
        );
    }

    /// The `_dirty` suffix survives `sanitize_kernel_label`
    /// transformation verbatim — `_` is alphanumeric-equivalent
    /// in the sanitizer's preservation table, so the nextest
    /// test-name suffix renders as `kernel_path_..._dirty`.
    /// Pins the producer↔consumer round-trip so a future
    /// sanitizer change that mangles `_` is caught here rather
    /// than only in operator-visible test reports.
    #[test]
    fn decorate_path_label_for_dirty_survives_sanitize() {
        let dirty_label = decorate_path_label_for_dirty("path_linux_a3b1c2", true);
        let sanitized = ktstr::test_support::sanitize_kernel_label(&dirty_label);
        assert_eq!(
            sanitized, "kernel_path_linux_a3b1c2_dirty",
            "`_dirty` must survive sanitize verbatim so the test report \
             distinguishes dirty runs from clean runs in the nextest suffix",
        );
    }

    /// Sanity pin on the clean-tree counterpart: the same base
    /// label without the dirty decoration sanitizes to a label
    /// that differs from the dirty form. The two test-report
    /// rows MUST be distinct identifiers downstream so the
    /// per-kernel column keys do not collide.
    #[test]
    fn decorate_path_label_for_dirty_clean_dirty_sanitize_to_distinct_ids() {
        let base = "path_linux_a3b1c2";
        let clean =
            ktstr::test_support::sanitize_kernel_label(&decorate_path_label_for_dirty(base, false));
        let dirty =
            ktstr::test_support::sanitize_kernel_label(&decorate_path_label_for_dirty(base, true));
        assert_ne!(
            clean, dirty,
            "clean ({clean:?}) and dirty ({dirty:?}) sanitized labels must \
             produce distinct nextest identifiers so test reports do not \
             collapse non-reproducible runs into the cache-stored row",
        );
    }

    // ---------------------------------------------------------------
    // format_built_age — cache-hit log line age suffix
    // ---------------------------------------------------------------
    //
    // The helper renders the persisted `built_at` ISO-8601 stamp as
    // `, built {age} ago`. It must produce the empty string on
    // unparseable inputs (so the cache-hit line still renders
    // gracefully without a malformed suffix), and must include a
    // leading comma+space prefix on the success path so the call
    // site can splice it directly into `(cache_key{age})`.

    #[test]
    fn format_built_age_unparseable_returns_empty_string() {
        // Malformed timestamp must not panic and must not yield a
        // half-formed suffix. The cache-hit log line stays valid
        // even when metadata is corrupt: `(cache_key)` with no
        // age portion.
        assert_eq!(format_built_age("not-a-timestamp"), "");
        assert_eq!(format_built_age(""), "");
        // Almost-valid RFC 3339 (missing trailing Z) must also
        // collapse to empty rather than returning a partial.
        assert_eq!(format_built_age("2026-01-02T03:04:05"), "");
    }

    #[test]
    fn format_built_age_future_timestamp_returns_empty_string() {
        // A timestamp far in the future fails
        // `duration_since` because the build moment hasn't
        // occurred yet relative to local clock — clock skew on a
        // shared cache between two hosts can produce this. The
        // helper collapses to empty rather than rendering
        // `built -2h ago` or panicking.
        assert_eq!(format_built_age("9999-12-31T23:59:59Z"), "");
    }

    #[test]
    fn format_built_age_past_timestamp_includes_leading_comma_and_seconds() {
        // A reachable past timestamp must produce the
        // `, built ... ago` shape. We don't pin the exact age
        // string (it depends on `SystemTime::now()` at test time),
        // but assert the structural invariants:
        //   * non-empty
        //   * starts with `, built ` (the leading comma+space lets
        //     the caller splice into `(cache_key{age})` without a
        //     conditional separator)
        //   * ends with ` ago` (the trailing keyword renders the
        //     duration as relative-past in human language)
        let one_hour_ago = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            .saturating_sub(3600);
        let timestamp = humantime::format_rfc3339(
            std::time::UNIX_EPOCH + std::time::Duration::from_secs(one_hour_ago),
        )
        .to_string();
        let age = format_built_age(&timestamp);
        assert!(
            age.starts_with(", built "),
            "age suffix must start with the splice prefix `, built `, got {age:?}",
        );
        assert!(
            age.ends_with(" ago"),
            "age suffix must end with the relative-past keyword ` ago`, got {age:?}",
        );
    }

    // ---------------------------------------------------------------
    // resolve_path_kernel — Path-spec error diagnostics
    // ---------------------------------------------------------------
    //
    // The diagnostic shape `--kernel {raw}: {inner}. {KTSTR_KERNEL_HINT}`
    // is what the user sees when `--kernel /path/...` fails. The
    // raw input must appear verbatim so a typo names the exact
    // string they passed; the inner error must come from the
    // shared resolution pipeline (currently
    // `cli::resolve_kernel_dir_to_entry`); the hint must guide
    // the user toward the supported `--kernel` shapes.

    /// Nonexistent path: the source-tree validation
    /// (`Makefile + Kconfig` exist) fails inside
    /// [`cli::resolve_kernel_dir_to_entry`] (via
    /// [`cli::resolve_kernel_dir_to_entry`] →
    /// `acquire_local_source_tree`), and `resolve_path_kernel`
    /// re-wraps the error with the user's raw input + the
    /// standard hint. Pins the `--kernel {raw}: ...` prefix and
    /// the trailing hint marker so a regression that dropped
    /// either surfaces here.
    #[test]
    fn resolve_path_kernel_nonexistent_returns_actionable_error() {
        let raw = "/this/path/should/not/exist/under/test";
        let result = resolve_path_kernel(std::path::Path::new(raw), raw);
        let err = result.expect_err("nonexistent path must surface as Err");
        assert!(
            err.contains(&format!("--kernel {raw}")),
            "error must lead with `--kernel {{raw_input}}:` so a typo \
             names the exact string the user passed. got: {err}",
        );
        // The hint string carries the documented `--kernel` value
        // shapes; pin its presence rather than its prose so a
        // future hint rewrite doesn't break this test.
        assert!(
            err.contains(ktstr::KTSTR_KERNEL_HINT),
            "error must end with KTSTR_KERNEL_HINT so the user sees \
             the supported `--kernel` shapes. got: {err}",
        );
    }

    /// Empty tempdir (real directory, no Makefile or Kconfig):
    /// `acquire_local_source_tree` rejects it as "not a kernel
    /// source tree" and `resolve_path_kernel` re-wraps with the
    /// user's raw input + hint. Distinct from
    /// `resolve_path_kernel_nonexistent_returns_actionable_error`
    /// because the inner error path differs (existence-check
    /// pass, content-shape fail) — both must surface the same
    /// outer wrapping.
    #[test]
    fn resolve_path_kernel_empty_tempdir_returns_not_a_source_tree_error() {
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let raw = tmp.path().display().to_string();
        let result = resolve_path_kernel(tmp.path(), &raw);
        let err = result.expect_err("empty tempdir must surface as Err");
        assert!(
            err.contains(&format!("--kernel {raw}")),
            "error must lead with `--kernel {{raw_input}}:`. got: {err}",
        );
        assert!(
            err.contains("not a kernel source tree"),
            "error must include the `not a kernel source tree` phrase \
             from `acquire_local_source_tree`'s diagnostic. got: {err}",
        );
        assert!(
            err.contains(ktstr::KTSTR_KERNEL_HINT),
            "error must end with KTSTR_KERNEL_HINT. got: {err}",
        );
    }

    // ---------------------------------------------------------------
    // encode_kernel_list — KTSTR_KERNEL_LIST wire-format encoding
    // ---------------------------------------------------------------
    //
    // The wire format is `label1=path1;label2=path2;...` per the
    // doc comment on `encode_kernel_list`. Empty input encodes to
    // an empty string (idempotent — env var consumers treat the
    // empty value as "no list, single-kernel mode"). Paths
    // containing `;` are rejected with an actionable error since
    // the separator collision would produce a malformed env var
    // the test-binary parser would split into garbage.

    #[test]
    fn encode_kernel_list_empty_input_returns_empty_string() {
        // Pin the idempotent empty case — `cargo ktstr` skips the
        // env-var export entirely on empty kernel sets, but the
        // encoder must not panic or produce garbage if it ever does
        // see an empty slice.
        let encoded = encode_kernel_list(&[]).expect("empty input must succeed");
        assert!(
            encoded.is_empty(),
            "empty resolved list must encode to empty string, got {encoded:?}",
        );
    }

    #[test]
    fn encode_kernel_list_single_entry_has_no_separator() {
        // Single-entry payload omits the `;` separator entirely:
        // the format is `label=path`, NOT `label=path;`.
        let resolved = vec![("6.14.2".to_string(), PathBuf::from("/cache/foo"))];
        let encoded = encode_kernel_list(&resolved).expect("single entry must succeed");
        assert_eq!(
            encoded, "6.14.2=/cache/foo",
            "single-entry encoding must be `label=path` with no trailing separator",
        );
    }

    #[test]
    fn encode_kernel_list_two_entries_uses_semicolon_separator() {
        // Two-entry payload uses `;` as the entry separator; `=`
        // separates the label from the path within each entry.
        let resolved = vec![
            ("6.14.2".to_string(), PathBuf::from("/cache/a")),
            ("6.15.0".to_string(), PathBuf::from("/cache/b")),
        ];
        let encoded = encode_kernel_list(&resolved).expect("two entries must succeed");
        assert_eq!(
            encoded, "6.14.2=/cache/a;6.15.0=/cache/b",
            "two-entry encoding must be `label=path;label=path`",
        );
    }

    #[test]
    fn encode_kernel_list_three_entries_preserves_order() {
        // The encoder iterates `resolved` in input order and writes
        // entries in that order. A regression that sorted entries
        // (e.g. by label alphabetically) would silently reorder the
        // multi-kernel test-name suffix dimension and break
        // operator-stable test naming.
        let resolved = vec![
            ("z-late".to_string(), PathBuf::from("/cache/z")),
            ("a-early".to_string(), PathBuf::from("/cache/a")),
            ("m-mid".to_string(), PathBuf::from("/cache/m")),
        ];
        let encoded = encode_kernel_list(&resolved).expect("three entries must succeed");
        assert_eq!(
            encoded, "z-late=/cache/z;a-early=/cache/a;m-mid=/cache/m",
            "encoder must preserve input order; sorting would change test-name suffix order",
        );
    }

    #[test]
    fn encode_kernel_list_rejects_semicolon_in_path() {
        // POSIX permits `;` in paths, but the wire format claims
        // `;` as the entry separator. The encoder must bail with an
        // actionable error rather than silently producing
        // `label=foo;bar` which the parser would split into a
        // malformed `(label, "foo")` + spurious `bar` segment.
        let resolved = vec![("6.14.2".to_string(), PathBuf::from("/cache/has;semicolon"))];
        let err = encode_kernel_list(&resolved)
            .expect_err("path containing `;` must be rejected by encoder");
        assert!(
            err.contains("`;`"),
            "error must reference the offending separator: {err}",
        );
        assert!(
            err.contains("6.14.2"),
            "error must name the offending label so the operator can locate the entry: {err}",
        );
        assert!(
            err.contains("/cache/has;semicolon"),
            "error must include the offending path: {err}",
        );
    }

    /// `;` in a label is a wire-format violation distinct from `;`
    /// in a path: the parser's outer `split(';')` upstream of
    /// `split_once('=')` would split a `;`-bearing label into two
    /// pseudo-entries. The encoder rejects with an actionable error
    /// before any output is built so the corrupted env never reaches
    /// the test-binary parser. Pins the label-side label-validation
    /// loop (sibling check to the path-side `;` rejection above).
    #[test]
    fn encode_kernel_list_rejects_semicolon_in_label() {
        let resolved = vec![("evil;label".to_string(), PathBuf::from("/cache/clean"))];
        let err = encode_kernel_list(&resolved)
            .expect_err("label containing `;` must be rejected by encoder");
        assert!(
            err.contains("`;`"),
            "error must reference the offending separator: {err}",
        );
        assert!(
            err.contains("evil;label"),
            "error must name the offending label so the operator \
             can locate the producer that emitted it: {err}",
        );
        // The error explicitly identifies it as a LABEL error, not
        // a path error — distinguishes from the path-side check
        // whose message starts with `kernel directory path`.
        assert!(
            err.contains("kernel label"),
            "error must classify the violation as a label problem (not \
             a path problem) so an operator reading the diagnostic \
             knows which side of the wire format is at fault: {err}",
        );
    }

    /// `=` in a label is a wire-format violation: the parser's
    /// inner `split_once('=')` consumes the FIRST `=` to separate
    /// label from path, so a label `a=b` paired with path `/x` would
    /// emit `a=b=/x`, and the parser would treat `a` as the label
    /// and `b=/x` as the path — silently misrouting the kernel
    /// directory. Pins the second label-validation check in
    /// `encode_kernel_list`. (Note: `=` in PATHS is fine — the
    /// parser only consumes the first `=` and subsequent ones land
    /// inside the path payload — so there is no symmetric path-side
    /// `=` rejection.)
    #[test]
    fn encode_kernel_list_rejects_equals_in_label() {
        let resolved = vec![("evil=label".to_string(), PathBuf::from("/cache/clean"))];
        let err = encode_kernel_list(&resolved)
            .expect_err("label containing `=` must be rejected by encoder");
        assert!(
            err.contains("`=`"),
            "error must reference the offending separator: {err}",
        );
        assert!(
            err.contains("evil=label"),
            "error must name the offending label so the operator \
             can locate the producer that emitted it: {err}",
        );
        assert!(
            err.contains("kernel label"),
            "error must classify the violation as a label problem: {err}",
        );
    }

    #[test]
    fn encode_kernel_list_first_entry_with_semicolon_rejected_before_emit() {
        // Even on a multi-entry payload where ONLY the first entry's
        // path has a `;`, the encoder must bail without emitting
        // anything — partial encoding would mean the caller exec's
        // a child with a corrupted env value where the early entries
        // succeeded.
        let resolved = vec![
            ("first".to_string(), PathBuf::from("/cache/has;semicolon")),
            ("second".to_string(), PathBuf::from("/cache/clean")),
        ];
        let err = encode_kernel_list(&resolved)
            .expect_err("path containing `;` must be rejected even when other entries are clean");
        assert!(err.contains("first"));
    }

    #[test]
    fn encode_kernel_list_later_entry_with_semicolon_still_rejected() {
        // The validation loop scans every entry before emit, so a
        // `;` in the second/later entry's path also bails.
        let resolved = vec![
            ("first".to_string(), PathBuf::from("/cache/clean")),
            ("second".to_string(), PathBuf::from("/cache/has;semicolon")),
        ];
        let err = encode_kernel_list(&resolved)
            .expect_err("`;` anywhere in any path must abort the encode");
        assert!(err.contains("second"));
    }

    // ---------------------------------------------------------------
    // detect_label_collisions — sanitization-collision guard
    // ---------------------------------------------------------------
    //
    // Two distinct producer-side labels that normalize to the same
    // nextest identifier via `sanitize_kernel_label` would shatter
    // their cache directories under one test-name suffix. The
    // helper bails before the encoded `KTSTR_KERNEL_LIST` reaches
    // the test binary so the operator gets an actionable
    // "spell each --kernel value distinctly" diagnostic rather
    // than silent misroute to the wrong kernel.

    #[test]
    fn detect_label_collisions_empty_input_succeeds() {
        // Trivial: an empty resolved set has no pairs to compare;
        // the helper must return Ok without error.
        let resolved: Vec<(String, PathBuf)> = Vec::new();
        detect_label_collisions(&resolved).expect("empty input must succeed");
    }

    #[test]
    fn detect_label_collisions_unique_labels_succeed() {
        // Two distinct labels that sanitize to distinct nextest
        // identifiers — no collision, no error.
        let resolved = vec![
            ("6.14.2".to_string(), PathBuf::from("/cache/a")),
            ("6.15.0".to_string(), PathBuf::from("/cache/b")),
        ];
        detect_label_collisions(&resolved).expect("distinct sanitized identifiers must succeed");
    }

    #[test]
    fn detect_label_collisions_period_vs_dash_collides() {
        // `sanitize_kernel_label` replaces both `.` and `-` with
        // `_` — so `6.14.2` and `6-14-2` both sanitize to
        // `kernel_6_14_2`. This is the canonical collision shape
        // referenced in the doc comment ("e.g. spell `6.14.2` and
        // `git+...#6.14.2` distinctly").
        let resolved = vec![
            ("6.14.2".to_string(), PathBuf::from("/cache/a")),
            ("6-14-2".to_string(), PathBuf::from("/cache/b")),
        ];
        let err = detect_label_collisions(&resolved)
            .expect_err("colliding sanitized identifiers must surface an error");
        // Both labels named in the diagnostic so the operator can
        // disambiguate without grepping the resolver source.
        assert!(
            err.contains("6.14.2"),
            "error must name first colliding label: {err}",
        );
        assert!(
            err.contains("6-14-2"),
            "error must name second colliding label: {err}",
        );
        // Sanitized form named so the operator sees the shared
        // identifier the dispatch side would have used.
        assert!(
            err.contains("kernel_6_14_2"),
            "error must include the shared sanitized identifier: {err}",
        );
        // Diagnostic carries the actionable hint.
        assert!(
            err.contains("Spell each --kernel value distinctly"),
            "error must include the actionable remediation hint: {err}",
        );
    }

    #[test]
    fn detect_label_collisions_uppercase_vs_lowercase_collides() {
        // `sanitize_kernel_label` lowercases its input, so `ABC`
        // and `abc` both sanitize to `kernel_abc`. Distinct
        // collision shape from the period-vs-dash case — pins the
        // case-folding contract.
        let resolved = vec![
            ("ABC".to_string(), PathBuf::from("/cache/a")),
            ("abc".to_string(), PathBuf::from("/cache/b")),
        ];
        let err = detect_label_collisions(&resolved)
            .expect_err("uppercase vs lowercase labels must collide post-sanitize");
        assert!(err.contains("kernel_abc"));
    }

    #[test]
    fn detect_label_collisions_identical_labels_collide() {
        // De-duplication of identical `--kernel` specs is the
        // operator's responsibility (or future task #21); this
        // helper is the LAST line of defense and must surface the
        // duplicate as a collision rather than silently letting
        // both entries through.
        let resolved = vec![
            ("6.14.2".to_string(), PathBuf::from("/cache/a")),
            ("6.14.2".to_string(), PathBuf::from("/cache/b")),
        ];
        let err = detect_label_collisions(&resolved)
            .expect_err("two identical labels must surface as a collision");
        assert!(err.contains("6.14.2"));
        assert!(err.contains("kernel_6_14_2"));
    }

    #[test]
    fn detect_label_collisions_three_entries_two_collide_one_unique() {
        // First two collide after sanitization; third is distinct.
        // The helper must bail on the first detected collision —
        // the unique third entry never reaches the diagnostic but
        // its absence from the error message is intentional (the
        // operator only needs to know which two labels conflict).
        let resolved = vec![
            ("6.14.2".to_string(), PathBuf::from("/cache/a")),
            ("6-14-2".to_string(), PathBuf::from("/cache/b")),
            ("7.0.0".to_string(), PathBuf::from("/cache/c")),
        ];
        let err = detect_label_collisions(&resolved)
            .expect_err("collision in the first two entries must surface");
        assert!(err.contains("6.14.2"));
        assert!(err.contains("6-14-2"));
        // Third entry's label not mentioned — only the conflicting
        // pair is named (the API contract is "name the first
        // colliding pair", not "enumerate every collision").
        assert!(
            !err.contains("7.0.0"),
            "non-conflicting label should not appear in the collision diagnostic: {err}",
        );
    }

    #[test]
    fn detect_label_collisions_first_two_unique_third_collides_with_first() {
        // First and third collide; second is unique. Ensures the
        // detection scans past the unique second entry rather than
        // bailing as soon as a non-collision is seen.
        let resolved = vec![
            ("6.14.2".to_string(), PathBuf::from("/cache/a")),
            ("7.0.0".to_string(), PathBuf::from("/cache/b")),
            ("6-14-2".to_string(), PathBuf::from("/cache/c")),
        ];
        let err = detect_label_collisions(&resolved)
            .expect_err("late-arriving collision against an earlier entry must surface");
        // The diagnostic names the EARLIER entry (the one already
        // in `seen`) as the `prior` label and the LATER entry as
        // the `label`. The shared sanitized form is also named.
        assert!(err.contains("6.14.2"), "earlier (prior) label must appear");
        assert!(err.contains("6-14-2"), "later label must appear");
        assert!(err.contains("kernel_6_14_2"));
    }

    // ---------------------------------------------------------------
    // 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.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 exact substring. Range-mode emits
    /// `{ range, start, end, versions }` per the schema block at
    /// `cli.rs:337-346`. Bare-word substring match is sufficient
    /// because the help copy embeds the field names in column-
    /// aligned table form (e.g. `  range     literal range string`)
    /// — distinct from the cache-walk schema's nullable-marker
    /// pattern which uses `{field} (nullable)` substrings.
    #[test]
    fn kernel_list_long_about_exposes_range_mode_json_keys() {
        let about = ktstr::cli::KERNEL_LIST_LONG_ABOUT;
        for range_field in ["range", "start", "end", "versions"] {
            assert!(
                about.contains(range_field),
                "KERNEL_LIST_LONG_ABOUT must mention range-mode JSON \
                 field `{range_field}` so scripted consumers discover \
                 the schema without `cargo doc`; got: {about:?}",
            );
        }
        // Stronger pin: 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). A regression that dropped the
        // range-mode block entirely while keeping the cache-walk
        // block (or vice versa) would pass the bare-word checks
        // above (`start` / `end` could match unrelated copy) but
        // fail this one.
        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:?}",
        );
        assert!(
            about.contains("range-preview") || about.contains("range mode"),
            "KERNEL_LIST_LONG_ABOUT must explain that --range switches \
             to a structurally-different output shape so scripted \
             consumers know to dispatch on the presence of the \
             `range` key: got: {about:?}",
        );
    }

    // ---------------------------------------------------------------
    // preflight_collision_check — pre-resolve fast-fail
    // ---------------------------------------------------------------
    //
    // Pre-flight runs BEFORE the rayon resolve pipeline so a
    // colliding pair of cheap-to-label specs (Version / CacheKey /
    // Git) bails sub-millisecond rather than after a multi-minute
    // download + build cycle. Path and Range specs are intentionally
    // deferred to the post-resolve `detect_label_collisions` because
    // their labels require I/O (canonicalization for Path, a
    // releases.json fetch for Range).

    #[test]
    fn preflight_collision_check_empty_input_succeeds() {
        // Empty spec set has no pairs to compare; the helper must
        // return Ok without iterating anything.
        preflight_collision_check(&[]).expect("empty input must succeed");
    }

    #[test]
    fn preflight_collision_check_unique_versions_succeed() {
        // Two distinct Version specs that sanitize to distinct
        // identifiers — no collision, no error.
        let specs = vec!["6.14.2".to_string(), "6.15.0".to_string()];
        preflight_collision_check(&specs)
            .expect("distinct sanitized identifiers must succeed at pre-flight");
    }

    #[test]
    fn preflight_collision_check_period_vs_dash_collides() {
        // The canonical collision shape: `6.14.2` parses as
        // KernelId::Version (label = "6.14.2"); `6-14-2` parses as
        // KernelId::CacheKey (no `.` → fails version-string check)
        // and its `cache_key_to_version_label` falls through to the
        // raw key "6-14-2" because no `-tarball-` / `-git-` /
        // `local-` tag matches. Both labels sanitize to
        // `kernel_6_14_2`. Pre-flight must bail with both labels and
        // the shared sanitized form named.
        let specs = vec!["6.14.2".to_string(), "6-14-2".to_string()];
        let err = preflight_collision_check(&specs)
            .expect_err("colliding labels must surface a pre-flight error");
        assert!(err.contains("6.14.2"), "error must name first label: {err}");
        assert!(
            err.contains("6-14-2"),
            "error must name second label: {err}"
        );
        assert!(
            err.contains("kernel_6_14_2"),
            "error must include the shared sanitized identifier: {err}",
        );
        // Pre-flight diagnostic distinguishes itself from the
        // post-resolve `detect_label_collisions` error by prefixing
        // with "pre-flight check found collision before any
        // download or build started" — the two diagnostics are
        // distinct so an operator can tell which gate fired.
        assert!(
            err.contains("pre-flight check found collision"),
            "error must be the pre-flight diagnostic, not the post-resolve one: {err}",
        );
    }

    #[test]
    fn preflight_collision_check_identical_versions_succeed() {
        // Two identical `--kernel 6.14.2` specs sanitize to the same
        // identifier but the `prior != label` guard inside
        // `preflight_collision_check` skips the bail on identical
        // labels — those folder into a single entry by
        // `dedupe_resolved` post-resolve. Pins that the helper does
        // NOT confuse "operator passed the same spec twice" with
        // "two distinct specs that collide".
        let specs = vec!["6.14.2".to_string(), "6.14.2".to_string()];
        preflight_collision_check(&specs)
            .expect("identical specs must NOT bail at pre-flight (handled by dedupe post-resolve)");
    }

    #[test]
    fn preflight_collision_check_skips_path_and_range_specs() {
        // Path specs (recognized by `/` prefix per
        // `KernelId::parse`) and Range specs (`A..B` shape) are
        // EXCLUDED from pre-flight because their labels require
        // I/O. Two paths that would collide on their `path_basename
        // _hash6` labels must NOT bail at pre-flight — they reach
        // post-resolve `detect_label_collisions` after
        // canonicalization. Pin the deferred branch by passing two
        // Path specs that, sans I/O, cannot have their labels
        // computed at pre-flight time.
        let specs = vec![
            "/tmp/kernel-a".to_string(),
            "/tmp/kernel-b".to_string(),
            "6.14.2..6.14.4".to_string(),
        ];
        preflight_collision_check(&specs).expect(
            "Path and Range specs must skip pre-flight — their labels are deferred to post-resolve",
        );
    }

    #[test]
    fn preflight_collision_check_skips_empty_and_whitespace_specs() {
        // `resolve_kernel_set` skips trim()-empty specs at the
        // parallel iterator (filter_map). The pre-flight loop
        // applies the same trim+empty skip so a spurious blank
        // `--kernel ""` doesn't reach `KernelId::parse` (which
        // would parse `""` as KernelId::CacheKey("") and produce
        // `sanitize_kernel_label("") == "kernel_"` — a real but
        // useless collision risk). Pin the upstream filter so a
        // regression that dropped the empty-skip guard surfaces
        // as a behavior change.
        let specs = vec!["".to_string(), "   ".to_string(), "6.14.2".to_string()];
        preflight_collision_check(&specs)
            .expect("blank / whitespace-only specs must be silently skipped");
    }

    #[test]
    fn preflight_collision_check_inverted_range_fails_validation() {
        // An inverted Range (`6.15..6.14`) fails `KernelId::validate`
        // pre-resolve. Pre-flight surfaces the inversion diagnostic
        // BEFORE the rayon resolve fires — matches the timing the
        // parallel pipeline preserved on its own pre-extraction.
        let specs = vec!["6.15..6.14".to_string()];
        let err = preflight_collision_check(&specs)
            .expect_err("inverted range must fail pre-flight validation");
        assert!(
            err.contains("inverted kernel range") || err.contains("--kernel"),
            "error must surface the inversion diagnostic with --kernel framing: {err}",
        );
    }

    #[test]
    fn preflight_collision_check_git_url_collision() {
        // Two distinct `git+URL#REF` specs that produce
        // `git_owner_repo_ref`-shape labels can collide if they
        // share owner/repo/ref segments. Construct two URLs whose
        // git_kernel_label outputs differ only in `.` vs `-`
        // characters that sanitize to `_`.
        // - `git+ssh://h/foo/bar#v6.14` → `git_foo_bar_v6.14`
        //   sanitizes to `kernel_git_foo_bar_v6_14`.
        // - `git+ssh://h/foo/bar#v6-14` → `git_foo_bar_v6-14`
        //   sanitizes to the same `kernel_git_foo_bar_v6_14`.
        let specs = vec![
            "git+ssh://host/foo/bar#v6.14".to_string(),
            "git+ssh://host/foo/bar#v6-14".to_string(),
        ];
        let err = preflight_collision_check(&specs)
            .expect_err("colliding git refs must surface a pre-flight error");
        assert!(err.contains("git_foo_bar_v6.14") || err.contains("git_foo_bar_v6-14"));
        assert!(err.contains("kernel_git_foo_bar_v6_14"));
    }

    // ---------------------------------------------------------------
    // dedupe_resolved — order-preserving tuple-level dedup
    // ---------------------------------------------------------------
    //
    // Identical `(label, path)` tuples are folded into one row so
    // `detect_label_collisions` does NOT trip on a benign duplicate
    // input. Tuples that share a label but DIFFER on the path are a
    // real cache-key collision and survive dedup intact.

    #[test]
    fn dedupe_resolved_empty_input_returns_empty() {
        let resolved: Vec<(String, PathBuf)> = Vec::new();
        let deduped = dedupe_resolved(resolved);
        assert!(deduped.is_empty());
    }

    #[test]
    fn dedupe_resolved_unique_inputs_pass_through() {
        // No duplicates → output identical to input, in order.
        let resolved = vec![
            ("a".to_string(), PathBuf::from("/cache/a")),
            ("b".to_string(), PathBuf::from("/cache/b")),
            ("c".to_string(), PathBuf::from("/cache/c")),
        ];
        let deduped = dedupe_resolved(resolved.clone());
        assert_eq!(deduped, resolved);
    }

    #[test]
    fn dedupe_resolved_two_identical_tuples_collapse_to_one() {
        // The canonical dedupe case: two `--kernel 6.14.2` specs
        // resolve to the same `(label, path)` tuple. Output must be
        // a single entry.
        let resolved = vec![
            ("6.14.2".to_string(), PathBuf::from("/cache/v")),
            ("6.14.2".to_string(), PathBuf::from("/cache/v")),
        ];
        let deduped = dedupe_resolved(resolved);
        assert_eq!(
            deduped.len(),
            1,
            "identical tuples must collapse to one entry"
        );
        assert_eq!(deduped[0].0, "6.14.2");
        assert_eq!(deduped[0].1, PathBuf::from("/cache/v"));
    }

    #[test]
    fn dedupe_resolved_same_label_different_paths_both_survive() {
        // CRITICAL: two specs that resolve to the SAME label but
        // DIFFERENT paths represent a real cache-key collision.
        // Tuple-level dedup must NOT fold them — both rows must
        // survive so the post-dedupe `detect_label_collisions`
        // catches the same-label collision.
        let resolved = vec![
            ("6.14.2".to_string(), PathBuf::from("/cache/a")),
            ("6.14.2".to_string(), PathBuf::from("/cache/b")),
        ];
        let deduped = dedupe_resolved(resolved);
        assert_eq!(
            deduped.len(),
            2,
            "same label + different paths must NOT dedupe — \
             this is a real cache-key collision that detect_label_collisions \
             must still catch downstream",
        );
    }

    #[test]
    fn dedupe_resolved_preserves_input_order() {
        // The downstream wire format is `;`-separated and
        // order-insensitive at the dispatch layer, but stderr
        // diagnostics list kernels in the order the operator passed
        // them — the order-preserving dedup keeps that mapping
        // intact across the rayon shuffle. Pin the order via a
        // first-seen pass on a 4-entry input where the duplicate
        // sits between two other unique entries.
        let resolved = vec![
            ("a".to_string(), PathBuf::from("/cache/a")),
            ("b".to_string(), PathBuf::from("/cache/b")),
            ("a".to_string(), PathBuf::from("/cache/a")),
            ("c".to_string(), PathBuf::from("/cache/c")),
        ];
        let deduped = dedupe_resolved(resolved);
        // Output: a, b, c — `a` first-seen at index 0, second
        // occurrence at index 2 dropped.
        assert_eq!(
            deduped,
            vec![
                ("a".to_string(), PathBuf::from("/cache/a")),
                ("b".to_string(), PathBuf::from("/cache/b")),
                ("c".to_string(), PathBuf::from("/cache/c")),
            ],
        );
    }

    #[test]
    fn dedupe_resolved_three_identical_tuples_collapse_to_one() {
        // Larger duplicate count: three identical tuples fold to
        // one. Pins that the dedupe is set-membership, not
        // pairwise — a regression that compared adjacent entries
        // only would still pass for two duplicates but produce
        // two outputs for three identical inputs.
        let resolved = vec![
            ("v".to_string(), PathBuf::from("/cache/v")),
            ("v".to_string(), PathBuf::from("/cache/v")),
            ("v".to_string(), PathBuf::from("/cache/v")),
        ];
        let deduped = dedupe_resolved(resolved);
        assert_eq!(deduped.len(), 1);
    }

    // -- resolve_commit_specs: revspec resolution --

    /// Build a chain of `n` commits in `dir` and return their
    /// `ObjectId`s in order (oldest first). Each commit gets a
    /// fresh tree containing one blob whose contents differ per
    /// commit so the trees never collide. Mirrors the structure
    /// of `init_clean_repo_with_file` in `test_support::sidecar`'s
    /// test mod but extends it to a multi-commit chain.
    ///
    /// `gix::Repository::commit` requires both an author and a
    /// committer signature. `committer_or_set_generic_fallback`
    /// only writes the committer fallback; without `user.name`/
    /// `user.email` in the runner's git config, the author cascade
    /// (author -> user) yields `None` and `commit` bails with
    /// `AuthorMissing`. CI runners that do not pre-seed `user.name`
    /// hit this. Plant `gitoxide.author.nameFallback` /
    /// `emailFallback` directly so the author cascade has a value
    /// regardless of ambient git config — same shape gix uses for
    /// the committer fallback in `committer_or_set_generic_fallback`
    /// (see `gix::config::tree::gitoxide::Author` for the keys).
    fn init_repo_with_chain(dir: &std::path::Path, n: usize) -> Vec<gix::ObjectId> {
        let mut repo = gix::init(dir).expect("gix::init");
        let _ = repo
            .committer_or_set_generic_fallback()
            .expect("committer fallback");
        // Author fallback: mirror the committer-fallback pattern from
        // gix-0.81 `committer_or_set_generic_fallback` against the
        // Author keys.
        {
            use gix::config::tree::gitoxide;
            let mut cfg = gix::config::File::new(gix::config::file::Metadata::api());
            cfg.set_raw_value(&gitoxide::Author::NAME_FALLBACK, "ktstr-test")
                .expect("set author name fallback");
            cfg.set_raw_value(
                &gitoxide::Author::EMAIL_FALLBACK,
                "ktstr-test@example.invalid",
            )
            .expect("set author email fallback");
            let mut snap = repo.config_snapshot_mut();
            snap.append(cfg);
        }
        let mut chain: Vec<gix::ObjectId> = Vec::with_capacity(n);
        for i in 0..n {
            let blob_id: gix::ObjectId = repo
                .write_blob(format!("v{i}\n").as_bytes())
                .expect("write blob")
                .detach();
            let tree = gix::objs::Tree {
                entries: vec![gix::objs::tree::Entry {
                    mode: gix::objs::tree::EntryKind::Blob.into(),
                    filename: "file.txt".into(),
                    oid: blob_id,
                }],
            };
            let tree_id: gix::ObjectId = repo.write_object(&tree).expect("write tree").detach();
            let parents: Vec<gix::ObjectId> = chain.last().copied().into_iter().collect();
            let commit_id: gix::ObjectId = repo
                .commit("HEAD", format!("c{i}"), tree_id, parents)
                .expect("commit")
                .detach();
            chain.push(commit_id);
        }
        chain
    }

    /// `repo: None` (no repo available — cwd outside any git tree
    /// or `KTSTR_KERNEL` unset / non-git) is a documented contract:
    /// every input passes through verbatim as a literal. Pins that
    /// `resolve_commit_specs` does not require a repo to function —
    /// the bare-string fallback is the load-bearing default for
    /// stats analysis on a host that's not the original build
    /// machine.
    #[test]
    fn resolve_commit_specs_no_repo_passes_through_literal() {
        let raw = vec![
            "abc1234".to_string(),
            "main".to_string(),
            "HEAD".to_string(),
        ];
        let out = resolve_commit_specs(None, &raw, "test");
        assert_eq!(out, raw, "no repo → every input lands as-is");
    }

    /// `HEAD` resolves to the 7-char short hex of the tip commit.
    /// Pins the `Spec::Include(id)` arm against a real repo: a
    /// regression that returned the input string verbatim instead
    /// of the resolved hash would silently break revspec resolution
    /// even when the repo is available.
    #[test]
    fn resolve_commit_specs_head_resolves_to_short_hash() {
        let tmp = tempfile::TempDir::new().unwrap();
        let chain = init_repo_with_chain(tmp.path(), 3);
        let head = *chain.last().unwrap();
        let repo = gix::open(tmp.path()).expect("gix::open");
        let raw = vec!["HEAD".to_string()];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        assert_eq!(
            out,
            vec![head.to_hex_with_len(7).to_string()],
            "HEAD must resolve to the tip commit's 7-char short hex",
        );
    }

    /// `HEAD~1` resolves to the parent of HEAD. Pins the navigate-
    /// up form which is the most common revspec users write when
    /// pointing at "the prior commit". Same `Spec::Include(id)`
    /// arm, just driven through a non-trivial revspec.
    #[test]
    fn resolve_commit_specs_head_tilde_resolves_to_parent() {
        let tmp = tempfile::TempDir::new().unwrap();
        let chain = init_repo_with_chain(tmp.path(), 3);
        // chain[0] is oldest; chain[2] is HEAD; chain[1] is HEAD~1.
        let head_tilde_1 = chain[1];
        let repo = gix::open(tmp.path()).expect("gix::open");
        let raw = vec!["HEAD~1".to_string()];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        assert_eq!(
            out,
            vec![head_tilde_1.to_hex_with_len(7).to_string()],
            "HEAD~1 must resolve to the parent commit's 7-char short hex",
        );
    }

    /// `A..B` (range revspec) expands to every commit reachable
    /// from B but not from A. With three commits c0→c1→c2 and the
    /// range `c0..HEAD`, the result must include c1 and c2 (c0 is
    /// excluded; HEAD is included). Pins the `Spec::Range` arm and
    /// the `rev_walk([to]).with_hidden([from]).all()` walk.
    #[test]
    fn resolve_commit_specs_range_expands_inclusive_of_to() {
        let tmp = tempfile::TempDir::new().unwrap();
        let chain = init_repo_with_chain(tmp.path(), 3);
        let c0 = chain[0];
        let c1 = chain[1];
        let c2 = chain[2];
        let repo = gix::open(tmp.path()).expect("gix::open");
        let raw = vec![format!("{}..HEAD", c0.to_hex_with_len(40))];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        // The walk yields c2 (HEAD) and c1 in some order; c0 is
        // hidden. Verify membership (order is walk-implementation
        // dependent and not pinned).
        assert!(
            out.contains(&c1.to_hex_with_len(7).to_string()),
            "range result must include c1 (the parent of HEAD); got {out:?}",
        );
        assert!(
            out.contains(&c2.to_hex_with_len(7).to_string()),
            "range result must include c2 (HEAD); got {out:?}",
        );
        assert!(
            !out.contains(&c0.to_hex_with_len(7).to_string()),
            "range result must NOT include c0 (the hidden side); got {out:?}",
        );
        assert_eq!(
            out.len(),
            2,
            "range c0..HEAD over 3-commit chain must yield exactly 2 commits; got {out:?}",
        );
    }

    /// A non-revspec input round-trips unchanged. Pins the
    /// literal-fallback arm: the existing exact-match contract
    /// for hand-typed strings must keep working when the input
    /// can't be parsed as a revspec at all.
    /// `gix::Repository::rev_parse` returns an error for any
    /// input that is neither a known ref nor a valid hex hash
    /// prefix; that error falls through to `out.push(input
    /// .clone())`. `"zzzzzzz"` is non-hex (z is outside
    /// `[0-9a-fA-F]`), so revspec parsing definitionally rejects
    /// it without needing to consult the object database.
    #[test]
    fn resolve_commit_specs_unknown_hash_falls_through_to_literal() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_repo_with_chain(tmp.path(), 1);
        let repo = gix::open(tmp.path()).expect("gix::open");
        let raw = vec!["zzzzzzz".to_string()];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        assert_eq!(
            out,
            vec!["zzzzzzz".to_string()],
            "non-hex input must pass through as literal",
        );
    }

    /// A literal `<hash>-dirty` form falls through to the literal
    /// arm. `gix::Repository::rev_parse` rejects the `-dirty`
    /// suffix as an invalid revspec; the function lands the input
    /// unchanged so it matches the `-dirty`-suffixed entries the
    /// sidecar writer produces. Pins the design contract that
    /// hand-typed dirty filters keep working alongside revspec
    /// expansion.
    #[test]
    fn resolve_commit_specs_dirty_suffix_falls_through_to_literal() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_repo_with_chain(tmp.path(), 1);
        let repo = gix::open(tmp.path()).expect("gix::open");
        let raw = vec!["abc1234-dirty".to_string()];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        assert_eq!(
            out,
            vec!["abc1234-dirty".to_string()],
            "-dirty-suffixed input must pass through as literal",
        );
    }

    /// Empty input → empty output, no work done. Pins the no-op
    /// pass for the common case where a side has no commit filter
    /// — the function returns an empty Vec without exercising
    /// any rev_parse machinery.
    #[test]
    fn resolve_commit_specs_empty_input_yields_empty_output() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_repo_with_chain(tmp.path(), 1);
        let repo = gix::open(tmp.path()).expect("gix::open");
        let out = resolve_commit_specs(Some(&repo), &[], "test");
        assert!(out.is_empty(), "empty input must yield empty output");
    }

    /// Mixed input: some revspecs resolve, some fall through to
    /// literals, all in the same call. Pins the per-input
    /// independence — one literal does not poison sibling
    /// resolutions, and one resolved revspec does not consume the
    /// literal fallback for its siblings. Mirrors the realistic
    /// case where a user types `--project-commit HEAD --project-commit
    /// abc1234-dirty` to combine "current HEAD" with a known dirty
    /// run from history.
    #[test]
    fn resolve_commit_specs_mixed_inputs_resolve_per_entry() {
        let tmp = tempfile::TempDir::new().unwrap();
        let chain = init_repo_with_chain(tmp.path(), 1);
        let head = chain[0];
        let repo = gix::open(tmp.path()).expect("gix::open");
        let raw = vec!["HEAD".to_string(), "abc1234-dirty".to_string()];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        assert_eq!(
            out,
            vec![
                head.to_hex_with_len(7).to_string(),
                "abc1234-dirty".to_string(),
            ],
            "HEAD resolves; -dirty input lands literal; order preserved",
        );
    }

    /// `HEAD` against a dirty worktree resolves to
    /// `<short>-dirty`, mirroring what `detect_project_commit`
    /// writes at sidecar-write time. Pins the dirty-suffix
    /// behavior on the Include/ExcludeParents arm: a regression
    /// that emitted just `<short>` would silently miss every
    /// sidecar row written from this same dirty worktree, since
    /// `RowFilter::matches` is strict equality on the
    /// commit-string field.
    #[test]
    fn resolve_commit_specs_head_in_dirty_repo_appends_dirty_suffix() {
        let tmp = tempfile::TempDir::new().unwrap();
        let chain = init_repo_with_chain(tmp.path(), 1);
        let head = chain[0];
        // Mutate the tracked file so index-vs-worktree diverges.
        // `init_repo_with_chain` writes the blob to ODB but does
        // not populate a worktree file or index — so create the
        // index from the tree, write the file, then mutate it.
        let repo = gix::open(tmp.path()).expect("gix::open");
        let head_tree = repo.head_tree().expect("head_tree").id;
        let mut idx = repo.index_from_tree(&head_tree).expect("index_from_tree");
        idx.write(gix::index::write::Options::default())
            .expect("write index");
        std::fs::write(tmp.path().join("file.txt"), b"original\n").unwrap();
        // Now mutate the tracked file to dirty the worktree.
        std::fs::write(tmp.path().join("file.txt"), b"modified\n").unwrap();
        let raw = vec!["HEAD".to_string()];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        let expected_short = head.to_hex_with_len(7).to_string();
        assert_eq!(
            out,
            vec![format!("{expected_short}-dirty")],
            "HEAD in a dirty repo must resolve to <short>-dirty",
        );
    }

    /// A historical commit (HEAD~1 in a 2-commit chain) does NOT
    /// get the `-dirty` suffix even when the worktree is dirty.
    /// Pins the team-lead's design constraint: only the resolved
    /// OID equal to current HEAD reflects worktree state; named
    /// historical commits keep their plain identity. A regression
    /// that propagated dirt to non-HEAD resolutions would
    /// fingerprint historical filters with the current local
    /// state, mis-matching every sidecar in the pool.
    #[test]
    fn resolve_commit_specs_non_head_does_not_get_dirty_suffix_in_dirty_repo() {
        let tmp = tempfile::TempDir::new().unwrap();
        let chain = init_repo_with_chain(tmp.path(), 2);
        let parent = chain[0];
        // Same dirty-worktree setup as the prior test.
        let repo = gix::open(tmp.path()).expect("gix::open");
        let head_tree = repo.head_tree().expect("head_tree").id;
        let mut idx = repo.index_from_tree(&head_tree).expect("index_from_tree");
        idx.write(gix::index::write::Options::default())
            .expect("write index");
        std::fs::write(tmp.path().join("file.txt"), b"v1\n").unwrap();
        std::fs::write(tmp.path().join("file.txt"), b"modified\n").unwrap();
        let raw = vec!["HEAD~1".to_string()];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        assert_eq!(
            out,
            vec![parent.to_hex_with_len(7).to_string()],
            "HEAD~1 (historical commit) must NOT get -dirty suffix \
             even when worktree is dirty",
        );
    }

    /// `<oid>^!` (ExcludeParents revspec, "this commit
    /// specifically") resolves to the commit's own 7-char short
    /// hex. gix maps `^!` to `Spec::ExcludeParents(id)`; the
    /// resolver groups it with `Spec::Include(id)` because both
    /// arms describe a single object the operator named directly.
    /// Pins the second arm of the Include/ExcludeParents match
    /// branch; without this test the branch could collapse to
    /// "Include only" without anyone noticing.
    #[test]
    fn resolve_commit_specs_exclude_parents_resolves_like_include() {
        let tmp = tempfile::TempDir::new().unwrap();
        let chain = init_repo_with_chain(tmp.path(), 2);
        let head = chain[1];
        let repo = gix::open(tmp.path()).expect("gix::open");
        let raw = vec![format!("{}^!", head.to_hex_with_len(40))];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        assert_eq!(
            out,
            vec![head.to_hex_with_len(7).to_string()],
            "<oid>^! must resolve to the same 7-char short hex as <oid>",
        );
    }

    /// A branch name resolves to the commit it points at. Pins
    /// that the resolver accepts ref-name inputs (not just OIDs)
    /// — without this test the branch-creation API change in a
    /// future gix version could silently drop branch resolution.
    #[test]
    fn resolve_commit_specs_branch_name_resolves_to_tip() {
        let tmp = tempfile::TempDir::new().unwrap();
        let chain = init_repo_with_chain(tmp.path(), 2);
        let parent = chain[0];
        let repo = gix::open(tmp.path()).expect("gix::open");
        // Create `refs/heads/feature` pointing at the parent
        // commit (chain[0]) so the test can distinguish it from
        // HEAD (chain[1]).
        repo.reference(
            "refs/heads/feature",
            parent,
            gix::refs::transaction::PreviousValue::MustNotExist,
            "create feature branch for test",
        )
        .expect("create branch");
        let raw = vec!["feature".to_string()];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        assert_eq!(
            out,
            vec![parent.to_hex_with_len(7).to_string()],
            "branch name must resolve to its tip commit",
        );
    }

    /// A tag name resolves to the commit it points at. Same
    /// shape as the branch test, against `refs/tags/<name>` —
    /// gix `rev_parse` looks up tags through the same ref-name
    /// resolver, so this exercises the ref-resolution code path
    /// for the tag namespace specifically.
    #[test]
    fn resolve_commit_specs_tag_name_resolves_to_target() {
        let tmp = tempfile::TempDir::new().unwrap();
        let chain = init_repo_with_chain(tmp.path(), 2);
        let parent = chain[0];
        let repo = gix::open(tmp.path()).expect("gix::open");
        // Lightweight tag (a ref under `refs/tags/`) pointing at
        // the parent commit. Distinct from an annotated tag
        // (which is its own object kind); rev_parse handles both
        // by peeling, but lightweight tags are simpler to set up
        // in a fixture without writing a Tag object.
        repo.reference(
            "refs/tags/v0",
            parent,
            gix::refs::transaction::PreviousValue::MustNotExist,
            "create v0 tag for test",
        )
        .expect("create tag");
        let raw = vec!["v0".to_string()];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        assert_eq!(
            out,
            vec![parent.to_hex_with_len(7).to_string()],
            "tag name must resolve to its target commit",
        );
    }

    /// `HEAD..HEAD` (empty range — `from == to`) yields zero
    /// commits because the walk hides every reachable commit
    /// from `from` and there are no remaining commits in the
    /// `to`-side. Pins that an empty range lands as an empty
    /// expansion (not a literal fallback), so a downstream
    /// filter built from this Vec excludes every row — which
    /// matches the operator's intent ("commits in `HEAD..HEAD`"
    /// is the empty set).
    #[test]
    fn resolve_commit_specs_empty_range_yields_no_entries() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_repo_with_chain(tmp.path(), 2);
        let repo = gix::open(tmp.path()).expect("gix::open");
        let raw = vec!["HEAD..HEAD".to_string()];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        assert!(
            out.is_empty(),
            "HEAD..HEAD must expand to zero commits; got {out:?}",
        );
    }

    /// A valid-hex 7-char prefix that does not match any commit
    /// in the repo (`deadbee`) falls through to literal. Pins
    /// the rev_parse-Err arm against a hex-shaped input —
    /// distinct from the prior `zzzzzzz` non-hex case, this one
    /// reaches the object-database lookup before failing, so it
    /// exercises a deeper rev_parse code path. The literal
    /// `deadbee` lands in the output because the warning is
    /// suppressed by [`looks_like_literal_hash`]; either way
    /// the value passes through.
    #[test]
    fn resolve_commit_specs_valid_hex_nonexistent_prefix_falls_through_to_literal() {
        let tmp = tempfile::TempDir::new().unwrap();
        init_repo_with_chain(tmp.path(), 1);
        let repo = gix::open(tmp.path()).expect("gix::open");
        let raw = vec!["deadbee".to_string()];
        let out = resolve_commit_specs(Some(&repo), &raw, "test");
        assert_eq!(
            out,
            vec!["deadbee".to_string()],
            "valid-hex non-existent prefix must pass through as literal",
        );
    }

    /// `looks_like_literal_hash` accepts the on-disk shape that
    /// `detect_*_commit` writes: 7..=40 lowercase hex chars,
    /// optionally followed by `-dirty`. Pins the gating predicate
    /// against the canonical writer's output so a regression that
    /// tightened the predicate (e.g. 7-only, no -dirty) would
    /// surface noisy warnings on legitimate inputs.
    #[test]
    fn looks_like_literal_hash_accepts_canonical_shapes() {
        // Bare 7-char hash (the most common operator-typed shape).
        assert!(looks_like_literal_hash("abc1234"));
        // 40-char full hash (upper bound).
        assert!(looks_like_literal_hash(
            "abcdef0123456789abcdef0123456789abcdef01"
        ));
        // 7-char + -dirty (the dirty-suffixed sidecar entry).
        assert!(looks_like_literal_hash("abc1234-dirty"));
        // 40-char + -dirty.
        assert!(looks_like_literal_hash(
            "abcdef0123456789abcdef0123456789abcdef01-dirty"
        ));
    }

    /// `looks_like_literal_hash` rejects revspec-shaped inputs
    /// so the gated rev_parse-Err warning still fires for them.
    /// Pins the negative side of the predicate against every
    /// shape the team-lead's gating spec calls out: alpha beyond
    /// hex, ~, .., ^, and out-of-bound lengths. Mixed-case hex
    /// is now ACCEPTED — see
    /// [`looks_like_literal_hash_accepts_uppercase_and_mixed_case`].
    #[test]
    fn looks_like_literal_hash_rejects_revspec_shapes() {
        // Alpha beyond hex.
        assert!(!looks_like_literal_hash("HEAD"));
        assert!(!looks_like_literal_hash("main"));
        // Tilde-form revspec.
        assert!(!looks_like_literal_hash("HEAD~1"));
        // Range form.
        assert!(!looks_like_literal_hash("HEAD~3..HEAD"));
        // Caret form.
        assert!(!looks_like_literal_hash("HEAD^"));
        // Below 7-char minimum.
        assert!(!looks_like_literal_hash("abc123"));
        // Above 40-char maximum (e.g. SHA-256 prefix or paste of
        // a longer string).
        assert!(!looks_like_literal_hash(
            "abcdef0123456789abcdef0123456789abcdef0123"
        ));
        // Empty input.
        assert!(!looks_like_literal_hash(""));
        // -dirty without enough hex prefix.
        assert!(!looks_like_literal_hash("abc-dirty"));
    }

    /// `looks_like_literal_hash` accepts uppercase and mixed-case
    /// hex. The sidecar writer produces lowercase, but operators
    /// commonly paste hashes from `git log` UIs or other tools that
    /// uppercase. Suppressing the rev_parse-Err warning on these
    /// keeps CLI noise down; the literal still passes through, and
    /// the (lowercase) sidecar pool simply produces no match — the
    /// same outcome as a legitimate-but-unknown short hash.
    #[test]
    fn looks_like_literal_hash_accepts_uppercase_and_mixed_case() {
        // Pure uppercase hex.
        assert!(looks_like_literal_hash("ABC1234"));
        // Mixed-case hex.
        assert!(looks_like_literal_hash("AbC1234"));
        // Uppercase + -dirty.
        assert!(looks_like_literal_hash("ABC1234-dirty"));
        // 40-char uppercase full hash.
        assert!(looks_like_literal_hash(
            "ABCDEF0123456789ABCDEF0123456789ABCDEF01"
        ));
    }
}