rch-common 2.1.20

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
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
//! 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 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",
    // The standalone cargo-zigbuild binary (hyphenated) does NOT word-match
    // "cargo", so it needs its own Tier-2 keyword or it is rejected before
    // classify_full's `cargo-zigbuild` route ever runs.
    "cargo-zigbuild",
    "cargo-xwin",
    "rustc",
    "gcc",
    "g++",
    "clang",
    "clang++",
    "make",
    "cmake",
    "ninja",
    "meson",
    "cc",
    "c++",
    "bun",
    "nextest",
    "nix",
    "nix-build",
    "go",
    "tsc",
    "npx",
];

/// 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` is checked in classify_cargo: only an explicit dry-run
    // with package verification enabled is a remote compilation command.
    "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
    // Go commands that mutate local state, run programs, or are trivially fast.
    // Only `go build` / `go test` / `go vet` are offloadable (see classify_go).
    "go get",      // mutates go.mod / module cache
    "go mod",      // mutates go.mod / go.sum
    "go work",     // mutates go.work
    "go install",  // writes a binary into local GOBIN
    "go run",      // runs a program locally (may be interactive / long-lived)
    "go generate", // executes arbitrary local codegen
    "go fmt",      // rewrites local source files
    "go clean",    // mutates local caches
    "go env",      // trivial; also used to *set* local env
    "go doc",      // trivial lookup
    "go version",  // trivial
    "go tool",     // arbitrary tool execution
    "go list",     // metadata query; cheap, and agents parse it locally
    // TypeScript: version/init are trivial or mutate local state
    "tsc --version",
    "tsc -v",
    "tsc --init",
];

/// 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,
    /// `cargo zigbuild` / `cargo-zigbuild zigbuild` — a cargo build that uses
    /// zig as the C compiler + cross-linker (`cargo-zigbuild`). It IS a Rust
    /// build (RequiredRuntime::Rust), but additionally needs `zig` +
    /// `cargo-zigbuild` on the worker and the requested `--target` rustup std.
    /// Unlike Go/Nix it PRODUCES a real binary under `target/<triple>/<profile>/`,
    /// so its artifacts must sync back (see artifact_patterns).
    CargoZigbuild,
    /// 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,

    // Go commands
    //
    // Builds require an explicit file output and durable artifact delivery.
    // Even ./... can select one main package and emit an implicit executable.
    /// `go build -o <file>` (required output returned through staged retrieval)
    GoBuild,
    /// `go test ./...`
    GoTest,
    /// `go vet ./...`
    GoVet,

    // TypeScript
    /// `tsc --noEmit` / `npx tsc --noEmit` (typecheck only; emitting runs stay local)
    Tsc,

    // Nix commands
    /// `nix build` / `nix-build` (derivation build), `nix flake check`
    /// (evaluate + build all outputs), and the non-interactive
    /// `nix develop -c <cmd>` / `nix shell -c <cmd>` forms.
    ///
    /// Nix outputs live in the worker's `/nix/store` behind a `result` symlink
    /// that is meaningless on a nix-less local host, so these run as
    /// streaming, no-artifact-return commands (exit status is the payload).
    NixBuild,

    // Explicit job admission
    /// Arbitrary non-compilation workload admitted explicitly via
    /// `rch exec --job` (sharded tests, fuzzing, benchmarks, mutation testing).
    ///
    /// NEVER produced by [`classify_command`] or the PreToolUse hook — the sole
    /// constructor is the explicit `--job` flag on `rch exec`, so the hook can
    /// never auto-delegate a command the classifier did not intercept. A job
    /// rides the normal selection/sync/execute/heartbeat/release rails, syncs
    /// no artifacts back automatically (exit status is the payload in this
    /// phase), and surfaces the remote exit status verbatim without
    /// toolchain/worker-environment reinterpretation.
    Job,
}

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
                | CompilationKind::GoTest
        )
    }

    /// 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
            // `cargo zigbuild` runs through cargo; the standalone `cargo-zigbuild`
            // binary is normalized to this kind too. Base "cargo" so it matches
            // the existing cargo allowlist entry.
            CompilationKind::CargoZigbuild => "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",
            // Nix commands. Both `nix build` and the legacy `nix-build` route
            // through this kind; the canonical allowlist base name is "nix".
            CompilationKind::NixBuild => "nix",
            // Go commands
            CompilationKind::GoBuild | CompilationKind::GoTest | CompilationKind::GoVet => "go",
            // TypeScript. Both `tsc` and `npx tsc` route through this kind; the
            // canonical allowlist base name is "tsc".
            CompilationKind::Tsc => "tsc",
            // Explicit job admission has no single executable base: a job's
            // argv[0] is arbitrary. The hook-path execution-allowlist gate can
            // never observe this kind (only `rch exec --job` constructs it), so
            // this token exists to keep the mapping total, not to match an
            // allowlist entry.
            CompilationKind::Job => "job",
        }
    }
}

/// Classify a shell command.
///
/// Implements the 5-tier classification system for maximum precision with
/// minimal latency on non-compilation commands.
///
/// Pure `&&` chains with a compilation command as the final segment are
/// accepted and rewritten to wrap only that final command. Other multi-command
/// strings are rejected by Tier 1 structure analysis to prevent unsafe partial
/// interception.
pub fn classify_command(cmd: &str) -> Classification {
    classify_command_inner(cmd, 0)
}

/// Detect a command that *would* be a compilation command if it weren't for an
/// (unsafe / unhandled) pipe/redirect/background/subshell structure — i.e. one
/// that the classifier declines purely because of its shell structure rather
/// than because the underlying program is not a compiler (issue #24, item 3).
///
/// Returns the structural reason (e.g. "piped command", "subshell execution")
/// when the leading program token IS a known compilation tool but the command
/// is declined by Tier 1 structure analysis. Returns `None` otherwise (so the
/// hint is only surfaced for genuine structure-driven declines, never for
/// `ls | grep cargo` and friends).
///
/// Callers (the hook) can use this to emit an observable hint/warn when running
/// on an orchestrator with `force_remote = true`, so the silent local fallback
/// becomes visible.
pub fn declined_compilation_due_to_structure(cmd: &str) -> Option<&'static str> {
    let trimmed = cmd.trim();
    if trimmed.is_empty() {
        return None;
    }
    // If the full classifier already accepts (and will offload) it, there is no
    // decline to report.
    if classify_command(trimmed).is_compilation {
        return None;
    }
    // Only report when Tier 1 structure analysis is the reason AND the leading
    // program word is a recognized compilation tool.
    let reason = check_structure(trimmed)?;
    let normalized = normalize_command(trimmed);
    if starts_with_compilation_command(normalized.as_ref()) {
        Some(reason)
    } else {
        None
    }
}

/// 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 0.6: Wrapper / benign-suffix handling (only at depth 0).
    //
    // Handles the dominant agent invocation forms that would otherwise be
    // rejected by Tier 1 structure analysis and silently fall back to local
    // compilation (issue #24):
    //   - `bash -c "cargo test ..."` / `sh -c "cargo test ..."` (extract inner)
    //   - `cargo check --lib 2>&1 | head`  (pipe into a benign pager)
    //   - `cargo test ... > file 2>&1`     (benign stdout/stderr file redirect)
    //   - `cargo test ... &`               (backgrounding)
    //
    // We stay conservative: only the leading compilation command is offloaded,
    // and the benign trailing structure is re-attached to the offloaded
    // command's output stream (`rch exec -- <cmd> <suffix>`). We never offload
    // when the pipeline transforms the command's INPUT or chains another build.
    if depth == 0 && cmd.len() < MAX_SPLIT_INPUT_LEN {
        if let Some(result) = try_classify_wrapped_command(cmd) {
            return result;
        }
        if let Some(result) = try_classify_benign_suffix_command(cmd) {
            return result;
        }
    }

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

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

    // Tier 2: quick check for compilation commands.
    //
    // This intentionally checks the normalized command word, not arbitrary
    // arguments. A Beads comment like `br comments add ... "cargo test ..."`
    // mentions compilation text, but it is not invoking a compiler.
    if !starts_with_compilation_command(normalized) {
        return Classification::not_compilation("no compilation keyword");
    }

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

    if segments.len() == 1 {
        // No prefix, just the command itself
        return None;
    }

    // Build the prefix: every earlier segment, joined back with " && ".
    //
    // Issue #50: earlier segments that are themselves compilations are wrapped
    // with `rch exec -- ` here, so the hook's `{prefix}rch exec -- {extracted}`
    // rewrite offloads EVERY build in the chain. Previously only the final
    // segment was wrapped and `cargo build --release && cargo test` compiled
    // the first half locally on the dispatcher with no summary line at all.
    // Segments that do not classify (cd, touch, implicit `go build`, ...)
    // are re-emitted verbatim.
    let mut prefix = String::with_capacity(cmd.len() + segments.len() * EXEC_REWRITE_PREFIX.len());
    for segment in &segments[..segments.len() - 1] {
        if classify_command_inner(segment, 1).is_compilation {
            prefix.push_str(EXEC_REWRITE_PREFIX);
        }
        prefix.push_str(segment);
        prefix.push_str(" && ");
    }

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

/// The rewrite the hook applies to an offloaded segment. Kept here so the
/// compound classifier and the hook agree byte-for-byte on the wrapped form.
const EXEC_REWRITE_PREFIX: &str = "rch exec -- ";

/// Segments of an `&&` chain (all but the last) that *look* like a compilation
/// command but were not classified as one, and therefore stay local when the
/// chain is rewritten by the hook (issue #50).
///
/// Example: `go build ./cmd && cargo test` — an implicit Go output cannot yet
/// be enumerated, so the hook rewrites only `cargo test`;
/// this returns `["go build ./cmd"]` so the hook can say so instead of
/// staying silent.
/// Returns an empty vector for anything that is not a plain `&&` chain.
pub fn compound_local_compilation_segments(cmd: &str) -> Vec<String> {
    let trimmed = cmd.trim();
    if trimmed.len() >= MAX_SPLIT_INPUT_LEN {
        return Vec::new();
    }
    let Some(segments) = split_and_chain(trimmed) else {
        return Vec::new();
    };
    if segments.len() < 2 {
        return Vec::new();
    }
    segments[..segments.len() - 1]
        .iter()
        .filter(|segment| {
            !classify_command_inner(segment, 1).is_compilation
                && starts_with_compilation_command(normalize_command(segment).as_ref())
        })
        .map(|segment| (*segment).to_string())
        .collect()
}

/// Benign pager/sink commands that may sit on the right-hand side of a pipe
/// without transforming the build's *input*. Piping a compilation command's
/// output into one of these is safe to offload — the offloaded command's
/// output is simply re-piped into the same pager locally.
///
/// We intentionally keep this list small and conservative. Commands that
/// would alter exit status semantics in a surprising way, or that consume
/// and re-emit transformed data feeding a subsequent build, are excluded.
const BENIGN_PAGER_COMMANDS: &[&str] = &[
    "tee", "head", "cat", "grep", "less", "more", "tail", "wc", "rg",
];

/// Try to classify a `bash -c "<cmd>"` / `sh -c "<cmd>"` wrapper by extracting
/// and classifying the inner command (issue #24, item 2).
///
/// On success the inner command is offloaded directly (the shell wrapper is
/// dropped, since `rch exec -- <inner>` runs the same program). We mirror the
/// `cd X && ...` compound handling: the inner command is classified at depth 0
/// so it can itself be a compound / benign-suffix / further-wrapped command.
///
/// Conservative: we only handle the simple, single-quoted-string form
/// `bash -c "<inner>"` with no trailing tokens after the inner string and no
/// extra flags before `-c`. Anything more exotic falls through to Tier 1.
fn try_classify_wrapped_command(cmd: &str) -> Option<Classification> {
    let cmd = cmd.trim();

    // Match `bash -c` or `sh -c` (also /bin/bash, /usr/bin/sh, etc.) followed by
    // a single quoted argument that is the entire remainder of the command.
    let rest = strip_shell_dash_c_prefix(cmd)?;
    let rest = rest.trim_start();

    // The remainder must be a single quoted string and nothing else after it.
    let inner = extract_single_quoted_argument(rest)?;
    if inner.trim().is_empty() {
        return None;
    }

    // Classify the inner command at depth 0 so it can itself be compound or
    // carry a benign suffix (e.g. `bash -c "cd x && cargo test > log 2>&1"`).
    let inner_classification = classify_command_inner(&inner, 0);
    if !inner_classification.is_compilation {
        return None;
    }

    // Rebuild the command that should actually be offloaded. If the inner
    // command was itself compound/suffixed, prefer its rewritten form so the
    // prefix/suffix is preserved; otherwise the inner command is offloaded
    // verbatim.
    let (prefix, extracted) = match (
        &inner_classification.command_prefix,
        &inner_classification.extracted_command,
    ) {
        (Some(p), Some(e)) => (p.clone(), e.clone()),
        _ => (String::new(), inner.trim().to_string()),
    };

    Some(Classification::compound_compilation(
        inner_classification.kind?,
        inner_classification.confidence,
        "shell -c wrapper with compilation command",
        prefix,
        extracted,
    ))
}

/// Strip a leading `bash -c` / `sh -c` (with optional absolute path) and return
/// the remainder of the command. Returns `None` if the prefix does not match.
fn strip_shell_dash_c_prefix(cmd: &str) -> Option<&str> {
    // Split the leading whitespace-delimited words to inspect the shell + flag,
    // but return a slice of the ORIGINAL string for the remainder so quoting in
    // the inner argument is preserved.
    let trimmed = cmd.trim_start();
    let mut idx = 0;
    let bytes = trimmed.as_bytes();

    // Word 1: the shell executable.
    let word1_end = next_word_end(bytes, idx)?;
    let shell = &trimmed[idx..word1_end];
    if !shell_basename_is(shell, "bash") && !shell_basename_is(shell, "sh") {
        return None;
    }
    idx = skip_spaces(bytes, word1_end);

    // Word 2: must be exactly `-c`.
    let word2_end = next_word_end(bytes, idx)?;
    if &trimmed[idx..word2_end] != "-c" {
        return None;
    }
    idx = skip_spaces(bytes, word2_end);

    if idx >= trimmed.len() {
        return None;
    }
    Some(&trimmed[idx..])
}

