rch-common 1.0.26

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

use memchr::memmem;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;

// Tier name constants (avoid allocations on hot path).
const TIER_INSTANT_REJECT: &str = "instant_reject";
const TIER_STRUCTURE_ANALYSIS: &str = "structure_analysis";
const TIER_KEYWORD_FILTER: &str = "keyword_filter";
const TIER_NEVER_INTERCEPT: &str = "never_intercept";
const TIER_FULL_CLASSIFICATION: &str = "full_classification";

/// Keywords that indicate a potential compilation command.
/// Used for SIMD-accelerated quick filtering (Tier 2).
pub static COMPILATION_KEYWORDS: &[&str] = &[
    "cargo", "rustc", "gcc", "g++", "clang", "clang++", "make", "cmake", "ninja", "meson", "cc",
    "c++", "bun", "nextest",
];

/// Commands that should NEVER be intercepted, even if they contain compilation keywords.
/// These either modify local state or have dependencies on local execution.
pub static NEVER_INTERCEPT: &[&str] = &[
    // Cargo commands that modify local state or shouldn't be intercepted
    "cargo install",
    "cargo publish",
    "cargo login",
    "cargo fmt",
    "cargo fix",
    "cargo clean",
    "cargo new",
    "cargo init",
    "cargo add",
    "cargo remove",
    "cargo update",
    "cargo generate-lockfile",
    "cargo watch",
    "cargo --version",
    "cargo -V",
    // Compiler version checks
    "rustc --version",
    "rustc -V",
    "gcc --version",
    "gcc -v",
    "clang --version",
    "clang -v",
    "make --version",
    "make -v",
    "cmake --version",
    // Bun package management - MUST NOT intercept (modifies local state)
    "bun install",
    "bun add",
    "bun remove",
    "bun link",
    "bun unlink",
    "bun pm",
    "bun init",
    "bun create",
    "bun upgrade",
    "bun completions",
    // Bun execution that shouldn't be intercepted
    "bun run",
    "bun build",
    "bun --help",
    "bun -h",
    "bun --version",
    "bun -v",
    // Bun dev/repl - require local interactivity
    "bun dev",
    "bun repl",
    // cargo-nextest commands that shouldn't be intercepted
    "cargo nextest list",    // Lists tests only, doesn't run them
    "cargo nextest archive", // Creates test archives
    "cargo nextest show",    // Shows config/setup info
];

/// Result of command classification.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Classification {
    /// Whether this is a compilation command.
    pub is_compilation: bool,
    /// Confidence score (0.0-1.0).
    pub confidence: f64,
    /// The kind of compilation if detected.
    pub kind: Option<CompilationKind>,
    /// Reason for the classification decision.
    pub reason: Cow<'static, str>,
    /// For compound commands (e.g., "cd /path && cargo build"), this contains
    /// the prefix that should run before the compilation ("cd /path && ").
    /// None for simple commands.
    pub command_prefix: Option<String>,
    /// For compound commands, this contains the extracted compilation command
    /// (e.g., "cargo build --release"). None for simple commands where the
    /// entire input is the compilation command.
    pub extracted_command: Option<String>,
}

/// Decision outcome for a classification tier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TierDecision {
    Pass,
    Reject,
}

/// Detailed result for a single classification tier.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ClassificationTier {
    /// Tier index (0-4).
    pub tier: u8,
    /// Tier name.
    pub name: Cow<'static, str>,
    /// Decision for this tier.
    pub decision: TierDecision,
    /// Reason for the decision.
    pub reason: Cow<'static, str>,
}

/// Detailed classification results with per-tier decisions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ClassificationDetails {
    /// Original command string.
    pub original: String,
    /// Normalized command string (wrappers stripped).
    pub normalized: String,
    /// Per-tier decisions.
    pub tiers: Vec<ClassificationTier>,
    /// Final classification result.
    pub classification: Classification,
}

impl Classification {
    /// Create a non-compilation classification.
    pub fn not_compilation(reason: impl Into<Cow<'static, str>>) -> Self {
        Self {
            is_compilation: false,
            confidence: 0.0,
            kind: None,
            reason: reason.into(),
            command_prefix: None,
            extracted_command: None,
        }
    }

    /// Create a compilation classification.
    pub fn compilation(
        kind: CompilationKind,
        confidence: f64,
        reason: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self {
            is_compilation: true,
            confidence,
            kind: Some(kind),
            reason: reason.into(),
            command_prefix: None,
            extracted_command: None,
        }
    }

    /// Create a compilation classification for a compound command.
    /// The prefix contains everything before the compilation command (including the final "&&" or ";").
    /// The extracted_command is the actual compilation command to intercept.
    pub fn compound_compilation(
        kind: CompilationKind,
        confidence: f64,
        reason: impl Into<Cow<'static, str>>,
        prefix: String,
        extracted: String,
    ) -> Self {
        Self {
            is_compilation: true,
            confidence,
            kind: Some(kind),
            reason: reason.into(),
            command_prefix: Some(prefix),
            extracted_command: Some(extracted),
        }
    }
}

/// Kind of compilation command detected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum CompilationKind {
    // Rust commands
    /// cargo build, cargo test, cargo check, etc.
    CargoBuild,
    CargoTest,
    CargoCheck,
    CargoClippy,
    CargoDoc,
    /// cargo nextest run - next-generation test runner
    CargoNextest,
    /// cargo bench - run benchmarks
    CargoBench,
    /// rustc invocation
    Rustc,

    // C/C++ commands
    /// GCC compilation
    Gcc,
    /// G++ compilation
    Gpp,
    /// Clang compilation
    Clang,
    /// Clang++ compilation
    Clangpp,

    // Build systems
    /// make build
    Make,
    /// cmake --build
    CmakeBuild,
    /// ninja build
    Ninja,
    /// meson compile
    Meson,

    // Bun commands
    /// bun test - Runs Bun's built-in test runner
    BunTest,
    /// bun typecheck - Runs TypeScript type checking
    BunTypecheck,
}

impl CompilationKind {
    /// Returns true if this is a test-related command.
    ///
    /// Test commands have special cache affinity behavior because test binaries
    /// (e.g., target/debug/deps/) are expensive to compile and benefit more
    /// from warm caches than regular builds.
    pub fn is_test_command(&self) -> bool {
        matches!(
            self,
            CompilationKind::CargoTest
                | CompilationKind::CargoNextest
                | CompilationKind::CargoBench
                | CompilationKind::BunTest
        )
    }

    /// Returns the base command name for allowlist matching (bd-785w).
    ///
    /// This is the primary executable name that should appear in the
    /// execution allowlist configuration.
    pub fn command_base(&self) -> &'static str {
        match self {
            // Rust commands
            CompilationKind::CargoBuild
            | CompilationKind::CargoTest
            | CompilationKind::CargoCheck
            | CompilationKind::CargoClippy
            | CompilationKind::CargoDoc
            | CompilationKind::CargoBench => "cargo",
            CompilationKind::CargoNextest => "cargo", // cargo nextest, base is still cargo
            CompilationKind::Rustc => "rustc",
            // C/C++ commands
            CompilationKind::Gcc => "gcc",
            CompilationKind::Gpp => "g++",
            CompilationKind::Clang => "clang",
            CompilationKind::Clangpp => "clang++",
            // Build systems
            CompilationKind::Make => "make",
            CompilationKind::CmakeBuild => "cmake",
            CompilationKind::Ninja => "ninja",
            CompilationKind::Meson => "meson",
            // Bun commands
            CompilationKind::BunTest | CompilationKind::BunTypecheck => "bun",
        }
    }
}

/// Classify a shell command.
///
/// Implements the 5-tier classification system for maximum precision with
/// minimal latency on non-compilation commands.
///
/// Multi-command strings (joined by `&&`, `||`, or `;`) are rejected by
/// Tier 1 structure analysis to prevent partial interception issues.
pub fn classify_command(cmd: &str) -> Classification {
    classify_command_inner(cmd, 0)
}

/// Maximum recursion depth for multi-command splitting.
/// Depth 0 = top-level call that may split; depth 1 = sub-command (no further splitting).
#[allow(dead_code)] // Reserved for future multi-command classification
const MAX_CLASSIFY_DEPTH: u8 = 1;

/// Maximum command length for multi-command splitting (10 KB).
/// Commands longer than this skip splitting and are classified as a single command.
#[allow(dead_code)] // Reserved for future multi-command classification
const MAX_SPLIT_INPUT_LEN: usize = 10 * 1024;

fn classify_command_inner(cmd: &str, depth: u8) -> Classification {
    let cmd = cmd.trim();

    // Tier 0: Instant reject - empty command
    if cmd.is_empty() {
        return Classification::not_compilation("empty command");
    }

    // Tier 0.5: Compound command handling (only at depth 0)
    // For commands like "cd /path && cargo build", extract and classify the last segment.
    // We only handle && chains (not || or ;) at depth 0 to avoid complex rewriting.
    if depth == 0
        && cmd.len() < MAX_SPLIT_INPUT_LEN
        && let Some(result) = try_classify_compound_command(cmd)
    {
        return result;
    }

    // Tier 1: Structure analysis - reject complex shell structures
    if let Some(reason) = check_structure(cmd) {
        return Classification::not_compilation(reason);
    }

    // Tier 2: SIMD keyword filter - quick check for compilation keywords
    if !contains_compilation_keyword(cmd) {
        return Classification::not_compilation("no compilation keyword");
    }

    // Normalize command for Tier 3 and 4
    let normalized_cow = normalize_command(cmd);
    let normalized = normalized_cow.as_ref();

    // Tier 3: Negative pattern check - never intercept these
    // Performance: use static string to avoid format! allocation on hot rejection path
    for pattern in NEVER_INTERCEPT {
        if let Some(rest) = normalized.strip_prefix(pattern) {
            // Ensure exact match or boundary match (e.g. "cargo clean" matches "cargo clean"
            // or "cargo clean ", but NOT "cargo cleanup")
            if rest.is_empty() || rest.starts_with(' ') {
                return Classification::not_compilation("matches never-intercept pattern");
            }
        }
    }

    // Tier 4: Full classification
    classify_full(normalized)
}

/// Try to classify a compound command (e.g., "cd /path && cargo build").
///
/// For && chains, we check if the LAST segment is a compilation command.
/// If so, we return a compound_compilation with the prefix (everything before
/// the compilation) and the extracted compilation command.
///
/// This allows commands like:
/// - "cd /path && cargo build" → prefix="cd /path && ", extracted="cargo build"
/// - "touch file && cargo test" → prefix="touch file && ", extracted="cargo test"
///
/// We only handle && chains, not || or ; for safety (those have different semantics).
/// We also reject commands with pipes, redirects, or subshells in ANY segment.
fn try_classify_compound_command(cmd: &str) -> Option<Classification> {
    // Quick check: must contain && but not other problematic operators
    if !cmd.contains("&&") {
        return None;
    }

    // Reject if command contains pipes, redirects, or subshells (anywhere)
    // These make command rewriting unsafe
    if cmd.contains('|') {
        return None; // Pipe or || chain
    }
    if has_file_redirect(cmd) {
        return None; // File redirects (but NOT fd-to-fd like 2>&1)
    }
    if cmd.contains('(') || cmd.contains('`') || cmd.contains("$(") {
        return None; // Subshells
    }
    if cmd.contains(';') {
        return None; // Only handle pure && chains for now
    }

    // Split on && (simple split, respects quotes via split_and_chain)
    let segments = split_and_chain(cmd)?;
    if segments.is_empty() {
        return None;
    }

    // Get the last segment and classify it
    let last_segment = segments.last()?.trim();
    if last_segment.is_empty() {
        return None;
    }

    // Classify the last segment at depth 1 (prevents infinite recursion)
    let last_classification = classify_command_inner(last_segment, 1);

    if !last_classification.is_compilation {
        return None;
    }

    // Build the prefix (everything before the last segment, including the final "&&")
    let prefix = if segments.len() == 1 {
        // No prefix, just the command itself
        return None;
    } else {
        // Find where the last segment starts in the original command
        // and take everything before it
        let last_pos = cmd.rfind(last_segment)?;
        cmd[..last_pos].to_string()
    };

    // Return compound classification
    Some(Classification::compound_compilation(
        last_classification.kind?,
        last_classification.confidence,
        "compound command with compilation suffix",
        prefix,
        last_segment.to_string(),
    ))
}

/// Split a command on && only (simpler than split_multi_command).
/// Returns None if no && found.
fn split_and_chain(cmd: &str) -> Option<Vec<&str>> {
    if !cmd.contains("&&") {
        return None;
    }

    let mut segments = Vec::new();
    let mut current_start = 0;
    let mut in_single = false;
    let mut in_double = false;
    let mut escaped = false;
    let bytes = cmd.as_bytes();
    let mut i = 0;

    while i < bytes.len() {
        let b = bytes[i];

        if escaped {
            escaped = false;
            i += 1;
            continue;
        }

        if b == b'\\' {
            escaped = true;
            i += 1;
            continue;
        }

        if b == b'\'' && !in_double {
            in_single = !in_single;
        } else if b == b'"' && !in_single {
            in_double = !in_double;
        } else if !in_single
            && !in_double
            && b == b'&'
            && i + 1 < bytes.len()
            && bytes[i + 1] == b'&'
        {
            let segment = &cmd[current_start..i];
            let trimmed = segment.trim();
            if !trimmed.is_empty() {
                segments.push(trimmed);
            }
            current_start = i + 2;
            i += 1; // Skip second '&'
        }

        i += 1;
    }

    // Add final segment
    let final_segment = &cmd[current_start..];
    let trimmed = final_segment.trim();
    if !trimmed.is_empty() {
        segments.push(trimmed);
    }

    if segments.len() > 1 {
        Some(segments)
    } else {
        None
    }
}

/// Split a multi-command string on `&&`, `||`, and `;` while respecting quotes.
///
/// Returns `None` if no multi-command operators are found.
/// Returns `Some(segments)` where each segment is a trimmed sub-command.
#[allow(dead_code)] // May be used for future enhancements
fn split_multi_command(cmd: &str) -> Option<Vec<&str>> {
    // Quick check: if no operators, return None early
    if !cmd.contains("&&") && !cmd.contains("||") && !cmd.contains(';') {
        return None;
    }

    let mut segments = Vec::new();
    let mut current_start = 0;
    let mut in_single = false;
    let mut in_double = false;
    let mut escaped = false;
    let chars: Vec<char> = cmd.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        let c = chars[i];

        if escaped {
            escaped = false;
            i += 1;
            continue;
        }

        if c == '\\' {
            escaped = true;
            i += 1;
            continue;
        }

        if c == '\'' && !in_double {
            in_single = !in_single;
        } else if c == '"' && !in_single {
            in_double = !in_double;
        } else if !in_single && !in_double {
            // Check for operators
            if c == ';' {
                let segment = &cmd[current_start..byte_index(&chars, i)];
                let trimmed = segment.trim();
                if !trimmed.is_empty() {
                    segments.push(trimmed);
                }
                current_start = byte_index(&chars, i + 1);
            } else if c == '&' && i + 1 < chars.len() && chars[i + 1] == '&' {
                let segment = &cmd[current_start..byte_index(&chars, i)];
                let trimmed = segment.trim();
                if !trimmed.is_empty() {
                    segments.push(trimmed);
                }
                current_start = byte_index(&chars, i + 2);
                i += 1; // Skip second '&'
            } else if c == '|' && i + 1 < chars.len() && chars[i + 1] == '|' {
                let segment = &cmd[current_start..byte_index(&chars, i)];
                let trimmed = segment.trim();
                if !trimmed.is_empty() {
                    segments.push(trimmed);
                }
                current_start = byte_index(&chars, i + 2);
                i += 1; // Skip second '|'
            }
        }

        i += 1;
    }

    // Add final segment
    let final_segment = &cmd[current_start..];
    let trimmed = final_segment.trim();
    if !trimmed.is_empty() {
        segments.push(trimmed);
    }

    // Only return Some if we actually split something
    if segments.len() > 1 {
        Some(segments)
    } else {
        None
    }
}

/// Convert char index to byte index for string slicing.
#[allow(dead_code)] // Reserved for future multi-command classification
fn byte_index(chars: &[char], char_idx: usize) -> usize {
    chars.iter().take(char_idx).map(|c| c.len_utf8()).sum()
}

