car-server-core 0.54.0

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
//! The coder's inspector chain — policy hardening for host tool execution.
//!
//! Every tool call the coder makes (model-proposed AND contract checks) passes
//! through this chain before dispatch; first Deny wins. CAR's built-ins run
//! first, followed by the operator's additive rules from `<CAR_HOME>/policies/`
//! and `<worktree>/.car/policies/`. The checks are deliberately conservative
//! token/substring matchers, not a shell parser — they block the unambiguous
//! footguns. The one exception in shape is
//! [`DenyForgePublication`], which pairs a read-only *allowlist* for the forge
//! CLIs (`gh`, `glab`, `hub`) with a small publication blacklist, because the
//! set of read-only `gh` subcommands is finite and the set of mutating ones is
//! not. This is hardening, not a sandbox — a shell alias or a script wrapping
//! the binary still gets through; the real gates are
//! contract confirmation and merge approval (see `coder::` module docs). Prefix
//! command carriers are unwrapped recursively so the command they launch still
//! reaches each applicable inspector.

use std::collections::{BTreeSet, HashMap};
use std::path::{Component, Path, PathBuf};

use car_ir::Action;
use car_policy::{InspectionResult, Inspector, InspectorChain, PolicyEngine, PolicyRules};
use car_state::StateStore;
use serde_json::Value;

/// Build the standard coder chain for a worktree.
pub fn coder_inspector_chain(worktree: &Path) -> InspectorChain {
    InspectorChain::new()
        .with(Box::new(DenyGitRemoteMutation))
        .with(Box::new(DenyForgePublication))
        .with(Box::new(DenyHistoryRewrite))
        .with(Box::new(DenyPrivilegeEscalation))
        .with(Box::new(DenyCredentialAccess))
        .with(Box::new(DenyEnvironmentRepair))
        .with(Box::new(DenyDestructiveOutsideWorktree {
            worktree: worktree.to_path_buf(),
        }))
        .with(Box::new(DenyPathEscape {
            worktree: worktree.to_path_buf(),
        }))
}

/// Build the standard coder chain plus every operator-authored policy that
/// governs this session.
///
/// The source order deliberately matches `car_policy::tool_gate`: machine-wide
/// rules first, then rules committed with the project. All current rule kinds
/// are prohibitions, so merging cannot relax a built-in or an earlier rule.
/// Built-ins remain ahead of the declarative inspector because first-Deny-wins
/// decides which actionable reason the model sees.
///
/// Tool names stay exact. A policy for a surface-specific tool the coder does
/// not expose (for example Claude Code's `WebFetch`) is loaded but has nothing
/// to match; CAR does not guess aliases between tools with different schemas.
/// Stateful `trace_rule` is also deliberately excluded: the shared loader
/// rejects it as unenforced instead of silently claiming it took effect.
/// The chain, plus the tools the operator's rules forbid **outright**.
///
/// Both come from one load of the policy files. The denied set is returned
/// rather than left inside the chain because it answers a question dispatch
/// cannot: which tools should never have been offered to the model in the first
/// place. See [`car_policy::PolicyEngine::blanket_denied_tools`].
pub struct CoderPolicy {
    pub chain: InspectorChain,
    pub denied_tools: BTreeSet<String>,
}

pub fn coder_inspector_chain_with_project_policies(
    worktree: &Path,
) -> Result<CoderPolicy, car_policy::PolicyLoadError> {
    let dirs = [
        car_home::root_or_relative().join("policies"),
        worktree.join(".car").join("policies"),
    ];
    coder_inspector_chain_from_policy_dirs(worktree, &dirs)
}

fn coder_inspector_chain_from_policy_dirs(
    worktree: &Path,
    dirs: &[PathBuf],
) -> Result<CoderPolicy, car_policy::PolicyLoadError> {
    let mut rules = PolicyRules::default();
    for dir in dirs {
        rules.merge(car_policy::load_policy_dir(dir)?);
    }

    let mut engine = PolicyEngine::new();
    rules.apply(&mut engine);
    // Read before the engine moves into the inspector.
    let denied_tools = engine.blanket_denied_tools();
    Ok(CoderPolicy {
        chain: coder_inspector_chain(worktree).with(Box::new(ProjectPolicyInspector {
            engine,
            state: StateStore::new(),
        })),
        denied_tools,
    })
}

/// Adapter from the declarative `PolicyEngine` to the coder's dispatch-time
/// inspector seam. One instance lives for the session, so rate-limit windows
/// cover the whole run rather than resetting for every tool call.
struct ProjectPolicyInspector {
    engine: PolicyEngine,
    state: StateStore,
}

impl Inspector for ProjectPolicyInspector {
    fn name(&self) -> &'static str {
        "project_policy"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        // Action is non-exhaustive outside car-ir; use its constructor so a new
        // field cannot make this adapter silently construct a stale shape.
        let mut action = Action::tool_call(tool);
        action.id = "coder-policy-check".to_string();
        action.parameters = params
            .as_object()
            .map(|m| {
                m.iter()
                    .map(|(key, value)| (key.clone(), value.clone()))
                    .collect::<HashMap<_, _>>()
            })
            .unwrap_or_default();

        match self.engine.check(&action, &self.state).into_iter().next() {
            Some(violation) => InspectionResult::Deny(format!(
                "operator policy '{}': {}",
                violation.policy_name, violation.reason
            )),
            None => InspectionResult::Allow,
        }
    }
}

/// Governed host execution is deliberately narrower than the legacy coder:
/// direct shell reads and directory changes must remain under the selected
/// repository. Toolchains may still load their own executables and libraries;
/// this gate prevents the model from naming host files as command operands.
struct DenyGovernedShellPathEscape {
    worktree: PathBuf,
    /// `OLDPWD` is inspectable only when the child inherits the repository
    /// root itself. Any other value would make a variable-prefixed operand an
    /// off-repository path.
    oldpwd_is_worktree: bool,
    /// An inherited target directory is a second governed read root. Cargo's
    /// config-file target is deliberately absent here: `$CARGO_TARGET_DIR`
    /// expands to nothing unless the environment variable itself is pinned.
    cargo_target_dir: Option<PathBuf>,
}

impl DenyGovernedShellPathEscape {
    fn new(worktree: &Path) -> Self {
        let inherited_path = |name: &str| {
            std::env::var_os(name).and_then(|value| {
                let path = PathBuf::from(value);
                (!path.as_os_str().is_empty()).then(|| {
                    if path.is_absolute() {
                        path
                    } else {
                        worktree.join(path)
                    }
                })
            })
        };
        let oldpwd_is_worktree = inherited_path("OLDPWD").is_some_and(|oldpwd| {
            match (oldpwd.canonicalize(), worktree.canonicalize()) {
                (Ok(oldpwd), Ok(worktree)) => oldpwd == worktree,
                _ => false,
            }
        });
        Self {
            worktree: worktree.to_path_buf(),
            oldpwd_is_worktree,
            cargo_target_dir: inherited_path("CARGO_TARGET_DIR"),
        }
    }
}

const READ_OR_CHDIR_VERBS: &[&str] = &[
    "cat", "head", "tail", "less", "more", "grep", "egrep", "fgrep", "rg", "sed", "awk", "find",
    "ls", "stat", "wc", "strings", "readlink", "realpath", "cd", "type",
];

/// Advance the byte index past whitespace in an inline program.
fn skip_program_whitespace(program: &str, index: &mut usize) {
    while let Some(ch) = program[*index..].chars().next() {
        if !ch.is_whitespace() {
            break;
        }
        *index += ch.len_utf8();
    }
}

/// Consume one sed address at the current byte index. The path-looking text in
/// `/regex/` remains program syntax; only the command that follows the address
/// may introduce an r/R/w/W file operand.
fn consume_sed_address(program: &str, index: &mut usize) -> bool {
    let Some(first) = program[*index..].chars().next() else {
        return false;
    };
    match first {
        '0'..='9' => {
            while let Some(ch) = program[*index..].chars().next() {
                if !ch.is_ascii_digit() {
                    break;
                }
                *index += ch.len_utf8();
            }
            true
        }
        '$' => {
            *index += 1;
            true
        }
        '/' => {
            *index += 1;
            let mut escaped = false;
            while let Some(ch) = program[*index..].chars().next() {
                *index += ch.len_utf8();
                if escaped {
                    escaped = false;
                } else if ch == '\\' {
                    escaped = true;
                } else if ch == '/' {
                    return true;
                }
            }
            true
        }
        // GNU/BSD sed alternate regex address: \%regex% (the character after
        // the backslash is the delimiter).
        '\\' => {
            *index += 1;
            let Some(delimiter) = program[*index..].chars().next() else {
                return true;
            };
            *index += delimiter.len_utf8();
            let mut escaped = false;
            while let Some(ch) = program[*index..].chars().next() {
                *index += ch.len_utf8();
                if escaped {
                    escaped = false;
                } else if ch == '\\' {
                    escaped = true;
                } else if ch == delimiter {
                    return true;
                }
            }
            true
        }
        _ => false,
    }
}

/// Consume one delimiter-terminated sed field, honoring escaped delimiters.
fn consume_sed_delimited_field(statement: &str, index: &mut usize, delimiter: char) -> bool {
    let mut escaped = false;
    while let Some(ch) = statement[*index..].chars().next() {
        *index += ch.len_utf8();
        if escaped {
            escaped = false;
        } else if ch == '\\' {
            escaped = true;
        } else if ch == delimiter {
            return true;
        }
    }
    false
}

fn sed_line_end(program: &str, index: usize) -> usize {
    program[index..]
        .find('\n')
        .map_or(program.len(), |offset| index + offset)
}

fn skip_to_sed_separator(program: &str, index: &mut usize) {
    while let Some(ch) = program[*index..].chars().next() {
        if matches!(ch, ';' | '\n' | '{' | '}') {
            break;
        }
        *index += ch.len_utf8();
    }
}

/// File operands embedded in one inline sed program. The program is walked as
/// sed syntax rather than split blindly: separators inside regex,
/// substitutions, or transliterations do not hide a later file operand or
/// become a false command. GNU sed's `e` command and substitution flag execute
/// a shell and are refused outright.
fn sed_program_paths(program: &str) -> Result<Vec<String>, String> {
    let mut paths = Vec::new();
    let mut index = 0;
    while index < program.len() {
        skip_program_whitespace(program, &mut index);
        while let Some(separator) = program[index..].chars().next() {
            if !matches!(separator, ';' | '{' | '}') {
                break;
            }
            index += separator.len_utf8();
            skip_program_whitespace(program, &mut index);
        }
        if index == program.len() {
            break;
        }

        loop {
            if !consume_sed_address(program, &mut index) {
                break;
            }
            skip_program_whitespace(program, &mut index);
            if program[index..].starts_with(',') || program[index..].starts_with('~') {
                index += 1;
                skip_program_whitespace(program, &mut index);
                continue;
            }
            break;
        }
        skip_program_whitespace(program, &mut index);
        if program[index..].starts_with('!') {
            index += 1;
            skip_program_whitespace(program, &mut index);
        }
        let Some(command) = program[index..].chars().next() else {
            break;
        };
        index += command.len_utf8();
        match command {
            'r' | 'R' | 'w' | 'W' => {
                // sed accepts both `w FILE` and `wFILE`. These commands consume
                // the remainder of their line as the filename.
                let end = sed_line_end(program, index);
                let operand = program[index..end].trim();
                if !operand.is_empty() {
                    paths.push(operand.to_string());
                }
                index = end;
            }
            's' => {
                let Some(delimiter) = program[index..].chars().next() else {
                    break;
                };
                index += delimiter.len_utf8();
                if !consume_sed_delimited_field(program, &mut index, delimiter)
                    || !consume_sed_delimited_field(program, &mut index, delimiter)
                {
                    continue;
                }
                while let Some(flag) = program[index..].chars().next() {
                    match flag {
                        'e' => {
                            return Err(
                                "sed shell execution through the e flag is not allowed in a governed session"
                                    .to_string(),
                            )
                        }
                        'w' => {
                            index += flag.len_utf8();
                            let end = sed_line_end(program, index);
                            let operand = program[index..end].trim();
                            if !operand.is_empty() {
                                paths.push(operand.to_string());
                            }
                            index = end;
                            break;
                        }
                        ';' | '\n' | '{' | '}' => break,
                        ch if ch.is_whitespace()
                            || ch.is_ascii_digit()
                            || matches!(ch, 'g' | 'i' | 'I' | 'm' | 'M' | 'p') =>
                        {
                            index += ch.len_utf8();
                        }
                        _ => {
                            // Malformed/unknown flags cannot safely be parsed
                            // as another command. Skip to the next separator.
                            skip_to_sed_separator(program, &mut index);
                            break;
                        }
                    }
                }
            }
            'y' => {
                // Transliteration has two delimiter-terminated fields, either
                // of which may contain characters that otherwise separate
                // commands (for example `y/a/;/`).
                let Some(delimiter) = program[index..].chars().next() else {
                    break;
                };
                index += delimiter.len_utf8();
                if !consume_sed_delimited_field(program, &mut index, delimiter)
                    || !consume_sed_delimited_field(program, &mut index, delimiter)
                {
                    continue;
                }
            }
            'e' => return Err(
                "sed shell execution through the e command is not allowed in a governed session"
                    .to_string(),
            ),
            // These commands consume text or a filename-like label through the
            // end of the physical program line. Do not reinterpret its bytes as
            // more commands.
            'a' | 'c' | 'i' | '#' => index = sed_line_end(program, index),
            // Labels and optional numeric arguments run until a separator.
            ':' | 'b' | 'l' | 'q' | 'Q' | 't' | 'T' | 'v' => {
                skip_to_sed_separator(program, &mut index)
            }
            _ => {}
        }
    }
    Ok(paths)
}

fn awk_program_tokens(program: &str) -> Vec<String> {
    fn finish(token: &mut String, result: &mut Vec<String>) {
        if !token.is_empty() {
            result.push(std::mem::take(token));
        }
    }

    let mut result = Vec::new();
    let mut token = String::new();
    let mut quote = None;
    let mut escaped = false;
    let mut chars = program.chars().peekable();
    while let Some(ch) = chars.next() {
        if let Some(delimiter) = quote {
            if escaped {
                token.push(ch);
                escaped = false;
            } else if ch == '\\' {
                escaped = true;
            } else if ch == delimiter {
                quote = None;
                finish(&mut token, &mut result);
            } else {
                token.push(ch);
            }
            continue;
        }
        match ch {
            '"' | '\'' => {
                finish(&mut token, &mut result);
                quote = Some(ch);
            }
            ch if ch.is_whitespace() => finish(&mut token, &mut result),
            '<' | '>' | '|' => {
                finish(&mut token, &mut result);
                let mut operator = ch.to_string();
                if (ch == '>' && chars.peek() == Some(&'>'))
                    || (ch == '|' && chars.peek() == Some(&'&'))
                {
                    let joined = chars.next().expect("peeked operator suffix");
                    operator.push(joined);
                }
                result.push(operator);
            }
            ';' | '{' | '}' | '(' | ')' | ',' => {
                finish(&mut token, &mut result);
                result.push(ch.to_string());
            }
            _ => token.push(ch),
        }
    }
    finish(&mut token, &mut result);
    result
}

/// File operands embedded in one inline awk program. `getline` reads only when
/// paired with `<`; print/printf write only through `>` or `>>`. General shell
/// execution through `system()` or a command pipe is refused outright so the
/// inner command cannot bypass the rest of the governed inspector chain.
fn awk_program_paths(program: &str) -> Result<Vec<String>, String> {
    let tokens = awk_program_tokens(program);
    if tokens
        .windows(2)
        .any(|pair| pair[0] == "system" && pair[1] == "(")
    {
        return Err("awk system() is not allowed in a governed session".to_string());
    }
    for (index, token) in tokens.iter().enumerate() {
        if !matches!(token.as_str(), "|" | "|&") {
            continue;
        }
        let start = tokens[..index]
            .iter()
            .rposition(|candidate| matches!(candidate.as_str(), ";" | "{" | "}"))
            .map_or(0, |position| position + 1);
        let end = tokens[index + 1..]
            .iter()
            .position(|candidate| matches!(candidate.as_str(), ";" | "{" | "}"))
            .map_or(tokens.len(), |offset| index + 1 + offset);
        if tokens[start..index]
            .iter()
            .any(|candidate| matches!(candidate.as_str(), "print" | "printf"))
            || tokens[index + 1..end]
                .iter()
                .any(|candidate| candidate == "getline")
        {
            return Err("awk command pipes are not allowed in a governed session".to_string());
        }
    }

    let mut paths = Vec::new();
    for (index, token) in tokens.iter().enumerate() {
        let wanted = match token.as_str() {
            "getline" => &["<"][..],
            "print" | "printf" => &[">", ">>"][..],
            _ => continue,
        };
        let end = tokens[index + 1..]
            .iter()
            .position(|candidate| matches!(candidate.as_str(), ";" | "{" | "}"))
            .map_or(tokens.len(), |offset| index + 1 + offset);
        let Some(operator) = tokens[index + 1..end]
            .iter()
            .position(|candidate| wanted.contains(&candidate.as_str()))
            .map(|offset| index + 1 + offset)
        else {
            continue;
        };
        if let Some(path) = tokens[operator + 1..end]
            .iter()
            .find(|candidate| candidate.as_str() != "(")
        {
            paths.push(path.clone());
        }
    }
    Ok(paths)
}

fn inline_program_paths(verb: &str, program: &str) -> Result<Vec<String>, String> {
    match verb {
        "sed" => sed_program_paths(program),
        "awk" => awk_program_paths(program),
        _ => Ok(Vec::new()),
    }
}

fn append_inline_program_paths(
    verb: &str,
    program: &str,
    paths: &mut Vec<String>,
) -> Result<(), String> {
    paths.extend(inline_program_paths(verb, program)?);
    Ok(())
}