/// Return true if `word`'s basename (after the last `/`) equals `name`.
fn shell_basename_is(word: &str, name: &str) -> bool {
    word.rsplit('/').next().map(|b| b == name).unwrap_or(false)
}

/// Index just past the end of the (unquoted) word starting at `start`.
/// Returns `None` if `start` is already at end of input.
fn next_word_end(bytes: &[u8], start: usize) -> Option<usize> {
    if start >= bytes.len() || bytes[start].is_ascii_whitespace() {
        return None;
    }
    let mut i = start;
    while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    Some(i)
}

/// Skip ASCII spaces/tabs starting at `start`, returning the next non-space index.
fn skip_spaces(bytes: &[u8], start: usize) -> usize {
    let mut i = start;
    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    i
}

/// Extract the contents of a single `"..."` or `'...'` quoted argument that
/// spans the ENTIRE input (modulo surrounding whitespace). Returns `None` if
/// the input is not exactly one quoted string (e.g. it has trailing tokens, or
/// embedded unescaped quotes of the same kind that would terminate early).
fn extract_single_quoted_argument(s: &str) -> Option<String> {
    let s = s.trim();
    let bytes = s.as_bytes();
    if bytes.len() < 2 {
        return None;
    }
    let quote = bytes[0];
    if quote != b'"' && quote != b'\'' {
        return None;
    }

    let mut out = String::with_capacity(s.len());
    let mut i = 1;
    while i < bytes.len() {
        let b = bytes[i];
        // Backslash escaping only applies inside double quotes (POSIX).
        if quote == b'"' && b == b'\\' && i + 1 < bytes.len() {
            out.push(bytes[i + 1] as char);
            i += 2;
            continue;
        }
        if b == quote {
            // Closing quote: everything after must be whitespace only.
            if s[i + 1..].trim().is_empty() {
                return Some(out);
            }
            return None;
        }
        out.push(b as char);
        i += 1;
    }
    // Unterminated quote.
    None
}

/// Try to classify a compilation command followed ONLY by a benign trailing
/// structure (issue #24, item 1):
///   - backgrounding: `cargo test ... &`
///   - benign stdout/stderr file redirect: `cargo test ... > file 2>&1`
///   - pipe into a benign pager: `cargo check --lib 2>&1 | head`
///
/// The leading command (everything before the first top-level structural
/// operator) is classified as a normal command. If it is a compilation
/// command, the benign suffix is re-attached to the offloaded command so the
/// shell re-applies it to `rch exec`'s output:
///   `cargo check --lib 2>&1 | head` → `rch exec -- cargo check --lib 2>&1 | head`
///
/// Conservative rejections (fall through to Tier 1):
///   - input redirects (`< file`) — transform the command's INPUT
///   - pipes into anything not on `BENIGN_PAGER_COMMANDS` (could chain a build
///     or transform data)
///   - any subshell / command substitution / `&&` / `||` / `;` chaining
///   - more than one pipe stage (keep it simple and safe)
fn try_classify_benign_suffix_command(cmd: &str) -> Option<Classification> {
    let cmd = cmd.trim();

    // This helper runs before the general Tier 1 structure check. Reject line
    // breaks here too, or a redirect/pipe on the first line can make a second
    // shell command look like part of an otherwise benign suffix.
    if cmd.bytes().any(|byte| matches!(byte, b'\n' | b'\r')) {
        return None;
    }

    // Bail out fast on chaining / subshell / capture / input-redirect forms;
    // those are handled (or rejected) elsewhere and are never "benign suffix".
    if cmd.contains("&&") || cmd.contains("||") || cmd.contains(';') {
        return None;
    }
    if cmd.contains('(') || cmd.contains('`') || cmd.contains("$(") {
        return None;
    }

    // Locate the first top-level (unquoted) structural boundary: a single `|`,
    // a standalone trailing `&`, or a file-redirect `>` / `<`.
    let boundary = find_first_structural_boundary(cmd)?;
    let (leading_raw, suffix_raw) = cmd.split_at(boundary.byte_pos);
    let leading = leading_raw.trim();
    let suffix = suffix_raw; // keep the operator + whatever follows
    if leading.is_empty() {
        return None;
    }

    // Validate the suffix is benign for this boundary kind.
    if !suffix_is_benign(boundary.kind, suffix) {
        return None;
    }

    // Classify the leading command at depth 1 so it is treated as a single
    // command (no further splitting / wrapper handling).
    let leading_classification = classify_command_inner(leading, 1);
    if !leading_classification.is_compilation {
        return None;
    }

    // Preserve the validated command verbatim. Rebuilding it with normalized
    // whitespace changes the meaning of adjacent file-descriptor redirects:
    // `cargo build 2>errors.txt` must not become `cargo build 2 >errors.txt`.
    let extracted = cmd.to_string();

    Some(Classification::compound_compilation(
        leading_classification.kind?,
        leading_classification.confidence,
        "compilation command with benign trailing redirect/pipe/background",
        String::new(),
        extracted,
    ))
}

/// Kind of structural boundary found at the top level of a command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BoundaryKind {
    /// A single `|` pipe.
    Pipe,
    /// A standalone trailing `&` (backgrounding).
    Background,
    /// A `>` / `>>` output file redirect.
    OutputRedirect,
    /// A `<` input file redirect (always rejected for offload).
    InputRedirect,
}

struct StructuralBoundary {
    byte_pos: usize,
    kind: BoundaryKind,
}

/// Find the first top-level (unquoted) structural boundary in `cmd`, skipping
/// fd-to-fd redirects like `2>&1` / `>&2` which are NOT boundaries (they belong
/// to the preceding command and are safe to offload inline).
fn find_first_structural_boundary(cmd: &str) -> Option<StructuralBoundary> {
    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'\\' && !in_single {
            escaped = true;
            i += 1;
            continue;
        }
        if b == b'\'' && !in_double {
            in_single = !in_single;
            i += 1;
            continue;
        }
        if b == b'"' && !in_single {
            in_double = !in_double;
            i += 1;
            continue;
        }
        if in_single || in_double {
            i += 1;
            continue;
        }

        match b {
            b'|' => {
                // `||` is chaining and is handled/rejected by the caller's guard,
                // but be defensive.
                if i + 1 < len && bytes[i + 1] == b'|' {
                    return None;
                }
                return Some(StructuralBoundary {
                    byte_pos: i,
                    kind: BoundaryKind::Pipe,
                });
            }
            b'&' => {
                // `&&` is chaining (rejected by caller). A standalone `&` is
                // backgrounding. `2>&1` / `>&2` are fd dups: prev byte is `>`.
                if i + 1 < len && bytes[i + 1] == b'&' {
                    return None;
                }
                let prev = if i > 0 { bytes[i - 1] } else { 0 };
                if prev == b'>' {
                    // part of an fd-to-fd redirect, not a boundary
                    i += 1;
                    continue;
                }
                return Some(StructuralBoundary {
                    byte_pos: i,
                    kind: BoundaryKind::Background,
                });
            }
            b'>' => {
                // Skip fd-to-fd redirects `>&` (e.g. 2>&1) — not a boundary.
                if i + 1 < len && bytes[i + 1] == b'&' {
                    i += 2;
                    if i < len && bytes[i].is_ascii_digit() {
                        i += 1;
                    }
                    continue;
                }
                // `>(` process substitution — leave for Tier 1 to reject.
                if i + 1 < len && bytes[i + 1] == b'(' {
                    return None;
                }
                return Some(StructuralBoundary {
                    byte_pos: i,
                    kind: BoundaryKind::OutputRedirect,
                });
            }
            b'<' => {
                if i + 1 < len && bytes[i + 1] == b'(' {
                    return None;
                }
                return Some(StructuralBoundary {
                    byte_pos: i,
                    kind: BoundaryKind::InputRedirect,
                });
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// Validate that the trailing structure (operator + remainder) is benign for
/// offloading, given the kind of the first boundary.
fn suffix_is_benign(kind: BoundaryKind, suffix: &str) -> bool {
    // The suffix must not itself contain a further top-level boundary that we
    // haven't validated (e.g. `> log | tee x` or `| head | build`). We allow at
    // most ONE structural stage by requiring that, after the first boundary,
    // the remainder has no additional unquoted boundary — EXCEPT fd-to-fd dups.
    match kind {
        BoundaryKind::InputRedirect => false,
        BoundaryKind::Background => {
            // `cmd &` — only valid if `&` is the LAST meaningful token.
            // Reject `cmd & other` (a second command after backgrounding).
            let after = suffix.trim_start_matches('&').trim();
            after.is_empty()
        }
        BoundaryKind::OutputRedirect => {
            // `> file 2>&1`, `>> file`, `> a.log` — must not contain a further
            // pipe / background / input redirect / chaining.
            !suffix_has_disallowed_followup(suffix)
        }
        BoundaryKind::Pipe => {
            // `| <pager> ...` — the RHS command word must be a benign pager and
            // there must be no further pipe stage or chaining.
            let rhs = suffix.trim_start_matches('|').trim();
            if rhs.is_empty() {
                return false;
            }
            let rhs_cmd = rhs.split_whitespace().next().unwrap_or("");
            let rhs_base = rhs_cmd.rsplit('/').next().unwrap_or(rhs_cmd);
            if !BENIGN_PAGER_COMMANDS.contains(&rhs_base) {
                return false;
            }
            !suffix_has_disallowed_followup(rhs)
        }
    }
}

/// Returns true if `s` contains ANY further disallowed top-level structural
/// operator (a pipe, backgrounding, or input redirect) anywhere after the
/// initial benign stage. Output redirects (`> file`, `2>&1`) are allowed to
/// repeat (e.g. `> out.log 2>&1`), but a pipe/background/input redirect mixed
/// into the suffix means it is more than a single benign stage and must not be
/// offloaded.
///
/// We scan the WHOLE string (not just the first boundary) so forms like
/// `> a.log < in.txt` — where the dangerous `< in.txt` follows a benign `>` —
/// are correctly rejected.
fn suffix_has_disallowed_followup(s: &str) -> bool {
    let mut rest = s;
    loop {
        match find_first_structural_boundary(rest) {
            Some(b) => {
                if matches!(
                    b.kind,
                    BoundaryKind::Pipe | BoundaryKind::Background | BoundaryKind::InputRedirect
                ) {
                    return true;
                }
                // Benign output redirect: advance past it and keep scanning the
                // remainder for any disallowed operator.
                let next = b.byte_pos + 1;
                if next >= rest.len() {
                    return false;
                }
                rest = &rest[next..];
            }
            None => return false,
        }
    }
}

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

        // POSIX: backslash is LITERAL inside single quotes; only honor it as an
        // escape when not in a single-quoted span, or the next `'` is wrongly
        // swallowed and the quote stays "open", hiding an exposed operator
        // (bd-review-singlequote-escape).
        if b == b'\\' && !in_single {
            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;
        }

        // POSIX: backslash is LITERAL inside single quotes (see
        // bd-review-singlequote-escape); only treat it as an escape elsewhere.
        if c == '\\' && !in_single {
            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 0.5: Compound / wrapper / benign-suffix handling, mirroring
    // classify_command_inner(). Without this branch, diagnostics could reject a
    // command such as `cd /repo && cargo build`, `bash -c "cargo test"`, or
    // `cargo check 2>&1 | head` while the hook classifier accepts and offloads
    // it (issue #24).
    if cmd.len() < MAX_SPLIT_INPUT_LEN
        && let Some((classification, structure_reason)) = try_classify_compound_command(cmd)
            .map(|c| (c, "safe compound command with compilation suffix"))
            .or_else(|| {
                try_classify_wrapped_command(cmd)
                    .map(|c| (c, "shell -c wrapper with compilation command"))
            })
            .or_else(|| {
                try_classify_benign_suffix_command(cmd).map(|c| {
                    (
                        c,
                        "compilation command with benign trailing redirect/pipe/background",
                    )
                })
            })
    {
        let normalized = classification
            .extracted_command
            .clone()
            .unwrap_or_else(|| cmd.to_string());

        tiers.push(ClassificationTier {
            tier: 1,
            name: Cow::Borrowed(TIER_STRUCTURE_ANALYSIS),
            decision: TierDecision::Pass,
            reason: Cow::Borrowed(structure_reason),
        });
        tiers.push(ClassificationTier {
            tier: 2,
            name: Cow::Borrowed(TIER_KEYWORD_FILTER),
            decision: TierDecision::Pass,
            reason: Cow::Borrowed("keyword present in extracted command"),
        });
        tiers.push(ClassificationTier {
            tier: 3,
            name: Cow::Borrowed(TIER_NEVER_INTERCEPT),
            decision: TierDecision::Pass,
            reason: Cow::Borrowed("extracted command passed never-intercept checks"),
        });
        tiers.push(ClassificationTier {
            tier: 4,
            name: Cow::Borrowed(TIER_FULL_CLASSIFICATION),
            decision: TierDecision::Pass,
            reason: classification.reason.clone(),
        });

        return ClassificationDetails {
            original,
            normalized,
            tiers,
            classification,
        };
    }

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

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

    // Tier 2: command-word compilation filter.
    if !starts_with_compilation_command(normalized) {
        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: normalized.to_string(),
            tiers,
            classification,
        };
    }

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

    // 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,
    }
}

/// Whether a `-flag VALUE` form for `wrapper` consumes the following token as
/// its value (so the value isn't mistaken for the wrapped command word).
/// Only the space-separated forms are listed; `=`-joined and space-attached
/// forms (`--adjustment=10`, `-n10`) carry their value in the same token.
fn wrapper_flag_takes_value(wrapper: &str, flag: &str) -> bool {
    match wrapper {
        "env" => matches!(flag, "-u" | "--unset"),
        "nice" => matches!(flag, "-n" | "--adjustment"),
        "ionice" => matches!(
            flag,
            "-c" | "--class" | "-n" | "--classdata" | "-p" | "--pid"
        ),
        "taskset" => matches!(flag, "-c" | "--cpu-list" | "-p" | "--pid"),
        "chrt" => matches!(flag, "-p" | "--pid"),
        "timeout" => matches!(flag, "-s" | "--signal" | "-k" | "--kill-after"),
        _ => false,
    }
}

/// Heuristic: does `token` look like a `timeout` duration (`60`, `1.5h`, `30s`)
/// or a `chrt` priority (`10`)? Used to decide whether to skip a positional
/// value token without ever eating a real command word.
fn looks_like_duration_or_priority(token: &str) -> bool {
    token.chars().next().is_some_and(|c| c.is_ascii_digit())
}

/// Read a wrapper argument without splitting a fully quoted token. `rch exec`
/// quotes literal flags such as `-f%U` when rebuilding its shell command.
/// Mixed/unterminated quoting is left unrecognized rather than guessing where
/// the wrapped command starts.
pub(crate) fn split_wrapper_word(input: &str) -> Option<(&str, &str)> {
    let input = input.trim_start();
    let first = input.chars().next()?;
    if matches!(first, '\'' | '"') {
        let end = input[1..].find(first)? + 1;
        let word = &input[1..end];
        let rest = &input[end + 1..];
        if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
            return None;
        }
        // Escaped quotes and expansions need shell parsing; do not interpret
        // them as literal flag names here.
        if first == '"' && word.contains(['\\', '$', '`']) {
            return None;
        }
        Some((word, rest.trim_start()))
    } else {
        let (word, rest) = input.split_once(char::is_whitespace).unwrap_or((input, ""));
        if word.contains(['\'', '"', '\\']) {
            return None;
        }
        Some((word, rest.trim_start()))
    }
}