/// Classify a multi-command string by evaluating each sub-command independently.
///
/// Returns compilation if ANY sub-command is compilation (highest confidence wins).
/// Returns non-compilation only if ALL sub-commands are non-compilation.
#[allow(dead_code)] // Reserved for future multi-command classification
fn classify_multi_command(segments: &[&str], depth: u8) -> Classification {
    let mut best_compilation: Option<Classification> = None;

    for &segment in segments {
        let result = classify_command_inner(segment, depth + 1);
        if result.is_compilation {
            let dominated = match &best_compilation {
                Some(prev) => result.confidence > prev.confidence,
                None => true,
            };
            if dominated {
                best_compilation = Some(result);
            }
        }
    }

    if let Some(compilation) = best_compilation {
        return compilation;
    }

    Classification::not_compilation("no sub-command is compilation")
}

/// Classify a shell command with detailed tier decisions for diagnostics.
pub fn classify_command_detailed(cmd: &str) -> ClassificationDetails {
    let original = cmd.to_string();
    let cmd = cmd.trim();
    let mut tiers = Vec::new();

    // Tier 0: Instant reject - empty command
    if cmd.is_empty() {
        let classification = Classification::not_compilation("empty command");
        tiers.push(ClassificationTier {
            tier: 0,
            name: Cow::Borrowed(TIER_INSTANT_REJECT),
            decision: TierDecision::Reject,
            reason: Cow::Borrowed("empty command"),
        });
        return ClassificationDetails {
            original,
            normalized: cmd.to_string(),
            tiers,
            classification,
        };
    }

    tiers.push(ClassificationTier {
        tier: 0,
        name: Cow::Borrowed(TIER_INSTANT_REJECT),
        decision: TierDecision::Pass,
        reason: Cow::Borrowed("command present"),
    });

    // Tier 1: Structure analysis
    if let Some(reason) = check_structure(cmd) {
        let classification = Classification::not_compilation(reason);
        tiers.push(ClassificationTier {
            tier: 1,
            name: Cow::Borrowed(TIER_STRUCTURE_ANALYSIS),
            decision: TierDecision::Reject,
            reason: Cow::Borrowed(reason),
        });
        return ClassificationDetails {
            original,
            normalized: cmd.to_string(),
            tiers,
            classification,
        };
    }

    tiers.push(ClassificationTier {
        tier: 1,
        name: Cow::Borrowed(TIER_STRUCTURE_ANALYSIS),
        decision: TierDecision::Pass,
        reason: Cow::Borrowed("no pipes/redirects/backgrounding"),
    });

    // Tier 2: SIMD keyword filter
    if !contains_compilation_keyword(cmd) {
        let classification = Classification::not_compilation("no compilation keyword");
        tiers.push(ClassificationTier {
            tier: 2,
            name: Cow::Borrowed(TIER_KEYWORD_FILTER),
            decision: TierDecision::Reject,
            reason: Cow::Borrowed("no compilation keyword"),
        });
        return ClassificationDetails {
            original,
            normalized: cmd.to_string(),
            tiers,
            classification,
        };
    }

    tiers.push(ClassificationTier {
        tier: 2,
        name: Cow::Borrowed(TIER_KEYWORD_FILTER),
        decision: TierDecision::Pass,
        reason: Cow::Borrowed("keyword present"),
    });

    // Normalize command for Tier 3 and 4
    let normalized_cow = normalize_command(cmd);
    let normalized = normalized_cow.as_ref();

    // Tier 3: Negative pattern check - never intercept these
    for pattern in NEVER_INTERCEPT {
        if let Some(rest) = normalized.strip_prefix(pattern)
            && (rest.is_empty() || rest.starts_with(' '))
        {
            let reason: Cow<'static, str> =
                Cow::Owned(format!("matches never-intercept: {pattern}"));
            let classification = Classification::not_compilation(reason.clone());
            tiers.push(ClassificationTier {
                tier: 3,
                name: Cow::Borrowed(TIER_NEVER_INTERCEPT),
                decision: TierDecision::Reject,
                reason,
            });
            return ClassificationDetails {
                original,
                normalized: normalized.to_string(),
                tiers,
                classification,
            };
        }
    }

    tiers.push(ClassificationTier {
        tier: 3,
        name: Cow::Borrowed(TIER_NEVER_INTERCEPT),
        decision: TierDecision::Pass,
        reason: Cow::Borrowed("no never-intercept match"),
    });

    // Tier 4: Full classification
    let classification = classify_full(normalized);
    let decision = if classification.is_compilation {
        TierDecision::Pass
    } else {
        TierDecision::Reject
    };
    tiers.push(ClassificationTier {
        tier: 4,
        name: Cow::Borrowed(TIER_FULL_CLASSIFICATION),
        decision,
        reason: classification.reason.clone(),
    });

    ClassificationDetails {
        original,
        normalized: normalized.to_string(),
        tiers,
        classification,
    }
}

/// Normalize a command by stripping common wrappers (sudo, time, env, etc.)
pub fn normalize_command(cmd: &str) -> Cow<'_, str> {
    let mut result = cmd.trim();

    // Strip common command prefixes/wrappers
    // Note: We match the command name, then ensure it's followed by whitespace
    let wrappers = [
        "sudo", "env", "time", "nice", "ionice", "strace", "ltrace", "perf", "taskset", "numactl",
    ];

    loop {
        let mut changed = false;
        for wrapper in wrappers {
            if let Some(rest) = result.strip_prefix(wrapper) {
                // Must be followed by whitespace or end of string
                // (e.g., "sudo" matches "sudo ls", but not "sudoku")
                if rest.is_empty() || rest.starts_with(char::is_whitespace) {
                    result = rest.trim_start();
                    changed = true;

                    // Strip flags that might follow the wrapper (e.g., "time -v", "sudo -E")
                    // We heuristically strip any token starting with '-' until we find a non-flag.
                    while result.starts_with('-') {
                        // Find the end of this token
                        let end_idx = result.find(char::is_whitespace).unwrap_or(result.len());

                        // Safety: we checked starts_with('-'), so token is not empty
                        result = result[end_idx..].trim_start();
                    }
                }
            }
        }

        // Handle env VAR=val syntax
        // Logic: if result starts with VAR=val (potentially quoted), strip it.
        // We need to parse the first token respecting quotes.
        let chars = result.chars();
        let mut token_len = 0;
        let mut in_quote = None; // None, Some('\''), Some('"')
        let mut escaped = false;
        let mut has_equals = false;
        let mut has_space = false;

        for c in chars {
            if escaped {
                escaped = false;
                token_len += c.len_utf8();
                continue;
            }

            if c == '\\' {
                escaped = true;
                token_len += c.len_utf8();
                continue;
            }

            if let Some(q) = in_quote {
                if c == q {
                    in_quote = None;
                } else if c == '=' {
                    has_equals = true;
                }
                token_len += c.len_utf8();
            } else if c == '"' || c == '\'' {
                in_quote = Some(c);
                token_len += c.len_utf8();
            } else if c.is_whitespace() {
                has_space = true;
                break;
            } else {
                if c == '=' {
                    has_equals = true;
                }
                token_len += c.len_utf8();
            }
        }

        if has_equals && in_quote.is_none() && has_space {
            // It was a complete token with an equals sign followed by space.
            // We assume it's an env var and strip it.
            result = result[token_len..].trim_start();
            changed = true;
        }

        // Strip absolute paths: /usr/bin/cargo -> cargo
        // We assume the command is the first word
        if result.starts_with('/') {
            if let Some(space_idx) = result.find(' ') {
                let cmd_part = &result[..space_idx];
                if let Some(last_slash) = cmd_part.rfind('/') {
                    // Result becomes substring starting after the last slash of the command word
                    result = &result[last_slash + 1..];
                    changed = true;
                }
            } else {
                // Single word command
                if let Some(last_slash) = result.rfind('/') {
                    result = &result[last_slash + 1..];
                    changed = true;
                }
            }
        }

        if !changed {
            break;
        }
    }

    if result == cmd {
        Cow::Borrowed(cmd)
    } else {
        Cow::Owned(result.to_string())
    }
}

/// Check if a command contains file redirects (NOT fd-to-fd redirects like `2>&1`).
///
/// Returns true for file redirects: `> file`, `>> file`, `2> file`, `&> file`
/// Returns false for fd-to-fd redirects: `2>&1`, `>&2`, `1>&2`
/// Also returns true for input redirects: `< file`
///
/// This is used by `try_classify_compound_command` which needs a quick text-level
/// check before doing more expensive parsing.
fn has_file_redirect(cmd: &str) -> bool {
    let bytes = cmd.as_bytes();
    let len = bytes.len();
    let mut in_single = false;
    let mut in_double = false;
    let mut escaped = false;
    let mut i = 0;

    while i < len {
        let b = bytes[i];

        if escaped {
            escaped = false;
            i += 1;
            continue;
        }
        if b == b'\\' {
            escaped = true;
            i += 1;
            continue;
        }
        match b {
            b'\'' if !in_double => {
                in_single = !in_single;
            }
            b'"' if !in_single => {
                in_double = !in_double;
            }
            b'>' if !in_single && !in_double => {
                // Check if this is a fd-to-fd redirect (N>&M or >&N)
                if i + 1 < len && bytes[i + 1] == b'&' {
                    // >&N or N>&M — fd-to-fd, skip
                    i += 2; // skip > and &
                    // skip optional digit
                    if i < len && bytes[i].is_ascii_digit() {
                        i += 1;
                    }
                    continue;
                }
                // >( is process substitution, not a file redirect per se,
                // but it's caught by the subshell check separately
                if i + 1 < len && bytes[i + 1] == b'(' {
                    i += 1;
                    continue;
                }
                return true; // File redirect: > file, >> file, N> file
            }
            b'<' if !in_single && !in_double => {
                // <( is process substitution, caught separately
                if i + 1 < len && bytes[i + 1] == b'(' {
                    i += 1;
                    continue;
                }
                return true; // Input redirect: < file
            }
            _ => {}
        }
        i += 1;
    }
    false
}

/// Check command structure for patterns that shouldn't be intercepted.
///
/// Performance: single-pass O(n) state machine instead of 11+ separate scans.
/// This is critical because structure analysis runs on EVERY command.
///
/// Detection priority (matches original behavior):
/// 1. Embedded newlines (security - command injection)
/// 2. Standalone & (backgrounding)
/// 3. Single | pipe (not ||)
/// 4. Subshell ( or >( or <(
/// 5. Output redirection >
/// 6. Input redirection <
/// 7. Semicolon ;
/// 8. && chaining
/// 9. || chaining
/// 10. Subshell capture $( or backtick
fn check_structure(cmd: &str) -> Option<&'static str> {
    let bytes = cmd.as_bytes();
    let len = bytes.len();

    let mut in_single = false;
    let mut in_double = false;
    let mut escaped = false;

    // Track what we find (in priority order, lower = higher priority)
    // Using Option to track if found, with priority encoded by check order
    let mut found_backgrounded = false;
    let mut found_piped = false;
    let mut found_subshell = false;
    let mut found_output_redirect = false;
    let mut found_input_redirect = false;
    let mut found_semicolon = false;
    let mut found_and_chain = false;
    let mut found_or_chain = false;
    let mut found_subshell_capture = false;

    let mut i = 0;
    while i < len {
        let b = bytes[i];

        // Handle escape sequences
        if escaped {
            escaped = false;
            i += 1;
            continue;
        }
        if b == b'\\' {
            escaped = true;
            i += 1;
            continue;
        }

        // Handle quote state transitions
        if b == b'\'' && !in_double {
            in_single = !in_single;
            i += 1;
            continue;
        }
        if b == b'"' && !in_single {
            in_double = !in_double;
            i += 1;
            continue;
        }

        // Skip quoted content
        if in_single || in_double {
            i += 1;
            continue;
        }

        // Check for problematic characters/patterns (unquoted)
        match b {
            // Embedded newlines - return immediately (highest priority, security issue)
            b'\n' | b'\r' => return Some("contains embedded newline"),

            // Ampersand: check for && vs standalone &
            b'&' => {
                if i + 1 < len && bytes[i + 1] == b'&' {
                    found_and_chain = true;
                    i += 1; // Skip second &
                } else {
                    // Check for redirection patterns like 2>&1 or &>
                    let prev = if i > 0 { bytes[i - 1] } else { 0 };
                    let next = if i + 1 < len { bytes[i + 1] } else { 0 };
                    if prev != b'>' && next != b'>' {
                        found_backgrounded = true;
                    }
                }
            }

            // Pipe: check for || vs single |
            b'|' => {
                if i + 1 < len && bytes[i + 1] == b'|' {
                    found_or_chain = true;
                    i += 1; // Skip second |
                } else {
                    found_piped = true;
                }
            }

            // Subshell/process substitution
            b'(' => found_subshell = true,

            // Output redirection (>( is process substitution, caught by ( check)
            // fd-to-fd redirects like 2>&1, >&2 are safe to intercept
            b'>' => {
                if i + 1 < len && bytes[i + 1] == b'(' {
                    found_subshell = true;
                } else if i + 1 < len && bytes[i + 1] == b'&' {
                    // Pattern: N>&M or >&N (fd-to-fd redirect) — safe, skip
                    // e.g. 2>&1, 1>&2, >&2
                    // Skip the '&' and any following digit
                    i += 1; // skip '&'
                    if i + 1 < len && bytes[i + 1].is_ascii_digit() {
                        i += 1; // skip digit after &
                    }
                } else if i + 1 < len && bytes[i + 1] == b'>' {
                    // Append redirect >> (to file) — NOT safe
                    found_output_redirect = true;
                    i += 1; // skip second >
                } else {
                    found_output_redirect = true;
                }
            }

            // Input redirection (<( is process substitution, caught by ( check)
            b'<' => {
                if i + 1 < len && bytes[i + 1] == b'(' {
                    found_subshell = true;
                } else {
                    found_input_redirect = true;
                }
            }

            // Semicolon chaining
            b';' => found_semicolon = true,

            // Backtick subshell capture
            b'`' => found_subshell_capture = true,

            // Dollar sign: check for $( subshell capture
            b'$' if i + 1 < len && bytes[i + 1] == b'(' => {
                found_subshell_capture = true;
            }

            _ => {}
        }

        i += 1;
    }

    // Return in priority order (matches original check_structure behavior)
    if found_backgrounded {
        return Some("backgrounded command");
    }
    // Pipe check: only if not ||
    if found_piped && !found_or_chain {
        return Some("piped command");
    }
    if found_subshell {
        return Some("subshell execution");
    }
    if found_output_redirect {
        return Some("output redirected");
    }
    if found_input_redirect {
        return Some("input redirected");
    }
    if found_semicolon {
        return Some("chained command (;)");
    }
    if found_and_chain {
        return Some("chained command (&&)");
    }
    if found_or_chain {
        return Some("chained command (||)");
    }
    if found_subshell_capture {
        return Some("subshell capture");
    }

    None
}

/// Check if command contains any compilation keyword (SIMD-accelerated).
fn contains_compilation_keyword(cmd: &str) -> bool {
    let cmd_bytes = cmd.as_bytes();
    for keyword in COMPILATION_KEYWORDS {
        if memmem::find(cmd_bytes, keyword.as_bytes()).is_some() {
            return true;
        }
    }
    false
}