/// Record a sed/awk script file, refusing sources whose contents arrive over a
/// shell channel or whose path is produced by word expansion. The governed
/// tokenizer cannot resolve heredoc, pipe, here-string, parameter, command,
/// process, or brace expansion before the shell runs, so accepting one as an
/// ordinary path would skip embedded file-I/O and shell-execution checks.
fn has_brace_expansion_comma(source: &str) -> bool {
    let mut braces = Vec::new();
    let mut escaped = false;
    for ch in source.chars() {
        if escaped {
            escaped = false;
            continue;
        }
        match ch {
            '\\' => escaped = true,
            '{' => braces.push(false),
            ',' => {
                if let Some(brace) = braces.last_mut() {
                    *brace = true;
                }
            }
            '}' if braces.pop().is_some_and(|has_comma| has_comma) => return true,
            _ => {}
        }
    }
    false
}

fn reject_shell_fed_program_source(verb: &str, source: &str) -> Result<(), String> {
    // `./-` is intentionally different from `-`: it names a literal
    // repository file and has the same governed-path posture as `script.sed`.
    let is_program_channel = source.is_empty()
        || source == "-"
        || source == "/dev/stdin"
        || source
            .strip_prefix("/dev/fd/")
            .is_some_and(|fd| !fd.is_empty())
        || source
            .strip_prefix("/proc/self/fd/")
            .is_some_and(|fd| !fd.is_empty())
        || source.starts_with("<(")
        || source.starts_with(">(")
        || source.contains('$')
        || source.contains('`')
        || has_brace_expansion_comma(source);
    if is_program_channel {
        return Err(format!(
            "{verb} script source '{source}' cannot be inspected in a governed session"
        ));
    }
    Ok(())
}

fn append_program_source_path(
    verb: &str,
    source: &str,
    paths: &mut Vec<String>,
) -> Result<(), String> {
    reject_shell_fed_program_source(verb, source)?;
    paths.push(source.to_string());
    Ok(())
}

/// Inspect every standalone script-file option by its own token position.
///
/// This is intentionally independent of preceding options: an empty quoted
/// `-e ''` operand must not let sequential argument consumption hide a later
/// `-f -`. Normal literal sources are collected by the full parser below; this
/// pass only rejects sources whose bytes the shell supplies at execution time.
fn reject_shell_fed_program_file_operands(verb: &str, args: &[String]) -> Result<(), String> {
    for (index, arg) in args.iter().enumerate() {
        if arg == "--" {
            break;
        }
        let is_file_option = matches!(
            (verb, arg.as_str()),
            ("sed", "-f" | "--file") | ("awk", "-f" | "-E" | "--file")
        );
        if is_file_option {
            let source = args.get(index + 1).map_or("", String::as_str);
            reject_shell_fed_program_source(verb, source)?;
        }
    }
    Ok(())
}

/// Arguments that can name files for a governed read command.
///
/// Most verbs use every non-option operand. `sed` and `awk` are different: the
/// first positional operand is a program, and regex addresses commonly begin
/// with `/`, so treating it as a path turns `sed -n '/pub fn/p' src/lib.rs`
/// into an attempted read of `/pub`. Their `-f` operands are real program
/// files and remain governed; shell-fed `-f` channels are refused because their
/// programs cannot be associated safely with the command. `-e` operands are
/// inline programs whose embedded file I/O is extracted and whose
/// command-execution forms are refused.
fn governed_path_arguments(verb: &str, tokens: &[String]) -> Result<Vec<String>, String> {
    let Some(verb_index) = tokens.iter().position(|token| !token.contains('=')) else {
        return Ok(Vec::new());
    };
    let args = &tokens[verb_index + 1..];
    if !matches!(verb, "sed" | "awk") {
        return Ok(args
            .iter()
            .filter(|arg| !arg.starts_with('-'))
            .cloned()
            .collect());
    }

    reject_shell_fed_program_file_operands(verb, args)?;

    let mut paths = Vec::new();
    let mut explicit_program = false;
    let mut positional_program_seen = false;
    let mut options = true;
    let mut index = 0;
    while index < args.len() {
        let arg = args[index].as_str();
        if options && arg == "--" {
            options = false;
            index += 1;
            continue;
        }
        if options && arg.starts_with('-') && arg != "-" {
            match (verb, arg) {
                ("sed", "-e" | "--expression") | ("awk", "-e" | "--source") => {
                    explicit_program = true;
                    if let Some(program) = args.get(index + 1) {
                        append_inline_program_paths(verb, program, &mut paths)?;
                    }
                    index += 2;
                    continue;
                }
                ("sed", "-f" | "--file") | ("awk", "-f" | "-E" | "--file") => {
                    explicit_program = true;
                    if let Some(source) = args.get(index + 1) {
                        append_program_source_path(verb, source, &mut paths)?;
                    }
                    index += 2;
                    continue;
                }
                ("awk", "-F" | "-v") => {
                    index += 2; // field separator / variable assignment
                    continue;
                }
                _ => {}
            }
            if let Some(source) = arg.strip_prefix("--file=") {
                explicit_program = true;
                append_program_source_path(verb, source, &mut paths)?;
                index += 1;
                continue;
            }
            if let Some(program) = arg
                .strip_prefix("--expression=")
                .or_else(|| arg.strip_prefix("--source="))
            {
                explicit_program = true;
                append_inline_program_paths(verb, program, &mut paths)?;
                index += 1;
                continue;
            }

            if verb == "sed" && !arg.starts_with("--") {
                // sed permits no-operand flags to be bundled before the final
                // option that consumes a program or script file: -ne and -nf.
                // In-place editing also accepts an attached backup suffix
                // (-i.bak), whose remainder is not another option.
                let cluster = &arg[1..];
                let mut cursor = 0;
                let mut handled = true;
                while let Some(option) = cluster[cursor..].chars().next() {
                    cursor += option.len_utf8();
                    match option {
                        'n' | 'E' | 'r' | 's' | 'u' | 'z' => {}
                        'e' | 'f' => {
                            explicit_program = true;
                            let attached = &cluster[cursor..];
                            if option == 'e' {
                                if attached.is_empty() {
                                    if let Some(program) = args.get(index + 1) {
                                        append_inline_program_paths("sed", program, &mut paths)?;
                                    }
                                    index += 2;
                                } else {
                                    append_inline_program_paths("sed", attached, &mut paths)?;
                                    index += 1;
                                }
                            } else if attached.is_empty() {
                                if let Some(source) = args.get(index + 1) {
                                    append_program_source_path("sed", source, &mut paths)?;
                                }
                                index += 2;
                            } else {
                                append_program_source_path("sed", attached, &mut paths)?;
                                index += 1;
                            }
                            break;
                        }
                        'i' => {
                            // Everything after i is the backup suffix. The next
                            // argument is still the positional sed program.
                            index += 1;
                            break;
                        }
                        _ => {
                            handled = false;
                            break;
                        }
                    }
                }
                if handled {
                    if cursor == cluster.len()
                        && !matches!(cluster.chars().last(), Some('e' | 'f' | 'i'))
                    {
                        index += 1;
                    }
                    continue;
                }
            }

            let attached_file_source = arg
                .strip_prefix("-f")
                .filter(|source| !source.is_empty())
                .or_else(|| {
                    if verb == "awk" {
                        arg.strip_prefix("-E").filter(|source| !source.is_empty())
                    } else {
                        None
                    }
                });
            if let Some(source) = attached_file_source {
                explicit_program = true;
                append_program_source_path(verb, source, &mut paths)?;
            } else if let Some(program) = arg.strip_prefix("-e").filter(|p| !p.is_empty()) {
                explicit_program = true;
                append_inline_program_paths(verb, program, &mut paths)?;
            }
            index += 1;
            continue;
        }

        if !explicit_program && !positional_program_seen {
            positional_program_seen = true;
            append_inline_program_paths(verb, arg, &mut paths)?;
        } else {
            paths.push(arg.to_string());
        }
        index += 1;
    }
    Ok(paths)
}

/// Remove physical line continuations before either policy tokenizer splits
/// commands at newlines. A shell removes backslash-newline (and the CRLF form)
/// before tokenization, so leaving the pair intact fabricates a command boundary
/// where the shell sees none and can move an outside path into verb position.
fn join_shell_line_continuations(command: &str) -> String {
    let mut logical = String::with_capacity(command.len());
    let mut chars = command.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '\\' {
            if chars.peek() == Some(&'\n') {
                chars.next();
                continue;
            }
            if chars.peek() == Some(&'\r') {
                let mut lookahead = chars.clone();
                if lookahead.next() == Some('\r') && lookahead.next() == Some('\n') {
                    chars.next();
                    chars.next();
                    continue;
                }
            }
        }
        logical.push(ch);
    }
    logical
}

/// Tokenize governed read commands while retaining quoted programs as one
/// argument. The general policy lexer intentionally splits quoted whitespace
/// conservatively, but doing that here changes one `sed` script into several
/// apparent operands and recreates the path false positive this gate avoids.
/// An empty quote attached to another token is retained as an empty following
/// operand so `-f""` cannot silently consume the next argument as its source.
fn governed_shell_segments(command: &str) -> Vec<Vec<String>> {
    fn finish_token(
        token: &mut String,
        started: &mut bool,
        attached_empty: &mut bool,
        tokens: &mut Vec<String>,
    ) {
        if std::mem::take(started) {
            tokens.push(std::mem::take(token));
            if std::mem::take(attached_empty) {
                tokens.push(String::new());
            }
        }
    }
    fn finish_segment(
        token: &mut String,
        started: &mut bool,
        attached_empty: &mut bool,
        tokens: &mut Vec<String>,
        result: &mut Vec<Vec<String>>,
    ) {
        finish_token(token, started, attached_empty, tokens);
        if !tokens.is_empty() {
            result.push(std::mem::take(tokens));
        }
    }

    let mut result = Vec::new();
    let mut tokens = Vec::new();
    let mut token = String::new();
    let mut token_started = false;
    let mut attached_empty = false;
    let mut quote = None;
    let logical_command = join_shell_line_continuations(command);
    let mut chars = logical_command.chars().peekable();
    while let Some(ch) = chars.next() {
        if let Some((delimiter, start_len, was_attached)) = quote {
            if ch == delimiter {
                quote = None;
                if was_attached && token.len() == start_len {
                    attached_empty = true;
                }
            } else if delimiter == '"' && ch == '\\' {
                // In double quotes the shell removes a backslash only before
                // $, `, ", and \. Single quotes preserve every backslash.
                if chars
                    .peek()
                    .is_some_and(|next| matches!(next, '$' | '`' | '"' | '\\'))
                {
                    token.push(chars.next().expect("peeked escaped character"));
                } else {
                    token.push(ch);
                }
                attached_empty = false;
            } else {
                token.push(ch);
                attached_empty = false;
            }
            continue;
        }
        match ch {
            // Outside quotes, the shell removes a backslash and treats the
            // following byte literally before argv reaches the command. Keep
            // that byte in this token so `\-`, `\/etc`, escaped whitespace,
            // and escaped separators reach the same policy checks as the
            // argument the command actually receives. Quoted backslashes are
            // handled above according to the quote kind because sed/awk
            // programs depend on escapes that the shell preserves.
            '\\' => {
                if let Some(escaped) = chars.next() {
                    token.push(escaped);
                } else {
                    token.push(ch);
                }
                token_started = true;
                attached_empty = false;
            }
            '\'' | '"' => {
                quote = Some((ch, token.len(), token_started));
                token_started = true;
            }
            // A shell newline starts a new command exactly like `;`. Handle it
            // before generic whitespace or the next line becomes an argument
            // to the first verb and can bypass that line's path gate.
            '\n' | '\r' => finish_segment(
                &mut token,
                &mut token_started,
                &mut attached_empty,
                &mut tokens,
                &mut result,
            ),
            ch if ch.is_whitespace() => finish_token(
                &mut token,
                &mut token_started,
                &mut attached_empty,
                &mut tokens,
            ),
            ';' | 'ï¼›' | '|' | '&' => {
                finish_segment(
                    &mut token,
                    &mut token_started,
                    &mut attached_empty,
                    &mut tokens,
                    &mut result,
                );
                if matches!(ch, '|' | '&') && chars.peek() == Some(&ch) {
                    chars.next();
                }
            }
            _ => {
                token.push(ch);
                token_started = true;
                attached_empty = false;
            }
        }
    }
    finish_segment(
        &mut token,
        &mut token_started,
        &mut attached_empty,
        &mut tokens,
        &mut result,
    );
    result
}

/// A command that launches the remaining arguments without changing their
/// meaning. Each carrier owns a different option grammar, so keep the arity in
/// one table rather than guessing that every option is a flag.
#[derive(Clone, Copy)]
struct CommandCarrier {
    name: &'static str,
    short_value_options: &'static [char],
    long_value_options: &'static [&'static str],
    leading_operands: usize,
    assignments: bool,
}

const COMMAND_CARRIERS: &[CommandCarrier] = &[
    CommandCarrier {
        name: "env",
        short_value_options: &['a', 'C', 'S', 'u'],
        long_value_options: &["--argv0", "--chdir", "--split-string", "--unset"],
        leading_operands: 0,
        assignments: true,
    },
    CommandCarrier {
        name: "command",
        short_value_options: &[],
        long_value_options: &[],
        leading_operands: 0,
        assignments: false,
    },
    CommandCarrier {
        name: "exec",
        short_value_options: &['a'],
        long_value_options: &[],
        leading_operands: 0,
        assignments: false,
    },
    CommandCarrier {
        name: "nohup",
        short_value_options: &[],
        long_value_options: &[],
        leading_operands: 0,
        assignments: false,
    },
    CommandCarrier {
        name: "time",
        short_value_options: &['f', 'o'],
        long_value_options: &["--format", "--output"],
        leading_operands: 0,
        assignments: false,
    },
    CommandCarrier {
        name: "nice",
        short_value_options: &['n'],
        long_value_options: &["--adjustment"],
        leading_operands: 0,
        assignments: false,
    },
    CommandCarrier {
        name: "caffeinate",
        short_value_options: &['t', 'w'],
        long_value_options: &[],
        leading_operands: 0,
        assignments: false,
    },
    CommandCarrier {
        name: "script",
        short_value_options: &['B', 'F', 'I', 'O', 'T', 'c', 'm', 't'],
        long_value_options: &[
            "--command",
            "--log-in",
            "--log-io",
            "--log-out",
            "--log-timing",
            "--logging-format",
        ],
        // BSD script accepts `file [command ...]`; the file is the carrier's
        // operand, not the launched command.
        leading_operands: 1,
        assignments: false,
    },
    CommandCarrier {
        name: "xargs",
        short_value_options: &['E', 'I', 'J', 'L', 'P', 'R', 'S', 'a', 'd', 'n', 's'],
        long_value_options: &[
            "--arg-file",
            "--delimiter",
            "--eof",
            "--max-args",
            "--max-chars",
            "--max-lines",
            "--max-procs",
            "--replace",
        ],
        leading_operands: 0,
        assignments: false,
    },
    CommandCarrier {
        name: "builtin",
        short_value_options: &[],
        long_value_options: &[],
        leading_operands: 0,
        assignments: false,
    },
    CommandCarrier {
        // BusyBox dispatches its first non-option operand as an applet. Expose
        // that applet to the same inspectors as a standalone command.
        name: "busybox",
        short_value_options: &[],
        long_value_options: &[],
        leading_operands: 0,
        assignments: false,
    },
    CommandCarrier {
        name: "sudo",
        short_value_options: &['C', 'D', 'R', 'T', 'a', 'g', 'h', 'p', 'r', 't', 'u'],
        long_value_options: &[
            "--auth-type",
            "--chdir",
            "--chroot",
            "--close-from",
            "--command-timeout",
            "--group",
            "--host",
            "--prompt",
            "--role",
            "--type",
            "--user",
        ],
        leading_operands: 0,
        assignments: false,
    },
    CommandCarrier {
        name: "ionice",
        short_value_options: &['P', 'c', 'n', 'p', 'u'],
        long_value_options: &["--class", "--classdata", "--pgid", "--pid", "--uid"],
        leading_operands: 0,
        assignments: false,
    },
    CommandCarrier {
        name: "timeout",
        short_value_options: &['k', 's'],
        long_value_options: &["--kill-after", "--signal"],
        // The duration belongs to timeout; the next operand is the command.
        leading_operands: 1,
        assignments: false,
    },
];

fn executable_name(raw: &str) -> String {
    let lower = raw.to_ascii_lowercase();
    let name = Path::new(&lower)
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(&lower);
    name.strip_suffix(".exe").unwrap_or(name).to_string()
}

#[derive(Clone, Copy)]
struct ShellAssignmentParts<'a> {
    name: &'a str,
    subscript: Option<&'a str>,
    value: &'a str,
}

fn shell_assignment_parts(token: &str) -> Option<ShellAssignmentParts<'_>> {
    let name_length = shell_name_len(token);
    if name_length == 0 {
        return None;
    }
    let name = &token[..name_length];
    let remainder = &token[name_length..];
    let (subscript, operator) = if remainder.starts_with('[') {
        let mut depth = 0usize;
        let mut close = None;
        for (index, ch) in remainder.char_indices() {
            match ch {
                '[' => depth += 1,
                ']' => {
                    depth = depth.checked_sub(1)?;
                    if depth == 0 {
                        close = Some(index);
                        break;
                    }
                }
                _ => {}
            }
        }
        let close = close?;
        (Some(&remainder[1..close]), &remainder[close + 1..])
    } else {
        (None, remainder)
    };
    // Shell append assignments have the same name and safety implications as
    // ordinary assignments; `+=` is the operator after either a scalar name or
    // an array subscript.
    let value = operator
        .strip_prefix("+=")
        .or_else(|| operator.strip_prefix('='))?;
    Some(ShellAssignmentParts {
        name,
        subscript,
        value,
    })
}

fn shell_subscript_contains_command_substitution(subscript: &str) -> bool {
    if subscript.contains('`') {
        return true;
    }
    let mut cursor = 0usize;
    while let Some(relative) = subscript[cursor..].find("$(") {
        let start = cursor + relative;
        // `$((...))` is arithmetic expansion, not command substitution. Keep
        // scanning its contents because they may themselves contain `$(...)`.
        if subscript[start + 2..].starts_with('(') {
            cursor = start + 3;
        } else {
            return true;
        }
    }
    false
}