/// 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", "timeout", "nice", "ionice", "chrt", "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"; "time"
                // must not swallow "timeout" — guarded by this whitespace check)
                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.
                    // For value-taking flags (e.g. `nice -n 10`, `taskset -c 0-3`, `env -u VAR`)
                    // we must ALSO consume the following value token, or it is left as the
                    // command word and a real `cargo build` is misclassified as non-compilation
                    // (silent local fallback). Space-attached forms (`-n10`, `--adjustment=10`)
                    // carry their value in the same token and need no extra consume.
                    while let Some((flag, rest_after_flag)) = split_wrapper_word(result) {
                        if !flag.starts_with('-') {
                            break;
                        }
                        result = rest_after_flag;

                        if wrapper_flag_takes_value(wrapper, flag) {
                            let Some((_value, rest_after_value)) = split_wrapper_word(result)
                            else {
                                break;
                            };
                            result = rest_after_value;
                        }
                    }

                    // Positional value wrappers: `timeout <duration> cmd` and
                    // `chrt <prio> cmd` carry a bare (non-flag) value token before
                    // the command. Skip exactly one such token when it looks like a
                    // duration/priority (leading digit), so we never eat the real
                    // command word (e.g. `timeout cargo build` keeps `cargo build`).
                    if matches!(wrapper, "timeout" | "chrt")
                        && let Some((first, after_first)) = result.split_once(char::is_whitespace)
                        && !first.starts_with('-')
                        && looks_like_duration_or_priority(first)
                    {
                        result = after_first.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.eq(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;
        }
        // POSIX: backslash is LITERAL inside single quotes; only honor it as an
        // escape when not in a single-quoted span, or the next `'` is wrongly
        // swallowed and the quote stays "open", hiding an exposed operator
        // (bd-review-singlequote-escape).
        if b == b'\\' && !in_single {
            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;
        }
        // POSIX: backslash is LITERAL inside single quotes; only honor it as an
        // escape when not in a single-quoted span, or the next `'` is wrongly
        // swallowed and the quote stays "open", hiding an exposed operator
        // (bd-review-singlequote-escape).
        if b == b'\\' && !in_single {
            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 whether the invoked command word is one of the compilation tools.
///
/// The keyword filter runs before full classification, so it must be cheap but
/// cannot treat arbitrary arguments as commands. `normalize_command` strips
/// wrappers and environment assignments before this helper is called.
fn starts_with_compilation_command(cmd: &str) -> bool {
    let cmd = cmd.trim_start();
    COMPILATION_KEYWORDS
        .iter()
        .any(|keyword| command_word_matches(cmd, keyword))
}

fn command_word_matches(cmd: &str, keyword: &str) -> bool {
    let Some(rest) = cmd.strip_prefix(keyword) else {
        return false;
    };
    rest.is_empty() || rest.starts_with(char::is_whitespace)
}

/// Bare positional target tokens of a `make`/`ninja` command.
///
/// Skips the program name, option flags (`-x`, `--long`, combined `-j8`), the
/// value token consumed by any flag in `value_flags`, and `VAR=value`
/// assignments. This lets the maintenance-target check match WHOLE tokens
/// (`clean`, `install`, …) instead of a substring anywhere in the command, so
/// real builds like `make CFLAGS=-Iinstall/include`, `make TARGET=cleanup`,
/// `ninja build/clean_obj.o`, and `make -C install` / `ninja -C clean` (a
/// directory argument, not the target) are no longer misclassified as
/// maintenance.
fn positional_build_targets<'a>(cmd: &'a str, value_flags: &[&str]) -> Vec<&'a str> {
    let mut targets = Vec::new();
    let toks: Vec<&str> = cmd.split_whitespace().skip(1).collect();
    let mut i = 0;
    while i < toks.len() {
        let tok = toks[i];
        if value_flags.contains(&tok) {
            i += 2; // flag consumes the following token as its value
        } else if tok.starts_with('-') || tok.contains('=') {
            i += 1; // other flag (incl. combined `-j8`) or VAR=value assignment
        } else {
            targets.push(tok);
            i += 1;
        }
    }
    targets
}

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

    // `cargo-zigbuild` invoked as a standalone binary (this is what `cargo
    // zigbuild ...` execs). Note the hyphen: it does NOT match `cargo ` above.
    if cmd.starts_with("cargo-zigbuild ") || cmd.eq("cargo-zigbuild") {
        return classify_cargo_zigbuild(cmd);
    }

    if cmd.starts_with("cargo-xwin ") || cmd.eq("cargo-xwin") {
        return if let Some(kind) = cargo_xwin_compilation_kind(cmd) {
            Classification::compilation(kind, 0.95, "cargo-xwin compilation")
        } else {
            Classification::not_compilation("cargo-xwin subcommand not interceptable")
        };
    }

    // rustc
    if cmd.starts_with("rustc ") || cmd.eq("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.eq("make") || cmd.starts_with("make ")) {
        // Don't intercept "make clean", "make install", etc. — but match them as
        // whole TARGET tokens, not as a substring anywhere. A `contains` check
        // rejected real builds like "make CFLAGS=-Iinstall/include" and
        // "make TARGET=cleanup" as maintenance.
        const MAKE_VALUE_FLAGS: [&str; 8] = [
            "-f",
            "-C",
            "-I",
            "-o",
            "-W",
            "--file",
            "--directory",
            "--include-dir",
        ];
        const MAKE_MAINTENANCE_TARGETS: [&str; 4] = ["clean", "install", "distclean", "uninstall"];
        let is_maintenance = positional_build_targets(cmd, &MAKE_VALUE_FLAGS)
            .iter()
            .any(|target| MAKE_MAINTENANCE_TARGETS.contains(target));
        if is_maintenance {
            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.eq("cmake") {
        let mut tokens = cmd.split_whitespace();
        let _ = tokens.next(); // "cmake"
        if tokens.any(|token| token.eq("--build") || token.starts_with("--build=")) {
            return Classification::compilation(CompilationKind::CmakeBuild, 0.90, "cmake --build");
        }
    }

    // Ninja
    if cmd.starts_with("ninja") && (cmd.eq("ninja") || cmd.starts_with("ninja ")) {
        // Match the `-t clean` tool form and a whole-token `clean` target — not
        // the substring "clean" anywhere ("ninja build/clean_obj.o" is a real
        // build, and "ninja -C clean" cleans a directory argument).
        const NINJA_VALUE_FLAGS: [&str; 8] = ["-C", "-f", "-j", "-k", "-l", "-d", "-t", "-w"];
        let raw: Vec<&str> = cmd.split_whitespace().collect();
        let is_clean_tool = raw.windows(2).any(|w| w[0] == "-t" && w[1] == "clean");
        let is_clean_target = positional_build_targets(cmd, &NINJA_VALUE_FLAGS).contains(&"clean");
        if is_clean_tool || is_clean_target {
            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.eq("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");
        }
    }

    // Nix commands (the `nix` multi-tool and the legacy `nix-build`).
    // Only build-like, NON-interactive, non-mutating invocations are offloaded;
    // classify_nix uses an allowlist so everything else falls back to local.
    if cmd.eq("nix-build")
        || cmd.starts_with("nix-build ")
        || cmd.eq("nix")
        || cmd.starts_with("nix ")
    {
        return classify_nix(cmd);
    }

    // Bun commands
    let mut tokens = cmd.split_whitespace();
    if tokens.next().is_some_and(|token| token.eq("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.eq("-w") || a.eq("--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.eq("-w") || a.eq("--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");
            }
            _ => {}
        }
    }

    // Go commands
    if cmd.starts_with("go ") {
        return classify_go(cmd);
    }

    // TypeScript: `tsc ...` and `npx tsc ...`.
    //
    // `npx` is not a normalize_command wrapper (it can run arbitrary packages),
    // so match it explicitly here rather than stripping it globally.
    if let Some(rest) = cmd
        .strip_prefix("tsc ")
        .or_else(|| cmd.strip_prefix("npx tsc "))
    {
        return classify_tsc(rest);
    }

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

/// Classify `tsc` / `npx tsc` invocations.
///
/// Only `--noEmit` typechecks are offloaded. An emitting `tsc` run writes `.js`
/// / `.d.ts` / `.tsbuildinfo` into the local tree, and these kinds are
/// stream-only (no artifact sync-back), so offloading an emitting run would
/// return exit 0 with no output files — a silent correctness bug. Emitting runs
/// stay local.
///
/// `args` is the command with the leading `tsc ` / `npx tsc ` already stripped.
fn classify_tsc(args: &str) -> Classification {
    let tokens = args.split_whitespace();
    let mut no_emit = false;
    for token in tokens {
        // --watch is interactive and never terminates; never intercept.
        if token.eq("-w") || token.eq("--watch") || token.eq("--watchFile") {
            return Classification::not_compilation("tsc --watch is interactive (not intercepted)");
        }
        // tsc's flag parsing is case-insensitive (--noemit == --noEmit).
        if token.eq_ignore_ascii_case("--noemit") {
            no_emit = true;
        }
    }

    if !no_emit {
        return Classification::not_compilation(
            "tsc without --noEmit emits output files locally (not intercepted)",
        );
    }

    Classification::compilation(CompilationKind::Tsc, 0.95, "tsc --noEmit typecheck")
}

/// Parse a bounded literal argv without interpreting shell expansions. Whole
/// quoted words cover `rch exec`'s reconstructed flags and output filenames;
/// mixed or escaped quoting is conservatively left to local execution.
fn literal_flag_words(mut command: &str) -> Option<Vec<&str>> {
    if command.len() > 65_536 || command.contains(['\0', '\r', '\n']) {
        return None;
    }
    let mut words = Vec::new();
    while !command.trim().is_empty() {
        command = command.trim_start();
        let quoted = command.starts_with(['\'', '"']);
        let (word, rest) = split_wrapper_word(command)?;
        if !quoted
            && word.contains([
                '$', '`', '*', '?', '[', '{', '}', '~', '|', '&', ';', '<', '>', '(', ')', '#',
            ])
        {
            return None;
        }
        words.push(word);
        if words.len() > 4096 {
            return None;
        }
        command = rest;
    }
    Some(words)
}

/// The common linker flags that do not introduce another output file. Go's
/// lower-level flags also include profiles, temporary directories and external
/// commands, so arbitrary -ldflags/-gcflags/-asmflags cannot share a one-file
/// delivery contract.
fn go_linker_flags_have_one_output(value: &str) -> bool {
    let mut flags = value.split_whitespace();
    let mut present = false;
    while let Some(flag) = flags.next() {
        present = true;
        match flag {
            "-s" | "-w" | "-s=true" | "-s=false" | "-w=true" | "-w=false" => {}
            "-X" => {
                if !flags.next().is_some_and(|value| {
                    value
                        .split_once('=')
                        .is_some_and(|(name, _)| !name.is_empty())
                }) {
                    return false;
                }
            }
            _ => return false,
        }
    }
    present
}

/// The one project-relative file promised by a supported `go build -o`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GoBuildOutput {
    /// Literal path, relative to the invocation directory.
    pub path: String,
    /// Index of the -o option in the normalized argv, including `go build`.
    /// The executor uses this to replace only the actual output option, never
    /// an opaque argument value that happens to resemble a flag.
    pub option_index: usize,
}