/// Full classification of a command (Tier 4).
fn classify_full(cmd: &str) -> Classification {
    // Cargo commands
    if cmd.starts_with("cargo ") || cmd == "cargo" {
        return classify_cargo(cmd);
    }

    // rustc
    if cmd.starts_with("rustc ") || cmd == "rustc" {
        return Classification::compilation(CompilationKind::Rustc, 0.95, "rustc invocation");
    }

    // GCC
    if cmd.starts_with("gcc ")
        && (cmd.contains(" -c ") || cmd.contains(" -o ") || cmd.contains(".c"))
    {
        return Classification::compilation(CompilationKind::Gcc, 0.90, "gcc compilation");
    }

    // G++
    if cmd.starts_with("g++ ")
        && (cmd.contains(" -c ")
            || cmd.contains(" -o ")
            || cmd.contains(".cpp")
            || cmd.contains(".cc"))
    {
        return Classification::compilation(CompilationKind::Gpp, 0.90, "g++ compilation");
    }

    // Clang
    if cmd.starts_with("clang ")
        && !cmd.starts_with("clang++ ")
        && (cmd.contains(" -c ") || cmd.contains(" -o ") || cmd.contains(".c"))
    {
        return Classification::compilation(CompilationKind::Clang, 0.90, "clang compilation");
    }

    // Clang++
    if cmd.starts_with("clang++ ")
        && (cmd.contains(" -c ")
            || cmd.contains(" -o ")
            || cmd.contains(".cpp")
            || cmd.contains(".cc"))
    {
        return Classification::compilation(CompilationKind::Clangpp, 0.90, "clang++ compilation");
    }

    // cc (standard C compiler)
    if cmd.starts_with("cc ")
        && (cmd.contains(" -c ") || cmd.contains(" -o ") || cmd.contains(".c"))
    {
        return Classification::compilation(CompilationKind::Gcc, 0.85, "cc compilation");
    }

    // c++ (standard C++ compiler)
    if cmd.starts_with("c++ ")
        && (cmd.contains(" -c ")
            || cmd.contains(" -o ")
            || cmd.contains(".cpp")
            || cmd.contains(".cc"))
    {
        return Classification::compilation(CompilationKind::Gpp, 0.85, "c++ compilation");
    }

    // Make
    if cmd.starts_with("make") && (cmd == "make" || cmd.starts_with("make ")) {
        // Don't intercept "make clean", "make install", etc.
        if cmd.contains("clean") || cmd.contains("install") || cmd.contains("distclean") {
            return Classification::not_compilation("make maintenance command");
        }
        return Classification::compilation(CompilationKind::Make, 0.85, "make build");
    }

    // CMake build (only when cmake is the invoked command)
    if cmd.starts_with("cmake ") || cmd == "cmake" {
        let mut tokens = cmd.split_whitespace();
        let _ = tokens.next(); // "cmake"
        if tokens.any(|token| token == "--build" || token.starts_with("--build=")) {
            return Classification::compilation(CompilationKind::CmakeBuild, 0.90, "cmake --build");
        }
    }

    // Ninja
    if cmd.starts_with("ninja") && (cmd == "ninja" || cmd.starts_with("ninja ")) {
        if cmd.contains("-t clean") || cmd.contains("clean") {
            return Classification::not_compilation("ninja clean");
        }
        return Classification::compilation(CompilationKind::Ninja, 0.90, "ninja build");
    }

    // Meson (only when meson is the invoked command)
    if cmd.starts_with("meson ") || cmd == "meson" {
        let mut tokens = cmd.split_whitespace();
        let _ = tokens.next(); // "meson"
        let mut subcommand = None;
        for token in tokens {
            if token.starts_with('-') {
                continue;
            }
            subcommand = Some(token);
            break;
        }
        if matches!(subcommand, Some("compile")) {
            return Classification::compilation(CompilationKind::Meson, 0.85, "meson compile");
        }
    }

    // Bun commands
    let mut tokens = cmd.split_whitespace();
    if tokens.next() == Some("bun") {
        match tokens.next() {
            Some("test") => {
                // Check for --watch flag - don't intercept interactive mode
                // Clone the iterator to check remaining args
                if tokens.any(|a| a == "-w" || a == "--watch") {
                    return Classification::not_compilation(
                        "bun test --watch is interactive (not intercepted)",
                    );
                }
                return Classification::compilation(
                    CompilationKind::BunTest,
                    0.95,
                    "bun test command",
                );
            }
            Some("typecheck") => {
                // Check for --watch flag - don't intercept interactive mode
                if tokens.any(|a| a == "-w" || a == "--watch") {
                    return Classification::not_compilation(
                        "bun typecheck --watch is interactive (not intercepted)",
                    );
                }
                return Classification::compilation(
                    CompilationKind::BunTypecheck,
                    0.95,
                    "bun typecheck command",
                );
            }
            Some("x") => {
                // bun x (alias for bunx - package runner)
                // NOT intercepted - similar to npx, runs arbitrary packages
                return Classification::not_compilation("bun x runs arbitrary packages");
            }
            _ => {}
        }
    }

    Classification::not_compilation("no matching pattern")
}

/// Classify cargo subcommands.
///
/// Performance: uses iterator `.nth()` to avoid Vec allocation on the hot path.
/// We only need tokens 0-3 (cargo, [+toolchain], subcommand, [nextest-subcommand]).
fn classify_cargo(cmd: &str) -> Classification {
    let mut tokens = cmd.split_whitespace();

    // Token 0: "cargo" (already validated by caller)
    let _cargo = tokens.next();

    // Token 1: subcommand or +toolchain
    let Some(token1) = tokens.next() else {
        return Classification::not_compilation("bare cargo command");
    };

    // Handle toolchain overrides (e.g., cargo +nightly build)
    let subcommand = if token1.starts_with('+') {
        let Some(sub) = tokens.next() else {
            return Classification::not_compilation("cargo +toolchain without subcommand");
        };
        sub
    } else {
        token1
    };

    match subcommand {
        "build" | "b" => {
            Classification::compilation(CompilationKind::CargoBuild, 0.95, "cargo build")
        }
        "test" | "t" => Classification::compilation(CompilationKind::CargoTest, 0.95, "cargo test"),
        "check" | "c" => {
            Classification::compilation(CompilationKind::CargoCheck, 0.90, "cargo check")
        }
        "clippy" => Classification::compilation(CompilationKind::CargoClippy, 0.90, "cargo clippy"),
        "doc" => Classification::compilation(CompilationKind::CargoDoc, 0.85, "cargo doc"),
        "run" | "r" => {
            // cargo run compiles first, so it's a compilation command
            Classification::compilation(
                CompilationKind::CargoBuild,
                0.85,
                "cargo run (includes build)",
            )
        }
        "bench" => Classification::compilation(CompilationKind::CargoBench, 0.90, "cargo bench"),
        "nextest" => {
            // cargo nextest has subcommands: run, list, archive, show
            // Only intercept "run" - the actual test execution
            // Next token is the nextest subcommand (e.g., "run", "list")
            let Some(nextest_sub) = tokens.next() else {
                return Classification::not_compilation("bare cargo nextest without subcommand");
            };

            match nextest_sub {
                "run" | "r" => Classification::compilation(
                    CompilationKind::CargoNextest,
                    0.95,
                    "cargo nextest run",
                ),
                _ => Classification::not_compilation("cargo nextest subcommand not interceptable"),
            }
        }
        _ => Classification::not_compilation("cargo subcommand not interceptable"),
    }
}