/// Why an array-assignment subscript found in the raw command cannot be trusted
/// to reach the tokenised assignment check intact.
#[derive(Clone, Copy, PartialEq, Eq)]
enum SubscriptFlaw {
    /// The subscript runs a command, so its value cannot be inspected at all.
    CommandSubstitution,
    /// The subscript holds characters the deliberately small tokenizer splits
    /// on or rewrites, so `NAME[subscript]=value` never reaches
    /// `shell_assignment_parts` as a single assignment token.
    BreaksTokenization,
}

/// Classify a raw subscript. A command substitution cannot be inspected at all;
/// whitespace, a shell separator, a quote, or a backslash escape hides the
/// assignment from the tokenised path in exactly the same way. One rule covers
/// both rather than a special case per spelling.
fn subscript_flaw(subscript: &str) -> Option<SubscriptFlaw> {
    if shell_subscript_contains_command_substitution(subscript) {
        return Some(SubscriptFlaw::CommandSubstitution);
    }
    subscript
        .chars()
        .any(|ch| ch.is_whitespace() || matches!(ch, ';' | 'ï¼›' | '|' | '&' | '\'' | '"' | '\\'))
        .then_some(SubscriptFlaw::BreaksTokenization)
}

/// Find the array-assignment subscripts in the raw command that the tokenised
/// assignment check cannot see intact. Single-quoted text is inert and is
/// skipped. A candidate must begin at a shell word boundary and have a closing
/// bracket followed immediately by `=` or `+=`.
fn uninspectable_assignment_subscripts(command: &str) -> Vec<(&str, SubscriptFlaw)> {
    let bytes = command.as_bytes();
    let mut found = Vec::new();
    let mut index = 0usize;
    let mut quote = None;
    let mut word_boundary = true;
    while index < bytes.len() {
        let byte = bytes[index];
        if let Some(delimiter) = quote {
            if byte == delimiter {
                quote = None;
            } else if delimiter == b'"' && byte == b'\\' {
                index += usize::from(index + 1 < bytes.len());
            }
            index += 1;
            continue;
        }
        match byte {
            b'\\' => {
                index += 1 + usize::from(index + 1 < bytes.len());
                word_boundary = false;
            }
            b'\'' | b'"' => {
                quote = Some(byte);
                word_boundary = false;
                index += 1;
            }
            b' ' | b'\t' | b'\r' | b'\n' | b';' | b'|' | b'&' | b'(' => {
                word_boundary = true;
                index += 1;
            }
            b'_' | b'a'..=b'z' | b'A'..=b'Z' if word_boundary => {
                let name_start = index;
                index += 1;
                while index < bytes.len()
                    && matches!(bytes[index], b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9')
                {
                    index += 1;
                }
                if bytes.get(index) == Some(&b'[') {
                    let subscript_start = index + 1;
                    let mut close_search = subscript_start;
                    while let Some(relative) = command[close_search..].find(']') {
                        let close = close_search + relative;
                        let after = &command[close + 1..];
                        if after.starts_with('=') || after.starts_with("+=") {
                            let subscript = &command[subscript_start..close];
                            if let Some(flaw) = subscript_flaw(subscript) {
                                found.push((&command[name_start..index], flaw));
                            }
                            break;
                        }
                        close_search = close + 1;
                    }
                }
                word_boundary = false;
            }
            _ => {
                word_boundary = false;
                index += 1;
            }
        }
    }
    found
}

fn shell_assignment(token: &str) -> bool {
    shell_assignment_parts(token).is_some()
}

fn carrier_option_consumes_next(spec: CommandCarrier, option: &str) -> bool {
    if spec.long_value_options.contains(&option) {
        return true;
    }
    if option.starts_with("--") {
        return false;
    }

    let mut options = option.strip_prefix('-').unwrap_or("").chars().peekable();
    while let Some(option) = options.next() {
        if spec.short_value_options.contains(&option) {
            // A value attached in the same token consumes the rest of the
            // cluster; only a final value-taking option consumes argv[i + 1].
            return options.peek().is_none();
        }
    }
    false
}

struct CarrierInvocation<'a> {
    command: &'a [String],
    assignments: Vec<&'a str>,
}

/// Return the command portion of one carrier invocation. `None` means the verb
/// is not a carrier; an empty `command` means it is a valid carrier-only
/// invocation. Assignments are returned separately so governed sessions can
/// inspect the environment that changes the launched command's meaning.
fn carrier_command<'a>(
    tokens: &'a [String],
    verb_index: usize,
    verb: &str,
) -> Option<CarrierInvocation<'a>> {
    let spec = *COMMAND_CARRIERS.iter().find(|spec| spec.name == verb)?;
    let args = &tokens[verb_index + 1..];
    // `command -v/-V` queries the shell's command table; it does not launch
    // the named operand. Treat it as a terminal carrier invocation so asking
    // whether (for example) sudo exists does not trigger sudo's policy.
    if verb == "command"
        && args
            .iter()
            .take_while(|arg| arg.as_str() != "--")
            .any(|arg| {
                arg.strip_prefix('-')
                    .filter(|short| !short.starts_with('-'))
                    .is_some_and(|short| short.contains('v') || short.contains('V'))
            })
    {
        return Some(CarrierInvocation {
            command: &[],
            assignments: Vec::new(),
        });
    }
    let mut index = 0;
    let mut options = true;
    let mut assignments = Vec::new();
    while index < args.len() {
        let arg = args[index].as_str();
        if options && arg == "--" {
            options = false;
            index += 1;
            continue;
        }
        if options && arg.starts_with('-') && arg != "-" {
            let consumes_next = !arg.contains('=') && carrier_option_consumes_next(spec, arg);
            index += 1 + usize::from(consumes_next && index + 1 < args.len());
            continue;
        }
        if spec.assignments && shell_assignment(arg) {
            assignments.push(arg);
            index += 1;
            continue;
        }
        break;
    }
    index = (index + spec.leading_operands).min(args.len());
    Some(CarrierInvocation {
        command: &args[index..],
        assignments,
    })
}

/// Find a command-string flag in a short-option cluster, stopping when an
/// option consumes the rest of that token (or the following argument).
fn has_short_command_flag(args: &[String], wanted: char, value_options: &[char]) -> bool {
    let mut index = 0;
    while index < args.len() {
        let arg = args[index].as_str();
        if arg == "--" || !arg.starts_with('-') || arg == "-" {
            break;
        }
        let Some(short) = arg
            .strip_prefix('-')
            .filter(|short| !short.starts_with('-'))
        else {
            index += 1;
            continue;
        };
        let mut options = short.chars().peekable();
        while let Some(option) = options.next() {
            if option == wanted {
                return true;
            }
            if value_options.contains(&option) {
                if options.peek().is_none() {
                    index += 1;
                }
                break;
            }
        }
        index += 1;
    }
    false
}

fn shell_has_script_operand(args: &[String]) -> bool {
    let mut index = 0;
    while index < args.len() {
        let arg = args[index].as_str();
        if arg == "--" {
            return index + 1 < args.len();
        }
        if !arg.starts_with('-') || arg == "-" {
            return true;
        }
        let consumes_next = matches!(arg, "-O" | "-o" | "--init-file" | "--rcfile");
        index += 1 + usize::from(consumes_next && index + 1 < args.len());
    }
    false
}

fn nested_command_carrier(verb: &str, args: &[String]) -> bool {
    if verb == "eval" {
        return true;
    }
    // env -S asks env to split one opaque argv item into a fresh command line.
    // Deny it like an interpreter command string rather than pretending the
    // split can be reproduced by this deliberately small tokenizer.
    if verb == "env" {
        return has_short_command_flag(args, 'S', &['a', 'C', 'S', 'u'])
            || args
                .iter()
                .any(|arg| arg == "--split-string" || arg.starts_with("--split-string="));
    }
    if matches!(
        verb,
        "bash" | "sh" | "zsh" | "dash" | "ksh" | "fish" | "ash"
    ) {
        return has_short_command_flag(args, 'c', &['O', 'o'])
            || (verb == "fish"
                && (has_short_command_flag(args, 'C', &['C'])
                    || args.iter().any(|arg| {
                        matches!(arg.as_str(), "--command" | "--init-command")
                            || arg.starts_with("--command=")
                            || arg.starts_with("--init-command=")
                    })))
            || !shell_has_script_operand(args);
    }
    if verb == "script" {
        return has_short_command_flag(args, 'c', &['B', 'F', 'I', 'O', 'T', 'c', 'm', 't'])
            || args
                .iter()
                .any(|arg| arg == "--command" || arg.starts_with("--command="));
    }
    if verb == "perl" {
        // Perl's -E is -e with optional features enabled. Stop at options such
        // as -M whose attached module name is an argument, not more flags.
        const PERL_VALUE_OPTIONS: &[char] =
            &['0', 'C', 'D', 'F', 'I', 'M', 'V', 'd', 'i', 'l', 'm', 'x'];
        return has_short_command_flag(args, 'e', PERL_VALUE_OPTIONS)
            || has_short_command_flag(args, 'E', PERL_VALUE_OPTIONS);
    }
    if matches!(verb, "ruby" | "node" | "osascript") {
        let value_options: &[char] = match verb {
            "ruby" => &['0', 'C', 'E', 'F', 'I', 'S', 'i', 'r', 'x'],
            "node" => &['C', 'r'],
            "osascript" => &['l'],
            _ => unreachable!("matched interpreter"),
        };
        return has_short_command_flag(args, 'e', value_options)
            || (verb == "node"
                && args
                    .iter()
                    .any(|arg| arg == "--eval" || arg.starts_with("--eval=")));
    }
    if verb == "python"
        || verb == "py"
        || verb == "python3"
        || verb
            .strip_prefix("python3.")
            .is_some_and(|minor| minor.chars().all(|ch| ch.is_ascii_digit()))
    {
        return has_short_command_flag(args, 'c', &['W', 'X', 'Q', 'm']);
    }
    false
}

struct LeadingShellVariable<'a> {
    /// Parameter-expansion syntax between the variable name and `}`. Even for
    /// an allowlisted name, modifiers can transform the known value and are
    /// therefore not inspectable by this deliberately small parser.
    modifier: &'a str,
    /// Empty for a bare variable operand; otherwise begins with `/`.
    suffix: &'a str,
}

fn shell_name_len(value: &str) -> usize {
    let mut chars = value.char_indices();
    let Some((_, first)) = chars.next() else {
        return 0;
    };
    if first != '_' && !first.is_ascii_alphabetic() {
        return 0;
    }
    chars
        .take_while(|(_, ch)| *ch == '_' || ch.is_ascii_alphanumeric())
        .last()
        .map_or(first.len_utf8(), |(index, ch)| index + ch.len_utf8())
}

/// Recognize a shell variable that controls the beginning of a path operand.
/// Exact dollar-named repository entries are handled as a narrow literal
/// exception by [`variable_operand_denial`].
fn leading_shell_variable(candidate: &str) -> Option<LeadingShellVariable<'_>> {
    if let Some(rest) = candidate.strip_prefix("${") {
        let length = shell_name_len(rest);
        if length == 0 {
            return None;
        }
        let mut depth = 1usize;
        let mut close = None;
        let mut index = length;
        while index < rest.len() {
            if rest[index..].starts_with("${") {
                depth += 1;
                index += 2;
                continue;
            }
            let ch = rest[index..].chars().next().expect("index is in bounds");
            if ch == '}' {
                depth -= 1;
                if depth == 0 {
                    close = Some(index);
                    break;
                }
            }
            index += ch.len_utf8();
        }
        let close = close?;
        let suffix = &rest[close + 1..];
        if !suffix.is_empty() && !suffix.starts_with('/') {
            return None;
        }
        return Some(LeadingShellVariable {
            modifier: &rest[length..close],
            suffix,
        });
    }

    let rest = candidate.strip_prefix('$')?;
    let length = shell_name_len(rest);
    if length == 0 {
        return None;
    }
    let suffix = &rest[length..];
    if !suffix.is_empty() && !suffix.starts_with('/') {
        return None;
    }
    Some(LeadingShellVariable {
        modifier: "",
        suffix,
    })
}

#[derive(Clone, Copy)]
struct ShellVariableReference<'a> {
    name: &'a str,
    start: usize,
    end: usize,
}

/// Parse every parameter expansion in a prospective path. Only plain `$NAME`
/// and `${NAME}` forms are inspectable. Positional/special parameters, command
/// substitution, malformed braces, and modifier expansions all fail closed.
fn shell_variable_references(candidate: &str) -> Result<Vec<ShellVariableReference<'_>>, ()> {
    let mut references = Vec::new();
    let mut cursor = 0;
    while let Some(relative) = candidate[cursor..].find('$') {
        let start = cursor + relative;
        let after_dollar = start + 1;
        let rest = &candidate[after_dollar..];
        if let Some(braced) = rest.strip_prefix('{') {
            let length = shell_name_len(braced);
            if length == 0 || !braced[length..].starts_with('}') {
                return Err(());
            }
            let end = after_dollar + 1 + length + 1;
            references.push(ShellVariableReference {
                name: &braced[..length],
                start,
                end,
            });
            cursor = end;
        } else {
            let length = shell_name_len(rest);
            if length == 0 {
                return Err(());
            }
            let end = after_dollar + length;
            references.push(ShellVariableReference {
                name: &rest[..length],
                start,
                end,
            });
            cursor = end;
        }
    }
    Ok(references)
}

fn resolved_shell_variable<'a>(
    gate: &'a DenyGovernedShellPathEscape,
    name: &str,
) -> Option<&'a Path> {
    match name {
        "PWD" => Some(gate.worktree.as_path()),
        "OLDPWD" if gate.oldpwd_is_worktree => Some(gate.worktree.as_path()),
        "CARGO_TARGET_DIR" => gate.cargo_target_dir.as_deref(),
        _ => None,
    }
}

/// Deny any uninspectable variable in a path operand, whether it is leading or
/// follows a fixed path segment. Known variables are expanded from values
/// pinned when the gate is constructed, then the resulting path is checked.
fn variable_operand_denial(
    gate: &DenyGovernedShellPathEscape,
    verb: &str,
    candidate: &str,
) -> Option<String> {
    if !candidate.contains('$') {
        return None;
    }

    // The tokenizer intentionally forgets shell quoting. Preserve only the
    // existing exact-dollar-name exception; suffix variables are expansions.
    if let Some(operand) = leading_shell_variable(candidate) {
        if operand.suffix.is_empty()
            && operand.modifier.is_empty()
            && gate.worktree.join(candidate).exists()
            && stays_under(&gate.worktree, candidate)
        {
            return None;
        }
    }

    let references = match shell_variable_references(candidate) {
        Ok(references) if !references.is_empty() => references,
        _ => {
            return Some(format!(
                "'{verb}' variable operand cannot be inspected: '{candidate}'"
            ));
        }
    };
    let mut expanded = String::with_capacity(candidate.len());
    let mut copied = 0;
    for reference in references {
        let Some(value) = resolved_shell_variable(gate, reference.name) else {
            return Some(format!(
                "'{verb}' variable operand cannot be inspected: '{candidate}'"
            ));
        };
        expanded.push_str(&candidate[copied..reference.start]);
        expanded.push_str(&value.to_string_lossy());
        copied = reference.end;
    }
    expanded.push_str(&candidate[copied..]);

    let expanded_path = Path::new(&expanded);
    let stays_governed = if expanded_path.is_absolute() {
        stays_under(&gate.worktree, &expanded)
            || gate
                .cargo_target_dir
                .as_deref()
                .is_some_and(|root| stays_under(root, &expanded))
    } else {
        stays_under(&gate.worktree, &expanded)
    };
    if stays_governed {
        None
    } else {
        Some(format!(
            "'{verb}' variable path '{candidate}' resolves outside its governed root"
        ))
    }
}

fn governed_operand_prefix_variables(segment: &[String]) -> BTreeSet<String> {
    let mut names = BTreeSet::new();
    let mut command = segment;
    while let Some(verb_index) = command.iter().position(|token| !shell_assignment(token)) {
        let verb = executable_name(&command[verb_index]);
        if READ_OR_CHDIR_VERBS.contains(&verb.as_str()) {
            if let Ok(paths) = governed_path_arguments(&verb, command) {
                for path in paths {
                    let candidate = path
                        .trim_matches(|c: char| matches!(c, '"' | '\'' | '(' | ')' | ',' | ';'));
                    if let Ok(references) = shell_variable_references(candidate) {
                        if let Some(reference) = references.first().filter(|item| item.start == 0) {
                            names.insert(reference.name.to_string());
                        }
                    }
                }
            }
        }
        let Some(invocation) = carrier_command(command, verb_index, &verb) else {
            break;
        };
        if invocation.command.is_empty() {
            break;
        }
        command = invocation.command;
    }
    names
}

fn shell_root_escape(candidate: &str) -> bool {
    ["HOME", "TMPDIR"].iter().any(|name| {
        let unbraced = format!("${name}");
        let unbraced_match = candidate.strip_prefix(&unbraced).is_some_and(|suffix| {
            suffix
                .chars()
                .next()
                .is_none_or(|ch| ch != '_' && !ch.is_ascii_alphanumeric())
        });
        let braced = format!("${{{name}");
        let braced_match = candidate.strip_prefix(&braced).is_some_and(|suffix| {
            suffix
                .chars()
                .next()
                .is_some_and(|ch| ch != '_' && !ch.is_ascii_alphanumeric())
        });
        unbraced_match || braced_match
    })
}

fn execution_redirecting_variable(name: &str) -> bool {
    matches!(
        name,
        "BASH_ENV"
            | "ENV"
            | "PATH"
            | "LD_PRELOAD"
            | "PYTHONPATH"
            | "PERL5LIB"
            | "RUBYLIB"
            | "NODE_OPTIONS"
            | "CARGO_HOME"
            | "RUSTUP_HOME"
            | "GIT_EXEC_PATH"
            | "GIT_SSH_COMMAND"
    ) || name.starts_with("DYLD_")
}