/// Plan the explicit file output of a supported Go build.
///
/// Classification and durable retrieval use this same parser. Implicit output
/// names depend on the selected packages (including what ./... matches), and
/// directories or native-library build modes can produce multiple files. Keep
/// those forms local until their complete output sets can be planned.
#[must_use]
pub fn go_build_output(command: &str) -> Option<GoBuildOutput> {
    let normalized = normalize_command(command);
    let words = literal_flag_words(&normalized)?;
    let mut args = words.into_iter().enumerate();
    if args.next()?.1 != "go" || args.next()?.1 != "build" {
        return None;
    }
    let mut output = None;
    let mut packages_started = false;
    while let Some((option_index, arg)) = args.next() {
        if !arg.starts_with('-') {
            packages_started = true;
            continue;
        }
        if packages_started {
            return None;
        }
        let (flag, inline) = arg
            .split_once('=')
            .map_or((arg, None), |(flag, value)| (flag, Some(value)));
        match flag {
            "-o" => {
                let path = inline.or_else(|| args.next().map(|(_, value)| value))?;
                if output
                    .replace(GoBuildOutput {
                        path: path.to_owned(),
                        option_index,
                    })
                    .is_some()
                    || path.is_empty()
                    || path == "-"
                    || path.ends_with('/')
                    || path.chars().any(char::is_control)
                    || !std::path::Path::new(path).components().all(|part| {
                        matches!(
                            part,
                            std::path::Component::Normal(_) | std::path::Component::CurDir
                        )
                    })
                    || !std::path::Path::new(path)
                        .components()
                        .any(|part| matches!(part, std::path::Component::Normal(_)))
                {
                    return None;
                }
            }
            "-buildmode" => {
                if !matches!(
                    inline.or_else(|| args.next().map(|(_, value)| value))?,
                    "default" | "exe" | "pie"
                ) {
                    return None;
                }
            }
            "-compiler" => {
                if inline.or_else(|| args.next().map(|(_, value)| value))? != "gc" {
                    return None;
                }
            }
            "-p" | "-tags" | "-covermode" | "-coverpkg" => {
                if inline
                    .or_else(|| args.next().map(|(_, value)| value))?
                    .is_empty()
                {
                    return None;
                }
            }
            "-ldflags" => {
                if !go_linker_flags_have_one_output(
                    inline.or_else(|| args.next().map(|(_, value)| value))?,
                ) {
                    return None;
                }
            }
            "-mod" => {
                if !matches!(
                    inline.or_else(|| args.next().map(|(_, value)| value))?,
                    "readonly" | "vendor"
                ) {
                    return None;
                }
            }
            "-buildvcs" => {
                if inline.is_some_and(|value| !matches!(value, "auto" | "true" | "false")) {
                    return None;
                }
            }
            "-a" | "-race" | "-msan" | "-asan" | "-v" | "-x" | "-trimpath" | "-modcacherw"
            | "-cover" => {
                if inline.is_some_and(|value| !matches!(value, "true" | "false")) {
                    return None;
                }
            }
            _ => return None,
        }
    }
    output
}

/// Classify Go builds with a complete explicit output contract, and streaming
/// test/vet commands. File-producing test modes remain local until they have an
/// equivalent contract; arbitrary subcommands are never offloaded here.
fn classify_go(cmd: &str) -> Classification {
    let mut tokens = cmd.split_whitespace();
    // Skip the leading "go".
    tokens.next();

    let subcommand = match tokens.next() {
        Some(sub) => sub,
        None => return Classification::not_compilation("bare `go` is not a compilation command"),
    };

    // Remaining args, used for flag checks below.
    let args: Vec<&str> = tokens.collect();

    match subcommand {
        "build" => {
            if go_build_output(cmd).is_none() {
                return Classification::not_compilation(
                    "go build requires a supported explicit -o file for artifact delivery",
                );
            }
            if !cfg!(unix) {
                return Classification::not_compilation(
                    "Go output delivery requires a Unix dispatcher and worker",
                );
            }
            Classification::compilation(CompilationKind::GoBuild, 0.95, "go build command")
        }
        "test" => {
            // These flags accept both separated and = values. Profiling flags
            // may also be passed directly to the test binary as -test.*.
            if args.iter().any(|arg| {
                // Also catch a quoted -flag=value whose value contains spaces.
                // A flag-looking value is conservatively left local.
                let arg = arg.trim_matches(['\'', '"']);
                if !arg.starts_with('-') {
                    return false;
                }
                let flag = arg.split_once('=').map_or(arg, |(flag, _)| flag);
                let flag = flag.trim_start_matches('-');
                let flag = flag.strip_prefix("test.").unwrap_or(flag);
                matches!(
                    flag,
                    "c" | "o"
                        | "exec"
                        | "coverprofile"
                        | "cpuprofile"
                        | "memprofile"
                        | "blockprofile"
                        | "mutexprofile"
                        | "trace"
                        | "outputdir"
                        | "fuzz"
                        | "fuzzcachedir"
                        | "gocoverdir"
                        | "testlogfile"
                )
            }) {
                return Classification::not_compilation(
                    "go test emits files or uses a local execution wrapper (not intercepted)",
                );
            }
            Classification::compilation(CompilationKind::GoTest, 0.95, "go test command")
        }
        "vet" => Classification::compilation(CompilationKind::GoVet, 0.95, "go vet command"),
        _ => Classification::not_compilation("go subcommand is not a compilation command"),
    }
}

/// Whether Cargo will build and verify a package archive without publishing it.
///
/// Kept separate from the protocol kind so the client can use the existing
/// `CargoBuild` worker contract and return the archive that Cargo verified.
/// Unknown options, shell expansion/quoting, and argument separators are
/// declined: a token that merely occurs inside an option value must never
/// authorize offloading a real `cargo publish` invocation.
pub fn is_cargo_package_verification(command: &str) -> bool {
    let normalized = normalize_command(command);
    let cmd = normalized.as_ref();
    if check_structure(cmd).is_some() || cmd.contains(['\'', '"', '\\', '$', '`']) {
        return false;
    }

    let mut tokens = cmd.split_whitespace();
    if tokens.next() != Some("cargo") {
        return false;
    }

    let mut subcommand = None;
    let mut dry_run = false;
    const VALUE_FLAGS: &[&str] = &[
        "--index",
        "--registry",
        "--token",
        "--color",
        "--config",
        "-Z",
        "-C",
        "-p",
        "--package",
        "--exclude",
        "-F",
        "--features",
        "-j",
        "--jobs",
        "--target",
        "--target-dir",
        "-m",
        "--manifest-path",
        "--lockfile-path",
        "--message-format",
    ];

    while let Some(token) = tokens.next() {
        if subcommand.is_none() && token.starts_with('+') {
            continue;
        }
        if matches!(token, "package" | "publish") && subcommand.is_none() {
            subcommand = Some(token);
            continue;
        }
        if VALUE_FLAGS.contains(&token) {
            if tokens.next().is_none_or(|value| value.starts_with('-')) {
                return false;
            }
            continue;
        }
        if let Some((flag, value)) = token.split_once('=')
            && VALUE_FLAGS.contains(&flag)
            && !value.is_empty()
        {
            continue;
        }
        if ["-j", "-p", "-F", "-m", "-Z"]
            .iter()
            .any(|flag| token.starts_with(flag) && token.len() > flag.len())
        {
            continue;
        }
        match token {
            "--dry-run" | "-n" => dry_run = true,
            "--workspace"
            | "--allow-dirty"
            | "--no-metadata"
            | "--exclude-lockfile"
            | "--all-features"
            | "--no-default-features"
            | "--keep-going"
            | "--locked"
            | "--offline"
            | "--frozen"
            | "--verbose"
            | "-v"
            | "-vv"
            | "-vvv"
            | "--quiet"
            | "-q" => {}
            // Includes --no-verify, --list/-l, --help/-h and --. Reject unknown
            // value-taking flags rather than mistaking their value for -n.
            _ => return false,
        }
    }

    matches!(subcommand, Some("package")) || (subcommand == Some("publish") && dry_run)
}

/// Recognize explicit cargo-xwin build, check, and clippy entry points, without
/// treating a mention in a Cargo option value as permission to relax the native
/// MSVC gate. Requested Rust targets and toolchains still go through admission.
/// Cache mutation, environment inspection, and other subcommands are deliberately
/// outside this offload surface.
#[must_use]
pub fn cargo_xwin_compilation_kind(command: &str) -> Option<CompilationKind> {
    let normalized = normalize_command(command);
    let cmd = normalized.as_ref();
    let mut tokens = cmd.split_whitespace().map(unquote_literal_option_word);
    if check_structure(cmd).is_some()
        || tokens
            .clone()
            .any(|token| token.contains(['\'', '"', '\\', '$', '`']))
    {
        return None;
    }
    let subcommand = match tokens.next() {
        Some("cargo-xwin") => {
            let subcommand = tokens.next();
            if subcommand == Some("xwin") {
                tokens.next()
            } else {
                subcommand
            }
        }
        Some("cargo") => loop {
            match tokens.next() {
                Some("xwin") => break tokens.next(),
                Some("--color" | "--config" | "-Z" | "-C") => {
                    if tokens.next().is_none_or(|value| value.starts_with('-')) {
                        return None;
                    }
                }
                Some("--locked" | "--offline" | "--frozen" | "-v" | "-vv" | "-q") => {}
                Some(token)
                    if token.starts_with('+')
                        || token.starts_with("--color=")
                        || token.starts_with("--config=") => {}
                _ => return None,
            }
        },
        _ => return None,
    };
    let kind = match subcommand? {
        "build" => CompilationKind::CargoBuild,
        "check" => CompilationKind::CargoCheck,
        "clippy" => CompilationKind::CargoClippy,
        _ => return None,
    };
    if tokens.any(|token| matches!(token, "--help" | "-h" | "--version" | "-V")) {
        return None;
    }
    Some(kind)
}

/// Backward compatibility helper for cargo-xwin build commands.
#[must_use]
pub fn is_cargo_xwin_build(command: &str) -> bool {
    matches!(
        cargo_xwin_compilation_kind(command),
        Some(CompilationKind::CargoBuild)
    )
}

/// `rch exec` rebuilds its command with `shell_words::join`, which single-quotes
/// every word containing `=`: `cargo --config=build.jobs=2 clippy` arrives as
/// `cargo '--config=build.jobs=2' clippy`. Read such a fully quoted word as its
/// content; a word with any other quoting is returned unchanged.
fn unquote_whole_word(token: &str) -> &str {
    token
        .strip_prefix('\'')
        .and_then(|rest| rest.strip_suffix('\''))
        .filter(|inner| !inner.contains('\''))
        .unwrap_or(token)
}

/// Read simple option words quoted by `shell_words::join` without interpreting
/// quoted command names, standalone values, mixed quoting, or shell syntax.
/// Keeping this decoder shared with admission preserves quoted target options.
pub(crate) fn unquote_literal_option_word(token: &str) -> &str {
    let word = unquote_whole_word(token);
    if word.starts_with('-')
        && word
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || b"-_./=:+,".contains(&byte))
    {
        word
    } else {
        token
    }
}

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

    // Skip an optional +toolchain override AND any leading global flags that can
    // precede the subcommand (e.g. `cargo --offline build`, `cargo -q test`,
    // `cargo --locked check`, `cargo --color never build`). Without this, a
    // global flag was read AS the subcommand, so a real build was misclassified
    // non-compilation and silently run locally. Value-taking global flags
    // written without `=` consume their following value token.
    const CARGO_VALUE_FLAGS: &[&str] = &["--color", "-Z", "-C", "--config"];
    let subcommand = loop {
        let Some(tok) = tokens.next().map(unquote_whole_word) else {
            return Classification::not_compilation("bare cargo command");
        };
        if tok.starts_with('+') {
            // +toolchain override — skip.
            continue;
        }
        if tok.starts_with('-') {
            if !tok.contains('=') && CARGO_VALUE_FLAGS.contains(&tok) {
                // Consume the separate value token (e.g. `--color never`).
                let _ = tokens.next();
            }
            continue;
        }
        break tok;
    };

    match subcommand {
        "build" | "b" => {
            Classification::compilation(CompilationKind::CargoBuild, 0.95, "cargo build")
        }
        "package" | "publish" => {
            if is_cargo_package_verification(cmd) {
                Classification::compilation(
                    CompilationKind::CargoBuild,
                    0.95,
                    "cargo package verification (includes build)",
                )
            } else {
                Classification::not_compilation(
                    "cargo package/publish without supported verification (never-intercept)",
                )
            }
        }
        "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"),
        // `cargo zigbuild ...` — cross-compile via zig. Same offload shape as
        // `cargo build` (produces a real artifact under target/<triple>/), but
        // gated additionally on the worker having zig + cargo-zigbuild + the
        // requested rustup target (enforced downstream by needs_zig/needs_targets).
        "zigbuild" => {
            Classification::compilation(CompilationKind::CargoZigbuild, 0.95, "cargo zigbuild")
        }
        "xwin" => {
            if let Some(kind) = cargo_xwin_compilation_kind(cmd) {
                Classification::compilation(kind, 0.95, "cargo xwin compilation")
            } else {
                Classification::not_compilation("cargo xwin subcommand not interceptable")
            }
        }
        "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"),
    }
}

/// Classify the standalone `cargo-zigbuild` binary (what `cargo zigbuild ...`
/// execs). Only the artifact-producing build forms are offloaded:
///
/// - `cargo-zigbuild zigbuild ...` → cross-build via zig (the canonical form)
/// - `cargo-zigbuild build ...` → same, spelled with the plain subcommand
///
/// Everything else (`check`, `test`, `run`, metadata) is declined here and runs
/// locally, matching the conservative stance in `classify_cargo` for non-build
/// forms. All accepted forms map to `CompilationKind::CargoZigbuild`.
fn classify_cargo_zigbuild(cmd: &str) -> Classification {
    let mut tokens = cmd.split_whitespace();
    // Token 0: "cargo-zigbuild" (already validated by caller).
    let _bin = tokens.next();

    // Skip an optional +toolchain override and leading global flags, mirroring
    // classify_cargo so `cargo-zigbuild +nightly zigbuild ...` still classifies.
    const CARGO_VALUE_FLAGS: &[&str] = &["--color", "-Z", "-C", "--config"];
    let subcommand = loop {
        let Some(tok) = tokens.next().map(unquote_whole_word) else {
            return Classification::not_compilation("bare cargo-zigbuild command");
        };
        if tok.starts_with('+') {
            continue;
        }
        if tok.starts_with('-') {
            if !tok.contains('=') && CARGO_VALUE_FLAGS.contains(&tok) {
                let _ = tokens.next();
            }
            continue;
        }
        break tok;
    };

    match subcommand {
        "zigbuild" | "build" | "b" => Classification::compilation(
            CompilationKind::CargoZigbuild,
            0.95,
            "cargo-zigbuild build",
        ),
        _ => Classification::not_compilation("cargo-zigbuild subcommand not interceptable"),
    }
}