/// Split a shell command string on unquoted `;`, `&&`, and `||` operators.
///
/// Returns a list of sub-commands with each segment trimmed of whitespace.
/// Characters inside single quotes, double quotes, or backticks are treated
/// as literal and are never split. Escaped quotes (`\'`, `\"`) do not toggle
/// quote state. Pipes (`|`) within a segment are preserved (they are part of
/// one command, not a command separator).
///
/// Performance: single-pass O(n) character state machine, no regex, no heap
/// allocation for the common single-command case.
pub fn split_shell_commands(cmd: &str) -> Vec<&str> {
    let bytes = cmd.as_bytes();
    let len = bytes.len();
    let mut segments: Vec<&str> = Vec::new();
    let mut start = 0;
    let mut i = 0;

    // Quote state
    let mut in_single = false;
    let mut in_double = false;
    let mut in_backtick = false;
    let mut escaped = false;

    while i < len {
        let b = bytes[i];

        if escaped {
            escaped = false;
            i += 1;
            continue;
        }

        if b == b'\\' {
            escaped = true;
            i += 1;
            continue;
        }

        // Toggle quote state
        if !in_double && !in_backtick && b == b'\'' {
            in_single = !in_single;
            i += 1;
            continue;
        }
        if !in_single && !in_backtick && b == b'"' {
            in_double = !in_double;
            i += 1;
            continue;
        }
        if !in_single && !in_double && b == b'`' {
            in_backtick = !in_backtick;
            i += 1;
            continue;
        }

        // Only split when outside all quotes
        if in_single || in_double || in_backtick {
            i += 1;
            continue;
        }

        // Check for `&&`
        if b == b'&' && i + 1 < len && bytes[i + 1] == b'&' {
            let seg = cmd[start..i].trim();
            if !seg.is_empty() {
                segments.push(seg);
            }
            i += 2;
            start = i;
            continue;
        }

        // Check for `||`
        if b == b'|' && i + 1 < len && bytes[i + 1] == b'|' {
            let seg = cmd[start..i].trim();
            if !seg.is_empty() {
                segments.push(seg);
            }
            i += 2;
            start = i;
            continue;
        }

        // Check for `;`
        if b == b';' {
            let seg = cmd[start..i].trim();
            if !seg.is_empty() {
                segments.push(seg);
            }
            i += 1;
            start = i;
            continue;
        }

        i += 1;
    }

    // Push the final segment
    let seg = cmd[start..].trim();
    if !seg.is_empty() {
        segments.push(seg);
    }

    segments
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_guard;

    #[test]
    fn test_cargo_build_with_toolchain() {
        let _guard = test_guard!();
        let result = classify_command("cargo +nightly build");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoBuild));
    }

    #[test]
    fn test_cargo_test_with_toolchain() {
        let _guard = test_guard!();
        let result = classify_command("cargo +1.80.0 test");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_nextest_with_toolchain() {
        let _guard = test_guard!();
        let result = classify_command("cargo +nightly nextest run");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));
    }

    #[test]
    fn test_cargo_build() {
        let _guard = test_guard!();
        let result = classify_command("cargo build");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoBuild));
        assert!(result.confidence >= 0.90);
    }

    #[test]
    fn test_cargo_build_release() {
        let _guard = test_guard!();
        let result = classify_command("cargo build --release");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoBuild));
    }

    #[test]
    fn test_cargo_test() {
        let _guard = test_guard!();
        let result = classify_command("cargo test");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_fmt_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("cargo fmt");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_cargo_install_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("cargo install ripgrep");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_piped_command_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("cargo build 2>&1 | grep error");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("piped"));
    }

    #[test]
    fn test_backgrounded_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("cargo build &");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("background"));
    }

    #[test]
    fn test_newline_injection_not_intercepted() {
        let _guard = test_guard!();
        // Newlines could cause command injection via `sh -c`
        let result = classify_command("cargo build\nrm -rf /");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("newline"));

        let result = classify_command("cargo build\r\nrm -rf /");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("newline"));
    }

    #[test]
    fn test_redirected_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("cargo build > log.txt");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("redirect"));
    }

    #[test]
    fn test_input_redirected_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("cargo build < input.txt");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("input redirected"));
    }

    #[test]
    fn test_process_substitution_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("cargo build --config <(echo ...)");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("subshell execution"));
    }

    #[test]
    fn test_subshell_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("(cargo build)");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("subshell execution"));
    }

    #[test]
    fn test_gcc_compile() {
        let _guard = test_guard!();
        let result = classify_command("gcc -c main.c -o main.o");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::Gcc));
    }

    #[test]
    fn test_make() {
        let _guard = test_guard!();
        let result = classify_command("make -j8");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::Make));
    }

    #[test]
    fn test_make_clean_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("make clean");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("make maintenance command"));
    }

    #[test]
    fn test_cmake_build_requires_cmake_command() {
        let _guard = test_guard!();
        let result = classify_command("echo cmake --build .");
        assert!(!result.is_compilation);
    }

    #[test]
    fn test_cmake_build_with_equals_flag() {
        let _guard = test_guard!();
        let result = classify_command("cmake --build=build");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CmakeBuild));
    }

    #[test]
    fn test_meson_compile_requires_meson_command() {
        let _guard = test_guard!();
        let result = classify_command("echo meson compile");
        assert!(!result.is_compilation);
    }

    #[test]
    fn test_non_compilation() {
        let _guard = test_guard!();
        let result = classify_command("ls -la");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("no compilation keyword"));
    }

    #[test]
    fn test_empty_command() {
        let _guard = test_guard!();
        let result = classify_command("");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("empty command"));
    }

    // Bun tests - keyword detection and never-intercept patterns

    #[test]
    fn test_bun_keyword_detected() {
        let _guard = test_guard!();
        // Verify "bun" triggers keyword detection (Tier 2 passes)
        assert!(contains_compilation_keyword("bun test"));
        assert!(contains_compilation_keyword("bun typecheck"));
        assert!(contains_compilation_keyword("bun install")); // keyword present, but will be blocked in Tier 3
    }

    #[test]
    fn test_bun_install_not_intercepted() {
        let _guard = test_guard!();
        // Package management - modifies node_modules
        let result = classify_command("bun install");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_add_not_intercepted() {
        let _guard = test_guard!();
        // Adding packages - modifies package.json and node_modules
        let result = classify_command("bun add lodash");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_remove_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("bun remove lodash");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_run_not_intercepted() {
        let _guard = test_guard!();
        // Generic script runner - could do anything
        let result = classify_command("bun run build");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_build_not_intercepted() {
        let _guard = test_guard!();
        // Creates bundles in local directory
        let result = classify_command("bun build ./src/index.ts");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_version_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("bun --version");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));

        let result = classify_command("bun -v");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_dev_not_intercepted() {
        let _guard = test_guard!();
        // Development server needs local ports
        let result = classify_command("bun dev");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_repl_not_intercepted() {
        let _guard = test_guard!();
        // Interactive REPL
        let result = classify_command("bun repl");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_link_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("bun link");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_init_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("bun init");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_create_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("bun create next-app");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_pm_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("bun pm cache");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bun_help_not_intercepted() {
        let _guard = test_guard!();
        let result = classify_command("bun --help");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));

        let result = classify_command("bun -h");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    // Bun Tier 4 classification tests

    #[test]
    fn test_bun_test_classification() {
        let _guard = test_guard!();
        // Basic command
        let result = classify_command("bun test");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::BunTest));
        assert!((result.confidence - 0.95).abs() < 0.001);

        // With directory argument
        let result = classify_command("bun test src/");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::BunTest));

        // With coverage flag (non-interactive)
        let result = classify_command("bun test --coverage");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::BunTest));

        // Specific file
        let result = classify_command("bun test auth.test.ts");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::BunTest));

        // With multiple flags
        let result = classify_command("bun test --bail --timeout 5000");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::BunTest));

        // With reporter
        let result = classify_command("bun test --reporter json");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::BunTest));
    }

    #[test]
    fn test_bun_test_watch_not_intercepted() {
        let _guard = test_guard!();
        // --watch mode is interactive and should NOT be intercepted
        let result = classify_command("bun test --watch");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("interactive"));

        // Watch with other flags
        let result = classify_command("bun test --watch --coverage");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("interactive"));

        // Watch with directory
        let result = classify_command("bun test src/ --watch");
        assert!(!result.is_compilation);

        // Short form -w
        let result = classify_command("bun test -w");
        assert!(!result.is_compilation);

        // Short form with args
        let result = classify_command("bun test -w src/");
        assert!(!result.is_compilation);
    }

    #[test]
    fn test_bun_typecheck_watch_not_intercepted() {
        let _guard = test_guard!();
        // --watch mode is interactive and should NOT be intercepted
        let result = classify_command("bun typecheck --watch");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("interactive"));

        // Short form -w
        let result = classify_command("bun typecheck -w");
        assert!(!result.is_compilation);
    }

    #[test]
    fn test_bun_typecheck_classification() {
        let _guard = test_guard!();
        // Basic command
        let result = classify_command("bun typecheck");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::BunTypecheck));
        assert!((result.confidence - 0.95).abs() < 0.001);

        // With directory argument
        let result = classify_command("bun typecheck src/");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::BunTypecheck));

        // NOTE: --watch mode is tested separately in test_bun_typecheck_watch_not_intercepted
        // It should NOT be intercepted as it's interactive
    }

    #[test]
    fn test_bun_edge_cases_not_matched() {
        let _guard = test_guard!();
        // Invalid commands should not match
        let result = classify_command("bun testing");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("no matching pattern"));

        let result = classify_command("bun typechecker");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("no matching pattern"));

        let result = classify_command("bun type");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("no matching pattern"));

        // bun x should not be intercepted (runs arbitrary packages like npx)
        let result = classify_command("bun x eslint");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("bun x runs arbitrary packages"));

        let result = classify_command("bun x prettier --write .");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("bun x runs arbitrary packages"));

        let result = classify_command("bun x vitest run");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("bun x runs arbitrary packages"));
    }

    #[test]
    fn test_bun_test_vs_never_intercept() {
        let _guard = test_guard!();
        // bun test should NOT be blocked by never-intercept
        let result = classify_command("bun test");
        assert!(!result.reason.contains("never-intercept"));
        assert!(result.is_compilation);
    }

    #[test]
    fn test_bun_typecheck_vs_never_intercept() {
        let _guard = test_guard!();
        // bun typecheck should NOT be blocked by never-intercept
        let result = classify_command("bun typecheck");
        assert!(!result.reason.contains("never-intercept"));
        assert!(result.is_compilation);
    }

    // Bun CompilationKind serialization tests

    #[test]
    fn test_bun_compilation_kind_serde() {
        let _guard = test_guard!();
        // BunTest serialization
        let kind = CompilationKind::BunTest;
        let json = serde_json::to_string(&kind).unwrap();
        assert_eq!(json, "\"bun_test\"");
        let parsed: CompilationKind = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, CompilationKind::BunTest);

        // BunTypecheck serialization
        let kind = CompilationKind::BunTypecheck;
        let json = serde_json::to_string(&kind).unwrap();
        assert_eq!(json, "\"bun_typecheck\"");
        let parsed: CompilationKind = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, CompilationKind::BunTypecheck);
    }

    #[test]
    fn test_bun_kinds_are_distinct() {
        let _guard = test_guard!();
        // BunTest and BunTypecheck are different
        assert_ne!(CompilationKind::BunTest, CompilationKind::BunTypecheck);
        // BunTest is different from CargoTest (different ecosystems)
        assert_ne!(CompilationKind::BunTest, CompilationKind::CargoTest);
    }

    #[test]
    fn test_wrapped_command_classification_repro() {
        let _guard = test_guard!();
        // This fails currently because classify_full expects command to start with "cargo"
        // Wrapper tools like "time", "sudo", "env" break this logic
        let result = classify_command("time cargo build");
        assert!(
            result.is_compilation,
            "Should classify 'time cargo build' as compilation"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoBuild));

        let result = classify_command("sudo cargo check");
        assert!(
            result.is_compilation,
            "Should classify 'sudo cargo check' as compilation"
        );

        let result = classify_command("env RUST_BACKTRACE=1 cargo test");
        assert!(
            result.is_compilation,
            "Should classify env-wrapped cargo test as compilation"
        );

        let result = classify_command("env 'CARGO_TARGET_DIR=/data/tmp/rch-target' cargo build");
        assert!(
            result.is_compilation,
            "Should classify shell-quoted env assignment before cargo build as compilation"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoBuild));
    }

    // =========================================================================
    // Bun E2E Edge Case Tests (from bead remote_compilation_helper-65m)
    // =========================================================================

    #[test]
    fn test_bun_piped_commands_not_intercepted() {
        let _guard = test_guard!();
        // Piped commands should be rejected at Tier 1 (structure analysis)
        let result = classify_command("bun test | grep error");
        assert!(!result.is_compilation);
        assert!(
            result.reason.contains("piped"),
            "Should be rejected as piped command"
        );

        // Piped with output filtering
        let result = classify_command("bun test 2>&1 | tee output.log");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("piped"));

        // Piped typecheck
        let result = classify_command("bun typecheck | head -20");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("piped"));
    }

    #[test]
    fn test_bunx_tsc_not_intercepted() {
        let _guard = test_guard!();
        // bunx (bun x) runs arbitrary packages - should NOT be intercepted
        // even for typecheck-like commands like tsc
        let result = classify_command("bun x tsc --noEmit");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("bun x"));

        // bunx with other tools
        let result = classify_command("bun x eslint .");
        assert!(!result.is_compilation);

        let result = classify_command("bun x prettier --write .");
        assert!(!result.is_compilation);

        let result = classify_command("bun x vitest run");
        assert!(!result.is_compilation);
    }

    #[test]
    fn test_bun_redirected_not_intercepted() {
        let _guard = test_guard!();
        // Output redirection should be rejected at Tier 1
        let result = classify_command("bun test > results.txt");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("redirect"));

        let result = classify_command("bun typecheck > errors.log");
        assert!(!result.is_compilation);
    }

    #[test]
    fn test_bun_backgrounded_not_intercepted() {
        let _guard = test_guard!();
        // Backgrounded commands should be rejected at Tier 1
        let result = classify_command("bun test &");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("background"));
    }

    #[test]
    fn test_bun_chained_commands_classified() {
        let _guard = test_guard!();
        // Multi-command strings should be rejected
        let result = classify_command("bun test && echo done");
        assert!(
            !result.is_compilation,
            "chained commands should be rejected"
        );
        assert!(result.reason.contains("chained"));

        let result = classify_command("bun typecheck; bun test");
        assert!(
            !result.is_compilation,
            "chained commands should be rejected"
        );
        assert!(result.reason.contains("chained"));
    }

    #[test]
    fn test_bun_subshell_capture_not_intercepted() {
        let _guard = test_guard!();
        // Subshell capture should be rejected at Tier 1
        let result = classify_command("bun test $(echo src/)");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("subshell"));
    }

    #[test]
    fn test_bun_wrapped_commands() {
        let _guard = test_guard!();
        // Wrapped bun commands should still be classified
        // (requires normalize_command to handle wrappers)
        let result = classify_command("time bun test");
        // Currently may or may not work depending on normalize_command
        // This test documents current behavior
        if result.is_compilation {
            assert_eq!(result.kind, Some(CompilationKind::BunTest));
        }

        let result = classify_command("env DEBUG=1 bun test");
        if result.is_compilation {
            assert_eq!(result.kind, Some(CompilationKind::BunTest));
        }
    }

    #[test]
    fn test_classify_command_detailed_matches_basic() {
        let _guard = test_guard!();
        let commands = [
            "cargo build",
            "cargo test --release",
            "bun typecheck",
            "gcc -c main.c -o main.o",
            "ls -la",
        ];

        for cmd in commands {
            let basic = classify_command(cmd);
            let detailed = classify_command_detailed(cmd);
            assert_eq!(basic, detailed.classification);
        }
    }

    #[test]
    fn test_classify_command_detailed_rejects_piped() {
        let _guard = test_guard!();
        let detailed = classify_command_detailed("cargo build | tee log.txt");
        assert!(!detailed.classification.is_compilation);
        let tier1 = detailed.tiers.iter().find(|t| t.tier == 1).unwrap();
        assert_eq!(tier1.decision, TierDecision::Reject);
        assert!(tier1.reason.contains("piped"));
    }

    #[test]
    fn test_classify_command_detailed_normalizes_wrappers() {
        let _guard = test_guard!();
        let detailed = classify_command_detailed("sudo cargo check");
        assert_eq!(detailed.normalized, "cargo check");
        assert!(detailed.classification.is_compilation);
    }

    // =========================================================================
    // Comprehensive cargo test variant tests (bead remote_compilation_helper-xcvl)
    // =========================================================================

    #[test]
    fn test_cargo_test_release() {
        let _guard = test_guard!();
        let result = classify_command("cargo test --release");
        assert!(
            result.is_compilation,
            "cargo test --release should be classified as compilation"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
        assert!(result.confidence >= 0.90);
    }

    #[test]
    fn test_cargo_test_specific_test_name() {
        let _guard = test_guard!();
        let result = classify_command("cargo test my_test_function");
        assert!(
            result.is_compilation,
            "cargo test with specific test name should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_with_nocapture() {
        let _guard = test_guard!();
        let result = classify_command("cargo test -- --nocapture");
        assert!(
            result.is_compilation,
            "cargo test -- --nocapture should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_workspace() {
        let _guard = test_guard!();
        let result = classify_command("cargo test --workspace");
        assert!(
            result.is_compilation,
            "cargo test --workspace should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_package() {
        let _guard = test_guard!();
        let result = classify_command("cargo test -p rch-common");
        assert!(result.is_compilation, "cargo test -p should be classified");
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_short_alias() {
        let _guard = test_guard!();
        // cargo t is an alias for cargo test
        let result = classify_command("cargo t");
        assert!(
            result.is_compilation,
            "cargo t (short alias) should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_all_features() {
        let _guard = test_guard!();
        let result = classify_command("cargo test --all-features");
        assert!(
            result.is_compilation,
            "cargo test --all-features should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_no_default_features() {
        let _guard = test_guard!();
        let result = classify_command("cargo test --no-default-features");
        assert!(
            result.is_compilation,
            "cargo test --no-default-features should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_with_env_var() {
        let _guard = test_guard!();
        let result = classify_command("RUST_BACKTRACE=1 cargo test");
        assert!(
            result.is_compilation,
            "cargo test with env var should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_with_multiple_flags() {
        let _guard = test_guard!();
        let result = classify_command("cargo test --release --workspace -p rch -- --nocapture");
        assert!(
            result.is_compilation,
            "cargo test with multiple flags should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_with_jobs() {
        let _guard = test_guard!();
        let result = classify_command("cargo test -j 8");
        assert!(result.is_compilation, "cargo test -j should be classified");
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_target() {
        let _guard = test_guard!();
        let result = classify_command("cargo test --target x86_64-unknown-linux-gnu");
        assert!(
            result.is_compilation,
            "cargo test --target should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_lib() {
        let _guard = test_guard!();
        let result = classify_command("cargo test --lib");
        assert!(
            result.is_compilation,
            "cargo test --lib should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_bins() {
        let _guard = test_guard!();
        let result = classify_command("cargo test --bins");
        assert!(
            result.is_compilation,
            "cargo test --bins should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_doc() {
        let _guard = test_guard!();
        let result = classify_command("cargo test --doc");
        assert!(
            result.is_compilation,
            "cargo test --doc should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_filter_pattern() {
        let _guard = test_guard!();
        let result = classify_command("cargo test test_classification");
        assert!(
            result.is_compilation,
            "cargo test with filter pattern should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_test_exact() {
        let _guard = test_guard!();
        let result = classify_command("cargo test --exact my_test");
        assert!(
            result.is_compilation,
            "cargo test --exact should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
    }

    // =========================================================================
    // cargo-nextest tests (bead remote_compilation_helper-c7ky)
    // =========================================================================

    #[test]
    fn test_nextest_keyword_detected() {
        let _guard = test_guard!();
        // Verify "nextest" triggers keyword detection (Tier 2 passes)
        assert!(contains_compilation_keyword("cargo nextest run"));
        assert!(contains_compilation_keyword("cargo nextest list"));
    }

    #[test]
    fn test_cargo_nextest_run_classification() {
        let _guard = test_guard!();
        // Basic command
        let result = classify_command("cargo nextest run");
        assert!(
            result.is_compilation,
            "cargo nextest run should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));
        assert!((result.confidence - 0.95).abs() < 0.001);
    }

    #[test]
    fn test_cargo_nextest_run_with_flags() {
        let _guard = test_guard!();
        // With release flag
        let result = classify_command("cargo nextest run --release");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));

        // With profile flag
        let result = classify_command("cargo nextest run --cargo-profile ci");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));

        // With workspace flag
        let result = classify_command("cargo nextest run --workspace");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));

        // With package filter
        let result = classify_command("cargo nextest run -p rch-common");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));

        // With test filter
        let result = classify_command("cargo nextest run test_classification");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));

        // With multiple flags
        let result = classify_command("cargo nextest run --release --no-fail-fast -j 8");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));
    }

    #[test]
    fn test_cargo_nextest_run_short_alias() {
        let _guard = test_guard!();
        // cargo nextest r is an alias for cargo nextest run
        let result = classify_command("cargo nextest r");
        assert!(
            result.is_compilation,
            "cargo nextest r should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));
    }

    #[test]
    fn test_cargo_nextest_list_not_intercepted() {
        let _guard = test_guard!();
        // cargo nextest list only shows tests, doesn't run them
        let result = classify_command("cargo nextest list");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_cargo_nextest_archive_not_intercepted() {
        let _guard = test_guard!();
        // cargo nextest archive creates archives
        let result = classify_command("cargo nextest archive");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_cargo_nextest_show_not_intercepted() {
        let _guard = test_guard!();
        // cargo nextest show displays config info
        let result = classify_command("cargo nextest show");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("never-intercept"));
    }

    #[test]
    fn test_bare_cargo_nextest_not_intercepted() {
        let _guard = test_guard!();
        // bare "cargo nextest" without subcommand
        let result = classify_command("cargo nextest");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("without subcommand"));
    }

    #[test]
    fn test_cargo_nextest_wrapped_commands() {
        let _guard = test_guard!();
        // Wrapped nextest commands should still be classified
        let result = classify_command("time cargo nextest run");
        assert!(
            result.is_compilation,
            "time cargo nextest run should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));

        let result = classify_command("RUST_BACKTRACE=1 cargo nextest run");
        assert!(
            result.is_compilation,
            "env-wrapped cargo nextest run should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));
    }

    #[test]
    fn test_cargo_nextest_compilation_kind_serde() {
        let _guard = test_guard!();
        // CargoNextest serialization
        let kind = CompilationKind::CargoNextest;
        let json = serde_json::to_string(&kind).unwrap();
        assert_eq!(json, "\"cargo_nextest\"");
        let parsed: CompilationKind = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, CompilationKind::CargoNextest);
    }

    #[test]
    fn test_cargo_nextest_vs_cargo_test_distinct() {
        let _guard = test_guard!();
        // CargoNextest and CargoTest are different
        assert_ne!(CompilationKind::CargoNextest, CompilationKind::CargoTest);

        // Both should be classified but as different kinds
        let nextest_result = classify_command("cargo nextest run");
        let test_result = classify_command("cargo test");
        assert!(nextest_result.is_compilation);
        assert!(test_result.is_compilation);
        assert_eq!(nextest_result.kind, Some(CompilationKind::CargoNextest));
        assert_eq!(test_result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_nextest_piped_not_intercepted() {
        let _guard = test_guard!();
        // Piped commands should be rejected at Tier 1
        let result = classify_command("cargo nextest run | grep FAIL");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("piped"));
    }

    #[test]
    fn test_cargo_nextest_redirected_not_intercepted() {
        let _guard = test_guard!();
        // Redirected commands should be rejected at Tier 1
        let result = classify_command("cargo nextest run > results.txt");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("redirect"));
    }

    #[test]
    fn test_cargo_nextest_backgrounded_not_intercepted() {
        let _guard = test_guard!();
        // Backgrounded commands should be rejected at Tier 1
        let result = classify_command("cargo nextest run &");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("background"));
    }

    // =========================================================================
    // cargo bench tests (bead remote_compilation_helper-8o52)
    // =========================================================================

    #[test]
    fn test_cargo_bench_classification() {
        let _guard = test_guard!();
        let result = classify_command("cargo bench");
        assert!(result.is_compilation, "cargo bench should be classified");
        assert_eq!(result.kind, Some(CompilationKind::CargoBench));
        assert!((result.confidence - 0.90).abs() < 0.001);
    }

    #[test]
    fn test_cargo_bench_with_filter() {
        let _guard = test_guard!();
        // Benchmarks with name filter
        let result = classify_command("cargo bench my_bench");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoBench));
    }

    #[test]
    fn test_cargo_bench_with_flags() {
        let _guard = test_guard!();
        // With release flag (benchmarks typically use release)
        let result = classify_command("cargo bench --release");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoBench));

        // With package flag
        let result = classify_command("cargo bench -p rch-common");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoBench));

        // With features
        let result = classify_command("cargo bench --features benchmarks");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoBench));

        // With target filter
        let result = classify_command("cargo bench --bench criterion_bench");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoBench));
    }

    #[test]
    fn test_cargo_bench_wrapped() {
        let _guard = test_guard!();
        // Wrapped with time
        let result = classify_command("time cargo bench");
        assert!(
            result.is_compilation,
            "time cargo bench should be classified"
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoBench));

        // With env var
        let result = classify_command("CARGO_INCREMENTAL=0 cargo bench");
        assert!(result.is_compilation);
        assert_eq!(result.kind, Some(CompilationKind::CargoBench));
    }

    #[test]
    fn test_cargo_bench_serde() {
        let _guard = test_guard!();
        // CargoBench serialization
        let kind = CompilationKind::CargoBench;
        let json = serde_json::to_string(&kind).unwrap();
        assert_eq!(json, "\"cargo_bench\"");
        let parsed: CompilationKind = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, CompilationKind::CargoBench);
    }

    #[test]
    fn test_cargo_bench_distinct_from_test() {
        let _guard = test_guard!();
        // CargoBench and CargoTest are different
        assert_ne!(CompilationKind::CargoBench, CompilationKind::CargoTest);

        // Both should be classified but as different kinds
        let bench_result = classify_command("cargo bench");
        let test_result = classify_command("cargo test");
        assert!(bench_result.is_compilation);
        assert!(test_result.is_compilation);
        assert_eq!(bench_result.kind, Some(CompilationKind::CargoBench));
        assert_eq!(test_result.kind, Some(CompilationKind::CargoTest));
    }

    #[test]
    fn test_cargo_bench_piped_not_intercepted() {
        let _guard = test_guard!();
        // Piped commands should be rejected at Tier 1
        let result = classify_command("cargo bench | tee output.txt");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("piped"));
    }

    #[test]

    fn test_normalize_path_and_wrapper_bug_repro() {
        let _guard = test_guard!();
        // Case: /usr/bin/time cargo build

        // Current behavior: strips path -> "time cargo build", then returns.

        // Desired behavior: strips path -> "time cargo build", then strips wrapper -> "cargo build".

        // This test asserts the CURRENT BROKEN behavior.

        let normalized = normalize_command("/usr/bin/time cargo build");

        assert_eq!(normalized, "cargo build");

        let result = classify_command("/usr/bin/time cargo build");

        assert!(result.is_compilation);
    }

    // ==========================================================================
    // Command Base Tests (bd-785w)
    // ==========================================================================

    #[test]
    fn test_command_base_rust() {
        let _guard = test_guard!();
        assert_eq!(CompilationKind::CargoBuild.command_base(), "cargo");
        assert_eq!(CompilationKind::CargoTest.command_base(), "cargo");
        assert_eq!(CompilationKind::CargoCheck.command_base(), "cargo");
        assert_eq!(CompilationKind::CargoClippy.command_base(), "cargo");
        assert_eq!(CompilationKind::CargoDoc.command_base(), "cargo");
        assert_eq!(CompilationKind::CargoBench.command_base(), "cargo");
        assert_eq!(CompilationKind::CargoNextest.command_base(), "cargo");
        assert_eq!(CompilationKind::Rustc.command_base(), "rustc");
    }

    #[test]
    fn test_command_base_c_cpp() {
        let _guard = test_guard!();
        assert_eq!(CompilationKind::Gcc.command_base(), "gcc");
        assert_eq!(CompilationKind::Gpp.command_base(), "g++");
        assert_eq!(CompilationKind::Clang.command_base(), "clang");
        assert_eq!(CompilationKind::Clangpp.command_base(), "clang++");
    }

    #[test]
    fn test_command_base_build_systems() {
        let _guard = test_guard!();
        assert_eq!(CompilationKind::Make.command_base(), "make");
        assert_eq!(CompilationKind::CmakeBuild.command_base(), "cmake");
        assert_eq!(CompilationKind::Ninja.command_base(), "ninja");
        assert_eq!(CompilationKind::Meson.command_base(), "meson");
    }

    #[test]
    fn test_command_base_bun() {
        let _guard = test_guard!();
        assert_eq!(CompilationKind::BunTest.command_base(), "bun");
        assert_eq!(CompilationKind::BunTypecheck.command_base(), "bun");
    }

    // ==========================================================================
    // Proptest: Command Classification with Random Inputs (bd-2kdm)
    // ==========================================================================

    mod proptest_classification {
        use super::*;
        use proptest::prelude::*;

        // Strategy for arbitrary strings (pure random)
        fn arbitrary_string() -> impl Strategy<Value = String> {
            prop::string::string_regex(".{0,500}").unwrap()
        }

        // Strategy for command-like strings with random suffixes
        fn command_like_string() -> impl Strategy<Value = String> {
            let prefixes = prop::sample::select(vec![
                "cargo", "rustc", "gcc", "g++", "clang", "make", "cmake", "ninja", "bun", "ls",
                "cd", "echo", "cat", "grep", "find", "rm", "mv", "cp", "mkdir",
            ]);
            (prefixes, "[ a-zA-Z0-9_.-]{0,200}")
                .prop_map(|(prefix, suffix)| format!("{}{}", prefix, suffix))
        }

        // Strategy for known compilation commands with random flags
        fn known_command_with_flags() -> impl Strategy<Value = String> {
            let base_commands = prop::sample::select(vec![
                "cargo build",
                "cargo test",
                "cargo check",
                "cargo clippy",
                "cargo run",
                "rustc",
                "gcc",
                "g++",
                "make",
                "bun test",
                "bun typecheck",
            ]);
            let flags = prop::collection::vec(
                prop::sample::select(vec![
                    "--release",
                    "--verbose",
                    "-j8",
                    "-p",
                    "--all",
                    "--workspace",
                    "--lib",
                    "--bin",
                    "-o",
                    "-c",
                ]),
                0..5,
            );
            (base_commands, flags).prop_map(|(cmd, flags)| {
                if flags.is_empty() {
                    cmd.to_string()
                } else {
                    format!("{} {}", cmd, flags.join(" "))
                }
            })
        }

        // Strategy for strings with unicode and control characters
        fn unicode_and_control_chars() -> impl Strategy<Value = String> {
            prop::string::string_regex(
                r"[\x00-\x1f\x80-\xff\u{100}-\u{10FFFF}a-zA-Z0-9 |>&;$()]{0,100}",
            )
            .unwrap()
        }

        // Strategy for shell-like commands with special characters
        fn shell_special_commands() -> impl Strategy<Value = String> {
            let components = prop::sample::select(vec![
                "cargo build",
                "ls -la",
                "echo test",
                "cat file.txt",
                "grep pattern",
            ]);
            let operators = prop::sample::select(vec![
                " | ", " && ", " || ", " ; ", " > ", " < ", " & ", " 2>&1 ", " $(", " `",
            ]);
            prop::collection::vec((components, operators), 1..4).prop_map(|pairs| {
                let mut result = String::new();
                for (i, (comp, op)) in pairs.iter().enumerate() {
                    if i > 0 {
                        result.push_str(op);
                    }
                    result.push_str(comp);
                }
                result
            })
        }

        // Strategy for wrapper-prefixed commands
        fn wrapped_commands() -> impl Strategy<Value = String> {
            let wrappers = prop::sample::select(vec![
                "sudo ",
                "env ",
                "time ",
                "nice ",
                "/usr/bin/time ",
                "RUST_BACKTRACE=1 ",
                "CC=clang ",
                "",
            ]);
            let commands = prop::sample::select(vec![
                "cargo build",
                "cargo test",
                "make",
                "gcc -c main.c",
                "ls -la",
            ]);
            (wrappers, commands).prop_map(|(wrapper, cmd)| format!("{}{}", wrapper, cmd))
        }

        proptest! {
            // Configure proptest for high-volume testing
            #![proptest_config(ProptestConfig::with_cases(1000))]

            // Test 1: Arbitrary strings never cause panics
            #[test]
            fn test_classify_arbitrary_no_panic(s in arbitrary_string()) {
                // Just call classify_command - if it panics, proptest will catch it
                let _ = classify_command(&s);
            }

            // Test 2: Command-like strings never cause panics
            #[test]
            fn test_classify_command_like_no_panic(s in command_like_string()) {
                let _ = classify_command(&s);
            }

            // Test 3: Known commands with flags produce valid classification
            #[test]
            fn test_classify_known_commands_valid(s in known_command_with_flags()) {
                let result = classify_command(&s);
                // Confidence should be in valid range
                prop_assert!(result.confidence >= 0.0 && result.confidence <= 1.0,
                    "Confidence {} out of range for command: {}", result.confidence, s);
                // If is_compilation, must have a kind
                if result.is_compilation {
                    prop_assert!(result.kind.is_some(),
                        "is_compilation=true but kind=None for: {}", s);
                }
            }

            // Test 4: Unicode and control characters never panic
            #[test]
            fn test_classify_unicode_no_panic(s in unicode_and_control_chars()) {
                let _ = classify_command(&s);
            }

            // Test 5: Shell special commands are handled
            #[test]
            fn test_classify_shell_special(s in shell_special_commands()) {
                let result = classify_command(&s);
                // Commands with shell operators should typically NOT be intercepted
                // (pipes, redirects, backgrounding, chaining)
                if s.contains(" | ") || s.contains(" > ") || s.contains(" < ") || s.contains(" & ") {
                    // May or may not be classified depending on quote handling
                    let _ = result; // Just ensure no panic
                }
            }

            // Test 6: Wrapped commands are handled
            #[test]
            fn test_classify_wrapped_commands(s in wrapped_commands()) {
                let result = classify_command(&s);
                prop_assert!(result.confidence >= 0.0 && result.confidence <= 1.0);
            }

            // Test 7: Classification is deterministic
            #[test]
            fn test_classify_deterministic(s in arbitrary_string()) {
                let result1 = classify_command(&s);
                let result2 = classify_command(&s);
                prop_assert_eq!(result1, result2,
                    "Non-deterministic classification for: {}", s);
            }

            // Test 8: Empty-ish strings handled correctly
            #[test]
            fn test_classify_whitespace_variants(s in "[ \t\n\r]{0,20}") {
        let _guard = test_guard!();
                let result = classify_command(&s);
                prop_assert!(!result.is_compilation,
                    "Whitespace-only command should not be classified as compilation: {:?}", s);
                prop_assert!(result.reason.contains("empty") || result.reason.contains("keyword"),
                    "Unexpected reason for whitespace: {}", result.reason);
            }

            // Test 9: Very long commands don't panic
            #[test]
            fn test_classify_long_commands(
                prefix in "cargo (build|test|check)",
                suffix in "[a-zA-Z0-9_ -]{0,10000}"
            ) {
                let long_cmd = format!("{} {}", prefix, suffix);
                let result = classify_command(&long_cmd);
                prop_assert!(result.confidence >= 0.0 && result.confidence <= 1.0);
            }

            // Test 10: Null bytes and special sequences
            #[test]
            fn test_classify_special_bytes(s in prop::collection::vec(any::<u8>(), 0..200)) {
                if let Ok(valid_str) = String::from_utf8(s.clone()) {
                    let _ = classify_command(&valid_str);
                }
                // Non-UTF8 sequences can't be tested with &str
            }
        }

        // Additional targeted proptest tests

        proptest! {
            #![proptest_config(ProptestConfig::with_cases(500))]

            // Test: Cargo subcommands with arbitrary suffixes
            #[test]
            fn test_cargo_subcommand_robustness(
                subcommand in "(build|test|check|clippy|fmt|clean|run|doc|bench|nextest)",
                suffix in "[a-zA-Z0-9_ -]{0,50}"
            ) {
                let cmd = format!("cargo {} {}", subcommand, suffix);
                let result = classify_command(&cmd);
                // Ensure valid result structure
                prop_assert!(result.confidence >= 0.0 && result.confidence <= 1.0);
                // fmt and clean should NEVER be classified as compilation
                if subcommand == "fmt" || subcommand == "clean" {
                    prop_assert!(!result.is_compilation,
                        "cargo {} should not be compilation: {}", subcommand, cmd);
                }
            }

            // Test: Bun commands robustness
            #[test]
            fn test_bun_command_robustness(
                subcommand in "(test|typecheck|install|add|remove|run|build|dev)",
                suffix in "[a-zA-Z0-9_ -]{0,30}"
            ) {
                let cmd = format!("bun {} {}", subcommand, suffix);
                let result = classify_command(&cmd);
                prop_assert!(result.confidence >= 0.0 && result.confidence <= 1.0);
                // install, add, remove, run, build, dev should NOT be compilation
                if matches!(subcommand.as_str(), "install" | "add" | "remove" | "run" | "build" | "dev") {
                    prop_assert!(!result.is_compilation,
                        "bun {} should not be compilation", subcommand);
                }
            }

            // Test: GCC/Clang commands with file patterns
            #[test]
            fn test_c_compiler_robustness(
                compiler in "(gcc|g\\+\\+|clang|clang\\+\\+)",
                flags in "(-[cCoOgW][a-z0-9]* )*",
                file in "[a-zA-Z_][a-zA-Z0-9_]*\\.(c|cpp|cc|h|hpp)"
            ) {
                let cmd = format!("{} {}{}", compiler, flags, file);
                let result = classify_command(&cmd);
                prop_assert!(result.confidence >= 0.0 && result.confidence <= 1.0);
            }

            // Test: Commands with quoted strings preserve correctness
            #[test]
            fn test_quoted_args_handling(
                base in "(cargo build|cargo test|gcc|make)",
                quoted_content in "[a-zA-Z0-9 _-]{0,30}"
            ) {
                // Single quotes
                let cmd_single = format!("{} '{}'", base, quoted_content);
                let _ = classify_command(&cmd_single);

                // Double quotes
                let cmd_double = format!("{} \"{}\"", base, quoted_content);
                let _ = classify_command(&cmd_double);
            }
        }

        // Regression test: ensure specific problematic inputs are handled
        #[test]
        fn test_known_edge_cases() {
            let _guard = test_guard!();
            // These are edge cases that might have caused issues
            let edge_cases = [
                "",
                " ",
                "\t",
                "\n",
                "cargo",
                "cargo ",
                "cargo  ",
                "cargo\tbuild",
                "cargo\nbuild",
                "cargo\rbuild",
                "cargo+nightly",
                "cargo +nightly",
                "cargo +nightly build",
                "  cargo build  ",
                "CARGO_TARGET_DIR=/tmp cargo build",
                "/usr/local/bin/cargo build",
                "~/.cargo/bin/cargo build",
                "./cargo build",
                "../cargo build",
                "cargo build 'test file.rs'",
                "cargo build \"test file.rs\"",
                "cargo build test\\ file.rs",
                "cargo build -- --test-threads=1",
                "cargo build --features \"feat1 feat2\"",
                "cargo build 2>&1",
                "cargo build 2>/dev/null",
                "gcc -DFOO=\"bar baz\" main.c",
                "make -j$(nproc)",
                "ninja -C build",
                "cmake --build . --target all",
                "bun test --timeout 5000 src/",
                "env -i PATH=/usr/bin cargo build",
            ];

            for cmd in edge_cases {
                let result = classify_command(cmd);
                assert!(
                    result.confidence >= 0.0 && result.confidence <= 1.0,
                    "Invalid confidence for: {:?}",
                    cmd
                );
            }
        }

        // Test that detailed classification matches simple classification
        #[test]
        fn test_detailed_matches_simple_proptest() {
            let _guard = test_guard!();
            let test_cases = [
                "cargo build --release",
                "cargo test",
                "make -j8",
                "ls -la",
                "echo hello",
            ];

            for cmd in test_cases {
                let simple = classify_command(cmd);
                let detailed = classify_command_detailed(cmd);
                assert_eq!(simple, detailed.classification, "Mismatch for: {}", cmd);
            }
        }

        // =================== split_shell_commands tests ===================

        #[test]
        fn test_split_single_command() {
            let _guard = test_guard!();
            assert_eq!(split_shell_commands("cargo build"), vec!["cargo build"]);
        }

        #[test]
        fn test_split_and_operator() {
            let _guard = test_guard!();
            assert_eq!(
                split_shell_commands("cargo fmt && cargo build"),
                vec!["cargo fmt", "cargo build"]
            );
        }

        #[test]
        fn test_split_quoted_operator() {
            let _guard = test_guard!();
            assert_eq!(
                split_shell_commands("echo '&&' && cargo build"),
                vec!["echo '&&'", "cargo build"]
            );
        }

        #[test]
        fn test_split_mixed_operators() {
            let _guard = test_guard!();
            assert_eq!(
                split_shell_commands("cd /tmp && make -j4 || echo fail"),
                vec!["cd /tmp", "make -j4", "echo fail"]
            );
        }

        #[test]
        fn test_split_semicolons() {
            let _guard = test_guard!();
            assert_eq!(split_shell_commands("a ; b ; c"), vec!["a", "b", "c"]);
        }

        #[test]
        fn test_split_quoted_semicolon() {
            let _guard = test_guard!();
            assert_eq!(
                split_shell_commands("echo 'hello;world' && make"),
                vec!["echo 'hello;world'", "make"]
            );
        }

        #[test]
        fn test_split_pipe_preserved() {
            let _guard = test_guard!();
            // Single pipe is NOT a command separator
            assert_eq!(
                split_shell_commands("cargo build 2>&1 | tee log"),
                vec!["cargo build 2>&1 | tee log"]
            );
        }

        #[test]
        fn test_split_double_quoted_operator() {
            let _guard = test_guard!();
            assert_eq!(
                split_shell_commands(r#"echo "&&" && cargo build"#),
                vec![r#"echo "&&""#, "cargo build"]
            );
        }

        #[test]
        fn test_split_nested_quotes() {
            let _guard = test_guard!();
            assert_eq!(
                split_shell_commands("echo \"he said 'hello && bye'\" && cargo test"),
                vec!["echo \"he said 'hello && bye'\"", "cargo test"]
            );
        }

        #[test]
        fn test_split_escaped_quote() {
            let _guard = test_guard!();
            // Escaped quotes don't toggle state
            assert_eq!(
                split_shell_commands(r"echo it\'s && cargo build"),
                vec![r"echo it\'s", "cargo build"]
            );
        }

        #[test]
        fn test_split_empty_string() {
            let _guard = test_guard!();
            assert!(split_shell_commands("").is_empty());
        }

        #[test]
        fn test_split_only_whitespace() {
            let _guard = test_guard!();
            assert!(split_shell_commands("   ").is_empty());
        }

        #[test]
        fn test_split_backtick_quoting() {
            let _guard = test_guard!();
            assert_eq!(
                split_shell_commands("echo `echo && fail` && cargo build"),
                vec!["echo `echo && fail`", "cargo build"]
            );
        }

        #[test]
        fn test_split_trailing_operator() {
            let _guard = test_guard!();
            // Trailing && with nothing after should yield just the first segment
            assert_eq!(split_shell_commands("cargo build &&"), vec!["cargo build"]);
        }

        // =================== fail-open safeguard tests (bd-16t3) ===================

        #[test]
        fn test_split_unclosed_single_quote() {
            let _guard = test_guard!();
            // Unclosed quote: everything stays "inside quotes", no split found
            let result = split_shell_commands("echo 'hello && cargo build");
            assert_eq!(result, vec!["echo 'hello && cargo build"]);
        }

        #[test]
        fn test_split_unclosed_double_quote() {
            let _guard = test_guard!();
            let result = split_shell_commands("echo \"hello && cargo build");
            assert_eq!(result, vec!["echo \"hello && cargo build"]);
        }

        #[test]
        fn test_split_unclosed_backtick() {
            let _guard = test_guard!();
            let result = split_shell_commands("echo `hello && cargo build");
            assert_eq!(result, vec!["echo `hello && cargo build"]);
        }

        #[test]
        fn test_split_embedded_nulls() {
            let _guard = test_guard!();
            // Embedded null bytes should not cause panic
            let input = "cargo build\0 && echo done";
            let result = split_shell_commands(input);
            assert_eq!(result.len(), 2);
        }

        #[test]
        fn test_split_unicode_input() {
            let _guard = test_guard!();
            let result = split_shell_commands("echo 'こんにちは' && cargo build");
            assert_eq!(result, vec!["echo 'こんにちは'", "cargo build"]);
        }

        #[test]
        fn test_split_extremely_long_input() {
            let _guard = test_guard!();
            // 20KB string should still work (split_shell_commands has no length limit)
            let long_cmd = format!("echo {} && cargo build", "x".repeat(20_000));
            let result = split_shell_commands(&long_cmd);
            assert_eq!(result.len(), 2);
        }

        #[test]
        fn test_classify_long_input_skips_splitting() {
            let _guard = test_guard!();
            // Commands >10KB skip multi-command splitting in classify_command
            let long_cmd = format!("cargo build && echo {}", "x".repeat(11_000));
            let result = classify_command(&long_cmd);
            // Falls through to single-command classification which rejects at check_structure
            assert!(!result.is_compilation);
            assert!(
                result.reason.to_string().contains("chained"),
                "long input should be rejected by check_structure, not split"
            );
        }

        #[test]
        fn test_split_only_operators() {
            let _guard = test_guard!();
            // Just operators with no commands
            let result = split_shell_commands("&& || ;");
            assert!(
                result.is_empty(),
                "only operators should yield empty result"
            );
        }

        #[test]
        fn test_split_consecutive_operators() {
            let _guard = test_guard!();
            let result = split_shell_commands("cargo build && && echo done");
            // Middle empty segment is dropped, yielding 2 segments
            assert_eq!(result, vec!["cargo build", "echo done"]);
        }

        #[test]
        fn test_classify_empty_after_split() {
            let _guard = test_guard!();
            // All sub-commands are non-compilation
            let result = classify_command("echo hello && ls -la || pwd");
            assert!(!result.is_compilation);
        }

        // =================== comprehensive multi-command tests (bd-1q0e) ===================

        // --- Split edge cases ---

        #[test]
        fn test_split_three_segment_chain() {
            let _guard = test_guard!();
            assert_eq!(
                split_shell_commands("cd /proj && cmake .. && make"),
                vec!["cd /proj", "cmake ..", "make"]
            );
        }

        #[test]
        fn test_split_single_with_flags() {
            let _guard = test_guard!();
            assert_eq!(
                split_shell_commands("cargo build --release"),
                vec!["cargo build --release"]
            );
        }

        #[test]
        fn test_split_nested_quotes_semicolon() {
            let _guard = test_guard!();
            assert_eq!(
                split_shell_commands("echo \"it's && done\" && make"),
                vec!["echo \"it's && done\"", "make"]
            );
        }

        #[test]
        fn test_split_pipe_then_and() {
            let _guard = test_guard!();
            // Single pipe within segment, && between segments
            assert_eq!(
                split_shell_commands("make 2>&1 | grep error && echo done"),
                vec!["make 2>&1 | grep error", "echo done"]
            );
        }

        #[test]
        fn test_split_leading_operator() {
            let _guard = test_guard!();
            // Leading && with nothing before
            assert_eq!(split_shell_commands("&& cargo build"), vec!["cargo build"]);
        }

        // --- Compound command classification tests ---
        // Compound && commands with compilation suffix are now ACCEPTED
        // This enables patterns like "cd /path && cargo build"

        #[test]
        fn test_classify_cargo_fmt_and_build() {
            let _guard = test_guard!();
            // Last segment is "cargo build" (compilation) → accepted
            let result = classify_command("cargo fmt && cargo build");
            assert!(
                result.is_compilation,
                "compound command with compilation suffix should be accepted"
            );
            assert!(result.reason.contains("compound"));
        }

        #[test]
        fn test_classify_cd_and_make() {
            let _guard = test_guard!();
            // Last segment is "make -j8" (compilation) → accepted
            let result = classify_command("cd /project && make -j8");
            assert!(
                result.is_compilation,
                "compound command with compilation suffix should be accepted"
            );
            assert!(result.reason.contains("compound"));
        }
        #[test]
        fn test_classify_export_and_cargo_build() {
            let _guard = test_guard!();
            // Last segment is "cargo build --release" (compilation) → accepted
            let result =
                classify_command("export RUSTFLAGS='-C opt-level=3' && cargo build --release");
            assert!(
                result.is_compilation,
                "compound command with compilation suffix should be accepted"
            );
            assert!(result.reason.contains("compound"));
        }
        #[test]
        fn test_classify_mkdir_cmake_chain() {
            let _guard = test_guard!();
            // Last segment is "cmake --build build" (compilation) → accepted
            let result =
                classify_command("mkdir -p build && cmake -B build && cmake --build build");
            assert!(
                result.is_compilation,
                "compound command with compilation suffix should be accepted"
            );
            assert!(result.reason.contains("compound"));
        }
        #[test]
        fn test_classify_echo_and_cargo_test() {
            let _guard = test_guard!();
            // Last segment is "cargo test" (compilation) → accepted
            let result = classify_command("echo 'Starting...' && cargo test");
            assert!(
                result.is_compilation,
                "compound command with compilation suffix should be accepted"
            );
            assert!(result.reason.contains("compound"));
        }
        #[test]
        fn test_classify_semicolon_chain_with_compilation() {
            let _guard = test_guard!();
            // Semicolon chains are NOT supported (only && is supported)
            let result = classify_command("cargo fmt; cargo build; cargo test");
            assert!(
                !result.is_compilation,
                "semicolon chained commands should be rejected"
            );
            assert!(result.reason.contains("chained"));
        }
        // --- Classification integration: should classify as NON-COMPILATION ---

        #[test]
        fn test_classify_echo_chain_non_compilation() {
            let _guard = test_guard!();
            let result = classify_command("echo hello && echo world");
            assert!(!result.is_compilation);
        }

        #[test]
        fn test_classify_ls_cat_non_compilation() {
            let _guard = test_guard!();
            let result = classify_command("ls -la && cat file.txt");
            assert!(!result.is_compilation);
        }

        #[test]
        fn test_classify_git_chain_non_compilation() {
            let _guard = test_guard!();
            let result = classify_command("git status && git log");
            assert!(!result.is_compilation);
        }

        // --- Performance test ---

        #[test]
        fn test_classify_multi_command_performance() {
            let _guard = test_guard!();
            let start = std::time::Instant::now();
            for _ in 0..100 {
                let _ = classify_command("cargo fmt && cargo build && cargo test");
            }
            let elapsed = start.elapsed();
            let per_call_us = elapsed.as_micros() / 100;
            // Each classify_command call should be well under 5ms
            assert!(
                per_call_us < 5_000,
                "classify_command took {}us per call, should be <5000us",
                per_call_us
            );
            eprintln!(
                "[perf] classify_command multi-command: {}us avg per call",
                per_call_us
            );
        }

        // --- Pipe preservation with split ---

        #[test]
        fn test_classify_pipe_preserved_in_segment() {
            let _guard = test_guard!();
            // Pipe within a segment is NOT a split point; segment stays whole
            // and gets rejected by check_structure (piped command)
            let result = classify_command("cargo build 2>&1 | tee log");
            assert!(!result.is_compilation, "piped command should be rejected");
        }

        #[test]
        fn test_classify_pipe_segment_and_operator() {
            let _guard = test_guard!();
            // Pipe within first segment, && separates from second
            let result = classify_command("make 2>&1 | grep error && cargo build");
            // Should be rejected due to chaining (&&) AND piping (|)
            assert!(
                !result.is_compilation,
                "chained commands should be rejected"
            );
            // The reason will likely be "chained command (&&)" because check_structure checks separators first or pipes first?
            // Let's check check_structure impl: pipes are checked AFTER backgrounding, separators are after pipes?
            // Actually, check_structure checks pipes, then redirects, then chaining.
            // So "piped command" might be the reason. Either is fine.
            assert!(result.reason.contains("piped") || result.reason.contains("chained"));
        }
    }

    // =========================================================================
    // WS2.4: Zero-allocation reject path tests (bd-3mog)
    //
    // Verify that the Cow<'static, str> conversion in Classification and
    // ClassificationTier produces Cow::Borrowed on the reject path (zero heap
    // allocations) and that serde roundtrips work correctly.
    // =========================================================================

    /// Helper: assert that a Cow is the Borrowed variant (no heap allocation).
    /// We need the actual &Cow to distinguish Borrowed from Owned.
    #[allow(clippy::ptr_arg)]
    fn assert_cow_borrowed(cow: &Cow<'static, str>, context: &str) {
        assert!(
            matches!(cow, Cow::Borrowed(_)),
            "{context}: expected Cow::Borrowed, got Cow::Owned({:?})",
            cow,
        );
    }

    // --- 1. Classification correctness after Cow conversion ---

    #[test]
    fn test_cow_reject_empty_command_correctness() {
        let _guard = test_guard!();
        let result = classify_command("");
        assert!(!result.is_compilation);
        assert_eq!(result.confidence, 0.0);
        assert_eq!(result.kind, None);
        assert!(result.reason.contains("empty"), "reason: {}", result.reason);
    }

    #[test]
    fn test_cow_reject_non_compilation_commands() {
        let _guard = test_guard!();
        let non_compilation = [
            "ls -la",
            "cat file.txt",
            "echo hello",
            "git status",
            "pwd",
            "cd /tmp",
        ];
        for cmd in non_compilation {
            let result = classify_command(cmd);
            assert!(
                !result.is_compilation,
                "'{cmd}' should NOT be classified as compilation"
            );
            assert_eq!(result.confidence, 0.0, "'{cmd}' should have 0.0 confidence");
            assert_eq!(result.kind, None, "'{cmd}' should have no CompilationKind");
            assert!(!result.reason.is_empty(), "'{cmd}' should have a reason");
        }
    }

    #[test]
    fn test_cow_accept_compilation_commands() {
        let _guard = test_guard!();
        let cases: &[(&str, CompilationKind)] = &[
            ("cargo build", CompilationKind::CargoBuild),
            ("cargo test", CompilationKind::CargoTest),
            ("cargo check", CompilationKind::CargoCheck),
            ("cargo clippy", CompilationKind::CargoClippy),
            ("gcc -o hello hello.c", CompilationKind::Gcc),
            ("make", CompilationKind::Make),
            ("bun test", CompilationKind::BunTest),
        ];
        for &(cmd, expected_kind) in cases {
            let result = classify_command(cmd);
            assert!(
                result.is_compilation,
                "'{cmd}' should be classified as compilation"
            );
            assert_eq!(
                result.kind,
                Some(expected_kind),
                "'{cmd}' should have kind {expected_kind:?}"
            );
            assert!(
                result.confidence > 0.0,
                "'{cmd}' should have positive confidence"
            );
            assert!(!result.reason.is_empty(), "'{cmd}' should have a reason");
        }
    }

    // --- 2. Zero-allocation verification on reject path ---

    #[test]
    fn test_cow_borrowed_on_tier0_reject() {
        let _guard = test_guard!();
        // Empty command -> Tier 0 instant reject
        let result = classify_command("");
        assert_cow_borrowed(&result.reason, "Tier 0 empty command reason");
    }

    #[test]
    fn test_cow_borrowed_on_tier1_reject() {
        let _guard = test_guard!();
        // Piped command -> Tier 1 structure analysis reject
        let result = classify_command("cargo build | tee log");
        assert!(!result.is_compilation);
        assert_cow_borrowed(&result.reason, "Tier 1 piped command reason");

        // Backgrounded command
        let result = classify_command("cargo build &");
        assert!(!result.is_compilation);
        assert_cow_borrowed(&result.reason, "Tier 1 backgrounded command reason");

        // Output redirected
        let result = classify_command("cargo build > log.txt");
        assert!(!result.is_compilation);
        assert_cow_borrowed(&result.reason, "Tier 1 redirected command reason");
    }

    #[test]
    fn test_cow_borrowed_on_tier2_reject() {
        let _guard = test_guard!();
        // Commands with no compilation keyword -> Tier 2 keyword filter reject
        let non_keyword_commands = [
            "ls -la",
            "cat file.txt",
            "echo hello world",
            "git status",
            "pwd",
            "cd /tmp",
            "grep pattern file",
            "find . -name '*.rs'",
            "cp src dst",
            "rm file.txt",
        ];
        for cmd in non_keyword_commands {
            let result = classify_command(cmd);
            assert!(!result.is_compilation, "'{cmd}' should be rejected");
            assert_cow_borrowed(&result.reason, &format!("Tier 2 reject for '{cmd}'"));
        }
    }

    #[test]
    fn test_cow_borrowed_on_tier3_reject() {
        let _guard = test_guard!();
        // Never-intercept commands now use static strings for performance (no format! allocation)
        let never_intercept = ["cargo fmt", "cargo install ripgrep", "cargo clean"];
        for cmd in never_intercept {
            let result = classify_command(cmd);
            assert!(!result.is_compilation, "'{cmd}' should be rejected");
            assert!(
                result.reason.contains("never-intercept"),
                "'{cmd}' reason should mention never-intercept: {}",
                result.reason
            );
            // Tier 3 now uses static string for performance -> Cow::Borrowed
            assert_cow_borrowed(&result.reason, &format!("Tier 3 reject for '{cmd}'"));
        }
    }

    // --- 3. ClassificationDetails tier Cow verification ---

    #[test]
    fn test_detailed_tiers_use_borrowed_names() {
        let _guard = test_guard!();
        // classify_command_detailed produces ClassificationTier entries
        // All tier names should be Cow::Borrowed (static constants)
        let details = classify_command_detailed("ls -la");
        for tier in &details.tiers {
            assert_cow_borrowed(&tier.name, &format!("Tier {} name", tier.tier));
        }
    }

    #[test]
    fn test_detailed_tier_reasons_borrowed_on_reject() {
        let _guard = test_guard!();
        // Non-compilation commands should have Cow::Borrowed reasons on all tiers
        let details = classify_command_detailed("ls -la");
        assert!(!details.classification.is_compilation);
        for tier in &details.tiers {
            assert_cow_borrowed(
                &tier.reason,
                &format!("Tier {} reason for 'ls -la'", tier.tier),
            );
        }
    }

    #[test]
    fn test_detailed_compilation_tier_names_borrowed() {
        let _guard = test_guard!();
        // Even for compilation commands, tier NAMES should always be Cow::Borrowed
        let details = classify_command_detailed("cargo build");
        assert!(details.classification.is_compilation);
        for tier in &details.tiers {
            assert_cow_borrowed(
                &tier.name,
                &format!("Tier {} name for 'cargo build'", tier.tier),
            );
        }
    }

    // --- 4. Serde roundtrip tests for Cow fields ---

    #[test]
    fn test_classification_serde_roundtrip_borrowed() {
        let _guard = test_guard!();
        let original = Classification::not_compilation("no compilation keyword");
        assert_cow_borrowed(&original.reason, "before serialize");

        let json = serde_json::to_string(&original).expect("serialize");
        let deserialized: Classification = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(deserialized.is_compilation, original.is_compilation);
        assert_eq!(deserialized.confidence, original.confidence);
        assert_eq!(deserialized.kind, original.kind);
        assert_eq!(deserialized.reason, original.reason);
        // Note: after deserialization, Cow will be Owned (serde deserializes into String)
        // This is correct behavior — only the pre-serialization path needs to be allocation-free
    }

    #[test]
    fn test_classification_serde_roundtrip_compilation() {
        let _guard = test_guard!();
        let original =
            Classification::compilation(CompilationKind::CargoBuild, 0.95, "cargo build detected");

        let json = serde_json::to_string(&original).expect("serialize");
        let deserialized: Classification = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(deserialized.is_compilation, original.is_compilation);
        assert_eq!(deserialized.confidence, original.confidence);
        assert_eq!(deserialized.kind, original.kind);
        assert_eq!(deserialized.reason.as_ref(), original.reason.as_ref());
    }

    #[test]
    fn test_classification_tier_serde_roundtrip() {
        let _guard = test_guard!();
        let tier = ClassificationTier {
            tier: 2,
            name: Cow::Borrowed(TIER_KEYWORD_FILTER),
            decision: TierDecision::Reject,
            reason: Cow::Borrowed("no compilation keyword"),
        };
        assert_cow_borrowed(&tier.name, "tier name before serialize");
        assert_cow_borrowed(&tier.reason, "tier reason before serialize");

        let json = serde_json::to_string(&tier).expect("serialize");
        let deserialized: ClassificationTier = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(deserialized.tier, tier.tier);
        assert_eq!(deserialized.name.as_ref(), tier.name.as_ref());
        assert_eq!(deserialized.decision, tier.decision);
        assert_eq!(deserialized.reason.as_ref(), tier.reason.as_ref());
    }

    #[test]
    fn test_classification_details_serde_roundtrip() {
        let _guard = test_guard!();
        let details = classify_command_detailed("cargo build");
        assert!(details.classification.is_compilation);

        let json = serde_json::to_string(&details).expect("serialize");
        let deserialized: ClassificationDetails = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(deserialized.original, details.original);
        assert_eq!(deserialized.normalized, details.normalized);
        assert_eq!(deserialized.tiers.len(), details.tiers.len());
        assert_eq!(
            deserialized.classification.is_compilation,
            details.classification.is_compilation
        );
        assert_eq!(
            deserialized.classification.kind,
            details.classification.kind
        );
    }

    // --- 5. Cow display and comparison tests ---

    #[test]
    fn test_cow_reason_display() {
        let _guard = test_guard!();
        let result = classify_command("ls");
        // Cow<str> should Display/Debug correctly
        let displayed = format!("{}", result.reason);
        assert!(!displayed.is_empty());
        let debugged = format!("{:?}", result.reason);
        assert!(!debugged.is_empty());
    }

    #[test]
    fn test_cow_reason_comparison() {
        let _guard = test_guard!();
        // Cow::Borrowed and Cow::Owned with same content should be equal
        let borrowed: Cow<'static, str> = Cow::Borrowed("no compilation keyword");
        let owned: Cow<'static, str> = Cow::Owned("no compilation keyword".to_string());
        assert_eq!(borrowed, owned);

        // Classification reasons should be comparable
        let r1 = classify_command("ls");
        let r2 = classify_command("pwd");
        // Both should be "no compilation keyword" (Tier 2 reject)
        assert_eq!(r1.reason, r2.reason);
    }
}

#[cfg(test)]
mod tests_bun_whitespace {
    use super::*;
    use crate::test_guard;

    #[test]
    fn test_bun_whitespace_resilience() {
        let _guard = test_guard!();

        // Standard single space
        let result = classify_command("bun test");
        assert!(result.is_compilation, "bun test failed");
        assert_eq!(result.kind, Some(CompilationKind::BunTest));

        // Multiple spaces
        let result = classify_command("bun  test");
        assert!(result.is_compilation, "bun  test failed");
        assert_eq!(result.kind, Some(CompilationKind::BunTest));

        // Tab separation
        let result = classify_command("bun\ttest");
        assert!(result.is_compilation, "bun\\ttest failed");
        assert_eq!(result.kind, Some(CompilationKind::BunTest));

        // Typecheck with extra spaces
        let result = classify_command("bun   typecheck   src/");
        assert!(result.is_compilation, "bun typecheck with spaces failed");
        assert_eq!(result.kind, Some(CompilationKind::BunTypecheck));
    }

    #[test]
    fn test_bun_watch_with_whitespace() {
        let _guard = test_guard!();

        // Watch with extra spaces
        let result = classify_command("bun  test  --watch");
        assert!(
            !result.is_compilation,
            "bun test --watch should be rejected"
        );
        assert!(result.reason.contains("interactive"));

        // Watch with short flag and tabs
        let result = classify_command("bun\ttypecheck\t-w");
        assert!(
            !result.is_compilation,
            "bun typecheck -w should be rejected"
        );
        assert!(result.reason.contains("interactive"));
    }

    #[test]
    fn test_bun_x_whitespace() {
        let _guard = test_guard!();

        // bun x with extra spaces
        let result = classify_command("bun  x  vitest");
        assert!(!result.is_compilation, "bun x should be rejected");
        assert!(result.reason.contains("bun x"));
    }
}

#[cfg(test)]
mod tests_normalize_whitespace {
    use super::*;
    use crate::test_guard;

    #[test]
    fn test_wrapper_whitespace_resilience() {
        let _guard = test_guard!();

        // Multiple spaces
        assert_eq!(normalize_command("sudo  cargo"), "cargo");

        // Tabs
        assert_eq!(normalize_command("sudo\tcargo"), "cargo");

        // Mixed wrappers with weird spacing
        assert_eq!(normalize_command("time\tsudo  cargo"), "cargo");

        // Prefix matching safety
        assert_eq!(normalize_command("sudocargo"), "sudocargo");

        // Bare wrapper (should become empty)
        assert_eq!(normalize_command("sudo"), "");
    }

    #[test]
    fn test_env_var_whitespace() {
        let _guard = test_guard!();

        // env with multiple spaces before VAR
        assert_eq!(normalize_command("env  RUST_BACKTRACE=1 cargo"), "cargo");

        // env with tabs
        assert_eq!(normalize_command("env\tRUST_BACKTRACE=1\tcargo"), "cargo");
    }
}

// ============================================================================
// REGRESSION SUITE: Command Classification (bd-vvmd.2.9)
//
// Table-driven regression tests protecting non-compilation UX. Every entry
// documents expected behavior with rationale so accidental interception of
// local-only commands is caught immediately.
// ============================================================================

#[cfg(test)]
mod regression_classification {
    use super::*;
    use crate::test_guard;

    /// A single regression test case.
    struct Case {
        cmd: &'static str,
        expect_compilation: bool,
        expected_kind: Option<CompilationKind>,
        /// Substring that MUST appear in the classification reason.
        reason_contains: &'static str,
        /// Minimum confidence (only checked when expect_compilation is true).
        min_confidence: f64,
    }

    fn run_cases(cases: &[Case]) {
        for (i, c) in cases.iter().enumerate() {
            let result = classify_command(c.cmd);
            assert_eq!(
                result.is_compilation, c.expect_compilation,
                "Case {i} ({:?}): expected is_compilation={}, got={}. reason={:?}",
                c.cmd, c.expect_compilation, result.is_compilation, result.reason
            );
            if c.expect_compilation {
                assert_eq!(
                    result.kind, c.expected_kind,
                    "Case {i} ({:?}): expected kind={:?}, got={:?}",
                    c.cmd, c.expected_kind, result.kind
                );
                assert!(
                    result.confidence >= c.min_confidence,
                    "Case {i} ({:?}): expected confidence >= {}, got={}",
                    c.cmd,
                    c.min_confidence,
                    result.confidence
                );
            }
            if !c.reason_contains.is_empty() {
                assert!(
                    result.reason.contains(c.reason_contains),
                    "Case {i} ({:?}): expected reason containing {:?}, got {:?}",
                    c.cmd,
                    c.reason_contains,
                    result.reason
                );
            }
        }
    }

    // ------------------------------------------------------------------
    // 1. Cargo: Positive compilation commands
    // ------------------------------------------------------------------

    #[test]
    fn regression_cargo_compilation_positive() {
        let _guard = test_guard!();
        let cases = [
            Case {
                cmd: "cargo build",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo build --release",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo build --workspace",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo build -p my-crate",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo b",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo test",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo test --release",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo test my_test",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo test -- --nocapture",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo test --workspace",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo test -p rch-common",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo t",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo test --lib",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo test --bins",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo test --doc",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo test -- --test-threads=4",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo check",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoCheck),
                reason_contains: "cargo check",
                min_confidence: 0.85,
            },
            Case {
                cmd: "cargo check --workspace --all-targets",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoCheck),
                reason_contains: "cargo check",
                min_confidence: 0.85,
            },
            Case {
                cmd: "cargo c",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoCheck),
                reason_contains: "cargo check",
                min_confidence: 0.85,
            },
            Case {
                cmd: "cargo clippy",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoClippy),
                reason_contains: "cargo clippy",
                min_confidence: 0.85,
            },
            Case {
                cmd: "cargo clippy --workspace --all-targets -- -D warnings",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoClippy),
                reason_contains: "cargo clippy",
                min_confidence: 0.85,
            },
            Case {
                cmd: "cargo doc",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoDoc),
                reason_contains: "cargo doc",
                min_confidence: 0.80,
            },
            Case {
                cmd: "cargo doc --no-deps",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoDoc),
                reason_contains: "cargo doc",
                min_confidence: 0.80,
            },
            Case {
                cmd: "cargo run",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo run",
                min_confidence: 0.80,
            },
            Case {
                cmd: "cargo run --release",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo run",
                min_confidence: 0.80,
            },
            Case {
                cmd: "cargo r",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo run",
                min_confidence: 0.80,
            },
            Case {
                cmd: "cargo bench",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBench),
                reason_contains: "cargo bench",
                min_confidence: 0.85,
            },
            Case {
                cmd: "cargo bench --bench my_bench",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBench),
                reason_contains: "cargo bench",
                min_confidence: 0.85,
            },
            Case {
                cmd: "cargo nextest run",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoNextest),
                reason_contains: "cargo nextest run",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo nextest run --workspace",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoNextest),
                reason_contains: "cargo nextest run",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo nextest r",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoNextest),
                reason_contains: "cargo nextest run",
                min_confidence: 0.90,
            },
            // Toolchain override variants
            Case {
                cmd: "cargo +nightly build",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo +1.80.0 test",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo +nightly nextest run",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoNextest),
                reason_contains: "cargo nextest run",
                min_confidence: 0.90,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 2. Cargo: Negative (NEVER intercept — must stay local)
    // ------------------------------------------------------------------

    #[test]
    fn regression_cargo_never_intercept() {
        let _guard = test_guard!();
        let cases = [
            Case {
                cmd: "cargo install ripgrep",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo publish",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo login",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo fmt",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo fmt --check",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo fix",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo clean",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo new my_project",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo init",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo add serde",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo remove serde",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo update",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo generate-lockfile",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo watch -x test",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo --version",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo -V",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            // cargo nextest non-run subcommands
            Case {
                cmd: "cargo nextest list",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo nextest archive",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo nextest show",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            // Bare cargo / bare cargo nextest
            Case {
                cmd: "cargo",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "bare cargo",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo nextest",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "bare cargo nextest",
                min_confidence: 0.0,
            },
            // Non-interceptable subcommands
            Case {
                cmd: "cargo tree",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "not interceptable",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo metadata",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "not interceptable",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo search serde",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "not interceptable",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo vendor",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "not interceptable",
                min_confidence: 0.0,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 3. Bun: Positive compilation (test, typecheck)
    // ------------------------------------------------------------------

    #[test]
    fn regression_bun_compilation_positive() {
        let _guard = test_guard!();
        let cases = [
            Case {
                cmd: "bun test",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::BunTest),
                reason_contains: "bun test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "bun test src/",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::BunTest),
                reason_contains: "bun test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "bun test --bail",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::BunTest),
                reason_contains: "bun test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "bun test --timeout 5000",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::BunTest),
                reason_contains: "bun test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "bun typecheck",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::BunTypecheck),
                reason_contains: "bun typecheck",
                min_confidence: 0.90,
            },
            Case {
                cmd: "bun typecheck src/",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::BunTypecheck),
                reason_contains: "bun typecheck",
                min_confidence: 0.90,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 4. Bun: Negative (package management, execution, interactive)
    // ------------------------------------------------------------------

    #[test]
    fn regression_bun_never_intercept() {
        let _guard = test_guard!();
        let cases = [
            // Package management — modifies local node_modules
            Case {
                cmd: "bun install",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun add react",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun remove react",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun link",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun unlink",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun pm ls",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun init",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun create my-app",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun upgrade",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            // Execution — binds local ports or runs scripts
            Case {
                cmd: "bun run dev",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun build src/index.ts",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun dev",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun repl",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            // Package runner — arbitrary execution like npx
            Case {
                cmd: "bun x vitest",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "bun x",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun x tsc --noEmit",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "bun x",
                min_confidence: 0.0,
            },
            // Interactive watch modes — must run locally for interactivity
            Case {
                cmd: "bun test --watch",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "interactive",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun test -w",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "interactive",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun typecheck --watch",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "interactive",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun typecheck -w",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "interactive",
                min_confidence: 0.0,
            },
            // Version/help
            Case {
                cmd: "bun --version",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun -v",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun --help",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun -h",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "bun completions",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 5. C/C++ compilers: Positive compilation
    // ------------------------------------------------------------------

    #[test]
    fn regression_c_cpp_compilation_positive() {
        let _guard = test_guard!();
        let cases = [
            Case {
                cmd: "gcc -c main.c -o main.o",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Gcc),
                reason_contains: "gcc",
                min_confidence: 0.85,
            },
            Case {
                cmd: "gcc main.c -o main",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Gcc),
                reason_contains: "gcc",
                min_confidence: 0.85,
            },
            Case {
                cmd: "g++ -c main.cpp -o main.o",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Gpp),
                reason_contains: "g++",
                min_confidence: 0.85,
            },
            Case {
                cmd: "g++ main.cc -o main",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Gpp),
                reason_contains: "g++",
                min_confidence: 0.85,
            },
            Case {
                cmd: "clang -c main.c -o main.o",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Clang),
                reason_contains: "clang",
                min_confidence: 0.85,
            },
            Case {
                cmd: "clang++ -c main.cpp -o main.o",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Clangpp),
                reason_contains: "clang++",
                min_confidence: 0.85,
            },
            Case {
                cmd: "clang++ main.cc -o main",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Clangpp),
                reason_contains: "clang++",
                min_confidence: 0.85,
            },
            Case {
                cmd: "cc -c main.c -o main.o",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Gcc),
                reason_contains: "cc",
                min_confidence: 0.80,
            },
            Case {
                cmd: "c++ -c main.cpp -o main.o",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Gpp),
                reason_contains: "c++",
                min_confidence: 0.80,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 6. C/C++ compilers: Version checks (NEVER intercept)
    // ------------------------------------------------------------------

    #[test]
    fn regression_c_cpp_version_checks_not_intercepted() {
        let _guard = test_guard!();
        let cases = [
            Case {
                cmd: "rustc --version",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "rustc -V",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "gcc --version",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "gcc -v",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "clang --version",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "clang -v",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "make --version",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "make -v",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cmake --version",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "never-intercept",
                min_confidence: 0.0,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 7. Build systems: Positive compilation
    // ------------------------------------------------------------------

    #[test]
    fn regression_build_systems_positive() {
        let _guard = test_guard!();
        let cases = [
            Case {
                cmd: "make",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Make),
                reason_contains: "make build",
                min_confidence: 0.80,
            },
            Case {
                cmd: "make -j8",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Make),
                reason_contains: "make build",
                min_confidence: 0.80,
            },
            Case {
                cmd: "make all",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Make),
                reason_contains: "make build",
                min_confidence: 0.80,
            },
            Case {
                cmd: "cmake --build build",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CmakeBuild),
                reason_contains: "cmake --build",
                min_confidence: 0.85,
            },
            Case {
                cmd: "cmake --build=build",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CmakeBuild),
                reason_contains: "cmake --build",
                min_confidence: 0.85,
            },
            Case {
                cmd: "ninja",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Ninja),
                reason_contains: "ninja build",
                min_confidence: 0.85,
            },
            Case {
                cmd: "ninja -j4",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Ninja),
                reason_contains: "ninja build",
                min_confidence: 0.85,
            },
            Case {
                cmd: "meson compile",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Meson),
                reason_contains: "meson compile",
                min_confidence: 0.80,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 8. Build systems: Negative (clean, install, version)
    // ------------------------------------------------------------------

    #[test]
    fn regression_build_systems_not_intercepted() {
        let _guard = test_guard!();
        let cases = [
            Case {
                cmd: "make clean",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "make maintenance",
                min_confidence: 0.0,
            },
            Case {
                cmd: "make install",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "make maintenance",
                min_confidence: 0.0,
            },
            Case {
                cmd: "make distclean",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "make maintenance",
                min_confidence: 0.0,
            },
            Case {
                cmd: "ninja -t clean",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "ninja clean",
                min_confidence: 0.0,
            },
            Case {
                cmd: "ninja clean",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "ninja clean",
                min_confidence: 0.0,
            },
            // meson without compile subcommand
            Case {
                cmd: "meson setup build",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no matching pattern",
                min_confidence: 0.0,
            },
            Case {
                cmd: "meson configure",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no matching pattern",
                min_confidence: 0.0,
            },
            // cmake without --build
            Case {
                cmd: "cmake .",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no matching pattern",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cmake -DCMAKE_BUILD_TYPE=Release ..",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no matching pattern",
                min_confidence: 0.0,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 9. Rustc: Direct invocation
    // ------------------------------------------------------------------

    #[test]
    fn regression_rustc_positive() {
        let _guard = test_guard!();
        let cases = [
            Case {
                cmd: "rustc main.rs",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Rustc),
                reason_contains: "rustc",
                min_confidence: 0.90,
            },
            Case {
                cmd: "rustc main.rs -o main",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Rustc),
                reason_contains: "rustc",
                min_confidence: 0.90,
            },
            Case {
                cmd: "rustc --edition 2021 main.rs",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::Rustc),
                reason_contains: "rustc",
                min_confidence: 0.90,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 10. Shell structure exclusions (pipes, redirects, bg, chains)
    // ------------------------------------------------------------------

    #[test]
    fn regression_shell_structure_exclusions() {
        let _guard = test_guard!();
        let cases = [
            // Pipes
            Case {
                cmd: "cargo build 2>&1 | grep error",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "piped",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo test | tee output.log",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "piped",
                min_confidence: 0.0,
            },
            // Background
            Case {
                cmd: "cargo build &",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "background",
                min_confidence: 0.0,
            },
            // Output redirect
            Case {
                cmd: "cargo build > log.txt",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "redirect",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo build >> log.txt",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "redirect",
                min_confidence: 0.0,
            },
            // Input redirect
            Case {
                cmd: "cargo build < input.txt",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "input redirect",
                min_confidence: 0.0,
            },
            // Subshell
            Case {
                cmd: "(cargo build)",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "subshell",
                min_confidence: 0.0,
            },
            Case {
                cmd: "$(cargo build)",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "subshell",
                min_confidence: 0.0,
            },
            Case {
                cmd: "`cargo build`",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "subshell capture",
                min_confidence: 0.0,
            },
            // Process substitution
            Case {
                cmd: "cargo build --config <(echo ...)",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "subshell",
                min_confidence: 0.0,
            },
            // Semicolon chains
            Case {
                cmd: "cargo build; cargo test",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "chained",
                min_confidence: 0.0,
            },
            // || chains
            Case {
                cmd: "cargo build || echo failed",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "chained",
                min_confidence: 0.0,
            },
            // Newline injection (security)
            Case {
                cmd: "cargo build\nrm -rf /",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "newline",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cargo build\r\nevil",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "newline",
                min_confidence: 0.0,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 11. fd-to-fd redirects are SAFE and should NOT block interception
    // ------------------------------------------------------------------

    #[test]
    fn regression_fd_redirect_safe() {
        let _guard = test_guard!();
        // Compound: "cd /path && cargo build 2>&1" should detect cargo build
        // via compound command handling (depth-0 splits on &&, depth-1 checks segment)
        // Simple fd-to-fd redirect like "cargo build 2>&1" is handled by check_structure
        // which explicitly skips fd-to-fd redirects. So "cargo build 2>&1" should be
        // classified as compilation.
        let result = classify_command("cargo build 2>&1");
        assert!(
            result.is_compilation,
            "cargo build 2>&1 should be classified as compilation (fd redirect is safe), got: {:?}",
            result.reason
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoBuild));
    }

    // ------------------------------------------------------------------
    // 12. Compound commands: && chains with compilation suffix
    // ------------------------------------------------------------------

    #[test]
    fn regression_compound_commands() {
        let _guard = test_guard!();
        // cd && cargo build should be detected as compilation
        let result = classify_command("cd /path && cargo build");
        assert!(
            result.is_compilation,
            "cd && cargo build should compile, got: {:?}",
            result.reason
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoBuild));
        assert!(result.command_prefix.is_some(), "should have prefix");
        assert!(
            result.extracted_command.is_some(),
            "should have extracted command"
        );

        let result = classify_command("cd /path && cargo test --workspace");
        assert!(
            result.is_compilation,
            "cd && cargo test should compile, got: {:?}",
            result.reason
        );
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));

        // Non-compilation suffix should not match
        let result = classify_command("cd /path && cargo fmt");
        assert!(!result.is_compilation, "cd && cargo fmt should NOT compile");

        let result = classify_command("cd /path && ls -la");
        assert!(!result.is_compilation, "cd && ls should NOT compile");
    }

    // ------------------------------------------------------------------
    // 13. Wrapper normalization: env, sudo, time, etc.
    // ------------------------------------------------------------------

    #[test]
    fn regression_wrapper_normalization() {
        let _guard = test_guard!();
        let cases = [
            Case {
                cmd: "sudo cargo build",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            Case {
                cmd: "time cargo test",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "env RUST_BACKTRACE=1 cargo test",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "RUST_BACKTRACE=1 cargo test",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "nice cargo build --release",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            Case {
                cmd: "/usr/bin/cargo build",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            Case {
                cmd: "sudo env RUSTFLAGS=-Dwarnings cargo clippy",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoClippy),
                reason_contains: "cargo clippy",
                min_confidence: 0.85,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 14. Non-compilation commands (must never trigger)
    // ------------------------------------------------------------------

    #[test]
    fn regression_non_compilation_passthrough() {
        let _guard = test_guard!();
        let cases = [
            Case {
                cmd: "ls -la",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "pwd",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "echo hello",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cat Cargo.toml",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "git status",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "git commit -m 'fix'",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "npm install",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "yarn build",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "python main.py",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "go build .",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "docker build -t myapp .",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "pip install -r requirements.txt",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "curl https://example.com",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "mkdir -p build",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "rm -rf target/",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "cp -r src/ backup/",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "no compilation keyword",
                min_confidence: 0.0,
            },
            Case {
                cmd: "",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "empty command",
                min_confidence: 0.0,
            },
            Case {
                cmd: "   ",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "empty command",
                min_confidence: 0.0,
            },
        ];
        run_cases(&cases);
    }

    // ------------------------------------------------------------------
    // 15. ClassificationDetails: structured log field verification
    // ------------------------------------------------------------------

    #[test]
    fn regression_classification_details_fields() {
        let _guard = test_guard!();

        // Compilation: verify all tiers pass and final has kind + confidence
        let details = classify_command_detailed("cargo build --release");
        assert_eq!(details.original, "cargo build --release");
        assert!(details.classification.is_compilation);
        assert_eq!(
            details.classification.kind,
            Some(CompilationKind::CargoBuild)
        );
        assert!(details.classification.confidence >= 0.90);
        // Should have 5 tiers: 0-4
        assert_eq!(details.tiers.len(), 5, "Should have 5 tier decisions");
        for tier in &details.tiers[..4] {
            assert_eq!(tier.decision, TierDecision::Pass);
        }
        // Tier 4 should also pass (compilation detected)
        assert_eq!(details.tiers[4].decision, TierDecision::Pass);
        assert_eq!(details.tiers[4].tier, 4);

        // Non-compilation: should reject early at Tier 2 (keyword filter)
        let details = classify_command_detailed("ls -la");
        assert!(!details.classification.is_compilation);
        assert!(
            details.tiers.len() >= 3,
            "Should have at least 3 tiers for keyword rejection"
        );
        assert_eq!(details.tiers.last().unwrap().decision, TierDecision::Reject);

        // Never-intercept: should reject at Tier 3
        let details = classify_command_detailed("cargo fmt --check");
        assert!(!details.classification.is_compilation);
        assert!(
            details.tiers.len() >= 4,
            "Should have at least 4 tiers for never-intercept rejection"
        );
        // Find tier 3
        let tier3 = details.tiers.iter().find(|t| t.tier == 3).unwrap();
        assert_eq!(tier3.decision, TierDecision::Reject);
        assert!(
            tier3.reason.contains("never-intercept"),
            "Tier 3 reason should mention never-intercept, got: {:?}",
            tier3.reason
        );

        // Piped command: should reject at Tier 1 (structure analysis)
        let details = classify_command_detailed("cargo build | grep error");
        assert!(!details.classification.is_compilation);
        let tier1 = details.tiers.iter().find(|t| t.tier == 1).unwrap();
        assert_eq!(tier1.decision, TierDecision::Reject);
        assert!(tier1.reason.contains("piped"));

        // Empty command: should reject at Tier 0
        let details = classify_command_detailed("");
        assert!(!details.classification.is_compilation);
        assert_eq!(details.tiers[0].tier, 0);
        assert_eq!(details.tiers[0].decision, TierDecision::Reject);
    }

    // ------------------------------------------------------------------
    // 16. Decision path completeness: every positive case has reason code
    // ------------------------------------------------------------------

    #[test]
    fn regression_every_compilation_has_reason_and_confidence() {
        let _guard = test_guard!();
        let compilation_cmds = [
            "cargo build",
            "cargo test",
            "cargo check",
            "cargo clippy",
            "cargo doc",
            "cargo run",
            "cargo bench",
            "cargo nextest run",
            "rustc main.rs",
            "gcc -c main.c -o main.o",
            "g++ -c main.cpp -o main.o",
            "clang -c main.c -o main.o",
            "clang++ -c main.cpp -o main.o",
            "make",
            "cmake --build build",
            "ninja",
            "meson compile",
            "bun test",
            "bun typecheck",
        ];
        for cmd in compilation_cmds {
            let result = classify_command(cmd);
            assert!(result.is_compilation, "{cmd:?} should be compilation");
            assert!(
                result.kind.is_some(),
                "{cmd:?} should have a CompilationKind"
            );
            assert!(
                result.confidence > 0.0,
                "{cmd:?} should have non-zero confidence"
            );
            assert!(
                !result.reason.is_empty(),
                "{cmd:?} should have a non-empty reason"
            );
        }
    }

    // ------------------------------------------------------------------
    // 17. Decision path completeness: every negative case has reason code
    // ------------------------------------------------------------------

    #[test]
    fn regression_every_rejection_has_reason() {
        let _guard = test_guard!();
        let non_compilation_cmds = [
            "",
            "ls",
            "pwd",
            "git status",
            "cargo fmt",
            "cargo install ripgrep",
            "cargo clean",
            "bun install",
            "bun add react",
            "bun run dev",
            "bun dev",
            "bun repl",
            "bun x vitest",
            "bun test --watch",
            "bun typecheck -w",
            "make clean",
            "ninja clean",
            "gcc --version",
            "rustc --version",
            "cargo build | grep error",
            "cargo build &",
            "cargo build > log.txt",
            "(cargo build)",
        ];
        for cmd in non_compilation_cmds {
            let result = classify_command(cmd);
            assert!(
                !result.is_compilation,
                "{cmd:?} should NOT be compilation, got kind={:?}",
                result.kind
            );
            assert!(
                !result.reason.is_empty(),
                "{cmd:?} should have a non-empty rejection reason"
            );
            assert_eq!(result.kind, None, "{cmd:?} should have no CompilationKind");
            assert_eq!(
                result.confidence, 0.0,
                "{cmd:?} should have zero confidence"
            );
        }
    }

    // ------------------------------------------------------------------
    // 18. Representative real-world agent workflow commands
    // ------------------------------------------------------------------

    #[test]
    fn regression_real_world_agent_workflows() {
        let _guard = test_guard!();

        // Typical Claude Code agent workflow: navigation + build
        let cd_build = classify_command(
            "cd /data/projects/remote_compilation_helper && cargo build --workspace --all-targets",
        );
        assert!(
            cd_build.is_compilation,
            "agent cd+build workflow should be intercepted"
        );

        // Agent running tests after code change
        let test_ws = classify_command("cargo test --workspace -- --nocapture");
        assert!(test_ws.is_compilation);
        assert_eq!(test_ws.kind, Some(CompilationKind::CargoTest));

        // Agent running clippy check
        let clippy = classify_command("cargo clippy --workspace --all-targets -- -D warnings");
        assert!(clippy.is_compilation);
        assert_eq!(clippy.kind, Some(CompilationKind::CargoClippy));

        // Agent checking format (should NOT intercept — modifies source)
        let fmt = classify_command("cargo fmt --check");
        assert!(!fmt.is_compilation);

        // Agent reading Cargo.toml (should NOT intercept)
        let cat = classify_command("cat Cargo.toml");
        assert!(!cat.is_compilation);

        // Agent checking git status (should NOT intercept)
        let gs = classify_command("git status");
        assert!(!gs.is_compilation);

        // Agent installing a tool (should NOT intercept)
        let install = classify_command("cargo install cargo-nextest");
        assert!(!install.is_compilation);

        // Agent running specific package tests
        let pkg_test = classify_command("cargo test -p rch-common");
        assert!(pkg_test.is_compilation);
        assert_eq!(pkg_test.kind, Some(CompilationKind::CargoTest));

        // Agent running with environment variable
        let env_test = classify_command("RUST_BACKTRACE=1 cargo test --workspace");
        assert!(env_test.is_compilation);
        assert_eq!(env_test.kind, Some(CompilationKind::CargoTest));

        // Agent running nextest
        let nxt = classify_command("cargo nextest run --workspace --no-fail-fast");
        assert!(nxt.is_compilation);
        assert_eq!(nxt.kind, Some(CompilationKind::CargoNextest));
    }

    // ------------------------------------------------------------------
    // 19. Boundary: commands that contain keywords but are NOT compilation
    // ------------------------------------------------------------------

    #[test]
    fn regression_keyword_in_non_compilation_context() {
        let _guard = test_guard!();
        // "cargo" appears as substring in path or argument, not as command
        let result = classify_command("echo cargo build");
        // "echo" has no compilation keyword... wait, "cargo" IS a keyword
        // but the command starts with "echo", which isn't a compilation command.
        // After normalization, it should still start with "echo".
        assert!(
            !result.is_compilation,
            "echo cargo should not compile, got: {:?}",
            result.reason
        );

        // grep for "make" in a log file - keyword present but not a build command
        let result = classify_command("grep make Makefile");
        // "make" is a keyword so passes Tier 2, but starts with "grep", not "make"
        assert!(
            !result.is_compilation,
            "grep make should not compile, got: {:?}",
            result.reason
        );

        // cat a file with "gcc" in its name
        let result = classify_command("cat gcc_output.log");
        // "gcc" keyword passes Tier 2, but the command is "cat"
        assert!(
            !result.is_compilation,
            "cat gcc_output should not compile, got: {:?}",
            result.reason
        );
    }

    // ------------------------------------------------------------------
    // 20. CompilationKind properties: is_test_command, command_base
    // ------------------------------------------------------------------

    #[test]
    fn regression_compilation_kind_properties() {
        let _guard = test_guard!();

        // Test commands
        assert!(CompilationKind::CargoTest.is_test_command());
        assert!(CompilationKind::CargoNextest.is_test_command());
        assert!(CompilationKind::CargoBench.is_test_command());
        assert!(CompilationKind::BunTest.is_test_command());

        // Non-test commands
        assert!(!CompilationKind::CargoBuild.is_test_command());
        assert!(!CompilationKind::CargoCheck.is_test_command());
        assert!(!CompilationKind::CargoClippy.is_test_command());
        assert!(!CompilationKind::CargoDoc.is_test_command());
        assert!(!CompilationKind::BunTypecheck.is_test_command());
        assert!(!CompilationKind::Gcc.is_test_command());
        assert!(!CompilationKind::Gpp.is_test_command());
        assert!(!CompilationKind::Clang.is_test_command());
        assert!(!CompilationKind::Clangpp.is_test_command());
        assert!(!CompilationKind::Make.is_test_command());
        assert!(!CompilationKind::CmakeBuild.is_test_command());
        assert!(!CompilationKind::Ninja.is_test_command());
        assert!(!CompilationKind::Meson.is_test_command());
        assert!(!CompilationKind::Rustc.is_test_command());

        // command_base
        assert_eq!(CompilationKind::CargoBuild.command_base(), "cargo");
        assert_eq!(CompilationKind::CargoTest.command_base(), "cargo");
        assert_eq!(CompilationKind::CargoNextest.command_base(), "cargo");
        assert_eq!(CompilationKind::Rustc.command_base(), "rustc");
        assert_eq!(CompilationKind::Gcc.command_base(), "gcc");
        assert_eq!(CompilationKind::Gpp.command_base(), "g++");
        assert_eq!(CompilationKind::Clang.command_base(), "clang");
        assert_eq!(CompilationKind::Clangpp.command_base(), "clang++");
        assert_eq!(CompilationKind::Make.command_base(), "make");
        assert_eq!(CompilationKind::CmakeBuild.command_base(), "cmake");
        assert_eq!(CompilationKind::Ninja.command_base(), "ninja");
        assert_eq!(CompilationKind::Meson.command_base(), "meson");
        assert_eq!(CompilationKind::BunTest.command_base(), "bun");
        assert_eq!(CompilationKind::BunTypecheck.command_base(), "bun");
    }
}