fn command_opens_editor(verb: &str, args: &[String]) -> bool {
    (verb == "git"
        && args.iter().any(|arg| {
            matches!(
                arg.as_str(),
                "add" | "commit" | "config" | "merge" | "rebase" | "tag"
            )
        }))
        || matches!(verb, "crontab" | "vipw" | "vigr" | "visudo")
}

fn assignment_value_names_path(value: &str) -> bool {
    value.contains('/')
        || value.contains('\\')
        || value.starts_with('~')
        || shell_root_escape(value)
        || value.contains("..")
        || (value.as_bytes().get(1) == Some(&b':')
            && value
                .as_bytes()
                .first()
                .is_some_and(u8::is_ascii_alphabetic))
}

fn effective_command(mut command: &[String]) -> Option<(String, &[String])> {
    loop {
        let verb_index = command.iter().position(|token| !shell_assignment(token))?;
        let current_verb = executable_name(&command[verb_index]);
        let args = &command[verb_index + 1..];
        let Some(invocation) = carrier_command(command, verb_index, &current_verb) else {
            return Some((current_verb, args));
        };
        if invocation.command.is_empty() {
            return Some((current_verb, args));
        }
        command = invocation.command;
    }
}

struct AssignmentBuiltinOperands<'a> {
    assignments: Vec<&'a str>,
    removed_names: Vec<&'a str>,
}

/// Extract assignments handled by shell builtins rather than by the shell's
/// leading-assignment grammar. These builtins mutate the current shell, so a
/// later command segment observes the assigned value just as it would for a
/// bare assignment-only segment.
fn assignment_builtin_operands<'a>(
    command: &'a [String],
    verb_index: usize,
    verb: &str,
) -> AssignmentBuiltinOperands<'a> {
    let args = &command[verb_index + 1..];
    let assignment_builtin = matches!(
        verb,
        "export" | "readonly" | "declare" | "typeset" | "local"
    );
    let assignments = if assignment_builtin {
        args.iter()
            .map(String::as_str)
            .filter(|arg| shell_assignment(arg))
            .collect()
    } else {
        Vec::new()
    };

    let removes_export_attribute = verb == "export"
        && args
            .iter()
            .take_while(|arg| arg.as_str() != "--")
            .filter_map(|arg| arg.strip_prefix('-'))
            .any(|options| !options.starts_with('-') && options.contains('n'));
    let removes_variables = verb == "unset" || removes_export_attribute;
    let removed_names = if removes_variables {
        args.iter()
            .skip_while(|arg| arg.starts_with('-') && arg.as_str() != "--")
            .filter(|arg| arg.as_str() != "--")
            .map(String::as_str)
            .filter(|arg| shell_name_len(arg) == arg.len())
            .collect()
    } else {
        Vec::new()
    };

    AssignmentBuiltinOperands {
        assignments,
        removed_names,
    }
}

fn assignment_name_denial(
    name: &str,
    opens_editor: bool,
    operand_prefix_variables: &BTreeSet<String>,
) -> Option<String> {
    if execution_redirecting_variable(name) || (matches!(name, "EDITOR" | "VISUAL") && opens_editor)
    {
        return Some(format!(
            "environment assignment '{name}' may redirect executable code in a governed session"
        ));
    }
    if matches!(
        name,
        "PWD" | "OLDPWD" | "CARGO_TARGET_DIR" | "HOME" | "TMPDIR" | "IFS" | "PATH"
    ) || operand_prefix_variables.contains(name)
    {
        return Some(format!(
            "environment assignment '{name}' may change a governed path operand"
        ));
    }
    None
}

fn assignment_denial(
    worktree: &Path,
    command: &[String],
    operand_prefix_variables: &BTreeSet<String>,
) -> Option<String> {
    let opens_editor =
        effective_command(command).is_some_and(|(verb, args)| command_opens_editor(&verb, args));
    let mut current = command;
    loop {
        // Assignment-only segments have no verb, but their assignments still
        // affect later shell segments and must not disappear from inspection.
        let verb_index = current
            .iter()
            .position(|token| !shell_assignment(token))
            .unwrap_or(current.len());
        let invocation = if verb_index < current.len() {
            let current_verb = executable_name(&current[verb_index]);
            carrier_command(current, verb_index, &current_verb)
        } else {
            None
        };
        let carrier_assignments = invocation
            .as_ref()
            .into_iter()
            .flat_map(|invocation| invocation.assignments.iter().copied());
        let builtin_operands = if verb_index < current.len() {
            assignment_builtin_operands(current, verb_index, &executable_name(&current[verb_index]))
        } else {
            AssignmentBuiltinOperands {
                assignments: Vec::new(),
                removed_names: Vec::new(),
            }
        };
        let assignments = current[..verb_index]
            .iter()
            .map(String::as_str)
            .chain(carrier_assignments)
            .chain(builtin_operands.assignments);
        for assignment in assignments {
            let Some(parts) = shell_assignment_parts(assignment) else {
                continue;
            };
            if parts
                .subscript
                .is_some_and(shell_subscript_contains_command_substitution)
            {
                return Some(format!(
                    "environment assignment '{}' has a subscript that cannot be inspected",
                    parts.name
                ));
            }
            if let Some(reason) =
                assignment_name_denial(parts.name, opens_editor, operand_prefix_variables)
            {
                return Some(reason);
            }
            if assignment_value_names_path(parts.value) && !stays_under(worktree, parts.value) {
                return Some(format!(
                    "environment assignment '{}' names path '{}' outside the governed repository",
                    parts.name, parts.value
                ));
            }
        }
        for name in builtin_operands.removed_names {
            if let Some(reason) =
                assignment_name_denial(name, opens_editor, operand_prefix_variables)
            {
                return Some(reason);
            }
        }
        let Some(invocation) = invocation else {
            break;
        };
        if invocation.command.is_empty() {
            break;
        }
        current = invocation.command;
    }
    None
}

/// Apply the assignment rules to an array-element assignment whose subscript
/// the tokenised path never sees. A command substitution is uninspectable
/// outright; otherwise the base name still gets the protected-name and
/// path-prefix checks it would have had if the subscript had survived
/// tokenisation, because bash assigns element 0 of a scalar to the scalar
/// itself whatever whitespace the subscript carries.
fn uninspectable_subscript_denial(
    command: &str,
    segments: &[Vec<String>],
    operand_prefix_variables: &BTreeSet<String>,
) -> Option<String> {
    let candidates = uninspectable_assignment_subscripts(command);
    if candidates.is_empty() {
        return None;
    }
    let opens_editor = segments.iter().any(|segment| {
        effective_command(segment).is_some_and(|(verb, args)| command_opens_editor(&verb, args))
    });
    for (name, flaw) in candidates {
        match flaw {
            SubscriptFlaw::CommandSubstitution => {
                return Some(format!(
                    "environment assignment '{name}' has a subscript that cannot be inspected"
                ));
            }
            SubscriptFlaw::BreaksTokenization => {
                if let Some(reason) =
                    assignment_name_denial(name, opens_editor, operand_prefix_variables)
                {
                    return Some(reason);
                }
            }
        }
    }
    None
}

impl Inspector for DenyGovernedShellPathEscape {
    fn name(&self) -> &'static str {
        "governed_host.deny_shell_path_escape"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        let segments = governed_shell_segments(&cmd);
        let mut future_operand_prefix_variables = vec![BTreeSet::new(); segments.len()];
        let mut suffix_variables = BTreeSet::new();
        for (index, segment) in segments.iter().enumerate().rev() {
            suffix_variables.extend(governed_operand_prefix_variables(segment));
            future_operand_prefix_variables[index] = suffix_variables.clone();
        }
        // `suffix_variables` now holds every variable used as a path prefix
        // anywhere in the command. A subscript that breaks tokenisation also
        // destroys the segment the assignment belonged to, so the whole-command
        // set is the only honest one to check it against.
        if let Some(reason) = uninspectable_subscript_denial(&cmd, &segments, &suffix_variables) {
            return InspectionResult::Deny(reason);
        }
        for (index, seg) in segments.into_iter().enumerate() {
            if let Some(reason) = assignment_denial(
                &self.worktree,
                &seg,
                &future_operand_prefix_variables[index],
            ) {
                return InspectionResult::Deny(reason);
            }
            let mut command = seg.as_slice();
            while let Some(verb_index) = command.iter().position(|token| !shell_assignment(token)) {
                let v = executable_name(&command[verb_index]);
                let args = &command[verb_index + 1..];
                if v == "busybox"
                    && args
                        .iter()
                        .any(|arg| arg == "--install" || arg.starts_with("--install="))
                {
                    return InspectionResult::Deny(
                        "busybox --install may write outside the governed repository".into(),
                    );
                }
                if nested_command_carrier(&v, args) {
                    return InspectionResult::Deny(format!(
                        "nested shell command through '{v}' cannot be inspected in a governed session"
                    ));
                }
                if READ_OR_CHDIR_VERBS.contains(&v.as_str()) {
                    let governed_args = match governed_path_arguments(&v, command) {
                        Ok(paths) => paths,
                        Err(reason) => return InspectionResult::Deny(reason),
                    };
                    for arg in governed_args {
                        let candidate = arg.trim_matches(|c: char| {
                            matches!(c, '"' | '\'' | '(' | ')' | ',' | ';')
                        });
                        if let Some(reason) = variable_operand_denial(self, &v, candidate) {
                            return InspectionResult::Deny(reason);
                        }
                        let names_path = candidate.starts_with('~')
                            || shell_root_escape(candidate)
                            || is_abs_or_traversal(candidate)
                            || self.worktree.join(candidate).exists();
                        if names_path && !stays_under(&self.worktree, candidate) {
                            return InspectionResult::Deny(format!(
                                "'{v}' path '{candidate}' resolves outside the governed repository"
                            ));
                        }
                    }
                }

                let Some(invocation) = carrier_command(command, verb_index, &v) else {
                    break;
                };
                if invocation.command.is_empty() {
                    break;
                }
                command = invocation.command;
            }
        }
        InspectionResult::Allow
    }
}

/// Unlike the general coder, governed host mode does not permit file-tool
/// reads outside the selected repository either.
struct DenyGovernedFilePathEscape {
    worktree: PathBuf,
}

impl Inspector for DenyGovernedFilePathEscape {
    fn name(&self) -> &'static str {
        "governed_host.deny_file_path_escape"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        if !matches!(
            tool,
            "read_file" | "write_file" | "edit_file" | "grep_files"
        ) {
            return InspectionResult::Allow;
        }
        let Some(path) = params.get("path").and_then(Value::as_str) else {
            return InspectionResult::Allow;
        };
        if stays_under(&self.worktree, path) {
            InspectionResult::Allow
        } else {
            InspectionResult::Deny(format!(
                "file access to '{path}' resolves outside the governed repository"
            ))
        }
    }
}

/// Host hardening for the governed supervised assistant. Unlike a coder
/// worktree, this workflow may perform one explicitly approved normal push;
/// remote reconfiguration, force pushes, history rewrite, credential access,
/// and path escape remain unconditional denials.
pub fn governed_host_inspector_chain(worktree: &Path) -> InspectorChain {
    InspectorChain::new()
        .with(Box::new(DenyGuiShellAutomation))
        .with(Box::new(DenyForcePushAndRemoteReconfiguration))
        .with(Box::new(DenyBroadGitStage))
        .with(Box::new(DenyHistoryRewrite))
        .with(Box::new(DenyPrivilegeEscalation))
        .with(Box::new(DenyCredentialAccess))
        .with(Box::new(DenyEnvironmentRepair))
        .with(Box::new(DenyDestructiveOutsideWorktree {
            worktree: worktree.to_path_buf(),
        }))
        .with(Box::new(DenyGovernedShellPathEscape::new(worktree)))
        .with(Box::new(DenyGovernedFilePathEscape {
            worktree: worktree.to_path_buf(),
        }))
}

/// A governed engineering session has a first-class host shell. Driving a
/// terminal (or a PowerShell window) through desktop automation would bypass
/// repository scoping, action classification, gate checks, and receipts.
struct DenyGuiShellAutomation;

impl Inspector for DenyGuiShellAutomation {
    fn name(&self) -> &'static str {
        "governed_host.deny_gui_shell_automation"
    }

    fn inspect(&self, tool: &str, _params: &Value) -> InspectionResult {
        if matches!(tool, "run_applescript" | "run_powershell") {
            InspectionResult::Deny(
                "desktop-driven shell execution is not allowed; use the governed shell tool".into(),
            )
        } else {
            InspectionResult::Allow
        }
    }
}

/// Preserve unrelated dirty-checkout changes by requiring explicit paths at
/// the staging boundary. Targeted `git add path` remains available.
struct DenyBroadGitStage;

impl Inspector for DenyBroadGitStage {
    fn name(&self) -> &'static str {
        "governed_host.deny_broad_git_stage"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            if verb(&seg) != Some("git") {
                continue;
            }
            let add = seg.iter().position(|token| token == "add");
            if let Some(index) = add {
                if seg
                    .iter()
                    .skip(index + 1)
                    .any(|token| matches!(token.as_str(), "." | "-A" | "--all" | "-u" | "--update"))
                {
                    return InspectionResult::Deny(
                        "broad git staging is not allowed; name only the files changed for this task"
                            .into(),
                    );
                }
            }
            if seg.iter().any(|token| token == "commit")
                && seg.iter().any(|token| {
                    token == "--all"
                        || token
                            .strip_prefix('-')
                            .filter(|short| !short.starts_with('-'))
                            .is_some_and(|short| short.contains('a'))
                })
            {
                return InspectionResult::Deny(
                    "git commit -a is not allowed; stage only explicit task files".into(),
                );
            }
        }
        InspectionResult::Allow
    }
}

/// Lexically resolve `candidate` against `root` and decide whether it stays
/// under `root`. Purely lexical (`..` popping) — symlinks inside the worktree
/// are out of scope here, consistent with the hardening-not-sandbox stance.
pub(crate) fn stays_under(root: &Path, candidate: &str) -> bool {
    // Shells expand leading `~`/`~user` and HOME/TMPDIR references before
    // invoking the command. Do not reinterpret those spellings as literal
    // directories under the repo; direct file tools use this helper too and
    // must keep the same boundary.
    if candidate.starts_with('~') || shell_root_escape(candidate) {
        return false;
    }
    // A variable-shaped path is not safely repository-relative merely because
    // its dollar sign is a legal filename byte. Preserve only an exact,
    // already-existing literal entry such as `$HOME_fixture`; slash-prefixed
    // suffixes and absent bare names are shell expansion, not repo paths.
    if let Some(variable) = leading_shell_variable(candidate) {
        if !variable.suffix.is_empty()
            || !variable.modifier.is_empty()
            || !root.join(candidate).exists()
        {
            return false;
        }
    }
    let p = Path::new(candidate);
    let joined = if p.is_absolute() {
        p.to_path_buf()
    } else {
        root.join(p)
    };
    // Existing paths get a filesystem-authoritative check first. This closes
    // the symlink escape (`repo/link -> /outside`, then `read_file link/x`)
    // that a purely lexical `..` clamp cannot see. Prospective writes fall
    // through to the lexical check; their nearest existing ancestor is also
    // checked by the governed RepositoryScope before host binding.
    if joined.exists() {
        if let (Ok(real_root), Ok(real_candidate)) = (root.canonicalize(), joined.canonicalize()) {
            return path_starts_with(&real_candidate, &real_root);
        }
        return false;
    }
    if let Ok(real_root) = root.canonicalize() {
        let mut ancestor = joined.as_path();
        while !ancestor.exists() {
            let Some(parent) = ancestor.parent() else {
                return false;
            };
            ancestor = parent;
        }
        match ancestor.canonicalize() {
            Ok(real_ancestor) if path_starts_with(&real_ancestor, &real_root) => {}
            _ => return false,
        }
    }
    let mut stack: Vec<Component> = Vec::new();
    for c in joined.components() {
        match c {
            Component::CurDir => {}
            Component::ParentDir => {
                if stack.pop().is_none() {
                    return false;
                }
            }
            other => stack.push(other),
        }
    }
    let normalized: PathBuf = stack.iter().collect();
    path_starts_with(&normalized, root)
}

/// Component-boundary prefix test. On Unix this is `Path::starts_with`. On
/// Windows it additionally strips the `\\?\` verbatim prefix (which
/// `Path::canonicalize` adds to the worktree root but a model-supplied absolute
/// path lacks) and folds case (NTFS is case-insensitive), so a legitimate
/// absolute write inside the worktree isn't spuriously denied.
#[cfg(not(windows))]
fn path_starts_with(path: &Path, base: &Path) -> bool {
    path.starts_with(base)
}

#[cfg(windows)]
fn path_starts_with(path: &Path, base: &Path) -> bool {
    fn key(p: &Path) -> String {
        let s = p.to_string_lossy().into_owned();
        let s = if let Some(r) = s.strip_prefix(r"\\?\UNC\") {
            format!(r"\\{r}")
        } else if let Some(r) = s.strip_prefix(r"\\?\") {
            r.to_string()
        } else {
            s
        };
        s.replace('/', "\\").to_ascii_lowercase()
    }
    let base_key = key(base);
    let base_trim = base_key.trim_end_matches('\\');
    let path_key = key(path);
    path_key == base_trim || path_key.starts_with(&format!("{base_trim}\\"))
}

/// True when a shell argument names an absolute path (POSIX `/…`, Windows
/// `C:\…` / `\\server\…`) or contains a `..` traversal — i.e. the argument may
/// point outside the worktree and must be checked against [`stays_under`].
/// The old code tested only `starts_with('/')`, which never matches a Windows
/// absolute path, so `del C:\…` slipped past the destructive-op guard.
fn is_abs_or_traversal(arg: &str) -> bool {
    arg.starts_with('/')
        || arg.starts_with('\\')
        || arg.contains("..")
        || Path::new(arg).is_absolute()
}