/// Nix global flags (appearing BEFORE the subcommand) that consume the following
/// whitespace-separated token as their value. Without skipping the value token
/// we could read it AS the subcommand and either miss a real build or, worse,
/// misclassify — so on any ambiguity we prefer to fall back to local execution.
///
/// This is a best-effort list of the common value-taking global flags; the
/// two-value `--option NAME VALUE` form is handled separately. Space-attached
/// (`--max-jobs=4`) forms carry their value in the same token and need no skip.
const NIX_GLOBAL_VALUE_FLAGS: &[&str] = &[
    "--extra-experimental-features",
    "--experimental-features",
    "--log-format",
    "--max-jobs",
    "-j",
    "--cores",
    "--builders",
    "--store",
    "--file",
    "-f",
    "-I",
    "--include",
];

/// Classify a `nix ...` (multi-tool) or `nix-build ...` (legacy) command.
///
/// Offloadable (build-like, non-interactive, non-mutating):
///   - `nix build ...`         → build a derivation
///   - `nix-build ...`         → legacy derivation build
///   - `nix flake check`       → evaluate + build ALL flake outputs
///   - `nix develop -c <cmd>`  → run a command non-interactively in a dev shell
///   - `nix shell -c <cmd>`    → run a command non-interactively with packages
///
/// NOT offloadable (declined here → local fallback):
///   - bare `nix develop` / `nix shell`  → interactive shells
///   - `nix run` / `nix repl`            → app execution / interactive
///   - `nix flake metadata|show|update|lock|...`, `nix eval|search|...` → metadata
///   - `nix profile|registry|store|copy|...`, `nix-env`, `nix-shell` (no keyword)
///     → mutating / package management
///
/// Nix outputs never travel back (they live in the worker's `/nix/store`); these
/// are streaming, exit-status-only commands. Requires the worker to have nix +
/// a populated `/nix/store` and network access to fetch flake inputs — enforced
/// by the `RequiredRuntime::Nix` capability gate in worker selection.
fn classify_nix(cmd: &str) -> Classification {
    // Legacy `nix-build` is unconditionally a derivation build.
    if cmd.eq("nix-build") || cmd.starts_with("nix-build ") {
        return Classification::compilation(
            CompilationKind::NixBuild,
            0.9,
            "nix-build (legacy) derivation build",
        );
    }

    let mut tokens = cmd.split_whitespace();
    let _nix = tokens.next(); // "nix" (validated by caller)

    // Locate the subcommand, skipping leading global flags (and their values).
    let subcommand = loop {
        let Some(tok) = tokens.next() else {
            return Classification::not_compilation("bare nix command (no subcommand)");
        };
        if tok.starts_with('-') {
            if tok.eq("--option") {
                // `--option NAME VALUE` consumes two following tokens.
                let _ = tokens.next();
                let _ = tokens.next();
            } else if !tok.contains('=') && NIX_GLOBAL_VALUE_FLAGS.contains(&tok) {
                let _ = tokens.next();
            }
            continue;
        }
        break tok;
    };

    // Remaining tokens after the subcommand (for -c/--command and --help checks).
    let rest: Vec<&str> = tokens.collect();
    let wants_help = rest.iter().any(|t| t.eq(&"--help") || t.eq(&"-h"));
    if wants_help {
        return Classification::not_compilation("nix --help (not a build)");
    }
    let has_command_flag = rest.iter().any(|t| t.eq(&"-c") || t.eq(&"--command"));

    match subcommand {
        // `nix build` builds a derivation → offload (streaming, no artifact return).
        "build" => {
            Classification::compilation(CompilationKind::NixBuild, 0.9, "nix build derivation")
        }
        // `nix flake check` evaluates AND builds every flake output (CPU-heavy) →
        // offload. Every other `nix flake <sub>` (metadata/show/update/lock/init/
        // archive/...) is metadata or mutating and must stay local.
        "flake" => {
            let flake_sub = rest.iter().find(|t| !t.starts_with('-'));
            if flake_sub == Some(&"check") {
                Classification::compilation(
                    CompilationKind::NixBuild,
                    0.9,
                    "nix flake check (evaluates + builds all outputs)",
                )
            } else {
                Classification::not_compilation("nix flake subcommand is not a build")
            }
        }
        // `nix develop -c <cmd>` / `nix shell -c <cmd>` run a command
        // non-interactively in the environment → offload. Bare forms are
        // interactive shells and must NOT be intercepted.
        "develop" | "shell" => {
            if has_command_flag {
                let reason = if subcommand == "develop" {
                    "nix develop -c (non-interactive command in dev shell)"
                } else {
                    "nix shell -c (non-interactive command with packages)"
                };
                Classification::compilation(CompilationKind::NixBuild, 0.9, reason)
            } else {
                Classification::not_compilation(
                    "interactive nix shell (no -c/--command; not intercepted)",
                )
            }
        }
        // run / repl / eval / search / profile / registry / store / copy /
        // path-info / why-depends / flake metadata|show|update / --version / ...
        // are execution, mutation, or metadata: never intercepted.
        _ => Classification::not_compilation("nix subcommand is not an offloadable build"),
    }
}

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

        // POSIX: backslash is LITERAL inside single quotes; only honor it as an
        // escape when not in a single-quoted span, or the next `'` is wrongly
        // swallowed and the quote stays "open", hiding an exposed operator
        // (bd-review-singlequote-escape).
        if b == b'\\' && !in_single {
            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::*;

    #[test]
    fn cargo_xwin_compilations_use_their_cargo_contracts() {
        for (subcommand, kind, arguments) in [
            (
                "build",
                CompilationKind::CargoBuild,
                "--release --locked --target x86_64-pc-windows-msvc",
            ),
            (
                "check",
                CompilationKind::CargoCheck,
                "--locked --all-targets --target aarch64-pc-windows-msvc",
            ),
            (
                "clippy",
                CompilationKind::CargoClippy,
                "--locked --all-targets --target=x86_64-pc-windows-msvc -- -D warnings",
            ),
        ] {
            for prefix in [
                "cargo xwin",
                "cargo +nightly-2026-08-31 xwin",
                "cargo --color never --locked xwin",
                "cargo --config build.jobs=2 xwin",
                "env CARGO_HOME=/root/.cargo cargo xwin",
                "cargo-xwin",
                "cargo-xwin xwin",
                "/home/ubuntu/.local/bin/cargo-xwin xwin",
            ] {
                let command = format!("{prefix} {subcommand} {arguments}");
                assert_eq!(
                    cargo_xwin_compilation_kind(&command),
                    Some(kind),
                    "{command}"
                );
                let classification = classify_command(&command);
                assert!(classification.is_compilation, "{command}");
                assert_eq!(classification.kind, Some(kind), "{command}");
            }
        }
    }

    #[test]
    fn cargo_xwin_recognition_declines_unsupported_commands_and_argument_mentions() {
        for command in [
            "cargo xwin",
            "cargo xwin env",
            "cargo xwin cache clear",
            "cargo xwin publish",
            "cargo xwin test",
            "cargo xwin run",
            "cargo xwin unknown",
            "cargo xwin build --help",
            "cargo xwin check --help",
            "cargo xwin clippy --version",
            "cargo-xwin --version",
            "cargo-xwin cache clear",
            "cargo-xwin xwin build --help",
            "cargo-xwin xwin check -h",
            "cargo-xwin clippy -V",
            "cargo-xwin xwin env",
            "cargo-xwin check-extra",
            "cargo xwin --help check",
            "cargo xwin 'check'",
            "cargo xwin $SUBCOMMAND",
            "cargo --config xwin build --target x86_64-pc-windows-msvc",
            "cargo --config xwin check --target x86_64-pc-windows-msvc",
            "cargo --config xwin clippy --target x86_64-pc-windows-msvc",
            "cargo build --manifest-path cargo-xwin --target x86_64-pc-windows-msvc",
            "cargo check --manifest-path 'cargo xwin check' --target x86_64-pc-windows-msvc",
            "cargo clippy --config 'alias.cross=xwin' --target x86_64-pc-windows-msvc",
            "echo cargo xwin check",
            "cargo xwin build && cargo build",
            "cargo xwin check && cargo check",
            "cargo xwin clippy | cat",
        ] {
            assert_eq!(cargo_xwin_compilation_kind(command), None, "{command}");
        }
        for command in [
            "cargo xwin env",
            "cargo xwin cache clear",
            "cargo xwin publish",
            "cargo xwin test",
            "cargo xwin run",
            "cargo xwin unknown",
            "cargo xwin check --help",
            "cargo xwin clippy --version",
            "cargo-xwin --version",
            "cargo-xwin xwin check -h",
            "cargo-xwin clippy -V",
            "cargo-xwin xwin env",
            "cargo-xwin check-extra",
            "cargo xwin 'check'",
        ] {
            assert!(!classify_command(command).is_compilation, "{command}");
        }
    }
    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));
    }

    // ===================== Nix classification (issue #26) =====================

    #[test]
    fn test_nix_build_offloadable() {
        let _guard = test_guard!();
        for cmd in [
            "nix build",
            "nix build .#foo",
            "nix build .#packages.x86_64-linux.default",
            "nix build /path/to/flake#pkg",
            "nix build --extra-experimental-features 'nix-command flakes' .#foo",
            "nix --option sandbox true build .#foo",
            "nix -j4 build .#foo",
            "nix build nixpkgs#hello -o result-hello",
        ] {
            let result = classify_command(cmd);
            assert!(result.is_compilation, "expected offload for `{cmd}`");
            assert_eq!(result.kind, Some(CompilationKind::NixBuild), "`{cmd}`");
            assert!(result.confidence >= 0.85, "`{cmd}` confidence too low");
        }
    }

    #[test]
    fn test_nix_build_legacy_offloadable() {
        let _guard = test_guard!();
        for cmd in ["nix-build", "nix-build .", "nix-build -A hello"] {
            let result = classify_command(cmd);
            assert!(result.is_compilation, "expected offload for `{cmd}`");
            assert_eq!(result.kind, Some(CompilationKind::NixBuild), "`{cmd}`");
        }
    }

    #[test]
    fn test_nix_flake_check_offloadable_but_metadata_not() {
        let _guard = test_guard!();
        let check = classify_command("nix flake check");
        assert!(check.is_compilation, "nix flake check should offload");
        assert_eq!(check.kind, Some(CompilationKind::NixBuild));

        for cmd in [
            "nix flake metadata",
            "nix flake show",
            "nix flake update",
            "nix flake lock",
            "nix flake info",
        ] {
            let result = classify_command(cmd);
            assert!(!result.is_compilation, "`{cmd}` must NOT offload");
        }
    }

    #[test]
    fn test_nix_develop_and_shell_only_with_command() {
        let _guard = test_guard!();
        // Non-interactive `-c`/`--command` forms are offloadable.
        for cmd in [
            "nix develop -c make",
            "nix develop --command cargo build",
            "nix develop .#dev -c bun test",
            "nix shell nixpkgs#gcc -c make",
            "nix shell nixpkgs#hello --command hello",
        ] {
            let result = classify_command(cmd);
            assert!(result.is_compilation, "expected offload for `{cmd}`");
            assert_eq!(result.kind, Some(CompilationKind::NixBuild), "`{cmd}`");
        }
        // Bare interactive shells must NOT be intercepted.
        for cmd in ["nix develop", "nix develop .#dev", "nix shell nixpkgs#gcc"] {
            let result = classify_command(cmd);
            assert!(
                !result.is_compilation,
                "`{cmd}` is interactive; must run local"
            );
        }
    }

    #[test]
    fn test_nix_execution_and_mutation_not_offloaded() {
        let _guard = test_guard!();
        for cmd in [
            "nix run .#app",
            "nix run nixpkgs#hello",
            "nix repl",
            "nix eval .#foo",
            "nix search nixpkgs hello",
            "nix profile install nixpkgs#hello",
            "nix registry list",
            "nix store gc",
            "nix copy --to ssh://host .#foo",
            "nix path-info .#foo",
            "nix --version",
            "nix build --help",
            "nix",
        ] {
            let result = classify_command(cmd);
            assert!(!result.is_compilation, "`{cmd}` must NOT be intercepted");
        }
    }

    #[test]
    fn test_nix_legacy_mutating_tools_have_no_keyword() {
        let _guard = test_guard!();
        // `nix-env`, `nix-shell`, `nix-store`, ... only share the "nix-" prefix;
        // they are NOT the `nix`/`nix-build` keywords, so Tier-2 rejects them
        // before classification (no accidental interception).
        for cmd in [
            "nix-env -iA nixpkgs.hello",
            "nix-shell",
            "nix-shell -p gcc",
            "nix-store --gc",
            "nix-collect-garbage -d",
            "nix-channel --update",
        ] {
            assert!(
                !starts_with_compilation_command(cmd),
                "`{cmd}` should not match any compilation keyword"
            );
            let result = classify_command(cmd);
            assert!(!result.is_compilation, "`{cmd}` must NOT be intercepted");
        }
    }

    #[test]
    fn test_nix_build_maps_to_nix_runtime_base() {
        let _guard = test_guard!();
        assert_eq!(CompilationKind::NixBuild.command_base(), "nix");
        assert!(!CompilationKind::NixBuild.is_test_command());
    }

    #[test]
    fn test_nix_build_compound_and_wrapped() {
        let _guard = test_guard!();
        // Compound `cd X && nix build` should offload the nix build tail.
        let compound = classify_command("cd /repo && nix build .#foo");
        assert!(compound.is_compilation, "compound nix build should offload");
        assert_eq!(compound.kind, Some(CompilationKind::NixBuild));
        // `bash -c "nix build .#foo"` wrapper should offload the inner command.
        let wrapped = classify_command("bash -c \"nix build .#foo\"");
        assert!(wrapped.is_compilation, "wrapped nix build should offload");
        assert_eq!(wrapped.kind, Some(CompilationKind::NixBuild));
    }

    #[test]
    fn test_job_kind_serde_and_base_token() {
        let _guard = test_guard!();
        // The wire name is stable snake_case so rchd/telemetry can record it.
        let json = serde_json::to_string(&CompilationKind::Job).unwrap();
        assert_eq!(json, "\"job\"");
        let round: CompilationKind = serde_json::from_str(&json).unwrap();
        assert_eq!(round, CompilationKind::Job);
        // Total mapping token (see command_base docs — the hook-path allowlist
        // gate can never observe this kind).
        assert_eq!(CompilationKind::Job.command_base(), "job");
        assert!(!CompilationKind::Job.is_test_command());
    }

    #[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_to_benign_pager_intercepted() {
        let _guard = test_guard!();
        // Issue #24: piping a compilation command's output into a benign pager
        // (grep/head/tee/...) is now offloaded, with the pipe re-attached to the
        // offloaded command's output.
        let result = classify_command("cargo build 2>&1 | grep error");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(result.kind, Some(CompilationKind::CargoBuild));
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo build 2>&1 | grep error")
        );
    }

    #[test]
    fn test_piped_to_nonbenign_command_not_intercepted() {
        let _guard = test_guard!();
        // Piping into a non-pager command stays conservative (declined).
        let result = classify_command("cargo build | xargs rm");
        assert!(!result.is_compilation);
        assert!(result.reason.contains("piped"));
    }

    #[test]
    fn test_backgrounded_intercepted() {
        let _guard = test_guard!();
        // Issue #24: a trailing `&` (backgrounding) is now offloaded.
        let result = classify_command("cargo build &");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(result.kind, Some(CompilationKind::CargoBuild));
        assert_eq!(result.extracted_command.as_deref(), Some("cargo build &"));
    }

    #[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"));

        for command in [
            "cargo build > out.log\nrm -rf /",
            "cargo build | tee out.log\r\nrm -rf /",
            "cargo build &\nrm -rf /",
        ] {
            let result = classify_command(command);
            assert!(
                !result.is_compilation,
                "newline-bearing benign suffix must fail closed: {command:?}"
            );
            assert!(result.reason.contains("newline"), "{result:?}");
        }
    }

    #[test]
    fn test_redirected_intercepted() {
        let _guard = test_guard!();
        // Issue #24: a benign stdout/stderr file redirect is now offloaded with
        // the redirect re-attached to the offloaded command's output.
        let result = classify_command("cargo build > log.txt");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(result.kind, Some(CompilationKind::CargoBuild));
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo build > log.txt")
        );

        let result = classify_command("cargo test --workspace > out.log 2>&1");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo test --workspace > out.log 2>&1")
        );

        // File-descriptor redirects must remain byte-for-byte adjacent. A
        // space before `>` turns the descriptor into a command argument.
        for command in [
            "cargo build 2>errors.txt",
            "cargo build 2>>errors.txt",
            "cargo build >out.log 2>&1",
        ] {
            let result = classify_command(command);
            assert!(result.is_compilation, "got: {:?}", result.reason);
            assert_eq!(result.extracted_command.as_deref(), Some(command));
        }
    }

    #[test]
    fn test_input_redirected_not_intercepted() {
        let _guard = test_guard!();
        // Input redirects transform the command's INPUT and are never offloaded.
        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_make_maintenance_matches_whole_target_tokens() {
        // Regression (bd-review-make-ninja-substring): maintenance targets must
        // match as whole TARGET tokens, not as a substring anywhere.
        let _guard = test_guard!();

        // Real maintenance targets are still rejected.
        for cmd in [
            "make clean",
            "make install",
            "make distclean",
            "make uninstall",
        ] {
            let r = classify_command(cmd);
            assert!(!r.is_compilation, "{cmd} should not be intercepted");
            assert!(r.reason.contains("make maintenance command"), "{cmd}");
        }
        // With parallelism flags too.
        let r = classify_command("make -j8 clean");
        assert!(!r.is_compilation);

        // Real builds whose tokens merely CONTAIN a maintenance word are builds.
        for cmd in [
            "make CFLAGS=-Iinstall/include",
            "make build INSTALL_DIR=/x",
            "make TARGET=cleanup",
            "make clean-all",  // distinct target, not "clean"
            "make -C install", // build in a directory named "install"
        ] {
            let r = classify_command(cmd);
            assert!(r.is_compilation, "{cmd} should be intercepted as a build");
            assert_eq!(r.kind, Some(CompilationKind::Make), "{cmd}");
        }
    }

    #[test]
    fn test_ninja_clean_matches_tool_and_whole_target() {
        // Regression (bd-review-make-ninja-substring): only `-t clean` and a
        // whole-token `clean` target are maintenance.
        let _guard = test_guard!();

        for cmd in ["ninja clean", "ninja -t clean", "ninja -j8 clean"] {
            let r = classify_command(cmd);
            assert!(!r.is_compilation, "{cmd} should not be intercepted");
            assert!(r.reason.contains("ninja clean"), "{cmd}");
        }

        for cmd in [
            "ninja build/clean_obj.o", // path containing "clean"
            "ninja -C clean",          // build in a directory named "clean"
            "ninja -j4",
        ] {
            let r = classify_command(cmd);
            assert!(r.is_compilation, "{cmd} should be intercepted as a build");
            assert_eq!(r.kind, Some(CompilationKind::Ninja), "{cmd}");
        }
    }

    #[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" command words trigger Tier 2 before Tier 3 decides
        // whether the subcommand is safe to intercept.
        assert!(starts_with_compilation_command("bun test"));
        assert!(starts_with_compilation_command("bun typecheck"));
        assert!(starts_with_compilation_command("bun install"));
    }

    #[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_to_benign_pager_intercepted() {
        let _guard = test_guard!();
        // Issue #24: piping a bun test/typecheck into a benign pager is offloaded.
        let result = classify_command("bun test | grep error");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(result.kind, Some(CompilationKind::BunTest));
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("bun test | grep error")
        );

        // Piped with output filtering
        let result = classify_command("bun test 2>&1 | tee output.log");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("bun test 2>&1 | tee output.log")
        );

        // Piped typecheck
        let result = classify_command("bun typecheck | head -20");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(result.kind, Some(CompilationKind::BunTypecheck));
    }

    #[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_intercepted() {
        let _guard = test_guard!();
        // Issue #24: a benign output redirect is offloaded.
        let result = classify_command("bun test > results.txt");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("bun test > results.txt")
        );

        let result = classify_command("bun typecheck > errors.log");
        assert!(result.is_compilation, "got: {:?}", result.reason);
    }

    #[test]
    fn test_bun_backgrounded_intercepted() {
        let _guard = test_guard!();
        // Issue #24: a trailing `&` is offloaded.
        let result = classify_command("bun test &");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(result.extracted_command.as_deref(), Some("bun test &"));
    }

    #[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",
            "cd /tmp && cargo build --release",
            "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!();
        // Pipe into a NON-benign command is still rejected at Tier 1. (A pipe
        // into a benign pager like `tee` is now offloaded per issue #24.)
        let detailed = classify_command_detailed("cargo build | xargs rm");
        assert!(!detailed.classification.is_compilation);
        let tier1 = detailed.tiers.iter().find(|t| t.tier.eq(&1)).unwrap();
        assert_eq!(tier1.decision, TierDecision::Reject);
        assert!(tier1.reason.contains("piped"));

        // A pipe into a benign pager passes Tier 1 and is offloaded.
        let detailed = classify_command_detailed("cargo build | tee log.txt");
        assert!(detailed.classification.is_compilation);
        assert_eq!(
            detailed.classification.extracted_command.as_deref(),
            Some("cargo build | tee log.txt")
        );
    }

    #[test]
    fn test_classify_command_detailed_normalizes_wrappers() {
        let _guard = test_guard!();
        for (cmd, normalized) in [
            ("sudo cargo check", "cargo check"),
            ("env -u RUST_LOG cargo test", "cargo test"),
        ] {
            let detailed = classify_command_detailed(cmd);
            assert_eq!(
                (
                    detailed.normalized.as_str(),
                    detailed.classification.is_compilation
                ),
                (normalized, true),
                "{cmd}"
            );
        }
    }

    #[test]
    fn test_classify_command_detailed_matches_compound_command() {
        let _guard = test_guard!();
        let detailed = classify_command_detailed("cd /tmp && cargo build --release");

        assert!(detailed.classification.is_compilation);
        assert_eq!(
            detailed.classification.kind,
            Some(CompilationKind::CargoBuild)
        );
        assert_eq!(
            detailed.classification.command_prefix.as_deref(),
            Some("cd /tmp && ")
        );
        assert_eq!(
            detailed.classification.extracted_command.as_deref(),
            Some("cargo build --release")
        );
        assert_eq!(detailed.normalized, "cargo build --release");
        assert_eq!(detailed.tiers.len(), 5);
        assert!(
            detailed
                .tiers
                .iter()
                .all(|tier| tier.decision == TierDecision::Pass)
        );
    }

    // =========================================================================
    // 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 command words trigger Tier 2 before subcommand checks.
        assert!(starts_with_compilation_command("cargo nextest run"));
        assert!(starts_with_compilation_command("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_to_pager_intercepted() {
        let _guard = test_guard!();
        // Issue #24: piping into a benign pager is offloaded.
        let result = classify_command("cargo nextest run | grep FAIL");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(result.kind, Some(CompilationKind::CargoNextest));
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo nextest run | grep FAIL")
        );
    }

    #[test]
    fn test_cargo_nextest_redirected_intercepted() {
        let _guard = test_guard!();
        // Issue #24: a benign output redirect is offloaded.
        let result = classify_command("cargo nextest run > results.txt");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo nextest run > results.txt")
        );
    }

    #[test]
    fn test_cargo_nextest_backgrounded_intercepted() {
        let _guard = test_guard!();
        // Issue #24: a trailing `&` is offloaded.
        let result = classify_command("cargo nextest run &");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo nextest run &")
        );
    }

    // =========================================================================
    // 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_to_pager_intercepted() {
        let _guard = test_guard!();
        // Issue #24: piping into a benign pager (tee) is offloaded.
        let result = classify_command("cargo bench | tee output.txt");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(result.kind, Some(CompilationKind::CargoBench));
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo bench | tee output.txt")
        );
    }

    #[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.eq("fmt") || subcommand.eq("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_backslash_literal_in_single_quotes() {
            let _guard = test_guard!();
            // POSIX: backslash is LITERAL inside single quotes, so 'a\' is the
            // string a\ and the closing quote ENDS the span — exposing the
            // following operator. Previously the \ swallowed the closing ',
            // kept the quote "open", and hid the && (bd-review-singlequote-escape).
            assert_eq!(
                split_shell_commands(r"cargo build 'a\' && rm -rf x"),
                vec![r"cargo build 'a\'", "rm -rf x"]
            );
        }

        #[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_to_pager_preserved() {
            let _guard = test_guard!();
            // Issue #24: a compilation command piped into a benign pager is
            // offloaded with the pipe re-attached to the offloaded output.
            let result = classify_command("cargo build 2>&1 | tee log");
            assert!(result.is_compilation, "got: {:?}", result.reason);
            assert_eq!(
                result.extracted_command.as_deref(),
                Some("cargo build 2>&1 | tee log")
            );
        }

        #[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!();
        // Pipe into a NON-benign command -> Tier 1 structure analysis reject
        // (benign pagers like tee/head are now offloaded per issue #24).
        let result = classify_command("cargo build | xargs rm");
        assert!(!result.is_compilation);
        assert_cow_borrowed(&result.reason, "Tier 1 piped command reason");

        // Input redirect -> still rejected (transforms the command's INPUT)
        let result = classify_command("cargo build < input.txt");
        assert!(!result.is_compilation);
        assert_cow_borrowed(&result.reason, "Tier 1 input redirect reason");

        // Subshell -> still rejected
        let result = classify_command("cargo build $(echo args)");
        assert!(!result.is_compilation);
        assert_cow_borrowed(&result.reason, "Tier 1 subshell 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 wrapper_value_flags_consume_their_value_token() {
        // Regression (bd-review-wrapper-flag-eater): value-taking wrapper flags
        // must consume the VALUE token too, or it is left as the command word
        // and a real build silently runs local.
        let _guard = test_guard!();
        assert_eq!(normalize_command("nice -n 10 cargo build"), "cargo build");
        assert_eq!(
            normalize_command("taskset -c 0-3 cargo build"),
            "cargo build"
        );
        assert_eq!(normalize_command("ionice -c 2 cargo test"), "cargo test");
        assert_eq!(
            normalize_command("ionice -c 2 -n 4 cargo build"),
            "cargo build"
        );
        assert_eq!(normalize_command("chrt -r 10 cargo build"), "cargo build");
        assert_eq!(normalize_command("timeout 60 cargo build"), "cargo build");
        assert_eq!(
            normalize_command("timeout -s KILL 90 cargo build"),
            "cargo build"
        );
        assert_eq!(
            normalize_command("sudo nice -n 5 cargo build"),
            "cargo build"
        );
        // Attached / `=`-joined values carry their own value (no extra consume).
        assert_eq!(normalize_command("nice -n10 cargo build"), "cargo build");
        assert_eq!(normalize_command("ionice -c2 cargo build"), "cargo build");
        // Existing env -u behavior preserved.
        assert_eq!(
            normalize_command("env -u RUSTFLAGS cargo build"),
            "cargo build"
        );
    }

    #[test]
    fn positional_wrapper_does_not_eat_a_non_numeric_command() {
        // Malformed `timeout cargo build` (no duration): the leading non-digit
        // token is the command and must NOT be skipped.
        let _guard = test_guard!();
        assert_eq!(normalize_command("timeout cargo build"), "cargo build");
    }

    #[test]
    fn wrapped_cargo_build_is_still_classified_as_compilation() {
        let _guard = test_guard!();
        for cmd in [
            "nice -n 10 cargo build",
            "taskset -c 0-3 cargo build",
            "ionice -c 2 cargo build",
            "chrt -r 10 cargo build",
            "timeout 60 cargo build",
            "timeout -s KILL 90 cargo test",
            "time '-f%U' cargo build",
            "time \"-f%U\" cargo build",
            "nice '--adjustment=+5' cargo build",
            "nice '-n' '5' cargo build",
            "env '--unset' 'RUSTFLAGS' cargo build",
        ] {
            assert!(
                classify_command(cmd).is_compilation,
                "wrapper must not defeat offload: {cmd}"
            );
        }
        // A wrapper around a non-build must still pass through (not offloaded).
        assert!(!classify_command("nice -n 10 ls -la").is_compilation);
        assert!(!classify_command("timeout 60 echo hi").is_compilation);
        assert!(!classify_command("time '-f%U' echo cargo build").is_compilation);
        assert!(!classify_command("time '-f%U cargo build").is_compilation);
        assert!(!classify_command("time '-f%U'echo cargo build").is_compilation);
    }

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

        for (cmd, normalized) in [
            // env with multiple spaces before VAR
            ("env  RUST_BACKTRACE=1 cargo", "cargo"),
            // env with tabs
            ("env\tRUST_BACKTRACE=1\tcargo", "cargo"),
            ("env -u RUST_LOG cargo test", "cargo test"),
            ("env --unset RUST_LOG cargo test", "cargo test"),
            ("env --unset=RUST_LOG cargo test", "cargo test"),
        ] {
            assert_eq!(normalize_command(cmd), normalized, "{cmd}");
        }
    }
}