/// True for a Windows `cmd` switch like `/q`, `/s`, `/f` — a leading `/`
/// followed by one or two alphanumerics and nothing else. Distinguished from a
/// POSIX absolute path (`/etc`, `/wt/...`), which is longer or contains another
/// separator. Only ever true on Windows, so Unix argument handling (where a
/// leading `/` is always a path) is unchanged.
fn is_windows_switch(arg: &str) -> bool {
    #[cfg(not(windows))]
    {
        let _ = arg;
        false
    }
    #[cfg(windows)]
    {
        arg.strip_prefix('/')
            .map(|rest| {
                (1..=2).contains(&rest.len()) && rest.chars().all(|c| c.is_ascii_alphanumeric())
            })
            .unwrap_or(false)
    }
}

/// Split a shell command into segments at unquoted-ish separators and each
/// segment into whitespace tokens. Naive on purpose (no quote handling): a
/// quoted `";"` may split a segment too eagerly, which only ever makes the
/// chain MORE likely to deny — never less. Carrier invocations additionally
/// yield each recursively launched command, while retaining the outer command
/// so a rule that governs the carrier itself (notably `sudo`) still fires.
fn segments(command: &str) -> Vec<Vec<String>> {
    let outer: Vec<Vec<String>> = join_shell_line_continuations(command)
        .replace("&&", "\n")
        .replace("||", "\n")
        .replace(['ï¼›', ';', '|'], "\n")
        .lines()
        .map(|seg| {
            seg.split_whitespace()
                .map(|t| t.trim_matches(|c| c == '"' || c == '\'').to_string())
                .filter(|t| !t.is_empty())
                .collect::<Vec<_>>()
        })
        .filter(|toks: &Vec<String>| !toks.is_empty())
        .collect();

    let mut expanded = Vec::new();
    for segment in outer {
        expanded.push(segment.clone());
        let mut command = segment.as_slice();
        while let Some(verb_index) = command.iter().position(|token| !shell_assignment(token)) {
            let v = executable_name(&command[verb_index]);
            let Some(invocation) = carrier_command(command, verb_index, &v) else {
                break;
            };
            if invocation.command.is_empty() {
                break;
            }
            expanded.push(invocation.command.to_vec());
            command = invocation.command;
        }
    }
    expanded
}

/// First non-env-assignment token of a segment (`FOO=bar cmd …` → `cmd`).
fn verb(tokens: &[String]) -> Option<&str> {
    tokens.iter().map(String::as_str).find(|t| !t.contains('='))
}

fn shell_command(tool: &str, params: &Value) -> Option<String> {
    if tool != "shell" {
        return None;
    }
    params
        .get("command")
        .and_then(Value::as_str)
        .map(str::to_string)
}

/// `git push`, `git remote add/set-url`, `git fetch --force` — the coder's
/// output leaves the machine only via the approved merge branch.
struct DenyGitRemoteMutation;

impl Inspector for DenyGitRemoteMutation {
    fn name(&self) -> &'static str {
        "coder.deny_git_remote_mutation"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            let is_git = verb(&seg) == Some("git");
            if !is_git {
                continue;
            }
            if seg.iter().any(|t| t == "push") {
                return InspectionResult::Deny(
                    "git push is not allowed from a coder session — results are delivered \
                     via the approved local branch"
                        .into(),
                );
            }
            if seg.iter().any(|t| t == "remote")
                && seg
                    .iter()
                    .any(|t| t == "add" || t == "set-url" || t == "remove")
            {
                return InspectionResult::Deny("mutating git remotes is not allowed".into());
            }
        }
        InspectionResult::Allow
    }
}

/// Publication by any route other than the approved merge branch. `git push`
/// is denied above, but a forge CLI reaches the world without touching git:
/// `gh pr create` opens a pull request, `gh release create` ships a release,
/// `gh api --method DELETE` edits branch protection, and `gh auth token`
/// prints the credential that does all three. The property the coder's gates
/// claim is "work leaves the worktree only through `coder.approve_merge`", and
/// one extra binary was enough to break it (car#1074).
///
/// Shape, deliberately mixed. For the forge CLIs (`gh`, `glab`, `hub`) this is
/// an **allowlist**: the read-only subcommands are a small finite set while the
/// mutating ones are not, so a `gh` verb nobody has vetted arrives denied. For
/// package registries it is a short **blacklist** of publish subcommands,
/// because the surrounding verbs (`npm`, `cargo`, `docker`) are ordinary build
/// tools a task legitimately runs. An unparseable forge invocation falls to
/// Deny, which is the safe side — the model gets a reason, not a silent push.
///
/// Out of scope on purpose: `aws`, `kubectl`, `terraform`, `gcloud`. Those are
/// cloud/infra mutation rather than publishing *this repo's work*, the blast
/// radius of a false denial is larger, and the honest fix for them is an
/// allowlist over network-reaching verbs (car#1074 option 2) rather than one
/// more name on a blacklist. A shell alias or a script that wraps `gh` still
/// reaches the binary — hardening, not a sandbox. Prefix carriers are unwrapped
/// by [`segments`], but aliases and wrapper scripts remain outside this
/// matcher's reach.
struct DenyForgePublication;

/// Forge CLIs: anything not on [`FORGE_READS`] is denied.
const FORGE_VERBS: &[&str] = &["gh", "glab", "hub"];

/// (group, allowed subcommands) for a forge CLI. An empty subcommand list
/// allows the whole group.
const FORGE_READS: &[(&str, &[&str])] = &[
    ("pr", &["view", "list", "diff", "checks", "status"]),
    ("mr", &["view", "list", "diff", "checks", "status"]),
    ("issue", &["view", "list"]),
    ("repo", &["view"]),
    ("run", &["view", "list", "watch"]),
    ("release", &["view", "list"]),
    ("workflow", &["view", "list"]),
    ("label", &["list"]),
    ("cache", &["list"]),
    ("gist", &["view", "list"]),
    ("auth", &["status"]),
    ("search", &[]),
    ("status", &[]),
    ("version", &[]),
];

/// Global flags that take a separate value, so the value isn't mistaken for
/// the subcommand group (`gh --repo o/r pr view` → group `pr`, not `o/r`).
const FORGE_VALUE_FLAGS: &[&str] = &["-r", "--repo", "--hostname"];

/// Registry/artifact publication, matched as (verb, first operand).
const PUBLICATION_COMMANDS: &[(&str, &[&str])] = &[
    ("npm", &["publish"]),
    ("pnpm", &["publish"]),
    ("yarn", &["publish"]),
    ("cargo", &["publish"]),
    ("gem", &["push"]),
    ("twine", &["upload"]),
    ("docker", &["push", "login"]),
];

impl Inspector for DenyForgePublication {
    fn name(&self) -> &'static str {
        "coder.deny_forge_publication"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            let Some(v) = verb(&seg) else { continue };
            // Match on the program NAME, as `DenyEnvironmentRepair` does:
            // `/opt/homebrew/bin/gh` is the same action as the bare verb.
            let v = Path::new(&v.to_ascii_lowercase())
                .file_name()
                .map(|f| f.to_string_lossy().into_owned())
                .unwrap_or_default();
            let v = v.strip_suffix(".exe").unwrap_or(&v).to_string();
            let args: Vec<String> = seg.iter().skip(1).map(|a| a.to_ascii_lowercase()).collect();

            if FORGE_VERBS.contains(&v.as_str()) {
                if let Some(reason) = forge_denial(&v, &args) {
                    return InspectionResult::Deny(reason);
                }
                continue;
            }