// ============================================================================
// 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;

    fn assert_golden_json(
        actual: serde_json::Value,
        expected: &serde_json::Value,
        fixture_path: &str,
    ) {
        if &actual == expected {
            return;
        }

        let actual_json = serde_json::to_string_pretty(&actual).expect("actual JSON renders");
        let expected_json = serde_json::to_string_pretty(expected).expect("expected JSON renders");
        panic!(
            "golden mismatch in {fixture_path}\n\
             expected_blake3={}\n\
             actual_blake3={}\n\
             bless path: review the semantic diff, update the fixture expected_* field, \
             and record both hashes in the Beads closeout.\n\
             expected:\n{expected_json}\n\
             actual:\n{actual_json}",
            blake3::hash(expected_json.as_bytes()),
            blake3::hash(actual_json.as_bytes())
        );
    }

    /// 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,
            },
            // Leading global flags before the subcommand must NOT hide the build
            // (regression for the flag-read-as-subcommand misclassification).
            Case {
                cmd: "cargo --offline build",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo -q test",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoTest),
                reason_contains: "cargo test",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo --locked --frozen check",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoCheck),
                reason_contains: "cargo check",
                min_confidence: 0.85,
            },
            Case {
                cmd: "cargo --color never build",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            Case {
                cmd: "cargo +nightly --offline -Z unstable-options build",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoBuild),
                reason_contains: "cargo build",
                min_confidence: 0.90,
            },
            // `rch exec` re-quotes every word containing `=` (shell_words::join).
            Case {
                cmd: "cargo '--config=build.jobs=2' -vvv clippy",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoClippy),
                reason_contains: "cargo clippy",
                min_confidence: 0.85,
            },
            Case {
                cmd: "cargo-zigbuild '--color=never' zigbuild",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::CargoZigbuild),
                reason_contains: "cargo-zigbuild build",
                min_confidence: 0.90,
            },
            // A quoted word is still read by its content, never as a flag.
            Case {
                cmd: "cargo 'fetch'",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "",
                min_confidence: 0.0,
            },
        ];
        run_cases(&cases);
    }

    #[test]
    fn regression_cargo_package_verification_is_compilation() {
        let _guard = test_guard!();
        for command in [
            "cargo package",
            "cargo package --workspace --locked -j2",
            "cargo package -p asupersync --features tls --target x86_64-unknown-linux-gnu",
            "cargo +nightly --offline package --allow-dirty --no-metadata",
            "cargo --color never package --target-dir=/data/tmp/package-check",
            "cargo publish --dry-run",
            "cargo publish -n --workspace --locked --keep-going -j 2",
            "cargo publish --registry crates-io -p asupersync --dry-run",
            "cargo +nightly --locked publish --dry-run --features=tls",
            "env CARGO_INCREMENTAL=0 cargo publish --dry-run --workspace",
        ] {
            let classification = classify_command(command);
            assert!(
                classification.is_compilation,
                "{command}: {classification:?}"
            );
            assert_eq!(classification.kind, Some(CompilationKind::CargoBuild));
            assert_eq!(
                classify_command_detailed(command).classification,
                classification,
                "diagnosis must agree with execution for {command}"
            );
        }
    }

    #[test]
    fn regression_cargo_package_verification_declines_publication_and_metadata() {
        let _guard = test_guard!();
        for command in [
            "cargo publish",
            "cargo publish --workspace --locked",
            "cargo +nightly --offline publish",
            "cargo publish --no-verify",
            "cargo publish --dry-run --no-verify",
            "cargo publish --no-verify -n",
            "cargo publish -qn --no-verify",
            "cargo package --no-verify",
            "cargo package --list",
            "cargo package -l",
            "cargo package -vl",
            "cargo package --help",
            "cargo --help package",
            "cargo publish --dry-run -h",
            "cargo publish -- --dry-run",
            "cargo publish --dry-run -- --no-verify",
            "cargo publish --dry-run=false",
            "cargo publish --registry=--dry-run",
            "cargo publish -p--dry-run",
            "cargo publish --token=--dry-run",
            "cargo publish --config --dry-run",
            "cargo publish --config alias.note=--dry-run",
            "cargo publish --unknown-option --dry-run",
            "cargo package --target --no-verify",
            "cargo package --package --list",
            "cargo package --config",
            "cargo publish --config 'alias.note=\"--dry-run\"'",
            "cargo publish --registry 'example --dry-run registry'",
            "cargo publish --dry-run --config 'alias.note=\"--no-verify\"'",
            "cargo publish --dry-run $EXTRA_CARGO_OPTIONS",
        ] {
            let classification = classify_command(command);
            assert!(
                !classification.is_compilation,
                "{command}: {classification:?}"
            );
            let detailed = classify_command_detailed(command).classification;
            assert!(!detailed.is_compilation, "{command}: {detailed:?}");
            assert!(!is_cargo_package_verification(command), "{command}");
        }
    }

    // ------------------------------------------------------------------
    // 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 = [
            // Pipe into a NON-benign command -> still rejected (issue #24 only
            // offloads pipes into benign pagers like tee/head/grep).
            Case {
                cmd: "cargo build 2>&1 | xargs rm",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "piped",
                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);
    }

    // ------------------------------------------------------------------
    // 10a. Every compilation segment of an `&&` chain is offloaded (issue #50).
    //
    // `cargo build --release && cargo test` used to rewrite only the final
    // segment; the first build ran locally on the dispatcher with no summary
    // line. Now every segment that classifies as a compilation is wrapped.
    // ------------------------------------------------------------------

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

        let result = classify_command("cargo build --release && cargo test");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
        assert_eq!(
            result.command_prefix.as_deref(),
            Some("rch exec -- cargo build --release && ")
        );
        assert_eq!(result.extracted_command.as_deref(), Some("cargo test"));

        // Three segments, non-compilation head: only the builds are wrapped.
        let result = classify_command("touch marker && cargo build && cargo test --workspace");
        assert_eq!(
            result.command_prefix.as_deref(),
            Some("touch marker && rch exec -- cargo build && ")
        );
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo test --workspace")
        );

        // Mixed tool families are each wrapped.
        let result = classify_command("go vet ./... && cargo check");
        assert_eq!(
            result.command_prefix.as_deref(),
            Some("rch exec -- go vet ./... && ")
        );

        // Existing contract: a plain `cd` prefix is untouched.
        let result = classify_command("cd /repo && cargo build");
        assert_eq!(result.command_prefix.as_deref(), Some("cd /repo && "));

        // A build-looking segment that must stay local is left verbatim ...
        let result = classify_command("go build ./cmd && cargo test");
        assert!(result.is_compilation);
        assert_eq!(result.command_prefix.as_deref(), Some("go build ./cmd && "));
        // ... and reported, so the hook can announce it instead of staying silent.
        assert_eq!(
            compound_local_compilation_segments("go build ./cmd && cargo test"),
            vec!["go build ./cmd".to_string()]
        );
        assert!(
            compound_local_compilation_segments("cargo build --release && cargo test").is_empty()
        );
        assert!(compound_local_compilation_segments("cd /repo && cargo build").is_empty());
        assert!(compound_local_compilation_segments("cargo test").is_empty());
        assert!(
            compound_local_compilation_segments("bash -c \"cargo build && cargo test\"").is_empty(),
            "quoted operators are not chain separators"
        );

        // `;` / `||` chains and a chain whose final segment is not a build stay
        // declined, and each carries a structure reason the hook prints.
        assert!(!classify_command("cargo build ; cargo test").is_compilation);
        assert!(declined_compilation_due_to_structure("cargo build ; cargo test").is_some());
        assert!(declined_compilation_due_to_structure("cargo build || echo failed").is_some());
        assert!(declined_compilation_due_to_structure("cargo build && ./run").is_some());
    }

    // ------------------------------------------------------------------
    // 10b. Benign trailing structure IS offloaded (issue #24).
    //
    // A compilation command followed only by a benign stdout/stderr redirect,
    // a pipe into a benign pager (tee/head/cat/grep/less/...), or backgrounding
    // is now extracted and offloaded, with the trailing structure re-attached
    // to the offloaded command's output.
    // ------------------------------------------------------------------

    #[test]
    fn regression_benign_trailing_structure_offloaded() {
        let _guard = test_guard!();
        let expectations: &[(&str, CompilationKind, &str)] = &[
            // Output redirects
            (
                "cargo build > log.txt",
                CompilationKind::CargoBuild,
                "cargo build > log.txt",
            ),
            (
                "cargo build >> log.txt",
                CompilationKind::CargoBuild,
                "cargo build >> log.txt",
            ),
            (
                "cargo test --workspace > out.log 2>&1",
                CompilationKind::CargoTest,
                "cargo test --workspace > out.log 2>&1",
            ),
            // Pipes into benign pagers
            (
                "cargo build 2>&1 | grep error",
                CompilationKind::CargoBuild,
                "cargo build 2>&1 | grep error",
            ),
            (
                "cargo test | tee output.log",
                CompilationKind::CargoTest,
                "cargo test | tee output.log",
            ),
            (
                "cargo check --lib 2>&1 | head",
                CompilationKind::CargoCheck,
                "cargo check --lib 2>&1 | head",
            ),
            // Backgrounding
            (
                "cargo build &",
                CompilationKind::CargoBuild,
                "cargo build &",
            ),
        ];
        for (cmd, kind, extracted) in expectations {
            let result = classify_command(cmd);
            assert!(
                result.is_compilation,
                "'{cmd}' should be offloaded, got: {:?}",
                result.reason
            );
            assert_eq!(result.kind, Some(*kind), "kind mismatch for '{cmd}'");
            assert_eq!(
                result.extracted_command.as_deref(),
                Some(*extracted),
                "extracted command mismatch for '{cmd}'"
            );
            // command_prefix is empty for benign-suffix (no leading prefix).
            assert_eq!(result.command_prefix.as_deref(), Some(""));
        }
    }

    #[test]
    fn regression_unsafe_trailing_structure_still_rejected() {
        let _guard = test_guard!();
        // Stay conservative: these forms transform input / chain a build / pipe
        // into a non-pager, and must NOT be offloaded.
        let rejected = [
            "cargo build < input.txt",           // input redirect
            "cargo build | xargs rm",            // non-benign pipe target
            "cargo build 2>&1 | grep e | sh",    // multi-stage pipe
            "cargo test | tee log && cargo run", // chained build
            "cargo build > a.log < in.txt",      // input redirect present
        ];
        for cmd in rejected {
            let result = classify_command(cmd);
            assert!(
                !result.is_compilation,
                "'{cmd}' should NOT be offloaded, got: {:?}",
                result
            );
        }
    }

    #[test]
    fn regression_shell_dash_c_wrapper_offloaded() {
        let _guard = test_guard!();
        // Issue #24 item 2: bash -c / sh -c wrappers extract the inner command.
        let result = classify_command("bash -c \"cargo test --workspace\"");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(result.kind, Some(CompilationKind::CargoTest));
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo test --workspace")
        );

        let result = classify_command("sh -c 'cargo build --release'");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(result.kind, Some(CompilationKind::CargoBuild));
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo build --release")
        );

        // Absolute-path shell.
        let result = classify_command("/bin/bash -c \"cargo check\"");
        assert!(result.is_compilation, "got: {:?}", result.reason);

        // Inner compound is preserved (cd prefix kept).
        let result = classify_command("bash -c \"cd /repo && cargo build\"");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo build"),
            "inner compound should keep extracted command"
        );
        assert_eq!(result.command_prefix.as_deref(), Some("cd /repo && "));

        // Inner benign suffix is preserved.
        let result = classify_command("bash -c \"cargo test > log 2>&1\"");
        assert!(result.is_compilation, "got: {:?}", result.reason);
        assert_eq!(
            result.extracted_command.as_deref(),
            Some("cargo test > log 2>&1")
        );

        // Non-compilation inner -> not intercepted.
        let result = classify_command("bash -c \"ls -la\"");
        assert!(!result.is_compilation);

        // Inner command that is itself a never-intercept stays declined.
        let result = classify_command("bash -c \"cargo fmt\"");
        assert!(!result.is_compilation);
    }

    // ------------------------------------------------------------------
    // 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: "env -u RUST_LOG 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,
            },
            // Explicit Go outputs use durable delivery on Unix.
            #[cfg(unix)]
            Case {
                cmd: "go build -o bin/app .",
                expect_compilation: true,
                expected_kind: Some(CompilationKind::GoBuild),
                reason_contains: "go build command",
                min_confidence: 0.9,
            },
            // Implicit output names require package-aware output planning.
            Case {
                cmd: "go build ./cmd/app",
                expect_compilation: false,
                expected_kind: None,
                reason_contains: "requires a supported explicit -o file",
                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
        );

        // Pipe into a NON-benign command: rejected at Tier 1 (structure
        // analysis). A pipe into a benign pager (grep/tee/head) is offloaded
        // instead (issue #24), so use a non-pager target here.
        let details = classify_command_detailed("cargo build | xargs rm");
        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 | xargs rm",
            "cargo build < input.txt",
            "cargo build || echo failed",
            "(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
        );
    }

    #[test]
    fn regression_build_words_in_non_build_arguments_are_not_compilation() {
        let _guard = test_guard!();
        let cases = [
            r#"br comments add ft-4tp7g.1 "remote proof blocked: cargo test -p rchd --lib""#,
            r#"AGENT_NAME=Codex br comments add ft-4tp7g.1 "proof lane: cargo clippy --workspace""#,
            r#"printf "cargo build --release""#,
            r#"echo 'cargo test -p rchd -- --nocapture'"#,
            r#"grep "cmake --build" docs/proof-notes.md"#,
        ];

        for cmd in cases {
            let result = classify_command(cmd);
            assert!(
                !result.is_compilation,
                "embedded build text should not compile for {cmd:?}: {:?}",
                result
            );
            assert_eq!(result.reason.as_ref(), "no compilation keyword");
        }
    }

    #[test]
    fn golden_non_build_arguments_with_build_words_stay_non_compilation() {
        let _guard = test_guard!();
        const FIXTURE_PATH: &str =
            "../../tests/goldens/ft_4tp7g/classification_non_build_arguments.json";

        #[derive(serde::Deserialize)]
        struct Golden {
            schema_version: String,
            cases: Vec<Case>,
            expected_results: serde_json::Value,
        }

        #[derive(serde::Deserialize)]
        struct Case {
            name: String,
            command: String,
        }

        let golden: Golden = serde_json::from_str(include_str!(
            "../../tests/goldens/ft_4tp7g/classification_non_build_arguments.json"
        ))
        .expect("classification golden fixture parses");
        assert_eq!(
            golden.schema_version,
            "rch.golden.classification_non_build_arguments.v1"
        );

        let mut actual_results = Vec::with_capacity(golden.cases.len());
        for case in golden.cases {
            let result = classify_command(&case.command);
            actual_results.push(serde_json::json!({
                "name": case.name,
                "is_compilation": result.is_compilation,
                "kind": result.kind,
                "reason": result.reason.as_ref(),
            }));
        }
        assert_golden_json(
            serde_json::Value::Array(actual_results),
            &golden.expected_results,
            FIXTURE_PATH,
        );
    }

    #[test]
    fn regression_keyword_filter_still_accepts_normalized_build_invocations() {
        let _guard = test_guard!();
        let cases = [
            ("RUST_BACKTRACE=1 cargo test", CompilationKind::CargoTest),
            (
                "env 'CARGO_TARGET_DIR=/data/tmp/rch-target' cargo build",
                CompilationKind::CargoBuild,
            ),
            ("sudo -E cargo check", CompilationKind::CargoCheck),
            ("/usr/bin/time cargo build", CompilationKind::CargoBuild),
        ];

        for (cmd, expected_kind) in cases {
            let result = classify_command(cmd);
            assert!(
                result.is_compilation,
                "normalized build invocation should compile for {cmd:?}: {:?}",
                result
            );
            assert_eq!(result.kind, Some(expected_kind));
        }
    }

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

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

    fn kind_of(cmd: &str) -> Option<CompilationKind> {
        classify_command(cmd).kind
    }

    // --- Go: the offloadable forms ---

    #[test]
    fn go_build_test_vet_are_classified() {
        assert_eq!(
            kind_of("go build -o bin/app ."),
            cfg!(unix).then_some(CompilationKind::GoBuild)
        );
        assert_eq!(kind_of("go test ./..."), Some(CompilationKind::GoTest));
        assert_eq!(kind_of("go vet ./..."), Some(CompilationKind::GoVet));
        // Real commands observed hammering the orchestrator.
        assert_eq!(
            kind_of("go test -tags=e2e ./e2e -run ^TestE2EAtomicAssignment$"),
            Some(CompilationKind::GoTest)
        );
        assert_eq!(
            kind_of("go test ./internal/robot ./internal/cli -run TestExitCode"),
            Some(CompilationKind::GoTest)
        );
    }

    #[test]
    fn go_commands_clear_the_confidence_threshold() {
        // Default confidence_threshold is 0.85; anything at or below it is never
        // intercepted, which would silently keep these local.
        for cmd in ["go build -o app .", "go test ./...", "go vet ./..."] {
            if !cfg!(unix) && cmd.starts_with("go build") {
                continue;
            }
            let c = classify_command(cmd);
            assert!(
                c.confidence > 0.85,
                "{cmd} scored {} which does not clear the 0.85 threshold",
                c.confidence
            );
        }
    }

    #[test]
    fn go_test_is_a_test_command() {
        // Drives cache affinity, the test-slot bucket, and the test timeout.
        assert!(CompilationKind::GoTest.is_test_command());
        assert!(!CompilationKind::GoBuild.is_test_command());
        assert!(!CompilationKind::GoVet.is_test_command());
    }

    // --- Go: forms that MUST stay local (would otherwise lose artifacts) ---

    #[test]
    fn go_build_explicit_outputs_share_one_literal_contract() {
        for (command, path, option_index) in [
            ("go build -o bin/app ./cmd/app", "bin/app", 2),
            ("go build -o=bin/app ./cmd/app", "bin/app", 2),
            ("go build '-o=bin/app' main.go", "bin/app", 2),
            (
                "go build -trimpath -p=2 -o './products/app [dev]*?' .",
                "./products/app [dev]*?",
                4,
            ),
            ("go build -ldflags '-s -w' -o app", "app", 4),
            ("go build -ldflags '-s -X main.version=v2' -o app", "app", 4),
            ("go build '-buildmode=pie' -o app .", "app", 3),
            ("go build -tags -o -o app .", "app", 4),
            ("env GOFLAGS= go build -o app .", "app", 2),
        ] {
            let selection = go_build_output(command).unwrap_or_else(|| panic!("{command}"));
            assert_eq!(selection.path, path, "{command}");
            assert_eq!(selection.option_index, option_index, "{command}");
            assert_eq!(
                kind_of(command),
                cfg!(unix).then_some(CompilationKind::GoBuild),
                "{command}"
            );
        }
    }

    #[test]
    fn go_build_implicit_ambiguous_and_extra_outputs_stay_local() {
        for command in [
            "go build",
            "go build .",
            "go build ./...",
            "go build main.go",
            "go build -o",
            "go build -o /tmp/app .",
            "go build -o ../app .",
            "go build -o . .",
            "go build -o bin/ .",
            "go build -o - .",
            "go build -o one -o two .",
            "go build -n -o app .",
            "go build -n=true -o app .",
            "go build -buildmode=c-shared -o app .",
            "go build -buildmode=c-archive -o app .",
            "go build -buildmode=plugin -o app .",
            "go build -toolexec wrapper -o app .",
            "go build -o $OUTPUT .",
            "go build -o app* .",
            "go build . -o app",
            "go build -tags -o app .",
            "go build -overlay overlay.json -o app .",
            "go build -mod=mod -o app .",
            "go build -ldflags '-cpuprofile=cpu.out' -o app .",
            "go build -ldflags '-s -w -tmpdir=products' -o app .",
            "go build -gcflags '-cpuprofile=cpu.out' -o app .",
            "go build -asmflags '-debug' -o app .",
        ] {
            assert!(go_build_output(command).is_none(), "{command}");
            assert_eq!(kind_of(command), None, "{command}");
        }
        assert!(go_build_output(&format!("go build -o {} .", "x".repeat(65_536))).is_none());
        assert!(go_build_output("go build -o 'app\nnext' .").is_none());
    }

    #[test]
    fn go_test_binary_profile_and_exec_outputs_stay_local() {
        for command in [
            "go test -c ./pkg",
            "go test -c=true ./pkg",
            "go test '-c=true' ./pkg",
            "go test -exec sudo ./pkg",
            "go test '-exec=sudo' ./pkg",
            "go test -o test.bin ./pkg",
            "go test -o=test.bin ./pkg",
            "go test '-o=test binary' ./pkg",
            "go test -coverprofile=coverage.out ./pkg",
            "go test -cpuprofile cpu.out ./pkg",
            "go test -memprofile=mem.out ./pkg",
            "go test -blockprofile=block.out ./pkg",
            "go test -mutexprofile=mutex.out ./pkg",
            "go test -trace trace.out ./pkg",
            "go test ./pkg -args -test.cpuprofile=cpu.out",
            "go test ./pkg '-test.coverprofile=coverage.out'",
            "go test -outputdir profiles ./pkg",
            "go test -fuzz=FuzzParser ./pkg",
            "go test ./pkg -args -test.fuzz FuzzParser",
            "go test ./pkg -args -test.fuzzcachedir=fuzz-corpus",
            "go test ./pkg -args -test.gocoverdir=coverage",
            "go test ./pkg -args '-test.testlogfile=test log'",
        ] {
            assert_eq!(kind_of(command), None, "{command}");
        }
        assert_eq!(kind_of("go test c o exec"), Some(CompilationKind::GoTest));
    }

    #[test]
    fn go_state_mutating_subcommands_are_never_intercepted() {
        for cmd in [
            "go get github.com/foo/bar",
            "go mod tidy",
            "go mod download",
            "go install ./cmd/tool",
            "go run main.go",
            "go generate ./...",
            "go fmt ./...",
            "go clean -cache",
            "go work sync",
            "go env GOPATH",
            "go version",
            "go list ./...",
            "go tool pprof",
        ] {
            assert_eq!(kind_of(cmd), None, "{cmd} must never be intercepted");
        }
    }

    #[test]
    fn go_prefixed_binaries_are_not_matched() {
        // Keyword matching is whole-word, so these must not be treated as `go`.
        assert_eq!(kind_of("gofmt -l ."), None);
        assert_eq!(kind_of("golangci-lint run"), None);
    }

    // --- TypeScript ---

    #[test]
    fn tsc_noemit_is_classified() {
        assert_eq!(kind_of("tsc --noEmit"), Some(CompilationKind::Tsc));
        assert_eq!(kind_of("npx tsc --noEmit"), Some(CompilationKind::Tsc));
        // Observed in the wild.
        assert_eq!(
            kind_of("npx tsc --noEmit --incremental false"),
            Some(CompilationKind::Tsc)
        );
        // tsc flags are case-insensitive.
        assert_eq!(kind_of("tsc --noemit"), Some(CompilationKind::Tsc));
    }

    #[test]
    fn emitting_tsc_stays_local() {
        // Without --noEmit, tsc writes .js/.d.ts into the local tree. Tsc is
        // stream-only, so offloading it would silently produce no output.
        assert_eq!(kind_of("tsc"), None);
        assert_eq!(kind_of("tsc -p tsconfig.json"), None);
        assert_eq!(kind_of("npx tsc --outDir dist"), None);
    }

    #[test]
    fn tsc_watch_is_not_intercepted() {
        assert_eq!(kind_of("tsc --noEmit --watch"), None);
        assert_eq!(kind_of("tsc --noEmit -w"), None);
    }

    #[test]
    fn tsc_trivial_forms_are_not_intercepted() {
        assert_eq!(kind_of("tsc --version"), None);
        assert_eq!(kind_of("tsc --init"), None);
    }

    #[test]
    fn npx_non_tsc_is_not_intercepted() {
        // "npx" is a compilation keyword only so `npx tsc` reaches classify_full;
        // every other npx invocation must fall through.
        assert_eq!(kind_of("npx jest"), None);
        assert_eq!(kind_of("npx prettier --write ."), None);
    }

    // --- command_base drives the execution allowlist ---

    #[test]
    fn command_base_is_allowlisted() {
        use crate::types::ExecutionConfig;
        let exec = ExecutionConfig::default();
        for kind in [
            CompilationKind::GoBuild,
            CompilationKind::GoTest,
            CompilationKind::GoVet,
            CompilationKind::Tsc,
        ] {
            let base = kind.command_base();
            assert!(
                exec.is_allowed(base),
                "{base} missing from the execution allowlist — the hook would fail \
                 open to LOCAL execution, silently losing offload"
            );
        }
        assert_eq!(CompilationKind::GoBuild.command_base(), "go");
        assert_eq!(CompilationKind::Tsc.command_base(), "tsc");
    }
}