            for (mgr, subs) in PUBLICATION_COMMANDS {
                if v != *mgr {
                    continue;
                }
                if leading_operands(&args).iter().any(|sub| subs.contains(sub)) {
                    return InspectionResult::Deny(format!(
                        "'{mgr}' publication is not allowed from a coder session — results \
                         leave the worktree only through the approved merge branch"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// Positional operands of a forge invocation, in order, with the values of the
/// known value-taking global flags skipped.
fn forge_operands(args: &[String]) -> Vec<&str> {
    let mut operands = Vec::new();
    let mut skip_value = false;
    for arg in args {
        if std::mem::take(&mut skip_value) {
            continue;
        }
        if FORGE_VALUE_FLAGS.contains(&arg.as_str()) {
            skip_value = true;
            continue;
        }
        if arg.starts_with('-') {
            continue;
        }
        operands.push(arg.as_str());
    }
    operands
}

/// The leading positional operands of a command, enough to find a subcommand
/// that ordinary leading tokens have pushed out of first place.
///
/// Reading only the FIRST operand missed three everyday spellings, each of
/// which reaches a registry:
///
/// - `cargo +stable publish` — the rustup toolchain selector is an operand
/// - `docker image push img` — the canonical modern form, subcommand in a group
/// - `npm --workspace x publish` — the flag's VALUE lands in first place
///
/// A `+toolchain` selector is dropped outright, and the next two operands are
/// returned so a group + subcommand pair is visible.
///
/// The trade-off is deliberate and worth stating: scanning two operands can
/// over-match a flag value (`cargo build --features publish` would be denied).
/// This half of the chain is a deny-list over registries, so it is defence in
/// depth rather than the boundary — a false positive is a red check with an
/// explicit reason, while a false negative publishes a package.
fn leading_operands(args: &[String]) -> Vec<&str> {
    args.iter()
        .map(String::as_str)
        .filter(|a| !a.starts_with('-') && !a.starts_with('+'))
        .take(2)
        .collect()
}

/// `Some(reason)` when this forge invocation is not on the read-only
/// allowlist. Everything unrecognised — a new subcommand, a group with no
/// subcommand, an argument shape this matcher cannot read — comes back denied.
fn forge_denial(verb: &str, args: &[String]) -> Option<String> {
    const BLOCKED: &str = "publishing from a coder session is not allowed — the runtime opens \
                           the pull request after `coder.approve_merge`";

    // `--version`/`--help` are flags, not operands, so read them off the raw
    // argument list before operand filtering drops them.
    //
    // `-h` is NOT in this set, and must not be. It was, and it made the whole
    // inspector an allow-all: pflag consumes the next token as a string flag's
    // value even when it starts with a dash, so `gh release create v9 --notes -h`
    // and `gh pr create --title -h --body b --head x --base main` both reached
    // this and returned None before the group was ever read. The premise was
    // wrong on its own terms too — in `gh auth status`, `-h` is `--hostname`.
    //
    // Matching only the long forms costs a coder nothing: `gh --help` still
    // works, and a denied `-h` is one retry away from the spelling that does.
    if args
        .iter()
        .any(|a| matches!(a.as_str(), "--version" | "--help"))
    {
        return None;
    }
    let operands = forge_operands(args);
    let Some(group) = operands.first().copied() else {
        return None; // bare `gh` prints usage
    };

    // `gh api` defaults to GET; an explicit non-GET method, or a field/input
    // flag (which implicitly switches it to POST), makes it a write.
    if group == "api" {
        // Every one of these must match the ATTACHED forms too. pflag accepts
        // `-XPOST` and `--field=k=v` exactly as it accepts the separated
        // spellings, so a matcher that only reads two-token pairs and exact
        // flag names lets `gh api -XPOST repos/O/R/pulls --input=-` straight
        // through — a pull request opened past the gate.
        let is_write_method = |v: &str| !v.is_empty() && v != "get";
        let explicit_method = args
            .windows(2)
            .any(|pair| matches!(pair[0].as_str(), "--method" | "-x") && is_write_method(&pair[1]))
            || args.iter().any(|a| {
                a.strip_prefix("--method=")
                    .or_else(|| a.strip_prefix("-x"))
                    .is_some_and(is_write_method)
            });
        // NB: args are lowercased, so `-f` covers `gh api -F` too.
        let field_flag = |a: &String| {
            matches!(a.as_str(), "-f" | "--field" | "--raw-field" | "--input")
                || a.starts_with("--field=")
                || a.starts_with("--raw-field=")
                || a.starts_with("--input=")
                || a.starts_with("-f")
        };
        // A field alone is not a write: read-only GraphQL REQUIRES `-f query=`,
        // and denying that while allowing `--field=query=mutation{…}` had the
        // detector inverted on the single endpoint where it matters most. What
        // makes a GraphQL call a write is the operation, not the flag shape.
        let graphql = operands.get(1).is_some_and(|o| *o == "graphql");
        let mutating_graphql = graphql
            && args
                .iter()
                .any(|a| a.contains("mutation") || a.contains("deletion"));
        let implicit_post = !graphql && args.iter().any(field_flag);
        return (explicit_method || implicit_post || mutating_graphql)
            .then(|| format!("'{verb} api' with a write method is not allowed — {BLOCKED}"));
    }

    // `gh auth status` is a read — except with `-t`/`--show-token`, which
    // PRINTS THE TOKEN. #1074 named `gh auth token` as the credential leak and
    // this allowlist quietly kept the other spelling of it. With the token in
    // hand the whole forge matcher is moot: `curl -X POST -H "Authorization:
    // bearer $T" .../pulls` has verb `curl` and is inspected by nothing.
    if group == "auth"
        && args
            .iter()
            .any(|a| a == "-t" || a == "--show-token" || a.starts_with("--show-token="))
    {
        return Some(format!(
            "'{verb} auth status --show-token' prints the forge credential — {BLOCKED}"
        ));
    }

    let Some((_, subs)) = FORGE_READS.iter().find(|(g, _)| *g == group) else {
        return Some(format!("'{verb} {group}' is not allowed — {BLOCKED}"));
    };
    if subs.is_empty() {
        return None;
    }
    match operands.get(1).copied() {
        Some(sub) if subs.contains(&sub) => None,
        Some(sub) => Some(format!("'{verb} {group} {sub}' is not allowed — {BLOCKED}")),
        // `gh pr` alone only prints usage, but a missing subcommand is exactly
        // the parse ambiguity to fail closed on.
        None => Some(format!(
            "'{verb} {group}' without a read-only subcommand is not allowed — {BLOCKED}"
        )),
    }
}

/// The governed assistant may perform an approved ordinary push, but never a
/// force push or remote-configuration mutation.
struct DenyForcePushAndRemoteReconfiguration;

impl Inspector for DenyForcePushAndRemoteReconfiguration {
    fn name(&self) -> &'static str {
        "governed_host.deny_force_push_and_remote_reconfiguration"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            if verb(&seg) != Some("git") {
                continue;
            }
            let push = seg.iter().any(|token| token == "push");
            let forced = seg.iter().any(|token| {
                token == "--force"
                    || token == "-f"
                    || token.starts_with("--force-with-lease")
                    || token.starts_with('+')
            });
            if push && forced {
                return InspectionResult::Deny("force-push is never allowed".into());
            }
            if seg.iter().any(|token| token == "remote")
                && seg.iter().any(|token| {
                    token == "add" || token == "set-url" || token == "remove" || token == "rename"
                })
            {
                return InspectionResult::Deny(
                    "mutating git remote configuration is not allowed".into(),
                );
            }
        }
        InspectionResult::Allow
    }
}

/// `git rebase/reset --hard/filter-branch` — the worktree HEAD is detached;
/// history rewrite is never needed and only ever destroys evidence.
struct DenyHistoryRewrite;

impl Inspector for DenyHistoryRewrite {
    fn name(&self) -> &'static str {
        "coder.deny_history_rewrite"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            if verb(&seg) != Some("git") {
                continue;
            }
            if seg.iter().any(|t| t == "rebase" || t == "filter-branch") {
                return InspectionResult::Deny("git history rewrite is not allowed".into());
            }
            if seg.iter().any(|t| t == "reset") && seg.iter().any(|t| t == "--hard") {
                return InspectionResult::Deny("git reset --hard is not allowed".into());
            }
            if seg.iter().any(|t| t == "worktree") && seg.iter().any(|t| t == "remove") {
                return InspectionResult::Deny(
                    "removing worktrees is the runtime's job, not the agent's".into(),
                );
            }
        }
        InspectionResult::Allow
    }
}

/// `sudo`/`doas`/service managers — the coder runs with user privileges, full
/// stop.
struct DenyPrivilegeEscalation;

const PRIVILEGE_VERBS: &[&str] = &[
    // POSIX
    "sudo",
    "doas",
    "su",
    "launchctl",
    "systemctl", //
    // Windows privilege elevation / service control.
    "runas",
    "sc",
    "psexec",
];

impl Inspector for DenyPrivilegeEscalation {
    fn name(&self) -> &'static str {
        "coder.deny_privilege_escalation"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            if let Some(v) = verb(&seg) {
                if PRIVILEGE_VERBS.contains(&v.to_ascii_lowercase().as_str()) {
                    return InspectionResult::Deny(format!(
                        "'{v}' is not allowed in a coder session"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// Reads of key stores and credential directories, via shell or file tools.
struct DenyCredentialAccess;

const CREDENTIAL_PATH_MARKERS: [&str; 6] = [
    "/.ssh",
    "/.aws",
    "/.gnupg",
    "/.kube",
    "/.car/secrets",
    "/.netrc",
];

impl Inspector for DenyCredentialAccess {
    fn name(&self) -> &'static str {
        "coder.deny_credential_access"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let haystacks: Vec<String> = if let Some(cmd) = shell_command(tool, params) {
            if cmd.contains("find-generic-password") || cmd.contains("find-internet-password") {
                return InspectionResult::Deny("keychain access is not allowed".into());
            }
            // Windows Credential Manager / DPAPI vault tooling.
            let cmd_lower = cmd.to_ascii_lowercase();
            if cmd_lower.contains("cmdkey") || cmd_lower.contains("vaultcmd") {
                return InspectionResult::Deny(
                    "Windows Credential Manager access is not allowed".into(),
                );
            }
            let sensitive_env = [
                "_key",
                "_token",
                "_secret",
                "_password",
                "openai_",
                "anthropic_",
                "azure_client_",
                "github_token",
                "connection_string",
            ];
            if sensitive_env
                .iter()
                .any(|marker| cmd_lower.contains(marker))
            {
                return InspectionResult::Deny(
                    "reading or expanding credential environment variables is not allowed".into(),
                );
            }
            for seg in segments(&cmd) {
                let Some(command) = verb(&seg).map(|value| value.to_ascii_lowercase()) else {
                    continue;
                };
                if command == "env" && seg.len() == 1
                    || command == "printenv"
                    || command == "set" && seg.len() == 1
                {
                    return InspectionResult::Deny(
                        "dumping the process environment is not allowed".into(),
                    );
                }
            }
            vec![cmd]
        } else if matches!(
            tool,
            "read_file" | "write_file" | "edit_file" | "grep_files"
        ) {
            params
                .get("path")
                .and_then(Value::as_str)
                .map(|p| vec![p.to_string()])
                .unwrap_or_default()
        } else {
            return InspectionResult::Allow;
        };
        for hay in &haystacks {
            // Normalize Windows separators and the various home spellings
            // ("~/.ssh", "$HOME/.ssh", "%USERPROFILE%\.ssh") into the same
            // forward-slash marker space as POSIX absolute paths.
            let hay = hay.replace('\\', "/");
            let hay = hay
                .replace("~/", "/HOME/.")
                .replace("$HOME/", "/HOME/.")
                .replace("%USERPROFILE%/", "/HOME/.")
                .replace("%HOMEPATH%/", "/HOME/.");
            let hay = hay.replace("/HOME/..", "/."); // "~/.ssh" → "/.ssh"
            for marker in CREDENTIAL_PATH_MARKERS {
                if hay.contains(marker) {
                    return InspectionResult::Deny(format!(
                        "access to credential path matching '{marker}' is not allowed"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// Destructive shell verbs aimed outside the worktree (absolute paths, `..`
/// escapes, `~`).
struct DenyDestructiveOutsideWorktree {
    worktree: PathBuf,
}

const DESTRUCTIVE_VERBS: &[&str] = &[
    // POSIX
    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", //
    // Windows `cmd.exe` (the coder shell runs `cmd /C` there) — without these
    // the destructive-outside-worktree guard did nothing on Windows.
    "del", "erase", "rd", "move", "copy", "format", "ren", "rename",
];

impl Inspector for DenyDestructiveOutsideWorktree {
    fn name(&self) -> &'static str {
        "coder.deny_destructive_outside_worktree"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            let Some(v) = verb(&seg) else { continue };
            // Case-insensitive: `cmd.exe` verbs are case-insensitive (DEL/del).
            let v_lower = v.to_ascii_lowercase();
            if !DESTRUCTIVE_VERBS.contains(&v_lower.as_str()) {
                continue;
            }
            // Skip flag-like args: POSIX `-x` and Windows `/x` (e.g. `del /q`).
            for arg in seg
                .iter()
                .skip(1)
                .filter(|a| !a.starts_with('-') && !is_windows_switch(a))
            {
                if arg.starts_with('~') {
                    return InspectionResult::Deny(format!(
                        "'{v}' on a home-relative path ('{arg}') is not allowed"
                    ));
                }
                if is_abs_or_traversal(arg) && !stays_under(&self.worktree, arg) {
                    return InspectionResult::Deny(format!(
                        "'{v}' outside the worktree ('{arg}') is not allowed"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// Environment repair — installing packages, creating interpreters, or dropping
/// an interpreter shim. The coder's job is the code; the runtime re-runs the
/// outcome contract in the correct environment to decide done, so a session that
/// "fixes" its interpreter is burning turns on a verdict it cannot change.
///
/// This used to live as ~140 words of prose in the coder system prompt — an
/// enumerated blacklist a model could reason its way around. As an inspector it
/// is enforced, and the model gets a denial *with a reason* instead, which the
/// loop already knows how to handle.
///
/// Deliberately scoped to what is mechanically decidable. `conftest.py`,
/// `pyproject.toml`, `tox.ini`, and `setup.cfg` are NOT denied: editing them is
/// often the actual task, and no matcher can separate "add a fixture" from
/// "change how tests run". Those stay a matter of judgment in the prompt.
/// `sitecustomize.py` has no legitimate task purpose and is denied.
struct DenyEnvironmentRepair;

/// Package-manager invocations that MUTATE the environment. Matched as
/// (verb, subcommand); a read-only subcommand (`pip list`, `pip show`) passes,
/// so a coder can still inspect what is installed.
const PACKAGE_MUTATIONS: &[(&str, &[&str])] = &[
    ("pip", &["install", "uninstall"]),
    ("pip3", &["install", "uninstall"]),
    ("conda", &["install", "remove", "uninstall", "update"]),
    ("poetry", &["add", "remove", "install", "update"]),
    ("uv", &["add", "remove", "sync"]),
    ("easy_install", &[]),
];

/// Interpreter/test-runner shims a coder has no task reason to author.
const SHIM_FILES: &[&str] = &["sitecustomize.py", "usercustomize.py"];

impl Inspector for DenyEnvironmentRepair {
    fn name(&self) -> &'static str {
        "coder.deny_environment_repair"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        if matches!(tool, "write_file" | "edit_file") {
            let path = params.get("path").and_then(Value::as_str).unwrap_or("");
            let base = Path::new(path)
                .file_name()
                .map(|f| f.to_string_lossy().to_ascii_lowercase())
                .unwrap_or_default();
            if SHIM_FILES.contains(&base.as_str()) {
                return InspectionResult::Deny(format!(
                    "writing '{base}' changes how the interpreter loads, not what your code \
                     does — the runtime re-runs the contract in the correct environment"
                ));
            }
            return InspectionResult::Allow;
        }

        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            let Some(v) = verb(&seg) else { continue };
            // Match on the program NAME, not the path it was invoked by:
            // `/usr/bin/python3.11 -m pip install` and `.venv/bin/pip install`
            // are the same action as the bare verb.
            let v = Path::new(&v.to_ascii_lowercase())
                .file_name()
                .map(|f| f.to_string_lossy().into_owned())
                .unwrap_or_default();
            let v = v.strip_suffix(".exe").unwrap_or(&v).to_string();
            let args: Vec<String> = seg.iter().skip(1).map(|a| a.to_ascii_lowercase()).collect();

            // `python -m pip install …` / `python -m venv …` — the verb is the
            // interpreter, so look past `-m` for the real module.
            let module = args
                .iter()
                .position(|a| a == "-m")
                .and_then(|i| args.get(i + 1))
                .cloned();
            let (effective, effective_args): (String, Vec<String>) = match module {
                Some(m) if v.starts_with("python") || v.starts_with("py") => {
                    let rest = args
                        .iter()
                        .skip_while(|a| **a != m)
                        .skip(1)
                        .cloned()
                        .collect();
                    (m, rest)
                }
                _ => (v.clone(), args.clone()),
            };

            if effective == "venv" || effective == "virtualenv" {
                return InspectionResult::Deny(
                    "creating an interpreter is environment repair, not part of the task — \
                     the runtime re-runs the contract in the correct environment"
                        .into(),
                );
            }
            for (mgr, subs) in PACKAGE_MUTATIONS {
                if effective != *mgr {
                    continue;
                }
                let mutates = subs.is_empty()
                    || effective_args.iter().any(|a| subs.contains(&a.as_str()))
                    // `uv pip install …` nests one level deeper.
                    || (effective == "uv" && effective_args.iter().any(|a| a == "install"));
                if mutates {
                    return InspectionResult::Deny(format!(
                        "'{mgr}' package mutation is environment repair, not part of the task \
                         — the runtime re-runs the contract in the correct environment"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// File-tool writes whose path resolves outside the worktree. (The executor
/// also clamps; defense in depth so a future executor change can't silently
/// drop the rule.)
struct DenyPathEscape {
    worktree: PathBuf,
}

impl Inspector for DenyPathEscape {
    fn name(&self) -> &'static str {
        "coder.deny_path_escape"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        if !matches!(tool, "write_file" | "edit_file") {
            return InspectionResult::Allow;
        }
        let Some(path) = params.get("path").and_then(Value::as_str) else {
            return InspectionResult::Allow; // missing param fails in the tool itself
        };
        if stays_under(&self.worktree, path) {
            InspectionResult::Allow
        } else {
            InspectionResult::Deny(format!("write to '{path}' resolves outside the worktree"))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn chain() -> InspectorChain {
        coder_inspector_chain(Path::new("/wt"))
    }

    fn denied(tool: &str, params: Value) -> bool {
        chain().check(tool, &params).is_some()
    }

    fn sh(cmd: &str) -> Value {
        json!({ "command": cmd })
    }

    fn write_policy(dir: &Path, body: &str) {
        std::fs::create_dir_all(dir).unwrap();
        std::fs::write(dir.join("rules.toml"), body).unwrap();
    }

    #[test]
    fn coder_chain_merges_machine_and_project_deny_rules() {
        let root = tempfile::tempdir().unwrap();
        let repo = root.path().join("repo");
        let machine = root.path().join("machine-policies");
        let project = repo.join(".car").join("policies");
        std::fs::create_dir_all(&repo).unwrap();
        write_policy(&machine, "deny_tool = [\"write_file\"]\n");
        write_policy(&project, "deny_keyword = [\"DO NOT RUN\"]\n");

        let policy =
            coder_inspector_chain_from_policy_dirs(&repo, &[machine.clone(), project.clone()])
                .unwrap();
        // The blanket deny is also readable back for tool-list assembly; the
        // keyword rule is argument-dependent and correctly is not.
        assert_eq!(
            policy.denied_tools.iter().cloned().collect::<Vec<_>>(),
            vec!["write_file".to_string()]
        );
        let chain = policy.chain;
        assert!(chain
            .check("write_file", &json!({"path": "x", "content": "ok"}))
            .is_some());
        assert!(chain
            .check("shell", &json!({"command": "echo DO NOT RUN"}))
            .is_some());
        assert!(chain.check("read_file", &json!({"path": "x"})).is_none());
    }

    #[test]
    fn built_in_denial_reason_wins_before_project_policy() {
        let root = tempfile::tempdir().unwrap();
        let policies = root.path().join("policies");
        write_policy(&policies, "deny_tool = [\"shell\"]\n");
        let chain = coder_inspector_chain_from_policy_dirs(root.path(), &[policies])
            .unwrap()
            .chain;

        let reason = chain
            .check("shell", &sh("git push origin main"))
            .expect("both rules deny");
        assert!(
            reason.contains("git push"),
            "built-in reason must win: {reason}"
        );
        assert!(
            !reason.contains("operator policy"),
            "wrong precedence: {reason}"
        );
    }

    #[test]
    fn malformed_or_unenforced_policy_refuses_chain_construction() {
        let root = tempfile::tempdir().unwrap();
        let malformed = root.path().join("malformed");
        write_policy(&malformed, "deny_tool = [not valid TOML\n");
        assert!(coder_inspector_chain_from_policy_dirs(root.path(), &[malformed]).is_err());

        let trace = root.path().join("trace");
        write_policy(
            &trace,
            "[[trace_rule]]\nkind = \"never\"\ntool = \"deploy\"\n",
        );
        let err = coder_inspector_chain_from_policy_dirs(root.path(), &[trace])
            .err()
            .expect("trace rules are deliberately unenforced");
        assert!(err.to_string().contains("not enforced"), "{err}");
    }

    #[test]
    fn denies_package_mutation_and_interpreter_creation() {
        for cmd in [
            "pip install requests",
            "pip3 uninstall -y six",
            "python -m pip install --upgrade pip",
            "/usr/bin/python3.11 -m pip install pytest",
            "conda install numpy",
            "poetry add httpx",
            "uv pip install ruff",
            "python -m venv .venv",
            "virtualenv env",
            "easy_install foo",
            "cd /wt && pip install -e .",
        ] {
            assert!(denied("shell", sh(cmd)), "should be denied: {cmd}");
        }
    }

    #[test]
    fn allows_read_only_package_queries_and_real_test_runs() {
        // Inspecting the environment is fine; only mutation is env repair. And
        // the contract's own verify command must never be caught by this rule.
        for cmd in [
            "pip list",
            "pip show pytest",
            "python -m pytest -q tests/test_x.py",
            "/wt/.venv/bin/python -m pytest -q tests/test_x.py",
            "cargo test -p car-engine",
            "npm test",
        ] {
            assert!(!denied("shell", sh(cmd)), "should be allowed: {cmd}");
        }
    }

    #[test]
    fn denies_interpreter_shims_but_not_ordinary_test_config() {
        assert!(denied(
            "write_file",
            json!({ "path": "sitecustomize.py", "content": "x" })
        ));
        assert!(denied(
            "write_file",
            json!({ "path": "src/usercustomize.py", "content": "x" })
        ));
        // Editing test config is often the actual task — no matcher can tell
        // "add a fixture" from "change how tests run", so it stays judgment.
        for path in ["conftest.py", "pyproject.toml", "tox.ini", "setup.cfg"] {
            assert!(
                !denied("write_file", json!({ "path": path, "content": "x" })),
                "must stay allowed: {path}"
            );
        }
    }

    #[test]
    fn git_push_and_remote_mutation_denied() {
        assert!(denied("shell", sh("git push origin main")));
        assert!(denied("shell", sh("cargo test && git push --force")));
        assert!(denied("shell", sh("git remote add evil https://x")));
        assert!(denied("shell", sh("git remote set-url origin https://x")));
        // Reading remotes and committing are fine.
        assert!(!denied("shell", sh("git remote -v")));
        assert!(!denied("shell", sh("git commit -m 'x'")));
        assert!(!denied("shell", sh("git status && git diff")));
        // "push" in a non-git segment is fine.
        assert!(!denied("shell", sh("echo push")));
    }

    /// car#1074: `git push` was denied and `gh pr create` was not, so a coder
    /// session could publish its work without passing `coder.approve_merge`.
    #[test]
    fn forge_publication_denied_but_reads_allowed() {
        for cmd in [
            "gh pr create --fill",
            "gh pr merge --admin",
            "gh api --method DELETE /repos/o/r/branches/main/protection",
            "gh api -X POST /repos/o/r/issues",
            "gh api repos/o/r/issues -f title=x",
            "gh release create v9.9.9 ./x",
            "gh auth token",
            "gh repo fork",
            "glab mr create",
            "npm publish",
            "cargo publish",
            "docker push img",
            "docker login ghcr.io",
            "cargo test && gh pr create",
            "/opt/homebrew/bin/gh pr create --fill",
            // --- Adversarial shapes (review of #1076). Every one of these was
            // a working bypass; without them here they regress silently. ---
            //
            // `-h` was in the help allow-all, so ANY command carrying it was
            // waved through before its group was read. pflag takes the next
            // token as a string flag's value even when it starts with a dash.
            "gh release create v9.9.9 --notes -h",
            "gh pr create --title -h --body b --head mybranch --base main",
            // `-t`/`--show-token` PRINTS the credential. #1074 named
            // `gh auth token`; this is the same leak by another spelling, and
            // it sat on the read allowlist.
            "gh auth status -t",
            "gh auth status --show-token",
            // Attached-value forms. pflag parses these exactly like the
            // separated spellings the matcher already knew.
            "gh api -XPOST repos/o/r/pulls --input=-",
            "gh api -XPOST repos/o/r/pulls --field=title=x",
            "gh api --method=post repos/o/r/pulls",
            "gh api repos/o/r/issues --raw-field=title=x",
            // A GraphQL mutation, whatever flag shape carries it.
            "gh api graphql --field=query=mutation{createpullrequest}",
            // Leading operands that shifted the subcommand out of first place.
            "cargo +stable publish",
            "docker image push img",
            "npm --workspace x publish",
        ] {
            assert!(denied("shell", sh(cmd)), "should be denied: {cmd}");
        }

        // Reading the forge is how a coder checks CI on its own branch.
        for cmd in [
            "gh pr view 12",
            "gh pr checks",
            "gh pr diff 12",
            "gh issue list",
            "gh run view 5",
            "gh run watch 5",
            "gh api repos/o/r",
            "gh api --method GET /repos/o/r",
            "gh --repo o/r pr view 12",
            "gh auth status",
            "gh --version",
            "/opt/homebrew/bin/gh pr list",
            // Verb position only, as elsewhere in this chain.
            "echo gh pr create",
            // Ordinary build verbs keep their non-publish subcommands.
            "cargo test -p car-engine",
            "npm run build",
            "docker build -t img .",
            // Read-only GraphQL REQUIRES `-f query=`. Denying it while the
            // attached mutation form passed had the detector inverted on the
            // one endpoint where it matters most.
            "gh api graphql -f query=query{viewer{login}}",
        ] {
            assert!(!denied("shell", sh(cmd)), "should be allowed: {cmd}");
        }
    }

    /// The governed assistant is designed to reach production: `governance.rs`
    /// scores `gh run` / `az pipelines` as CI evidence and an approved
    /// `git push` as remote-main evidence. The forge guard is coder-only, and
    /// that carve-out is pinned here rather than by a comment.
    #[test]
    fn governed_host_still_allows_ci_reads_and_approved_push() {
        let chain = governed_host_inspector_chain(Path::new("/wt"));
        for command in [
            "gh run list",
            "az pipelines runs list",
            "git push origin HEAD:main",
        ] {
            assert!(
                chain.check("shell", &sh(command)).is_none(),
                "governed host must still allow {command}"
            );
        }
    }

    #[test]
    fn governed_host_allows_only_normal_push_shape() {
        let chain = governed_host_inspector_chain(Path::new("/wt"));
        assert!(chain
            .check("shell", &sh("git push origin HEAD:main"))
            .is_none());
        for command in [
            "git push --force origin main",
            "git push --force-with-lease origin main",
            "git push origin +HEAD:main",
            "git remote set-url origin https://evil",
            "git rebase -i HEAD~2",
            "git add .",
            "git add -A",
            "git commit -am fix",
        ] {
            assert!(
                chain.check("shell", &sh(command)).is_some(),
                "must deny {command}"
            );
        }
    }

    #[test]
    fn governed_host_denies_direct_reads_outside_repository() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("repo");
        let outside = temp.path().join("outside.txt");
        std::fs::create_dir(&repo).unwrap();
        std::fs::write(&outside, "secret").unwrap();
        let chain = governed_host_inspector_chain(&repo);

        assert!(chain
            .check("read_file", &json!({"path": outside}))
            .is_some());
        assert!(chain
            .check("shell", &sh(&format!("cat {}", outside.display())))
            .is_some());
        assert!(chain.check("shell", &sh("cd ..")).is_some());
        assert!(chain.check("shell", &sh(r"cat \../outside.txt")).is_some());
        for path in [
            "~/notes.txt",
            "$HOME/notes.txt",
            "${HOME}/notes.txt",
            "${HOME:-/tmp}/notes.txt",
            "${HOME:=/tmp}/notes.txt",
            "$TMPDIR/notes.txt",
            "${TMPDIR}/notes.txt",
            "${TMPDIR:-/tmp}/notes.txt",
        ] {
            assert!(
                chain.check("read_file", &json!({"path": path})).is_some(),
                "expanded shell root must be denied by read_file: {path}"
            );
        }
        for command in [
            "cat ~/notes.txt",
            "cat ~someone/notes.txt",
            "cat $HOME/notes.txt",
            "cat ${HOME}/notes.txt",
            "cat ${HOME:-/tmp}/notes.txt",
            "cat ${HOME:=/tmp}/notes.txt",
            "cat $TMPDIR/notes.txt",
            "cat ${TMPDIR}/notes.txt",
            "cat ${TMPDIR:=/tmp}/notes.txt",
            "sed -f ~/evil.sed file",
        ] {
            assert!(
                chain.check("shell", &sh(command)).is_some(),
                "home-relative path must be denied: {command}"
            );
        }
        assert!(chain.check("shell", &sh("cat src/lib.rs")).is_none());

        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(&outside, repo.join("escape")).unwrap();
            assert!(chain
                .check("read_file", &json!({"path": "escape"}))
                .is_some());
            assert!(chain.check("shell", &sh("cat escape")).is_some());
        }
    }

    #[test]
    fn governed_host_denies_uninspectable_variable_operands() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("repo");
        let cargo_target = temp.path().join("cargo-target");
        std::fs::create_dir_all(repo.join("src")).unwrap();
        std::fs::create_dir_all(cargo_target.join("debug")).unwrap();
        std::fs::write(repo.join("src/x"), "x\n").unwrap();
        std::fs::write(repo.join("src/lib.rs"), "pub fn control() {}\n").unwrap();
        std::fs::write(repo.join("$HOME_fixture"), "literal\n").unwrap();
        let chain = governed_host_inspector_chain(&repo);

        for command in [
            "cat $NOPE/etc/hosts",
            "cat ${NOPE}/x",
            "cat ${NOPE:-${PWD}}/x",
            "cat $NOPE",
            "cat $MISSING_fixture",
            "cat $HOME_fixture/inside",
            "cat ${HOME_fixture}/inside",
            "cat ${PWD%repo}/x",
            "cat $1/etc/hosts",
            "cat ${1}",
            "cat $@",
            "cat $*",
            "cat $?",
            "cat $-",
            "cat $$",
            "cat $!",
            "cat src/$x",
            "cat src/${x}/file",
            "cat src/deeper/$x",
            "cat src/file$x",
            "cat src/$1",
            "cat $PWD/src/$x",
        ] {
            let reason = chain
                .check("shell", &sh(command))
                .unwrap_or_else(|| panic!("variable operand must be denied: {command}"));
            assert!(
                reason.contains("variable operand cannot be inspected"),
                "unexpected variable denial for {command}: {reason}"
            );
        }

        for command in [
            "cat $PWD/src/x",
            "cat ${PWD}/src/x",
            "cat src/$PWD",
            "cat src/${PWD}/x",
            "cat src/lib.rs",
            "cat $HOME_fixture",
            "env RUST_LOG=debug cargo test",
        ] {
            assert!(
                chain.check("shell", &sh(command)).is_none(),
                "resolvable or repo-prefixed control must stay allowed: {command}"
            );
        }

        // Pin the two conditional allowlist entries without mutating the
        // process-wide environment that parallel tests share.
        let path_gate = DenyGovernedShellPathEscape {
            worktree: repo.clone(),
            oldpwd_is_worktree: true,
            cargo_target_dir: Some(cargo_target.clone()),
        };
        for command in [
            "cat $OLDPWD/src/x",
            "cat $CARGO_TARGET_DIR/debug/output",
            "cat src/$OLDPWD/x",
            "cat src/$CARGO_TARGET_DIR/output",
        ] {
            assert!(
                matches!(
                    path_gate.inspect("shell", &sh(command)),
                    InspectionResult::Allow
                ),
                "pinned variable root must stay allowed: {command}"
            );
        }
        assert!(matches!(
            path_gate.inspect("shell", &sh("cat $CARGO_TARGET_DIR/../outside")),
            InspectionResult::Deny(reason)
                if reason.contains("resolves outside its governed root")
        ));
    }

    #[test]
    fn governed_host_gates_every_shell_command_segment() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("repo");
        let outside = temp.path().join("outside.txt");
        std::fs::create_dir(&repo).unwrap();
        std::fs::write(&outside, "secret").unwrap();
        let chain = governed_host_inspector_chain(&repo);

        for separator in ["\n", "\r\n", ";", "&&", "||"] {
            let command = format!("printf harmless{separator}cat {}", outside.display());
            assert!(
                chain.check("shell", &sh(&command)).is_some(),
                "the command after separator {separator:?} must be path-gated"
            );
        }
    }

    #[test]
    fn governed_host_joins_continued_lines_before_path_gating() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("repo");
        let outside = temp.path().join("outside.txt");
        std::fs::create_dir_all(repo.join("src")).unwrap();
        std::fs::write(repo.join("src/lib.rs"), "pub fn example() {}\n").unwrap();
        std::fs::write(&outside, "secret").unwrap();
        let chain = governed_host_inspector_chain(&repo);

        for verb in ["cat", "rm"] {
            let command = format!("{verb} \\\n{}", outside.display());
            assert!(
                chain.check("shell", &sh(&command)).is_some(),
                "a continued {verb} path must remain governed: {command:?}"
            );
        }
        assert!(
            chain
                .check("shell", &sh("sed -n '/pub fn/p' \\\n  src/lib.rs"))
                .is_none(),
            "a continued repository-local sed operand must remain allowed"
        );
    }

    #[test]
    fn governed_host_gates_paths_embedded_in_sed_and_awk_programs() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("repo");
        let outside = temp.path().join("outside.txt");
        std::fs::create_dir(&repo).unwrap();
        std::fs::write(repo.join("file"), "x\n").unwrap();
        std::fs::write(repo.join("script.sed"), "p\n").unwrap();
        std::fs::write(&outside, "secret").unwrap();
        let chain = governed_host_inspector_chain(&repo);
        let outside = outside.display();

        for command in [
            format!("sed 'r {outside}' file"),
            format!("sed -n 'R {outside}' file"),
            format!("sed -e '1w {outside}' file"),
            format!("sed '/x/W {outside}' file"),
            format!("awk '{{ getline < \"{outside}\" }}' file"),
            format!("awk '{{ getline line < \"{outside}\" }}' file"),
            format!("awk '{{ print $0 > \"{outside}\" }}' file"),
            format!("awk '{{ print $0 > (\"{outside}\") }}' file"),
            format!("awk '{{ printf \"%s\", $0 >> \"{outside}\" }}' file"),
            // Substitution w flags write a file, including after another flag
            // or an address and a second substitution command.
            format!("sed -n 's/x/y/w {outside}' file"),
            format!("sed -n '/x/s//y/gw {outside}' file"),
            format!("sed -n 's/x/;/w {outside}' file"),
            format!("sed -n 's;x;y;w {outside}' file"),
            format!("sed -n 's/x/{{/w {outside}' file"),
            // r/R/w/W accept the filename immediately after the command.
            format!("sed -n 'r{outside}' file"),
            format!("sed -n 'R{outside}' file"),
            format!("sed -n 'w{outside}' file"),
            format!("sed -n 'W{outside}' file"),
            // Bundled options must preserve the operand-taking final option.
            format!("sed -nf {outside} file"),
            format!("sed -ne 'r {outside}' file"),
            format!("sed -i.bak 's/x/y/' {outside}"),
            // Inline command execution is denied rather than treated as an
            // opaque program that bypasses the governed inspector chain.
            format!("awk 'BEGIN {{ system(\"cat {outside}\") }}'"),
            format!("awk 'BEGIN {{ \"cat {outside}\" | getline line }}'"),
            format!("awk 'BEGIN {{ \"cat {outside}\" |& getline line }}'"),
            format!("awk '{{ print $0 | \"cat > {outside}\" }}' file"),
            format!("awk '{{ printf \"%s\", $0 | \"cat > {outside}\" }}' file"),
            format!("sed -n '1e cat {outside}' file"),
            "sed -n 's/x/y/e' file".to_string(),
        ] {
            assert!(
                chain.check("shell", &sh(&command)).is_some(),
                "dangerous embedded operand or command execution must be denied: {command}"
            );
        }

        for separator in ["\n", "\r\n"] {
            let command = format!("printf harmless{separator}sed -n 's/x/y/w {outside}' file");
            assert!(
                chain.check("shell", &sh(&command)).is_some(),
                "a sed write after {separator:?} must remain governed"
            );
        }
        for continuation in ["\\\n", "\\\r\n"] {
            let command = format!("sed -n 's/x/y/w {continuation}{outside}' file");
            assert!(
                chain.check("shell", &sh(&command)).is_some(),
                "a continued sed write must remain governed: {command:?}"
            );
        }

        for command in [
            "sed 'r file' file",
            "sed -e '1w generated.txt' file",
            "awk '{ getline < \"file\" }' file",
            "awk '{ print $0 > \"generated.txt\" }' file",
            "sed -nf script.sed file",
            "sed -ne '/x/p' file",
            "sed -i.bak 's/x/y/' file",
            "sed 'y/x/;/' file",
            "sed ':example; /x/p' file",
        ] {
            assert!(
                chain.check("shell", &sh(command)).is_none(),
                "repository-relative embedded file operand must remain allowed: {command}"
            );
        }
    }

    #[test]
    fn governed_host_denies_shell_fed_sed_and_awk_programs() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("repo");
        let outside = temp.path().join("outside.txt");
        std::fs::create_dir(&repo).unwrap();
        std::fs::write(repo.join("file"), "x\n").unwrap();
        std::fs::write(&outside, "secret").unwrap();
        let chain = governed_host_inspector_chain(&repo);
        let outside = outside.display();

        for command in [
            // Heredoc-fed stdin, including the /dev/stdin spelling.
            format!("sed -f - file <<'EOF'\nw {outside}\nEOF"),
            format!("awk -f /dev/stdin file <<'EOF'\n{{ print > \"{outside}\" }}\nEOF"),
            // Here-string and pipe-fed stdin.
            format!("sed -f - file <<< 'w {outside}'"),
            format!("printf 'w {outside}\\n' | sed -f - file"),
            // A shell expands process substitution to /dev/fd/N; direct fd
            // spellings must be refused for the same reason.
            format!("sed -f <(printf 'w {outside}\\n') file"),
            format!("awk -f /dev/fd/0 file <<'EOF'\n{{ print > \"{outside}\" }}\nEOF"),
            "awk -f /proc/self/fd/0 file".to_string(),
            // Empty inline-program padding must not make the parser consume
            // the following -f option as the -e program.
            format!("sed -e '' -f - file <<'EOF'\nw {outside}\nEOF"),
            format!("awk -e '' -f - file <<'EOF'\n{{ print > \"{outside}\" }}\nEOF"),
            // Empty and shell-computed -f sources cannot be inspected as
            // literal repository paths.
            "sed -f '' file".to_string(),
            "sed -f\"\" file".to_string(),
            "sed -f $(printf -) file".to_string(),
            "awk -f `printf -` file".to_string(),
            "sed -f >(printf p) file".to_string(),
            // Backslash quote removal happens before argv reaches sed/awk.
            r"sed -f \- file".to_string(),
            r"awk -f \- file".to_string(),
            "busybox awk -f - file".to_string(),
            r"sed --file=\- file".to_string(),
            // Brace and parameter expansion can turn a source that looks
            // repository-relative here into stdin when the shell executes it.
            "sed -f {-,} file".to_string(),
            "x=-; sed -f $x file".to_string(),
            "x=-; sed -f \"$x\" file".to_string(),
        ] {
            let reason = chain
                .check("shell", &sh(&command))
                .unwrap_or_else(|| panic!("shell-fed program must be denied: {command}"));
            assert!(
                reason.contains("script source") && reason.contains("cannot be inspected"),
                "program channels must not be misclassified as governed paths: {reason}"
            );
        }
    }

    #[test]
    fn governed_host_denies_nested_shell_command_carriers() {
        let chain = governed_host_inspector_chain(Path::new("/wt"));
        for command in [
            "eval 'sed -f - file'",
            "bash -c 'sed -f - file'",
            "sh -c 'cat /etc/passwd'",
            "zsh -c 'awk -f - file'",
            "dash -c 'cat /etc/passwd'",
            "ksh -c 'cat /etc/passwd'",
            "fish -c 'cat /etc/passwd'",
            "busybox sh -c 'cat /etc/passwd'",
            "busybox ash -c 'cat /etc/passwd'",
            "perl -e 'open F, q(/etc/passwd)'",
            "perl -E 'say qx(cat /etc/passwd)'",
            "perl -wE 'say qx(cat /etc/passwd)'",
            "python3 -c 'open(\"/etc/passwd\").read()'",
            "python3.14 -c 'open(\"/etc/passwd\").read()'",
            "ruby -e 'puts File.read(\"/etc/passwd\")'",
            "node -e 'require(\"fs\").readFileSync(\"/etc/passwd\")'",
            "osascript -e 'do shell script \"cat /etc/passwd\"'",
            "script -c 'cat /etc/passwd'",
            "bash -lc 'cat /etc/passwd'",
            "MODE=check /bin/bash --noprofile -c 'cat /etc/passwd'",
            "env -S 'cat /etc/passwd'",
            "bash",
            "nice bash",
            "nohup bash",
        ] {
            let reason = chain
                .check("shell", &sh(command))
                .unwrap_or_else(|| panic!("nested shell carrier must be denied: {command}"));
            assert!(
                reason.contains("nested shell command"),
                "unexpected nested-shell denial reason: {reason}"
            );
        }
        assert!(chain.check("shell", &sh("echo eval")).is_none());
        assert!(chain.check("shell", &sh("bash script.sh")).is_none());
        assert!(chain
            .check("shell", &sh("nice bash scripts/check.sh"))
            .is_none());
        assert!(chain.check("shell", &sh("python3 script.py")).is_none());
        assert!(chain.check("shell", &sh("python3 -E script.py")).is_none());
        assert!(chain
            .check("shell", &sh("ruby -E UTF-8 script.rb"))
            .is_none());
        assert!(chain.check("shell", &sh("node script.js")).is_none());
        assert!(chain
            .check("shell", &sh("perl -MExtUtils::MakeMaker scripts/build.pl"))
            .is_none());
        assert!(chain.check("shell", &sh("command -v sudo")).is_none());
    }

    #[test]
    fn governed_host_inspects_command_environment_assignments() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("repo");
        let outside = temp.path().join("outside");
        std::fs::create_dir_all(repo.join("target")).unwrap();
        std::fs::create_dir_all(&outside).unwrap();
        let chain = governed_host_inspector_chain(&repo);

        for name in [
            "BASH_ENV",
            "ENV",
            "PATH",
            "LD_PRELOAD",
            "DYLD_INSERT_LIBRARIES",
            "PYTHONPATH",
            "PERL5LIB",
            "RUBYLIB",
            "NODE_OPTIONS",
            "CARGO_HOME",
            "RUSTUP_HOME",
            "GIT_EXEC_PATH",
            "GIT_SSH_COMMAND",
        ] {
            let command = format!("env {name}=repo-local cargo test");
            let reason = chain
                .check("shell", &sh(&command))
                .unwrap_or_else(|| panic!("redirecting assignment must be denied: {command}"));
            assert!(reason.contains("redirect executable code"), "{reason}");
        }

        for command in [
            "BASH_ENV=repo-local bash script.sh".to_string(),
            format!("env CACHE_DIR={} cargo test", outside.display()),
            "env EDITOR=repo-editor git commit".to_string(),
            "VISUAL=repo-editor git rebase --interactive main".to_string(),
            "env CARGO_TARGET_DIR=target cargo test".to_string(),
        ] {
            assert!(
                chain.check("shell", &sh(&command)).is_some(),
                "unsafe assignment must be denied: {command}"
            );
        }

        for command in [
            "env RUST_LOG=debug cargo test".to_string(),
            "RUST_LOG=debug".to_string(),
            "RUST_LOG[0]=debug; cargo test".to_string(),
            "RUST_LOG[$index]=debug; cargo test".to_string(),
            "RUST_LOG[$((1+1))]=debug; cargo test".to_string(),
            // A whitespace subscript is uninspectable, not forbidden: an
            // unprotected name stays allowed through every spelling.
            "RUST_LOG[ 0 ]=debug; cargo test".to_string(),
            "RUST_LOG[0 ]=debug; cargo test".to_string(),
            "RUST_LOG[ 0]=debug; cargo test".to_string(),
            "RUST_LOG[\t0]=debug; cargo test".to_string(),
            "RUST_LOG[ 0 ]+=,debug; cargo test".to_string(),
            "cargo test 'a[0]'".to_string(),
            "CACHE_KIND=local".to_string(),
            "env EDITOR=vim cargo test".to_string(),
        ] {
            assert!(
                chain.check("shell", &sh(&command)).is_none(),
                "plain assignment must stay allowed: {command}"
            );
        }

        for command in [
            "PWD=repo-local",
            "OLDPWD=repo-local",
            "CARGO_TARGET_DIR=target",
            "HOME=repo-local",
            "TMPDIR=tmp",
            "IFS=: ",
            "PATH=bin",
            "PWD=/etc; cat $PWD/passwd",
            "PWD[0]=/etc; cat $PWD/passwd",
            "PWD[0]+=/x",
            // bash accepts whitespace inside a subscript and still assigns the
            // scalar, so every spelling the tokenizer splits apart must be
            // denied on the base name.
            "PWD[ 0 ]=/etc; cat $PWD/passwd",
            "PWD[0 ]=/etc; cat $PWD/passwd",
            "PWD[ 0]=/etc; cat $PWD/passwd",
            "PWD[\t0]=/etc; cat $PWD/passwd",
            "PWD[\t0]+=/x",
            "env PWD[0]=/etc cat $PWD/passwd",
            "source=../../outside; cat $source/file",
            "source[0]=repo-local; cat $source/file",
            "env input=../../outside cat $input/file",
        ] {
            let reason = chain
                .check("shell", &sh(command))
                .unwrap_or_else(|| panic!("path-changing assignment must be denied: {command}"));
            assert!(
                reason.contains("environment assignment"),
                "unexpected assignment denial for {command}: {reason}"
            );
        }
    }

    #[test]
    fn governed_host_inspects_assignment_builtins() {
        let chain = governed_host_inspector_chain(Path::new("/wt"));

        for command in [
            "export PWD=/etc; cat $PWD/passwd",
            "readonly PWD=/etc; cat $PWD/passwd",
            "declare PWD=/etc; cat $PWD/passwd",
            "typeset PWD=/etc; cat $PWD/passwd",
            "local PWD=/etc; cat $PWD/passwd",
            "export PWD[1]=/etc; cat $PWD/passwd",
            "export PWD[ 1 ]=/etc; cat $PWD/passwd",
            "declare -a PWD[\t0]=/etc; cat $PWD/passwd",
            "readonly PWD[1]=/etc; cat $PWD/passwd",
            "declare PATH[0]=/tmp; cargo test",
            "declare -a arr[0]=/etc",
            "typeset HOME[0]=/tmp; cargo test",
            "local PWD[1]=/etc; cat $PWD/passwd",
            "unset PWD",
            "export -n PWD",
        ] {
            let reason = chain
                .check("shell", &sh(command))
                .unwrap_or_else(|| panic!("assignment builtin must be denied: {command}"));
            assert!(
                reason.contains("environment assignment"),
                "unexpected assignment-builtin denial for {command}: {reason}"
            );
        }

        for builtin in ["export", "readonly", "declare", "typeset", "local"] {
            for assignment in ["source=repo-local", "source[0]=repo-local"] {
                let command = format!("{builtin} {assignment}; cat $source/file");
                let reason = chain.check("shell", &sh(&command)).unwrap_or_else(|| {
                    panic!("later operand-prefix assignment must be denied: {command}")
                });
                assert!(reason.contains("environment assignment"), "{reason}");
            }
        }

        for command in [
            "PWD+=/../../../etc; cat $PWD/passwd",
            "env PWD+=/../../../etc cat $PWD/passwd",
            "export PWD+=/../../../etc; cat $PWD/passwd",
            "readonly PWD+=/../../../etc; cat $PWD/passwd",
            "declare PATH+=/../../../bin; cargo test",
            "typeset PWD+=/../../../etc; cat $PWD/passwd",
            "local PWD+=/../../../etc; cat $PWD/passwd",
        ] {
            let reason = chain
                .check("shell", &sh(command))
                .unwrap_or_else(|| panic!("append assignment must be denied: {command}"));
            assert!(
                reason.contains("environment assignment"),
                "unexpected append-assignment denial for {command}: {reason}"
            );
        }

        for command in [
            "RUST_LOG[$(id)]=debug; cargo test",
            "RUST_LOG[$(printf 0)]=debug; cargo test",
            "env RUST_LOG[$(id)]=debug cargo test",
            "export RUST_LOG[$(id)]=debug; cargo test",
            "readonly RUST_LOG[`printf 0`]=debug; cargo test",
            "declare RUST_LOG[$(id)]=debug; cargo test",
            "typeset RUST_LOG[$(id)]=debug; cargo test",
            "local RUST_LOG[$(id)]=debug; cargo test",
        ] {
            let reason = chain.check("shell", &sh(command)).unwrap_or_else(|| {
                panic!("command-substitution subscript must be denied: {command}")
            });
            assert!(reason.contains("cannot be inspected"), "{reason}");
        }

        for command in [
            "export RUST_LOG=debug; cargo test",
            "export RUST_LOG+=,debug; cargo test",
            "export RUST_LOG[0]=debug; cargo test",
            "export RUST_LOG[ 0 ]=debug; cargo test",
            "declare RUST_LOG[\t0]=debug; cargo test",
            "declare RUST_LOG[$index]=debug; cargo test",
            "typeset RUST_LOG[$((1+1))]=debug; cargo test",
            "echo 'RUST_LOG[$(id)]=debug'",
            "local x=1",
            "unset RUST_LOG",
            "export -n RUST_LOG",
        ] {
            assert!(
                chain.check("shell", &sh(command)).is_none(),
                "harmless assignment builtin must stay allowed: {command}"
            );
        }
    }

    #[test]
    fn governed_host_denies_busybox_install_mode() {
        let chain = governed_host_inspector_chain(Path::new("/wt"));
        for command in [
            "busybox --install",
            "busybox --install -s",
            "busybox --install=/tmp/bin",
        ] {
            let reason = chain
                .check("shell", &sh(command))
                .unwrap_or_else(|| panic!("busybox install must be denied: {command}"));
            assert!(reason.contains("busybox --install"), "{reason}");
        }
        assert!(chain
            .check("shell", &sh("busybox grep foo src/input.txt"))
            .is_none());
    }

    #[test]
    fn governed_host_unwraps_prefix_command_carriers() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("repo");
        let outside = temp.path().join("outside.txt");
        std::fs::create_dir_all(repo.join("src")).unwrap();
        std::fs::write(repo.join("src/input.txt"), "foo\n").unwrap();
        std::fs::write(&outside, "secret\n").unwrap();
        let chain = governed_host_inspector_chain(&repo);
        let path_gate = DenyGovernedShellPathEscape::new(&repo);
        let outside = outside.display();

        for command in [
            format!("env FOO=1 bash -c 'cat {outside}'"),
            format!("env -i -u FOO FOO=1 cat {outside}"),
            format!("command -p cat {outside}"),
            format!("exec -a reader cat {outside}"),
            format!("nohup -- cat {outside}"),
            format!("time -f '%E' cat {outside}"),
            format!("nice --adjustment 5 cat {outside}"),
            format!("caffeinate -t 1 cat {outside}"),
            format!("script -q transcript cat {outside}"),
            format!("xargs -0P 2 cat {outside}"),
            "builtin eval 'cat /etc/passwd'".to_string(),
            format!("sudo -u root cat {outside}"),
            format!("ionice -c 2 cat {outside}"),
            format!("timeout --signal TERM 5 cat {outside}"),
            format!("env -i time nice -n 1 cat {outside}"),
        ] {
            assert!(
                chain.check("shell", &sh(&command)).is_some(),
                "carrier must not hide the governed command: {command}"
            );
        }

        // A carrier with no command adds no denial in the path gate. The full
        // chain separately (and intentionally) denies bare `env` because it
        // dumps all environment variables.
        assert!(matches!(
            path_gate.inspect("shell", &sh("env")),
            InspectionResult::Allow
        ));
        for command in [
            "time cargo build",
            "xargs -0 grep foo src/input.txt",
            "busybox grep foo src/input.txt",
        ] {
            assert!(
                chain.check("shell", &sh(command)).is_none(),
                "safe carrier control must stay allowed: {command}"
            );
        }
    }

    #[test]
    fn prefix_carriers_do_not_bypass_other_shell_inspectors() {
        for command in [
            "env FOO=1 git push origin main",
            "command gh pr create --fill",
            "time cargo publish",
            "nice -n 1 pip install requests",
        ] {
            assert!(
                denied("shell", sh(command)),
                "must deny carried command: {command}"
            );
        }
    }

    #[test]
    fn governed_host_distinguishes_sed_and_awk_programs_from_paths() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("repo");
        std::fs::create_dir_all(repo.join("src")).unwrap();
        std::fs::write(repo.join("src/lib.rs"), "pub fn example() {}\n").unwrap();
        std::fs::write(repo.join("file.rs"), "pub fn example() {}\n").unwrap();
        std::fs::write(repo.join("file"), "x\n").unwrap();
        std::fs::write(repo.join("script.sed"), "p\n").unwrap();
        std::fs::write(repo.join("-"), "p\n").unwrap();
        #[cfg(unix)]
        {
            // The name `\-` is deliberate: a backslash is an ordinary filename
            // byte on unix, and the policy must resolve the shell-escaped
            // operand `\-` to this file. `Path::join` reads a leading backslash
            // as a path separator, so build the path by pushing instead.
            let mut escaped_dash = repo.clone();
            escaped_dash.push(r"\-");
            std::fs::write(escaped_dash, "p\n").unwrap();
        }
        let chain = governed_host_inspector_chain(&repo);

        assert!(
            chain
                .check("shell", &sh("sed -n /pub fn/p file.rs"))
                .is_none(),
            "a sed address is a program, not the absolute path /pub"
        );
        assert!(
            chain
                .check("shell", &sh("sed -n '/pub fn/p' src/lib.rs"))
                .is_none(),
            "a quoted sed address is a program, not the absolute path /pub"
        );
        assert!(
            chain
                .check("shell", &sh("sed -e '/pub fn/p' src/lib.rs"))
                .is_none(),
            "a sed -e operand is an inline program, not a path"
        );
        assert!(
            chain
                .check("shell", &sh("sed -n '/pub \\/etc/p' src/lib.rs"))
                .is_none(),
            "quoted whitespace must not split one sed program into path operands"
        );
        assert!(
            chain.check("shell", &sh("awk /pub/ file.rs")).is_none(),
            "an awk pattern is a program, not the absolute path /pub"
        );
        assert!(
            chain.check("shell", &sh("awk '/x/{print}' file")).is_none(),
            "an awk pattern-action is a program, not a path"
        );
        assert!(
            chain
                .check("shell", &sh("awk '/x/ { print \"/etc\" }' file"))
                .is_none(),
            "a quoted awk program remains one non-path argument"
        );
        assert!(
            chain.check("shell", &sh("sed -n p /etc/passwd")).is_some(),
            "sed input files remain governed"
        );
        assert!(
            chain.check("shell", &sh("sed -f /etc/evil")).is_some(),
            "sed -f names a script file and must remain governed"
        );
        assert!(
            chain.check("shell", &sh("awk -E/path file")).is_some(),
            "an attached awk -E script path must remain governed"
        );
        assert!(
            chain
                .check("shell", &sh("sed -f script.sed file"))
                .is_none(),
            "a literal repository script must remain allowed"
        );
        assert!(
            chain
                .check("shell", &sh("sed -e '' -f script.sed file"))
                .is_none(),
            "empty -e padding must not deny a literal repository script"
        );
        assert!(
            chain.check("shell", &sh("sed -f ./- file")).is_none(),
            "./- is a literal repository path, not sed's stdin marker"
        );
        #[cfg(unix)]
        {
            for command in [r"sed -f '\-' file", r#"sed -f "\-" file"#] {
                assert!(
                    chain.check("shell", &sh(command)).is_none(),
                    "a backslash preserved by shell quotes remains a repository filename: {command}"
                );
            }
        }
    }

    #[test]
    fn governed_host_denies_gui_shell_automation() {
        let chain = governed_host_inspector_chain(Path::new("/wt"));
        assert!(chain
            .check(
                "run_applescript",
                &json!({"script": "tell application \"Terminal\" to do script \"az deploy\""})
            )
            .is_some());
        assert!(chain
            .check("run_powershell", &json!({"script": "az deploy"}))
            .is_some());
    }

    #[test]
    fn history_rewrite_denied() {
        assert!(denied("shell", sh("git rebase -i HEAD~3")));
        assert!(denied("shell", sh("git reset --hard HEAD~1")));
        assert!(denied("shell", sh("git filter-branch --all")));
        assert!(denied("shell", sh("git worktree remove /wt")));
        assert!(!denied("shell", sh("git reset HEAD file.txt"))); // soft reset ok
    }

    #[test]
    fn privilege_escalation_denied() {
        assert!(denied("shell", sh("sudo rm -rf /tmp/x")));
        assert!(denied("shell", sh("doas pkg_add x")));
        assert!(denied("shell", sh("FOO=1 sudo make install")));
        assert!(denied("shell", sh("launchctl unload foo")));
        assert!(!denied("shell", sh("echo sudo"))); // verb position only
    }

    #[test]
    fn credential_access_denied_for_shell_and_file_tools() {
        assert!(denied("shell", sh("cat ~/.ssh/id_rsa")));
        assert!(denied("shell", sh("cat $HOME/.aws/credentials")));
        assert!(denied("shell", sh("security find-generic-password -s x")));
        assert!(denied("read_file", json!({"path": "/Users/u/.ssh/id_rsa"})));
        assert!(denied("read_file", json!({"path": "~/.netrc"})));
        assert!(!denied("read_file", json!({"path": "src/main.rs"})));
        // ".ssh" as a repo-relative dir name is unfortunate but stays denied —
        // conservative beats clever here.
    }

    #[test]
    fn destructive_ops_scoped_to_worktree() {
        assert!(denied("shell", sh("rm -rf /etc")));
        assert!(denied("shell", sh("rm -rf ../other-checkout")));
        assert!(denied("shell", sh("mv target ~/elsewhere")));
        assert!(denied("shell", sh("chmod 777 /usr/local/bin/x")));
        // Inside the worktree: fine, relative or absolute.
        assert!(!denied("shell", sh("rm -rf target/debug")));
        assert!(!denied("shell", sh("rm /wt/scratch.txt")));
        assert!(!denied("shell", sh("cp a.txt b.txt")));
    }

    #[test]
    fn write_path_escape_denied_but_reads_allowed() {
        assert!(denied(
            "write_file",
            json!({"path": "/etc/hosts", "content": "x"})
        ));
        assert!(denied("edit_file", json!({"path": "../outside.txt"})));
        assert!(!denied(
            "write_file",
            json!({"path": "src/new.rs", "content": "x"})
        ));
        assert!(!denied(
            "write_file",
            json!({"path": "/wt/src/new.rs", "content": "x"})
        ));
        // Reads outside the worktree are allowed (context gathering) unless
        // they hit credential markers.
        assert!(!denied(
            "read_file",
            json!({"path": "/usr/include/stdio.h"})
        ));
    }

    #[test]
    fn stays_under_is_lexical_and_strict() {
        let root = Path::new("/wt");
        assert!(stays_under(root, "src/x.rs"));
        assert!(stays_under(root, "a/../b.txt"));
        assert!(stays_under(root, "/wt/deep/file"));
        assert!(!stays_under(root, "../escape"));
        assert!(!stays_under(root, "a/../../escape"));
        assert!(!stays_under(root, "/etc/passwd"));
        assert!(!stays_under(root, "/wtevil/file")); // prefix, not component, match
        assert!(!stays_under(root, "~"));
        assert!(!stays_under(root, "~/outside"));
        assert!(!stays_under(root, "~someone/outside"));
        assert!(!stays_under(root, "$HOME"));
        assert!(!stays_under(root, "$HOME/outside"));
        assert!(!stays_under(root, "${HOME}/outside"));
        assert!(!stays_under(root, "${HOME:-/tmp}/outside"));
        assert!(!stays_under(root, "${HOME:=/tmp}/outside"));
        assert!(!stays_under(root, "$TMPDIR/outside"));
        assert!(!stays_under(root, "${TMPDIR}/outside"));
        assert!(!stays_under(root, "${TMPDIR:-/tmp}/outside"));
        assert!(!stays_under(root, "${TMPDIR:=/tmp}/outside"));
        assert!(!stays_under(root, "$HOME_fixture"));
        assert!(!stays_under(root, "${HOME_fixture}/inside"));
        assert!(stays_under(root, "src/$x"));
        assert!(stays_under(root, "src/~fixture"));

        let temp = tempfile::tempdir().unwrap();
        std::fs::write(temp.path().join("$HOME_fixture"), "literal").unwrap();
        assert!(stays_under(temp.path(), "$HOME_fixture"));
    }

    #[cfg(windows)]
    #[test]
    fn windows_destructive_and_privilege_denied() {
        let chain = coder_inspector_chain(Path::new(r"C:\wt"));
        let denied = |cmd: &str| chain.check("shell", &sh(cmd)).is_some();
        // `cmd.exe` destructive verbs aimed outside the worktree.
        assert!(denied(r"del C:\Windows\System32\drivers\etc\hosts"));
        assert!(denied(r"rd /s /q C:\Windows"));
        assert!(denied(r"del /q C:\Users\victim\file")); // `/q` switch is skipped
        assert!(denied(r"move C:\wt\keep.txt C:\Users\public\stolen.txt"));
        // Windows privilege elevation.
        assert!(denied("runas /user:Administrator cmd"));
        assert!(denied("sc stop windefend"));
        // Inside the worktree: allowed (absolute or relative).
        assert!(!denied(r"del C:\wt\target\debug\app.exe"));
        assert!(!denied(r"del build\out.txt"));
        assert!(!denied("dir")); // non-destructive verb untouched
    }

    #[cfg(windows)]
    #[test]
    fn windows_credential_access_denied() {
        let chain = coder_inspector_chain(Path::new(r"C:\wt"));
        assert!(chain
            .check("shell", &sh(r"type %USERPROFILE%\.ssh\id_rsa"))
            .is_some());
        assert!(chain.check("shell", &sh("cmdkey /list")).is_some());
        assert!(chain
            .check(
                "read_file",
                &json!({"path": r"C:\Users\u\.aws\credentials"})
            )
            .is_some());
        // A normal source read is fine.
        assert!(chain
            .check("read_file", &json!({"path": r"C:\wt\src\main.rs"}))
            .is_none());
    }

    #[cfg(windows)]
    #[test]
    fn stays_under_handles_verbatim_prefix_and_case() {
        // A canonicalized worktree carries the `\\?\` verbatim prefix; a plain
        // absolute candidate inside it (any case) must still count as inside,
        // and NTFS case-insensitivity is honoured.
        let root = Path::new(r"\\?\C:\wt");
        assert!(stays_under(root, r"C:\WT\src\main.rs"));
        assert!(stays_under(root, r"c:\wt\src\main.rs"));
        assert!(!stays_under(root, r"C:\other\x"));
        assert!(!stays_under(root, r"C:\wtevil\x")); // prefix, not component
    }
}