workpen 0.8.0

Workpen dest-deny and a per-child process jail (Landlock, Seatbelt, Windows).
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
//! Dest-deny predicate. Glob match, hardlink sibling, patch dests, argv tokens.

use std::ffi::OsStr;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::Arc;

#[cfg(unix)]
use std::cell::{Cell, RefCell};
#[cfg(unix)]
use std::collections::HashMap;

use crate::agent_lock::{AgentLockError, load_agent_lock};
use crate::guard::{PathGuard, PathGuardError};

/// Portable dest-deny policy. Same globs on every OS.
/// Hosts hold this value. There is no process-wide default slot. Clone is cheap.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DenyPolicy {
    globs: Arc<Vec<String>>,
}

impl Default for DenyPolicy {
    fn default() -> Self {
        Self {
            globs: Arc::new(default_secret_denies()),
        }
    }
}

impl DenyPolicy {
    pub fn new(globs: Vec<String>) -> Self {
        Self {
            globs: Arc::new(globs),
        }
    }

    /// Intern a host-held glob list. Does not copy the strings.
    /// There is still no process-wide deny slot.
    pub fn from_arc(globs: Arc<Vec<String>>) -> Self {
        Self { globs }
    }

    /// Same allocation as [`DenyPolicy::from_arc`] / clone.
    pub fn globs_arc(&self) -> Arc<Vec<String>> {
        Arc::clone(&self.globs)
    }

    /// `default_secret_denies()` plus extras. Extras never replace defaults.
    pub fn with_extra(extra: impl IntoIterator<Item = String>) -> Self {
        let mut globs = default_secret_denies();
        for g in extra {
            if !globs.iter().any(|x| x == &g) {
                globs.push(g);
            }
        }
        Self {
            globs: Arc::new(globs),
        }
    }

    /// Defaults plus workspace `agent.lock` extras. Missing lock equals default.
    /// Extras never replace defaults. Invalid lock is [`AgentLockError`].
    pub fn from_workspace(path: impl AsRef<Path>) -> Result<Self, AgentLockError> {
        Ok(Self::with_extra(load_agent_lock(path.as_ref())?))
    }

    pub fn globs(&self) -> &[String] {
        &self.globs
    }
}

/// Why dest-deny rejected a path. Hosts branch on this; do not parse messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DestDenyKind {
    /// Basename or full path matched a deny glob (raw or canonical).
    DenyGlob,
    /// Another directory entry shares this inode / NTFS file index and is denied.
    HardlinkSibling,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DestDeny {
    pub kind: DestDenyKind,
    pub path: PathBuf,
    pub display: String,
    /// Matching deny glob, or the other hardlink's basename.
    pub matched: Option<String>,
}

impl DestDeny {
    /// Wording distinguishes glob vs hardlink.
    /// Hardlink must not say "matches deny glob".
    pub fn message(&self) -> String {
        match (&self.kind, self.matched.as_deref()) {
            (DestDenyKind::DenyGlob, Some(glob)) => format!(
                "path denied by sandbox profile (matches deny glob {glob}): {}",
                self.display
            ),
            (DestDenyKind::DenyGlob, None) => format!(
                "path denied by sandbox profile (matches deny glob): {}",
                self.display
            ),
            (DestDenyKind::HardlinkSibling, Some(sib)) => format!(
                "path denied by sandbox profile (hardlink of a denied name {sib}): {}",
                self.display
            ),
            (DestDenyKind::HardlinkSibling, None) => format!(
                "path denied by sandbox profile (hardlink of a denied name): {}",
                self.display
            ),
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum DestDenyError {
    #[error("{0}")]
    Denied(DestDeny),
    /// Argv token hit. Distinct wording from [`DestDeny::message`].
    #[error("command references path denied by sandbox profile: {token}")]
    CommandToken { token: String },
    /// PowerShell `-EncodedCommand` payload is not UTF-16LE RFC 4648.
    #[error("invalid -EncodedCommand payload (need UTF-16LE base64); child was not started")]
    EncodedCommand,
    /// PowerShell `-Command -` / `-File -` (and unique prefixes), or positional `-`, read a script from stdin.
    #[error(
        "PowerShell stdin script (-Command - or -File -) cannot be dest-denied; child was not started"
    )]
    StdinScript,
    /// Post-open hardlink hit. Distinct wording from [`DestDeny::message`].
    #[error(
        "path denied: {path} is a hardlink of a denied name; unlink extra names or do not share the inode"
    )]
    LateHardlink { path: String },
    /// Path identity changed between check and open.
    #[error("TOCTOU race detected: {path} changed between check and open")]
    Toctou { path: String },
    #[error("TOCTOU check failed: {0}")]
    ToctouStat(String),
}

/// Host composition error. Dest-deny vs PathGuard; do not parse messages.
#[derive(Debug, thiserror::Error)]
pub enum CheckDestError {
    #[error(transparent)]
    DestDeny(#[from] DestDenyError),
    #[error(transparent)]
    PathGuard(#[from] PathGuardError),
    #[error("path contains a NUL byte")]
    Nul,
    /// Fifo, socket, or device. `/dev/null` and Windows `NUL` are not
    /// this error. They stay allowed.
    #[error("refuse special file ({kind}): {path}")]
    SpecialFile { path: String, kind: &'static str },
    /// Read helper only. [`check_dest`] still allows directories.
    #[error("refuse directory read: {path}")]
    Directory { path: String },
    #[error("open failed: {0}")]
    Io(String),
    #[error("command argument is not valid UTF-8")]
    NonUtf8,
}

impl std::fmt::Display for DestDeny {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message())
    }
}

/// Classify one dest. Glob vs hardlink only. Does not jail `..`.
pub fn classify_dest(path: &Path, policy: &DenyPolicy) -> Option<DestDenyKind> {
    classify_dest_hit(path, policy).map(|hit| hit.kind)
}

struct DestDenyHit {
    kind: DestDenyKind,
    matched: Option<String>,
}

fn classify_dest_hit(path: &Path, policy: &DenyPolicy) -> Option<DestDenyHit> {
    classify_dest_hit_root(path, policy, None)
}

/// A directory named `.env` is denied as that directory. Seatbelt then
/// applies the deny to everything inside it. Match those children here
/// so `why` does not call them allowed. Stop at the workspace root so a
/// parent directory outside the workspace cannot deny the whole tree.
fn ancestor_deny_glob(path: &Path, policy: &DenyPolicy, root: Option<&Path>) -> Option<String> {
    let mut cursor = path.parent();
    while let Some(dir) = cursor {
        if dir.as_os_str().is_empty() {
            break;
        }
        if dir.is_absolute()
            && let Some(root) = root
            && !ancestor_inside_workspace(dir, root)
        {
            break;
        }
        if let Some(glob) = deny_glob_name(first_matching_deny_glob_under(
            policy.globs(),
            &path_as_glob(dir),
            root,
        )) {
            return Some(glob);
        }
        let next = dir.parent();
        if next == Some(dir) {
            break;
        }
        cursor = next;
    }
    None
}

fn ancestor_inside_workspace(dir: &Path, root: &Path) -> bool {
    let dir_s = path_as_glob(dir);
    for spelling in firmlink_spellings(root) {
        let root_s = path_as_glob(&spelling).trim_end_matches('/').to_string();
        if root_s.is_empty() {
            continue;
        }
        let prefix = format!("{root_s}/");
        if dir_s.len() > prefix.len()
            && dir_s.is_char_boundary(prefix.len())
            && dir_s[..prefix.len()].eq_ignore_ascii_case(&prefix)
        {
            return true;
        }
    }
    false
}

fn classify_dest_hit_root(
    path: &Path,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> Option<DestDenyHit> {
    if let Some(glob) = deny_glob_name(first_matching_deny_glob_under(
        policy.globs(),
        &path_as_glob(path),
        root,
    )) {
        return Some(DestDenyHit {
            kind: DestDenyKind::DenyGlob,
            matched: Some(glob),
        });
    }

    let canon = std::fs::canonicalize(path).ok();
    if let Some(canon) = &canon
        && let Some(glob) = deny_glob_name(first_matching_deny_glob_under(
            policy.globs(),
            &path_as_glob(canon),
            root,
        ))
    {
        return Some(DestDenyHit {
            kind: DestDenyKind::DenyGlob,
            matched: Some(glob),
        });
    }
    if let Some(glob) = ancestor_deny_glob(path, policy, root) {
        return Some(DestDenyHit {
            kind: DestDenyKind::DenyGlob,
            matched: Some(glob),
        });
    }
    if let Some(canon) = &canon
        && let Some(glob) = ancestor_deny_glob(canon, policy, root)
    {
        return Some(DestDenyHit {
            kind: DestDenyKind::DenyGlob,
            matched: Some(glob),
        });
    }
    match hardlink_sibling_hit(path, canon.as_deref(), policy, root) {
        HardlinkHit::Denied { sibling } => Some(DestDenyHit {
            kind: DestDenyKind::HardlinkSibling,
            matched: sibling,
        }),
        HardlinkHit::Allowed => None,
    }
}

pub(crate) fn dest_deny_at(
    classified: &Path,
    display: String,
    policy: &DenyPolicy,
) -> Option<DestDeny> {
    dest_deny_at_root(classified, display, policy, None)
}

pub(crate) fn dest_deny_at_root(
    classified: &Path,
    display: String,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> Option<DestDeny> {
    classify_dest_hit_root(classified, policy, root).map(|hit| DestDeny {
        kind: hit.kind,
        path: classified.to_path_buf(),
        display,
        matched: hit.matched,
    })
}

/// Glob-name dest-deny only. No canonicalize and no hardlink sibling
/// scan. Cache trees use this so rustc artifacts are not O(n^2)
/// readdir'd. Plants `**/.env` names, not every `target/debug/deps`
/// inode.
pub(crate) fn dest_deny_glob_only(
    classified: &Path,
    display: String,
    policy: &DenyPolicy,
) -> Option<DestDeny> {
    first_matching_deny_glob(policy.globs(), &path_as_glob(classified)).map(|glob| DestDeny {
        kind: DestDenyKind::DenyGlob,
        path: classified.to_path_buf(),
        display,
        matched: Some(glob),
    })
}

pub fn is_path_denied(path: &Path, policy: &DenyPolicy) -> bool {
    classify_dest(path, policy).is_some()
}

pub fn dest_deny_message(path: &Path, display: &str, policy: &DenyPolicy) -> Option<String> {
    dest_deny_at(path, display.to_owned(), policy).map(|d| d.message())
}

/// Dest-deny raw; if `guard` is `Some`, PathGuard; dest-deny resolved.
///
/// `guard: None` dest-denies raw and, if the path exists, dest-denies the
/// cwd-joined canonicalize. Does not treat cwd as a workspace root.
/// Rejects a NUL byte and an existing fifo, socket, or device. Does not peel.
/// Does not refuse directories (write dests). See [`open_verified_read`].
///
/// On Windows, `CON`, `PRN`, `AUX`, `NUL`, `COM1` through `COM9`, `LPT1`
/// through `LPT9`, `CONIN$`, and `CONOUT$` are devices. That includes the
/// `\\.\` and `\\?\` device forms (`\\.\NUL`, `\\?\CON`) and a normal path
/// whose final component is one of those names. Trailing spaces, dots, and
/// a trailing colon still count (`NUL.`, `CON:`), as do `::` and a colon
/// with spaces before a second colon (`CON::`, `CON: :`). `CON:::` does not.
/// `NUL` stays allowed.
/// That is the null-device grant, the same way `/dev/null` stays allowed.
/// [`crate::explain`] reports `allowed`. The other names are
/// [`CheckDestError::SpecialFile`]. A suffixed name such as `NUL.txt` stays
/// an ordinary path. An extended `\\?\` or `\\.\` path that continues with
/// a drive or UNC prefix is a literal path, not that device.
pub fn check_dest(
    path: &str,
    policy: &DenyPolicy,
    guard: Option<&PathGuard>,
) -> Result<PathBuf, CheckDestError> {
    check_dest_rooted(path, policy, guard, None)
}

fn check_dest_rooted(
    path: &str,
    policy: &DenyPolicy,
    guard: Option<&PathGuard>,
    workspace: Option<&Path>,
) -> Result<PathBuf, CheckDestError> {
    if path.contains('\0') {
        return Err(CheckDestError::Nul);
    }
    let raw = Path::new(path);
    let glob_root = workspace.or_else(|| guard.map(|g| g.canon_root()));
    if let Some(deny) = dest_deny_at_root(raw, path.to_owned(), policy, glob_root) {
        return Err(CheckDestError::DestDeny(DestDenyError::Denied(deny)));
    }

    // Before the workspace guard, so `why` agrees with `run`.
    // `/dev/null` and Windows `NUL` stay allowed. Other devices are
    // special files, not "path escapes workspace".
    #[cfg(unix)]
    if is_null_device(raw) {
        return Ok(raw.to_path_buf());
    }
    #[cfg(windows)]
    if let Some(kind) = windows_device_kind(path) {
        return match kind {
            WinDev::Null => Ok(raw.to_path_buf()),
            WinDev::Other => Err(CheckDestError::SpecialFile {
                path: path.to_owned(),
                kind: "device",
            }),
        };
    }

    let resolved = match guard {
        Some(g) => match g.check(raw) {
            Ok(checked) => checked,
            Err(err) => {
                reject_special_file(raw)?;
                return Err(err.into());
            }
        },
        None => {
            let joined = if raw.is_absolute() {
                raw.to_path_buf()
            } else {
                match std::env::current_dir() {
                    Ok(cwd) => cwd.join(raw),
                    Err(_) => raw.to_path_buf(),
                }
            };
            if joined.exists() {
                std::fs::canonicalize(&joined).unwrap_or(joined)
            } else {
                joined
            }
        }
    };

    if let Some(deny) = dest_deny_at_root(&resolved, path.to_owned(), policy, glob_root) {
        return Err(CheckDestError::DestDeny(DestDenyError::Denied(deny)));
    }
    reject_special_file(&resolved)?;
    Ok(resolved)
}

/// `check_dest`, refuse directories, open for read, then [`verify_post_open`].
pub fn open_verified_read(
    path: &str,
    policy: &DenyPolicy,
    guard: Option<&PathGuard>,
) -> Result<File, CheckDestError> {
    let resolved = check_dest(path, policy, guard)?;
    refuse_directory(&resolved)?;
    let file = File::open(&resolved).map_err(|e| CheckDestError::Io(e.to_string()))?;
    if file.metadata().map(|m| m.is_dir()).unwrap_or(false) {
        return Err(directory_read_error(&resolved));
    }
    verify_post_open(&resolved, &file, policy)?;
    Ok(file)
}

fn refuse_directory(path: &Path) -> Result<(), CheckDestError> {
    let Ok(meta) = std::fs::metadata(path) else {
        return Ok(());
    };
    if meta.is_dir() {
        return Err(directory_read_error(path));
    }
    Ok(())
}

fn directory_read_error(path: &Path) -> CheckDestError {
    CheckDestError::Directory {
        path: path.display().to_string(),
    }
}

/// The process null device, and only when it is still a character device.
/// A symlink to a regular file is not this device.
#[cfg(unix)]
pub(crate) fn is_null_device(path: &Path) -> bool {
    use std::os::unix::fs::FileTypeExt;
    use std::os::unix::fs::MetadataExt;
    let Ok(meta) = std::fs::metadata(path) else {
        return false;
    };
    if !meta.file_type().is_char_device() {
        return false;
    }
    let Ok(null_meta) = std::fs::metadata("/dev/null") else {
        return false;
    };
    null_meta.file_type().is_char_device() && meta.rdev() == null_meta.rdev()
}

fn reject_special_file(path: &Path) -> Result<(), CheckDestError> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::FileTypeExt;
        let Ok(meta) = std::fs::metadata(path) else {
            return Ok(());
        };
        let ft = meta.file_type();
        let kind = if ft.is_fifo() {
            Some("fifo")
        } else if ft.is_socket() {
            Some("socket")
        } else if ft.is_char_device() || ft.is_block_device() {
            Some("device")
        } else {
            None
        };
        if let Some(kind) = kind {
            if kind == "device" && is_null_device(path) {
                return Ok(());
            }
            return Err(CheckDestError::SpecialFile {
                path: path.display().to_string(),
                kind,
            });
        }
    }
    #[cfg(windows)]
    {
        if let Some(text) = path.to_str()
            && windows_device_kind(text) == Some(WinDev::Other)
        {
            return Err(CheckDestError::SpecialFile {
                path: path.display().to_string(),
                kind: "device",
            });
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = path;
    }
    Ok(())
}

/// `NUL` is the null-device grant. The other names are devices.
/// `\\?\C:\dir\NUL` is a literal file. `\\?\NUL` is the device.
#[cfg(windows)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum WinDev {
    Null,
    Other,
}

#[cfg(windows)]
fn windows_device_kind(text: &str) -> Option<WinDev> {
    if let Some(rest) = device_namespace_body(text) {
        let rest = rest.trim_end_matches(['\\', '/']);
        if rest.contains('\\') || rest.contains('/') {
            return None;
        }
        return reserved_device_name(rest);
    }
    let component = text.rsplit(['\\', '/']).next().unwrap_or(text);
    reserved_device_name(component).or_else(|| reserved_two_colons(component))
}

/// Body after `\\.\`, `\\?\`, `//./`, or `//?/`.
#[cfg(windows)]
fn device_namespace_body(text: &str) -> Option<&str> {
    let bytes = text.as_bytes();
    if bytes.len() < 4 {
        return None;
    }
    let sep = bytes[0];
    if (sep != b'\\' && sep != b'/') || bytes[1] != sep || bytes[3] != sep {
        return None;
    }
    let mark = bytes[2].to_ascii_lowercase();
    if mark != b'.' && mark != b'?' {
        return None;
    }
    Some(&text[4..])
}

#[cfg(windows)]
fn reserved_device_name(component: &str) -> Option<WinDev> {
    let trimmed = component.trim_end_matches([' ', '.']);
    let name = match trimmed.strip_suffix(':') {
        Some(head) => {
            let head = head.trim_end_matches([' ', '.']);
            if head.is_empty() || head.contains(':') || head.contains('.') {
                trimmed
            } else {
                head
            }
        }
        None => trimmed,
    };
    classify_reserved(name)
}

/// `CON::` and `CON: :` still open the console. One `strip_suffix(':')`
/// leaves the other colon, and `run` joins the token onto the workspace
/// before this check, so the final component is the spelling the child opens.
/// `CON:::` and a trailing space or dot after `::` stay ordinary.
/// Device-namespace paths do not use this rule (`\\.\CON::` is not the console).
#[cfg(windows)]
fn reserved_two_colons(component: &str) -> Option<WinDev> {
    if let Some(head) = component.strip_suffix("::") {
        if head.is_empty() || head.ends_with([' ', '.', ':']) {
            return None;
        }
        return classify_reserved(head);
    }
    let bytes = component.as_bytes();
    let mut i = bytes.len();
    if i == 0 || bytes[i - 1] != b':' {
        return None;
    }
    i -= 1;
    if i == 0 || bytes[i - 1] != b' ' {
        return None;
    }
    while i > 0 && bytes[i - 1] == b' ' {
        i -= 1;
    }
    if i == 0 || bytes[i - 1] != b':' {
        return None;
    }
    i -= 1;
    while i > 0 && bytes[i - 1] == b' ' {
        i -= 1;
    }
    classify_reserved(&component[..i])
}

#[cfg(windows)]
fn classify_reserved(name: &str) -> Option<WinDev> {
    if name.is_empty() || name.contains('.') || name.contains(':') || name.contains(' ') {
        return None;
    }
    match name.to_ascii_uppercase().as_str() {
        "NUL" => Some(WinDev::Null),
        "CON" | "PRN" | "AUX" | "CONIN$" | "CONOUT$" => Some(WinDev::Other),
        other => {
            let rest = other
                .strip_prefix("COM")
                .or_else(|| other.strip_prefix("LPT"))?;
            match rest.as_bytes() {
                [digit] if (b'1'..=b'9').contains(digit) => Some(WinDev::Other),
                _ => None,
            }
        }
    }
}

/// Unix inode/dev; Windows file index + volume serial.
/// Re-runs hardlink dest-deny when nlink / nNumberOfLinks > 1.
pub fn verify_post_open(path: &Path, fd: &File, policy: &DenyPolicy) -> Result<(), DestDenyError> {
    #[cfg(unix)]
    {
        verify_post_open_unix(path, fd, policy)
    }
    #[cfg(windows)]
    {
        verify_post_open_windows(path, fd, policy)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (path, fd, policy);
        Ok(())
    }
}

#[cfg(unix)]
fn verify_post_open_unix(path: &Path, fd: &File, policy: &DenyPolicy) -> Result<(), DestDenyError> {
    use std::os::unix::fs::MetadataExt;

    let path_meta = std::fs::symlink_metadata(path)
        .map_err(|e| DestDenyError::ToctouStat(format!("cannot stat {}: {e}", path.display())))?;
    let fd_meta = fd
        .metadata()
        .map_err(|e| DestDenyError::ToctouStat(format!("cannot fstat fd: {e}")))?;
    if path_meta.ino() != fd_meta.ino() || path_meta.dev() != fd_meta.dev() {
        return Err(DestDenyError::Toctou {
            path: path.display().to_string(),
        });
    }
    if fd_meta.nlink() > 1 {
        let canon = std::fs::canonicalize(path).ok();
        if hardlink_sibling_denied(path, canon.as_deref(), policy) {
            return Err(DestDenyError::LateHardlink {
                path: path.display().to_string(),
            });
        }
    }
    Ok(())
}

#[cfg(windows)]
fn verify_post_open_windows(
    path: &Path,
    fd: &File,
    policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
    use std::os::windows::io::AsRawHandle;

    let path_info = win_path_by_handle(path)
        .map_err(|e| DestDenyError::ToctouStat(format!("cannot stat {}: {e}", path.display())))?;
    let fd_info = win_handle_info(fd.as_raw_handle())
        .map_err(|e| DestDenyError::ToctouStat(format!("cannot fstat fd: {e}")))?;
    if path_info.index != fd_info.index || path_info.volume != fd_info.volume {
        return Err(DestDenyError::Toctou {
            path: path.display().to_string(),
        });
    }
    if fd_info.nlink > 1 {
        let canon = std::fs::canonicalize(path).ok();
        if hardlink_sibling_denied(path, canon.as_deref(), policy) {
            return Err(DestDenyError::LateHardlink {
                path: path.display().to_string(),
            });
        }
    }
    Ok(())
}

/// Refuse if any host-extracted dest is a secret glob or hardlink sibling.
///
/// Does not check out-of-tree. Hosts then run PathGuard on the same dests.
pub fn deny_patch_dests(
    dests: &[impl AsRef<Path>],
    policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
    for dest in dests {
        let dest = dest.as_ref();
        if let Some(deny) = dest_deny_at(dest, dest.display().to_string(), policy) {
            return Err(DestDenyError::Denied(deny));
        }
    }
    Ok(())
}

/// Like [`deny_patch_dests`], with a host-chosen display string per dest.
pub fn deny_patch_dests_with_display(
    dests: &[(&Path, &str)],
    policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
    for (dest, display) in dests {
        if let Some(deny) = dest_deny_at(dest, (*display).to_owned(), policy) {
            return Err(DestDenyError::Denied(deny));
        }
    }
    Ok(())
}

/// Argv / command token scan. Does not parse a full shell.
pub fn reject_command_secret_path_tokens(
    command: &str,
    policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
    for (display, candidate) in command_path_tokens(command) {
        if candidate_is_denied(&candidate, policy) {
            return Err(DestDenyError::CommandToken { token: display });
        }
    }
    Ok(())
}

/// Join a relative dest to `root`. Absolute dests stay as given.
pub fn dest_under_root(root: &Path, path: &str) -> PathBuf {
    let p = Path::new(path);
    if p.is_absolute() {
        p.to_path_buf()
    } else {
        root.join(p)
    }
}

/// Script body after a shell `-c` cluster (`-c`, `-lc`, `-ic`) or `-cBODY`.
///
/// Cluster letters are the usual bash short options that combine with
/// `-c`. A long word such as `-color` is not a cluster.
fn shell_c_body<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
    let rest = token.strip_prefix('-')?;
    if rest.starts_with('-') {
        return None;
    }
    if is_shell_c_cluster(rest) {
        return next;
    }
    let c_at = rest.find('c')?;
    let prefix = rest.get(..=c_at)?;
    if !is_shell_c_cluster(prefix) {
        return None;
    }
    let after = rest.get(c_at + 1..)?;
    if after.is_empty() {
        return next;
    }
    Some(after)
}

fn is_shell_c_cluster(rest: &str) -> bool {
    let len = rest.len();
    // `-cwa` is pwsh -CommandWithArgs, not a bash short-option cluster.
    if rest.eq_ignore_ascii_case("cwa") {
        return false;
    }
    (1..=4).contains(&len) && rest.contains('c') && rest.chars().all(|ch| ch.is_ascii_alphabetic())
}

/// Dest-deny each raw argv dest under `root`.
///
/// Empty and flag-looking tokens are skipped. A shell `-c` token, including
/// short-option clusters that contain `c` (`-lc`, `-ic`, `-lic`, `-cl`)
/// and an attached `-cBODY`, dest-denies paths inside the script body
/// via [`check_command_dests`]. When that body (or any peeled command
/// string) contains an `env`/`env.exe` token, dest-denies the following
/// tokens with the same env-flag dest check used for argv0 env.
/// When argv0 is `env`/`env.exe`, dest-denies the operand of
/// `-S`/`--split-string` via [`check_command_dests`], then leftover
/// tokens in that string as env flags (`--file=`, `-f`, `NAME=value`).
/// An `env`/`env.exe` token in any argv slot is walked the same way, so
/// a prefix that is not `timeout`/`nohup`/`nice`/`time`/`stdbuf` cannot
/// hide `-S`/`--file`. A nested `env` operand (or `env -- env …`) is
/// walked the same way.
/// `cmd /c` and `powershell -Command` / `-EncodedCommand` bodies are
/// dest-denied as command strings. After `cmd` / `pwsh`, remaining
/// argv is walked so `/s` / `-NoProfile` cannot hide `/c`,
/// `-EncodedCommand`, `-EncodedArguments`, or `-File`. Unique prefixes
/// (`-en`, `-comma`, `-cwa`) match. A second leading `-`/`/` is stripped
/// (`--Command`, `--EncodedCommand`, `--File`). `-File` / `-f` / `/File`
/// (and `-File:…`) dest-deny the script path. `pwsh -Command -`,
/// `pwsh -File -` (including `--switch` and unique prefixes), and
/// positional `pwsh -` / `powershell -` are
/// [`DestDenyError::StdinScript`]: dest-deny does not read host stdin.
/// `cmd /c -` is unchanged. Those bodies are also peeled
/// inside a shell `-c` string. Generic `/c`, `-Command`, `-EncodedCommand`,
/// `-cwa`, or `-File` on another argv0 is not.
/// Dest-denies argv `-f`/`--file` (including attached `--file=.env`) via
/// [`check_dest`]. Also dest-denies the suffix after `=` on any `--*` /
/// `-*=` token (`tool --config=.env`). A GNU glued short dest (`-a.env`,
/// `-D.env`, `-C.env`, clustered `-la.env`) dest-denies the remainder
/// after an ASCII-letter cluster when that remainder starts with `.`
/// `/` or `~`. `-areadme.md` and `-color` stay allowed. `--color=always`
/// and `--jobs=4` stay allowed when the suffix is not a dest-deny name.
/// A non-flag `NAME=value` dest-denies the value. Does not dest-deny a
/// flattened join of all argv. Does not dest-deny a following separate
/// token unless that token is already a raw dest.
/// A relative token that is a symlink out of the workspace is refused,
/// the same way `why` refuses it. Absolute tokens stay on dest-deny
/// only, so `/bin/cat` and `/etc/passwd` are unchanged.
pub fn check_command_argv(
    cmd: &[impl AsRef<str>],
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    let guard = workspace_guard(root);
    for (i, token) in cmd.iter().enumerate() {
        let token = token.as_ref();
        if !token.is_empty() && !token.starts_with('-') {
            let dest = dest_under_root(root, token);
            check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
            refuse_relative_symlink(guard.as_ref(), token)?;
            if let Some(value) = assignment_dest_value(token) {
                let dest = dest_under_root(root, value);
                check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
                refuse_relative_symlink(guard.as_ref(), value)?;
            }
        }
        if let Some(value) = attached_flag_dest(token) {
            let dest = dest_under_root(root, value);
            check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
            refuse_relative_symlink(guard.as_ref(), value)?;
        }
        if let Some(body) = shell_c_body(token, cmd.get(i + 1).map(|s| s.as_ref())) {
            check_command_dests(body, root, policy)?;
        }
        if is_cmd_program(token) || is_powershell_program(token) {
            check_cmd_powershell_remaining_dests(token, &cmd[i + 1..], root, policy)?;
        }
        if is_env_program(token) {
            check_env_flag_dests(&cmd[i + 1..], root, policy)?;
        }
    }
    Ok(())
}

pub(crate) fn is_env_program(program: impl AsRef<OsStr>) -> bool {
    let raw = program.as_ref().to_string_lossy();
    let name = program_basename(&raw);
    name.eq_ignore_ascii_case("env") || name.eq_ignore_ascii_case("env.exe")
}

fn program_basename(program: &str) -> &str {
    program.rsplit(['/', '\\']).next().unwrap_or(program)
}

fn is_cmd_program(program: &str) -> bool {
    let name = program_basename(program);
    name.eq_ignore_ascii_case("cmd") || name.eq_ignore_ascii_case("cmd.exe")
}

fn is_powershell_program(program: &str) -> bool {
    let name = program_basename(program);
    name.eq_ignore_ascii_case("powershell")
        || name.eq_ignore_ascii_case("powershell.exe")
        || name.eq_ignore_ascii_case("pwsh")
        || name.eq_ignore_ascii_case("pwsh.exe")
}

/// `cmd /c` / `/k` script body (`/c`, `/C`, `/kBODY`).
fn cmd_script_body<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
    let rest = token.strip_prefix('/')?;
    let first = rest.chars().next()?;
    if !matches!(first, 'c' | 'C' | 'k' | 'K') {
        return None;
    }
    let after = rest.get(first.len_utf8()..)?;
    if after.is_empty() {
        return next;
    }
    Some(after)
}

/// Strip one or two leading `-`/`/` from a PowerShell host switch.
/// `--Command` and `/Command` both yield `Command`.
fn strip_ps_switch(token: &str) -> Option<&str> {
    let rest = token.strip_prefix(['-', '/'])?;
    Some(rest.strip_prefix(['-', '/']).unwrap_or(rest))
}

/// PowerShell `-Command` / `-c` / `/C` / `-cwa` / `-CommandWithArgs` script
/// body, including attached `-Command:…` and unique prefixes (`-comm`).
/// Not `-EncodedCommand` (see [`powershell_encoded_payload`]).
fn powershell_command_body<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
    let rest = strip_ps_switch(token)?;
    if let Some((name, value)) = rest.split_once(':') {
        if is_powershell_command_name(name) {
            return Some(value);
        }
        return None;
    }
    if is_powershell_command_name(rest) {
        return next;
    }
    None
}

/// PowerShell `-EncodedCommand` / `-enc` / `-ec` / `-en` / `-e` payload, including
/// attached `-EncodedCommand:…` and unique prefixes (`-en`). Not `-Command`.
fn powershell_encoded_payload<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
    let rest = strip_ps_switch(token)?;
    if let Some((name, value)) = rest.split_once(':') {
        if is_powershell_encoded_command_name(name) {
            return Some(value);
        }
        return None;
    }
    if is_powershell_encoded_command_name(rest) {
        return next;
    }
    None
}

/// PowerShell `-EncodedArguments` / `-ea` payload, including attached
/// `-EncodedArguments:…`. Unique prefixes of `encodedarguments` that are
/// not prefixes of `encodedcommand` (`-encodeda`). Host `-ea` is this
/// switch, not `-ErrorAction`.
fn powershell_encoded_arguments_payload<'a>(
    token: &'a str,
    next: Option<&'a str>,
) -> Option<&'a str> {
    let rest = strip_ps_switch(token)?;
    if let Some((name, value)) = rest.split_once(':') {
        if is_powershell_encoded_arguments_name(name) {
            return Some(value);
        }
        return None;
    }
    if is_powershell_encoded_arguments_name(rest) {
        return next;
    }
    None
}

fn is_powershell_encoded_command_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower == "encodedcommand"
        || lower == "enc"
        || lower == "ec"
        || lower == "e"
        || ("encodedcommand".starts_with(&lower)
            && !"erroraction".starts_with(&lower)
            && !"errorvariable".starts_with(&lower)
            && !"executionpolicy".starts_with(&lower))
}

/// PowerShell `-File` / `-f` / `/File` script dest, including attached
/// `-File:…` / `-f:…` and unique prefixes (`-fi`, `-fil`).
fn powershell_file_dest<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
    let rest = strip_ps_switch(token)?;
    if let Some((name, value)) = rest.split_once(':') {
        if is_powershell_file_name(name) {
            return Some(value);
        }
        return None;
    }
    if is_powershell_file_name(rest) {
        return next;
    }
    None
}

fn is_powershell_file_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower == "file" || lower == "f" || (lower.len() >= 2 && "file".starts_with(&lower))
}

fn is_powershell_command_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower == "command"
        || lower == "c"
        || (lower.len() >= 4 && "command".starts_with(&lower))
        || lower == "commandwithargs"
        || lower == "cwa"
        || (lower.len() >= 8 && "commandwithargs".starts_with(&lower))
}

fn is_powershell_encoded_arguments_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower == "encodedarguments"
        || lower == "ea"
        || ("encodedarguments".starts_with(&lower) && !"encodedcommand".starts_with(&lower))
}

/// After `cmd` / `pwsh`, walk remaining tokens. First `/c`/`/k`,
/// `-EncodedCommand`, `-EncodedArguments`, `-File`, or `-Command`
/// (including `--switch` and unique prefixes) wins. A leftover
/// operand that is exactly `-` is positional File-from-stdin.
fn check_cmd_powershell_remaining_dests(
    program: &str,
    rest: &[impl AsRef<str>],
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    if is_cmd_program(program) {
        for (j, token) in rest.iter().enumerate() {
            if let Some(body) = cmd_script_body(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
            {
                return check_command_dests(body, root, policy);
            }
        }
    }
    if is_powershell_program(program) {
        for (j, token) in rest.iter().enumerate() {
            if let Some(payload) =
                powershell_encoded_payload(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
            {
                return check_powershell_encoded_dests(payload, root, policy);
            }
            if let Some(payload) = powershell_encoded_arguments_payload(
                token.as_ref(),
                rest.get(j + 1).map(|s| s.as_ref()),
            ) {
                return check_powershell_encoded_dests(payload, root, policy);
            }
            if let Some(path) =
                powershell_file_dest(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
            {
                refuse_powershell_stdin_dash(path)?;
                let dest = dest_under_root(root, path);
                check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
                return refuse_relative_symlink(workspace_guard(root).as_ref(), path);
            }
            if let Some(body) =
                powershell_command_body(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
            {
                refuse_powershell_stdin_dash(body)?;
                return check_command_dests(body, root, policy);
            }
        }
        // File is the default positional. `pwsh -` reads a script from stdin.
        for token in rest {
            if token.as_ref() == "-" {
                return Err(DestDenyError::StdinScript.into());
            }
        }
    }
    Ok(())
}

fn refuse_powershell_stdin_dash(body: &str) -> Result<(), CheckDestError> {
    if body == "-" {
        return Err(DestDenyError::StdinScript.into());
    }
    Ok(())
}

/// Decode `-EncodedCommand` UTF-16LE base64 and dest-deny the script.
/// Invalid payloads fail closed as [`DestDenyError::EncodedCommand`].
fn check_powershell_encoded_dests(
    payload: &str,
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    let script = decode_powershell_encoded_command(payload).ok_or(DestDenyError::EncodedCommand)?;
    check_command_dests(&script, root, policy)
}

/// RFC 4648 base64 of UTF-16LE. Fail-closed on empty, invalid alphabet,
/// leftover bits, odd length, or unpaired surrogates.
fn decode_powershell_encoded_command(payload: &str) -> Option<String> {
    let stripped: String = payload
        .chars()
        .filter(|c| !matches!(*c, ' ' | '\t' | '\r' | '\n'))
        .collect();
    if stripped.is_empty() {
        return None;
    }
    let bytes = decode_rfc4648_base64(stripped.as_bytes())?;
    if bytes.len() % 2 != 0 {
        return None;
    }
    let units: Vec<u16> = bytes
        .chunks_exact(2)
        .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
        .collect();
    String::from_utf16(&units).ok()
}

fn decode_rfc4648_base64(input: &[u8]) -> Option<Vec<u8>> {
    fn digit(b: u8) -> Option<u8> {
        match b {
            b'A'..=b'Z' => Some(b - b'A'),
            b'a'..=b'z' => Some(b - b'a' + 26),
            b'0'..=b'9' => Some(b - b'0' + 52),
            b'+' => Some(62),
            b'/' => Some(63),
            _ => None,
        }
    }

    let mut pad = 0usize;
    let mut end = input.len();
    while end > 0 && input[end - 1] == b'=' {
        pad += 1;
        end -= 1;
        if pad > 2 {
            return None;
        }
    }
    if input[..end].contains(&b'=') {
        return None;
    }
    if end % 4 == 1 {
        return None;
    }

    let mut out = Vec::with_capacity(end * 3 / 4);
    let mut acc: u32 = 0;
    let mut bits: u32 = 0;
    for &b in &input[..end] {
        let v = u32::from(digit(b)?);
        acc = (acc << 6) | v;
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push((acc >> bits) as u8);
            acc &= (1 << bits) - 1;
        }
    }
    if acc != 0 {
        return None;
    }
    Some(out)
}

/// Suffix after `=` on a flag token (`--config=.env`, `-f=.env`), or
/// a GNU glued short dest (`-a.env`, clustered `-la.env`). After one
/// or more ASCII letters of a short option with no `=`, a remainder
/// that starts with `.` `/` or `~` is the dest. Not `NAME=value` (no
/// leading `-`). Empty values are ignored. `--flag`, `-la`, and
/// `-areadme.md` are not dests.
fn attached_flag_dest(token: &str) -> Option<&str> {
    if !token.starts_with('-') || token == "-" || token == "--" {
        return None;
    }
    if let Some((_, value)) = token.split_once('=') {
        if value.is_empty() {
            return None;
        }
        return Some(value);
    }
    if token.starts_with("--") {
        return None;
    }
    let rest = token.get(1..)?;
    let mut letters = 0usize;
    for (i, ch) in rest.char_indices() {
        if ch.is_ascii_alphabetic() {
            letters += 1;
            continue;
        }
        if letters == 0 {
            return None;
        }
        let remainder = rest.get(i..)?;
        if remainder.starts_with(['.', '/', '~']) {
            return Some(remainder);
        }
        return None;
    }
    None
}

/// Value after the first `=` on a non-flag token.
///
/// Empty tokens and tokens that start with `-` are ignored
/// (`--file=.env` stays on [`attached_flag_dest`]). One matching
/// quote pair around the value is stripped. An empty value is ignored.
fn assignment_dest_value(token: &str) -> Option<&str> {
    if token.is_empty() || token.starts_with('-') {
        return None;
    }
    let (_, mut value) = token.split_once('=')?;
    let bytes = value.as_bytes();
    if bytes.len() >= 2 {
        let quote = bytes[0];
        if (quote == b'\'' || quote == b'"') && bytes[bytes.len() - 1] == quote {
            value = &value[1..bytes.len() - 1];
        }
    }
    if value.is_empty() { None } else { Some(value) }
}

#[cfg(feature = "nono")]
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum CmdWrapper {
    Timeout,
    Nohup,
    Nice,
    Time,
    Stdbuf,
}

#[cfg(feature = "nono")]
pub(crate) fn cmd_wrapper(program: impl AsRef<OsStr>) -> Option<CmdWrapper> {
    let raw = program.as_ref().to_string_lossy();
    let name = raw.rsplit(['/', '\\']).next().unwrap_or(raw.as_ref());
    if name.eq_ignore_ascii_case("timeout") || name.eq_ignore_ascii_case("timeout.exe") {
        Some(CmdWrapper::Timeout)
    } else if name.eq_ignore_ascii_case("nohup") || name.eq_ignore_ascii_case("nohup.exe") {
        Some(CmdWrapper::Nohup)
    } else if name.eq_ignore_ascii_case("nice") || name.eq_ignore_ascii_case("nice.exe") {
        Some(CmdWrapper::Nice)
    } else if name.eq_ignore_ascii_case("time") || name.eq_ignore_ascii_case("time.exe") {
        Some(CmdWrapper::Time)
    } else if name.eq_ignore_ascii_case("stdbuf") || name.eq_ignore_ascii_case("stdbuf.exe") {
        Some(CmdWrapper::Stdbuf)
    } else {
        None
    }
}

/// Skip wrapper flags plus the timeout duration. Returns the index of
/// the first remaining command operand.
#[cfg(feature = "nono")]
pub(crate) fn skip_wrapper_prefix(kind: CmdWrapper, args: &[impl AsRef<str>]) -> usize {
    let mut i = 0;
    let mut options_done = false;
    let mut skip_timeout_duration = kind == CmdWrapper::Timeout;
    while i < args.len() {
        let raw = args[i].as_ref();
        if !options_done {
            if raw == "--" {
                options_done = true;
                i += 1;
                continue;
            }
            if let Some(skip) = wrapper_flag_skip(kind, raw) {
                i = i.saturating_add(skip);
                continue;
            }
        }
        if skip_timeout_duration {
            skip_timeout_duration = false;
            i += 1;
            continue;
        }
        return i;
    }
    i
}

#[cfg(feature = "nono")]
fn wrapper_takes_value(kind: CmdWrapper, flag: char) -> bool {
    match kind {
        CmdWrapper::Timeout => matches!(flag, 's' | 'k'),
        CmdWrapper::Nice => flag == 'n',
        CmdWrapper::Nohup | CmdWrapper::Time => false,
        CmdWrapper::Stdbuf => matches!(flag, 'o' | 'e' | 'i'),
    }
}

#[cfg(feature = "nono")]
fn wrapper_long_takes_value(kind: CmdWrapper, long: &str) -> bool {
    match kind {
        CmdWrapper::Timeout => matches!(long, "signal" | "kill-after"),
        CmdWrapper::Nice => long == "adjustment",
        CmdWrapper::Nohup | CmdWrapper::Time => false,
        CmdWrapper::Stdbuf => matches!(long, "output" | "error" | "input"),
    }
}

#[cfg(feature = "nono")]
fn wrapper_flag_skip(kind: CmdWrapper, arg: &str) -> Option<usize> {
    if arg == "-" {
        return Some(1);
    }
    if !arg.starts_with('-') {
        return None;
    }
    if let Some(long) = arg.strip_prefix("--") {
        if long.contains('=') {
            return Some(1);
        }
        return Some(if wrapper_long_takes_value(kind, long) {
            2
        } else {
            1
        });
    }
    let mut chars = arg[1..].chars();
    while let Some(c) = chars.next() {
        if wrapper_takes_value(kind, c) {
            return Some(if chars.next().is_some() { 1 } else { 2 });
        }
    }
    Some(1)
}

pub(crate) fn env_takes_value(flag: char) -> bool {
    matches!(flag, 'u' | 'C' | 'S' | 'P' | 'a' | 'f')
}

pub(crate) fn env_flag_skip(arg: &str) -> Option<usize> {
    if arg == "-" {
        return Some(1);
    }
    if !arg.starts_with('-') {
        return None;
    }
    if let Some(long) = arg.strip_prefix("--") {
        if long.contains('=') {
            return Some(1);
        }
        return Some(match long {
            "unset" | "split-string" | "chdir" | "argv0" | "file" => 2,
            _ => 1,
        });
    }
    let mut chars = arg[1..].chars();
    while let Some(c) = chars.next() {
        if env_takes_value(c) {
            return Some(if chars.next().is_some() { 1 } else { 2 });
        }
    }
    Some(1)
}

fn check_env_flag_dests(
    args: &[impl AsRef<str>],
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    check_env_flag_dests_inner(args, root, policy, false)
}

/// Dest-deny a `-S`/`--split-string` operand as a command string, then
/// re-walk leftover tokens as env flags (`--file=`, `-f`, `NAME=value`).
fn check_env_split_string_dests(
    operand: &str,
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    check_command_dests(operand, root, policy)?;
    let leftover: Vec<&str> = operand.split_whitespace().collect();
    check_env_flag_dests_inner(&leftover, root, policy, true)
}

fn check_env_flag_dests_inner(
    args: &[impl AsRef<str>],
    root: &Path,
    policy: &DenyPolicy,
    deny_assign_values: bool,
) -> Result<(), CheckDestError> {
    let mut i = 0;
    while i < args.len() {
        let raw = args[i].as_ref();
        if raw == "--" || raw == "-" {
            return continue_env_after_operand(&args[i + 1..], root, policy);
        }
        if !raw.starts_with('-') {
            if raw.contains('=') {
                if deny_assign_values
                    && let Some((_, value)) = raw.split_once('=')
                    && !value.is_empty()
                {
                    check_env_file_dest(value, root, policy)?;
                }
                i += 1;
                continue;
            }
            return continue_env_after_operand(&args[i..], root, policy);
        }
        if let Some(long) = raw.strip_prefix("--") {
            if let Some((name, value)) = long.split_once('=') {
                check_env_named_operand(name, value, root, policy)?;
                i += 1;
                continue;
            }
            let next = args.get(i + 1).map(|s| s.as_ref());
            match long {
                "split-string" | "file" | "unset" | "chdir" | "argv0" => {
                    if let Some(next) = next {
                        check_env_named_operand(long, next, root, policy)?;
                    }
                    i += 2;
                }
                _ => i += 1,
            }
            continue;
        }
        let mut chars = raw[1..].chars();
        let mut value_flag = None;
        let mut attached = String::new();
        while let Some(c) = chars.next() {
            if env_takes_value(c) {
                value_flag = Some(c);
                attached = chars.collect();
                break;
            }
        }
        match value_flag {
            Some(flag) => {
                let operand = if attached.is_empty() {
                    args.get(i + 1).map(|s| s.as_ref())
                } else {
                    Some(attached.as_str())
                };
                if let Some(operand) = operand {
                    match flag {
                        'S' => check_env_split_string_dests(operand, root, policy)?,
                        'f' => check_env_file_dest(operand, root, policy)?,
                        _ => {}
                    }
                }
                i += if attached.is_empty() { 2 } else { 1 };
            }
            None => i += 1,
        }
    }
    Ok(())
}

fn continue_env_after_operand(
    args: &[impl AsRef<str>],
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    for (i, token) in args.iter().enumerate() {
        if is_env_program(token.as_ref()) {
            return check_env_flag_dests(&args[i + 1..], root, policy);
        }
    }
    Ok(())
}

fn check_env_named_operand(
    name: &str,
    value: &str,
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    match name {
        "split-string" => check_env_split_string_dests(value, root, policy),
        "file" => check_env_file_dest(value, root, policy),
        _ => Ok(()),
    }
}

fn check_env_file_dest(path: &str, root: &Path, policy: &DenyPolicy) -> Result<(), CheckDestError> {
    let dest = dest_under_root(root, path);
    check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
    refuse_relative_symlink(workspace_guard(root).as_ref(), path)
}

fn workspace_guard(root: &Path) -> Option<PathGuard> {
    PathGuard::with_extra_roots(root, std::iter::empty::<&Path>()).ok()
}

/// Relative argv dests use the same symlink rule as `why`.
/// Absolute program paths are not workspace dests.
fn refuse_relative_symlink(guard: Option<&PathGuard>, token: &str) -> Result<(), CheckDestError> {
    let Some(guard) = guard else {
        return Ok(());
    };
    // `/bin/cat` is absolute on Unix. On Windows `Path::is_absolute`
    // is false for `/bin/cat` and for `cmd /c`, so a leading slash
    // or backslash is also not a workspace-relative dest.
    let lead = token.as_bytes().first().copied();
    if token.is_empty() || Path::new(token).is_absolute() || matches!(lead, Some(b'/' | b'\\')) {
        return Ok(());
    }
    // `NUL` and `CON` are devices. `check_dest` already classified them.
    #[cfg(windows)]
    if windows_device_kind(token).is_some() {
        return Ok(());
    }
    match guard.check(Path::new(token)) {
        Ok(_) => Ok(()),
        Err(err @ PathGuardError::Denied(_)) => Err(err.into()),
        Err(_) => Ok(()),
    }
}

/// Join extracted command dests under `root` and dest-deny each.
///
/// Absolute dests stay as given. Empty tokens are skipped. Flag-looking
/// peeled tokens are skipped except an attached `--flag=.env` /
/// `-f=.env` suffix or a GNU glued short dest (`-a.env`, clustered
/// `-la.env`), which is dest-denied via [`check_dest`]. After
/// peeling, an `env`/`env.exe` token dest-denies the following tokens
/// with the same env-flag dest check used for argv0 env.
pub fn check_command_dests(
    command: &str,
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    let guard = workspace_guard(root);
    for (_display, candidate) in command_path_tokens(command) {
        for peeled in peel_shell_parts(&candidate) {
            if peeled.is_empty() {
                continue;
            }
            if let Some(value) = attached_flag_dest(peeled) {
                let dest = dest_under_root(root, value);
                check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
                refuse_relative_symlink(guard.as_ref(), value)?;
                continue;
            }
            if peeled.starts_with('-') {
                continue;
            }
            let dest = dest_under_root(root, peeled);
            check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
            refuse_relative_symlink(guard.as_ref(), peeled)?;
            if let Some(value) = assignment_dest_value(peeled) {
                let dest = dest_under_root(root, value);
                check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
                refuse_relative_symlink(guard.as_ref(), value)?;
            }
        }
    }
    check_command_string_env_dests(command, root, policy)
}

/// After peeling a command string, dest-deny env `-S`/`--file` operands.
///
/// Recurses into a shell `-c` body. Also peels `cmd` / `pwsh` `/c`,
/// `-Command`, `-CommandWithArgs`, `-EncodedCommand`, `-EncodedArguments`,
/// and `-File` (including `--switch` and unique prefixes) from remaining
/// string tokens. Attached `--flag=.env` and GNU glued shorts
/// (`-a.env`, clustered `-la.env`) are dest-denied via
/// [`check_command_dests`].
fn check_command_string_env_dests(
    command: &str,
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    for part in peel_shell_parts(command) {
        let tokens = command_string_tokens(part);
        for (i, token) in tokens.iter().enumerate() {
            if is_env_program(*token) {
                check_env_flag_dests(&tokens[i + 1..], root, policy)?;
            }
            if let Some(body) = shell_c_body(token, tokens.get(i + 1).copied()) {
                check_command_string_env_dests(body, root, policy)?;
            }
            if is_cmd_program(token) || is_powershell_program(token) {
                check_cmd_powershell_remaining_dests(token, &tokens[i + 1..], root, policy)?;
            }
        }
    }
    Ok(())
}

/// Whitespace words; matching quotes yield the inner string as one token.
fn command_string_tokens(command: &str) -> Vec<&str> {
    let bytes = command.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i].is_ascii_whitespace() {
            i += 1;
            continue;
        }
        if bytes[i] == b'\'' || bytes[i] == b'"' {
            let q = bytes[i];
            i += 1;
            let start = i;
            while i < bytes.len() && bytes[i] != q {
                i += 1;
            }
            out.push(&command[start..i]);
            if i < bytes.len() {
                i += 1;
            }
            continue;
        }
        let start = i;
        while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        out.push(&command[start..i]);
    }
    out
}

/// Committed dotenv templates, not live env files.
pub fn is_env_template_basename(name: &str) -> bool {
    let base = name
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(name)
        .to_ascii_lowercase();
    base.starts_with(".env.")
        && (base.ends_with(".example") || base.ends_with(".sample") || base.ends_with(".template"))
}

/// Gitignore-style dest-deny glob subset.
///
/// Rejects brace alternation, backslash escapes, empty path segments,
/// and `.` / `..` segments. Default [`default_secret_denies`] rows pass.
/// Hosts match [`AgentLockError`] when an `agent.lock` extra fails.
pub fn validate_deny_glob(glob: &str) -> Result<(), &'static str> {
    let glob = glob.trim();
    if glob.is_empty() {
        return Err("empty dest-deny glob");
    }
    if glob.contains('{') || glob.contains('}') {
        return Err("brace alternation is not supported");
    }
    if glob.contains('\\') {
        return Err("backslash escapes are not supported");
    }
    let normalized = normalize_glob_text(glob);
    let segs: Vec<&str> = normalized.split('/').collect();
    if segs.iter().any(|s| s.is_empty()) {
        return Err("empty path segment");
    }
    if segs.iter().any(|s| *s == "." || *s == "..") {
        return Err("'.' / '..' path segment");
    }
    Ok(())
}

/// Seatbelt regex for one dest-deny glob under an RW prefix.
///
/// `**/.env` matches `prefix/.env` and `prefix/sub/.env`. Interior `**`
/// is recursive (`src/**/*.pem` matches `src/x.pem` and `src/a/b.pem`).
/// ASCII letters become `[Aa]` so Seatbelt matches the case-insensitive
/// userspace glob dialect. SBPL has no in-tree `(?i)` support.
/// Used by macOS wrap and by the dialect table test on every OS.
pub fn dest_deny_glob_regex(prefix: &str, glob: &str) -> Option<String> {
    validate_deny_glob(glob).ok()?;
    let mut glob = glob.trim();
    if glob.is_empty() {
        return None;
    }
    let nested = glob.starts_with("**/");
    if nested {
        glob = glob.strip_prefix("**/")?;
    }
    let trailing_dir = glob.ends_with("/**");
    if trailing_dir {
        glob = glob.strip_suffix("/**")?;
    }
    if glob.is_empty() {
        return None;
    }
    let mut body = String::new();
    let chars: Vec<char> = glob.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '*' {
            if i + 1 < chars.len() && chars[i + 1] == '*' {
                body.push_str("(.*/)?");
                i += 2;
                if i < chars.len() && chars[i] == '/' {
                    i += 1;
                }
                continue;
            }
            body.push_str("[^/]*");
            i += 1;
            continue;
        }
        if matches!(
            chars[i],
            '.' | '+' | '?' | '(' | ')' | '[' | ']' | '|' | '^' | '$'
        ) {
            body.push('\\');
            body.push(chars[i]);
            i += 1;
            continue;
        }
        push_ascii_letter_class(&mut body, chars[i]);
        i += 1;
    }
    if trailing_dir {
        body.push_str("(/.*)?");
    }
    let prefix = case_fold_regex_letters(prefix);
    if nested {
        Some(format!("^{prefix}/(.*/)?{body}$"))
    } else {
        Some(format!("^{prefix}/{body}$"))
    }
}

fn push_ascii_letter_class(out: &mut String, c: char) {
    if c.is_ascii_alphabetic() {
        out.push('[');
        out.push(c.to_ascii_uppercase());
        out.push(c.to_ascii_lowercase());
        out.push(']');
    } else {
        out.push(c);
    }
}

fn case_fold_regex_letters(s: &str) -> String {
    let mut out = String::new();
    let mut escaped = false;
    for c in s.chars() {
        if escaped {
            out.push(c);
            escaped = false;
            continue;
        }
        if c == '\\' {
            out.push('\\');
            escaped = true;
            continue;
        }
        push_ascii_letter_class(&mut out, c);
    }
    out
}

pub fn path_matches_deny_glob(pattern: &str, path: &str) -> bool {
    let pattern = normalize_glob_text(pattern);
    let path = windows_secret_spelling(&normalize_glob_text(path));
    let pat: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect();
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    match_glob_segments(&pat, &segs)
}

/// Win32 opens `name.`, `name `, and `name::$DATA` as `name`.
/// An extended `//?/` path is the literal spelling.
fn windows_secret_spelling(path: &str) -> String {
    #[cfg(windows)]
    {
        if path.starts_with("//?/") {
            return path.to_string();
        }
        let (dir, name) = match path.rfind('/') {
            Some(i) => (&path[..=i], &path[i + 1..]),
            None => ("", path),
        };
        let name = name.trim_end_matches([' ', '.']);
        let name = name.split(':').next().unwrap_or(name);
        let name = name.trim_end_matches([' ', '.']);
        if name.is_empty() {
            return path.to_string();
        }
        format!("{dir}{name}")
    }
    #[cfg(not(windows))]
    {
        path.to_string()
    }
}

pub fn path_is_denied_glob(globs: &[String], path: &str) -> bool {
    first_matching_deny_glob(globs, path).is_some()
}

fn first_matching_deny_glob(globs: &[String], path: &str) -> Option<String> {
    deny_glob_name(first_matching_deny_glob_under(globs, path, None))
}

/// `".."` means the path left the workspace. It is not a deny glob.
fn deny_glob_name(glob: Option<String>) -> Option<String> {
    glob.filter(|name| name != "..")
}

/// Glob match for `path` relative to `root` when `root` is set.
///
/// Slash-globs are anchored at the workspace, after stripping either
/// firmlink spelling (`/tmp` and `/private/tmp`). A `..` that leaves the
/// root is denied. Single-segment globs (`*.pem`, `id_rsa`) also match
/// the basename. `**/` globs still match paths outside the root.
pub fn path_is_denied_under_root(globs: &[String], path: &str, root: &Path) -> bool {
    first_matching_deny_glob_under(globs, path, Some(root)).is_some()
}

fn first_matching_deny_glob_under(
    globs: &[String],
    path: &str,
    root: Option<&Path>,
) -> Option<String> {
    let Some(root) = root else {
        return first_matching_deny_glob_unscoped(globs, path);
    };
    let had_dotdot = path.split(['/', '\\']).any(|seg| seg == "..");
    let Some(collapsed) = lexical_absolute(path) else {
        return Some("..".to_string());
    };
    let (match_path, outside) = match strip_workspace_root(&collapsed, root) {
        Some(rel) => (rel, false),
        None if had_dotdot => return Some("..".to_string()),
        None => (collapsed, true),
    };
    let template = is_env_template_basename(&match_path);
    let base = match_path.rsplit('/').next().unwrap_or(match_path.as_str());
    globs
        .iter()
        .find(|g| {
            if template && is_default_env_star_glob(g) {
                return false;
            }
            let slashed = normalize_glob_text(g).contains('/');
            if outside && slashed && !normalize_glob_text(g).starts_with("**/") {
                return false;
            }
            if path_matches_deny_glob(g, &match_path) {
                return true;
            }
            !slashed && path_matches_deny_glob(g, base)
        })
        .cloned()
}

/// Collapse `.` and `..`. `Err` is not used; `None` means `..` left the
/// filesystem root.
fn lexical_absolute(path: &str) -> Option<String> {
    let norm = normalize_glob_text(path);
    let absolute = norm.starts_with('/');
    let mut segs = Vec::new();
    for seg in norm.split('/') {
        if seg.is_empty() || seg == "." {
            continue;
        }
        if seg == ".." {
            // `/..` stays at the filesystem root.
            let _ = segs.pop();
            continue;
        }
        segs.push(seg);
    }
    if absolute {
        Some(format!("/{}", segs.join("/")))
    } else {
        Some(segs.join("/"))
    }
}

fn strip_workspace_root(path: &str, root: &Path) -> Option<String> {
    let path_segs = lexical_absolute(path)?;
    for spelling in firmlink_spellings(root) {
        let Some(root_s) = lexical_absolute(&path_as_glob(&spelling)) else {
            continue;
        };
        if let Some(rel) = strip_prefix_path(&path_segs, &root_s) {
            return Some(rel);
        }
    }
    None
}

fn strip_prefix_path(path: &str, root: &str) -> Option<String> {
    let path = path.trim_end_matches('/');
    let root = root.trim_end_matches('/');
    if path.eq_ignore_ascii_case(root) {
        return Some(String::new());
    }
    let prefix = format!("{root}/");
    if path.len() >= prefix.len()
        && path.is_char_boundary(prefix.len())
        && path[..prefix.len()].eq_ignore_ascii_case(&prefix)
    {
        return Some(path[prefix.len()..].to_string());
    }
    None
}

fn firmlink_spellings(path: &Path) -> Vec<PathBuf> {
    let mut out = vec![path.to_path_buf()];
    if let Some(alias) = firmlink_alias_path(path)
        && !out.iter().any(|p| p == &alias)
    {
        out.push(alias);
    }
    out
}

fn firmlink_alias_path(path: &Path) -> Option<PathBuf> {
    let raw = path.to_str()?.replace('\\', "/");
    const PAIRS: [(&str, &str); 3] = [
        ("/tmp", "/private/tmp"),
        ("/var", "/private/var"),
        ("/etc", "/private/etc"),
    ];
    for (public, private) in PAIRS {
        if raw == public || raw.starts_with(&format!("{public}/")) {
            return Some(PathBuf::from(format!(
                "{private}{}",
                raw.strip_prefix(public).unwrap_or("")
            )));
        }
        if raw == private || raw.starts_with(&format!("{private}/")) {
            return Some(PathBuf::from(format!(
                "{public}{}",
                raw.strip_prefix(private).unwrap_or("")
            )));
        }
    }
    None
}

pub(crate) fn first_matching_deny_glob_unscoped(globs: &[String], path: &str) -> Option<String> {
    let template = is_env_template_basename(path);
    let base = path.rsplit(['/', '\\']).next().unwrap_or(path);
    globs
        .iter()
        .find(|g| {
            if template && is_default_env_star_glob(g) {
                return false;
            }
            let slashed = normalize_glob_text(g).contains('/');
            path_matches_deny_glob(g, path) || (!slashed && path_matches_deny_glob(g, base))
        })
        .cloned()
}

pub(crate) fn is_default_env_star_glob(pattern: &str) -> bool {
    normalize_glob_text(pattern) == "**/.env.*"
}

fn path_as_glob(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

fn normalize_glob_text(s: &str) -> String {
    s.replace('\\', "/").to_ascii_lowercase()
}

fn match_glob_segments(pat: &[&str], path: &[&str]) -> bool {
    let mut memo = vec![None; (pat.len() + 1) * (path.len() + 1)];
    match_glob_at(pat, path, &mut memo, 0, 0)
}

/// Repeated `**` segments are exponential without this table.
/// Fifteen `**` plus a final `z` did not return on a 25-segment path.
fn match_glob_at(
    pat: &[&str],
    path: &[&str],
    memo: &mut [Option<bool>],
    pat_i: usize,
    path_i: usize,
) -> bool {
    let slot = pat_i * (path.len() + 1) + path_i;
    if let Some(done) = memo[slot] {
        return done;
    }
    let matched = match pat.get(pat_i) {
        None => path_i == path.len(),
        Some(&"**") => {
            if pat_i + 1 == pat.len() {
                true
            } else {
                (path_i..=path.len()).any(|next| match_glob_at(pat, path, memo, pat_i + 1, next))
            }
        }
        Some(segment) => {
            path_i < path.len()
                && glob_segment(segment, path[path_i])
                && match_glob_at(pat, path, memo, pat_i + 1, path_i + 1)
        }
    };
    memo[slot] = Some(matched);
    matched
}

fn glob_segment(pat: &str, text: &str) -> bool {
    match_star(pat.as_bytes(), text.as_bytes())
}

/// `*` is the only wildcard. One saved star keeps this linear in the
/// pattern and the text. The recursive split of every star is exponential:
/// twenty stars and a final `z` never returns on a short name.
fn match_star(pat: &[u8], text: &[u8]) -> bool {
    let mut pat_i = 0;
    let mut text_i = 0;
    let mut star_pat: Option<usize> = None;
    let mut star_text = 0;
    while text_i < text.len() {
        if pat_i < pat.len() && pat[pat_i] == b'*' {
            star_pat = Some(pat_i);
            star_text = text_i;
            pat_i += 1;
        } else if pat_i < pat.len() && pat[pat_i] == text[text_i] {
            pat_i += 1;
            text_i += 1;
        } else if let Some(saved) = star_pat {
            star_text += 1;
            text_i = star_text;
            pat_i = saved + 1;
        } else {
            return false;
        }
    }
    while pat_i < pat.len() && pat[pat_i] == b'*' {
        pat_i += 1;
    }
    pat_i == pat.len()
}

#[derive(Debug)]
enum HardlinkHit {
    Allowed,
    Denied { sibling: Option<String> },
}

/// Earliest deny glob wins. Equal globs use the basename so the
/// reported sibling does not follow directory order.
fn denied_basename_rank(
    globs: &[String],
    path: &Path,
    root: Option<&Path>,
) -> Option<(usize, String)> {
    let glob = first_matching_deny_glob_under(globs, &path_as_glob(path), root)?;
    if glob == ".." {
        return None;
    }
    let idx = globs
        .iter()
        .position(|candidate| candidate == &glob)
        .unwrap_or(usize::MAX);
    let base = path.file_name()?.to_string_lossy().into_owned();
    Some((idx, base))
}

fn prefer_sibling(best: Option<(usize, String)>, next: (usize, String)) -> Option<(usize, String)> {
    match best {
        None => Some(next),
        Some((idx, name)) if next.0 < idx || (next.0 == idx && next.1 < name) => Some(next),
        Some(kept) => Some(kept),
    }
}

fn hardlink_sibling_denied(path: &Path, canon: Option<&Path>, policy: &DenyPolicy) -> bool {
    matches!(
        hardlink_sibling_hit(path, canon, policy, None),
        HardlinkHit::Denied { .. }
    )
}

fn hardlink_sibling_hit(
    path: &Path,
    canon: Option<&Path>,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> HardlinkHit {
    #[cfg(unix)]
    {
        hardlink_sibling_hit_unix(path, canon, policy, root)
    }
    #[cfg(windows)]
    {
        hardlink_sibling_hit_windows(path, canon, policy, root)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (path, canon, policy, root);
        HardlinkHit::Allowed
    }
}

#[cfg(unix)]
#[derive(Clone)]
struct SiblingSeen {
    dev: u64,
    ino: u64,
    path: PathBuf,
}

#[cfg(unix)]
#[derive(Clone)]
enum ParentScan {
    Entries(Vec<SiblingSeen>),
    Unreadable,
}

#[cfg(unix)]
enum ParentStep {
    Next,
    Break,
    Deny,
}

#[cfg(unix)]
struct ParentFold {
    step: ParentStep,
    found_add: u64,
    best: Option<(usize, String)>,
}

#[cfg(unix)]
thread_local! {
    static HARDLINK_SCAN_DEPTH: Cell<u32> = const { Cell::new(0) };
    static HARDLINK_PARENT_SCANS: RefCell<Option<HashMap<PathBuf, ParentScan>>> =
        const { RefCell::new(None) };
    static HARDLINK_DIR_READS: Cell<u32> = const { Cell::new(0) };
    #[cfg(test)]
    static TEST_LINK_DIRS: RefCell<Vec<PathBuf>> = const { RefCell::new(Vec::new()) };
}

/// Shares parent-directory hardlink scans for one `run` collect.
/// Nested collects keep the outer map. Dropping the outermost scope
/// drops it, so a later `why` scans its own parent again.
#[cfg(unix)]
pub(crate) struct HardlinkScanScope;

#[cfg(unix)]
impl HardlinkScanScope {
    pub(crate) fn new() -> Self {
        HARDLINK_SCAN_DEPTH.with(|depth| {
            if depth.get() == 0 {
                HARDLINK_PARENT_SCANS.with(|scans| *scans.borrow_mut() = Some(HashMap::new()));
            }
            depth.set(depth.get() + 1);
        });
        Self
    }
}

#[cfg(unix)]
impl Drop for HardlinkScanScope {
    fn drop(&mut self) {
        HARDLINK_SCAN_DEPTH.with(|depth| {
            let next = depth.get().saturating_sub(1);
            depth.set(next);
            if next == 0 {
                HARDLINK_PARENT_SCANS.with(|scans| *scans.borrow_mut() = None);
            }
        });
    }
}

#[cfg(unix)]
fn note_hardlink_dir_read() {
    HARDLINK_DIR_READS.with(|n| n.set(n.get().saturating_add(1)));
}

#[cfg(all(unix, test))]
fn reset_hardlink_dir_reads() {
    HARDLINK_DIR_READS.with(|n| n.set(0));
}

#[cfg(all(unix, test))]
fn hardlink_dir_reads() -> u32 {
    HARDLINK_DIR_READS.with(|n| n.get())
}

#[cfg(unix)]
fn read_parent_siblings(parent: &Path) -> ParentScan {
    use std::os::unix::fs::MetadataExt;

    note_hardlink_dir_read();
    let entries = match std::fs::read_dir(parent) {
        Ok(rd) => rd,
        Err(_) => return ParentScan::Unreadable,
    };
    let mut seen = Vec::new();
    for entry in entries.flatten() {
        let entry_path = entry.path();
        let sibling_meta = match std::fs::symlink_metadata(&entry_path) {
            Ok(meta) => meta,
            Err(_) => continue,
        };
        if sibling_meta.file_type().is_dir() {
            continue;
        }
        seen.push(SiblingSeen {
            dev: sibling_meta.dev(),
            ino: sibling_meta.ino(),
            path: entry_path,
        });
    }
    ParentScan::Entries(seen)
}

#[cfg(unix)]
fn with_parent_siblings<R>(parent: &Path, f: impl FnOnce(&ParentScan) -> R) -> R {
    let in_scope = HARDLINK_PARENT_SCANS.with(|slot| slot.borrow().is_some());
    if !in_scope {
        let scan = read_parent_siblings(parent);
        return f(&scan);
    }
    let hit = HARDLINK_PARENT_SCANS.with(|slot| {
        slot.borrow()
            .as_ref()
            .is_some_and(|map| map.contains_key(parent))
    });
    if hit {
        return HARDLINK_PARENT_SCANS.with(|slot| {
            let borrowed = slot.borrow();
            let scan = borrowed
                .as_ref()
                .and_then(|map| map.get(parent))
                .unwrap_or(&ParentScan::Unreadable);
            f(scan)
        });
    }
    let scan = read_parent_siblings(parent);
    let result = f(&scan);
    HARDLINK_PARENT_SCANS.with(|slot| {
        if let Some(map) = slot.borrow_mut().as_mut() {
            map.insert(parent.to_path_buf(), scan);
        }
    });
    result
}

#[cfg(unix)]
fn hardlink_sibling_hit_unix(
    path: &Path,
    canon: Option<&Path>,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> HardlinkHit {
    use std::os::unix::fs::MetadataExt;

    let meta = match canon
        .map(std::fs::metadata)
        .unwrap_or_else(|| std::fs::symlink_metadata(path))
    {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
            return HardlinkHit::Denied { sibling: None };
        }
        Err(_) => return HardlinkHit::Allowed,
    };
    // Directory nlink counts children, not extra names for this inode.
    if meta.file_type().is_dir() {
        return HardlinkHit::Allowed;
    }
    let nlink = meta.nlink();
    if nlink <= 1 {
        return HardlinkHit::Allowed;
    }
    let mut parents = Vec::new();
    push_scan_parent(&mut parents, path.parent());
    if let Some(c) = canon {
        push_scan_parent(&mut parents, c.parent());
    }
    if parents.is_empty() {
        return HardlinkHit::Denied { sibling: None };
    }
    let mut found = 0u64;
    let mut best: Option<(usize, String)> = None;
    for parent in &parents {
        let folded = fold_link_parent(parent, meta.dev(), meta.ino(), policy, root, best, true);
        found += folded.found_add;
        best = folded.best;
        match folded.step {
            ParentStep::Next => {}
            ParentStep::Break => break,
            ParentStep::Deny => return HardlinkHit::Denied { sibling: None },
        }
    }
    if let Some((_, sibling)) = best {
        return HardlinkHit::Denied {
            sibling: Some(sibling),
        };
    }
    if found < nlink {
        for parent in extra_link_dirs() {
            let key = std::fs::canonicalize(&parent).unwrap_or(parent);
            if parents.iter().any(|seen| seen == &key) {
                continue;
            }
            parents.push(key.clone());
            let folded = fold_link_parent(&key, meta.dev(), meta.ino(), policy, root, best, false);
            found += folded.found_add;
            best = folded.best;
            if best.is_some() || found >= nlink {
                break;
            }
        }
    }
    if let Some((_, sibling)) = best {
        return HardlinkHit::Denied {
            sibling: Some(sibling),
        };
    }
    if found < nlink {
        HardlinkHit::Denied { sibling: None }
    } else {
        HardlinkHit::Allowed
    }
}

/// PATH plus the Ubuntu cargo coreutils multicall directory.
///
/// A multicall `echo` is one inode with a name in `/usr/bin` and another
/// under `/usr/lib/cargo/bin/coreutils`. The parents of one path do not
/// list every name. An unseen name still denies when those directories
/// do not account for `nlink`.
#[cfg(unix)]
fn extra_link_dirs() -> Vec<PathBuf> {
    #[cfg(test)]
    {
        let hooked = TEST_LINK_DIRS.with(|dirs| dirs.borrow().clone());
        if !hooked.is_empty() {
            return hooked;
        }
    }
    let mut dirs = Vec::new();
    if let Some(path) = std::env::var_os("PATH") {
        dirs.extend(std::env::split_paths(&path));
    }
    for extra in [
        "/bin",
        "/usr/bin",
        "/usr/lib/cargo/bin",
        "/usr/lib/cargo/bin/coreutils",
    ] {
        dirs.push(PathBuf::from(extra));
    }
    dirs
}

#[cfg(unix)]
fn fold_link_parent(
    parent: &Path,
    dev: u64,
    ino: u64,
    policy: &DenyPolicy,
    root: Option<&Path>,
    best: Option<(usize, String)>,
    missing_denies: bool,
) -> ParentFold {
    with_parent_siblings(parent, |scan| match scan {
        ParentScan::Unreadable => {
            let step = if missing_denies && best.is_none() {
                ParentStep::Deny
            } else if missing_denies {
                ParentStep::Break
            } else {
                ParentStep::Next
            };
            ParentFold {
                step,
                found_add: 0,
                best,
            }
        }
        ParentScan::Entries(entries) => {
            let mut found_add = 0u64;
            let mut best = best;
            for sibling in entries {
                if sibling.dev != dev || sibling.ino != ino {
                    continue;
                }
                found_add += 1;
                if let Some(rank) = denied_basename_rank(policy.globs(), &sibling.path, root) {
                    best = prefer_sibling(best, rank);
                }
            }
            ParentFold {
                step: ParentStep::Next,
                found_add,
                best,
            }
        }
    })
}

#[cfg(unix)]
fn push_scan_parent(parents: &mut Vec<PathBuf>, parent: Option<&Path>) {
    let parent = match parent {
        Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
        Some(_) => PathBuf::from("."),
        None => return,
    };
    let key = std::fs::canonicalize(&parent).unwrap_or(parent);
    if !parents.iter().any(|p| p == &key) {
        parents.push(key);
    }
}

/// Win32 `ERROR_NO_MORE_FILES` (FindNextFile).
#[cfg(any(windows, test))]
const WIN_ERROR_NO_MORE_FILES: u32 = 18;
/// Win32 `ERROR_HANDLE_EOF` (FindNextFileNameW).
#[cfg(any(windows, test))]
const WIN_ERROR_HANDLE_EOF: u32 = 38;

#[cfg(any(windows, test))]
fn win_find_next_exhausted(err: u32) -> bool {
    err == WIN_ERROR_NO_MORE_FILES || err == WIN_ERROR_HANDLE_EOF
}

/// Dest-deny from NTFS names plus `nNumberOfLinks`.
/// Incomplete listing (`names.len() < nlink`) is HardlinkSibling.
#[cfg(any(windows, test))]
fn hardlink_hit_from_win_names(
    names: &[std::ffi::OsString],
    nlink: u32,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> HardlinkHit {
    if names.len() < nlink as usize {
        return HardlinkHit::Denied { sibling: None };
    }
    if names.len() <= 1 {
        return HardlinkHit::Allowed;
    }
    let mut best: Option<(usize, String)> = None;
    for n in names {
        let s = n.to_string_lossy().replace('\\', "/");
        if let Some(rank) = denied_basename_rank(policy.globs(), Path::new(&s), root) {
            best = prefer_sibling(best, rank);
        }
    }
    if let Some((_, sibling)) = best {
        return HardlinkHit::Denied {
            sibling: Some(sibling),
        };
    }
    HardlinkHit::Allowed
}

/// `MetadataExt::file_index` is unstable (`windows_by_handle`). List names
/// with FindFirstFileNameW instead.
#[cfg(windows)]
fn hardlink_sibling_hit_windows(
    path: &Path,
    canon: Option<&Path>,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> HardlinkHit {
    let probe = canon.unwrap_or(path);
    let meta = match std::fs::metadata(probe) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
            return HardlinkHit::Denied { sibling: None };
        }
        Err(_) => return HardlinkHit::Allowed,
    };
    if meta.is_dir() {
        return HardlinkHit::Allowed;
    }
    let nlink = match win_path_by_handle(probe) {
        Ok(info) => info.nlink,
        Err(_) => return HardlinkHit::Denied { sibling: None },
    };
    match win_hardlink_names(probe) {
        Ok(names) => hardlink_hit_from_win_names(&names, nlink, policy, root),
        Err(_) => HardlinkHit::Denied { sibling: None },
    }
}

#[cfg(windows)]
fn win_hardlink_names(path: &Path) -> std::io::Result<Vec<std::ffi::OsString>> {
    use std::os::windows::ffi::{OsStrExt, OsStringExt};

    type Handle = *mut core::ffi::c_void;
    type Dword = u32;
    const INVALID_HANDLE_VALUE: Handle = -1isize as Handle;
    const ERROR_MORE_DATA: Dword = 234;

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn FindFirstFileNameW(
            lp_file_name: *const u16,
            dw_flags: Dword,
            string_length: *mut Dword,
            link_name: *mut u16,
        ) -> Handle;
        fn FindNextFileNameW(
            h_find_stream: Handle,
            string_length: *mut Dword,
            link_name: *mut u16,
        ) -> i32;
        fn FindClose(h_find_file: Handle) -> i32;
        fn GetLastError() -> Dword;
    }

    struct FindNameHandle(Handle);
    impl Drop for FindNameHandle {
        fn drop(&mut self) {
            if self.0 != INVALID_HANDLE_VALUE {
                // SAFETY: `self.0` came from FindFirstFileNameW.
                unsafe {
                    FindClose(self.0);
                }
                self.0 = INVALID_HANDLE_VALUE;
            }
        }
    }

    fn wide_to_os(buf: &[u16], claimed: usize) -> std::ffi::OsString {
        let end = buf
            .iter()
            .position(|&c| c == 0)
            .unwrap_or(claimed.min(buf.len()));
        std::ffi::OsString::from_wide(&buf[..end])
    }

    let wide: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let mut len: Dword = 256;
    let mut buf = vec![0u16; 256];
    let handle = loop {
        // SAFETY: `wide` is a NUL-terminated path; `buf` is at least `len` units.
        let h = unsafe { FindFirstFileNameW(wide.as_ptr(), 0, &mut len, buf.as_mut_ptr()) };
        if h != INVALID_HANDLE_VALUE {
            break FindNameHandle(h);
        }
        let err = unsafe { GetLastError() };
        if err == ERROR_MORE_DATA {
            buf.resize(len as usize, 0);
            continue;
        }
        return Err(std::io::Error::from_raw_os_error(err as i32));
    };

    let mut names = vec![wide_to_os(&buf, len as usize)];
    loop {
        len = buf.len() as Dword;
        // SAFETY: `handle.0` came from FindFirstFileNameW; `buf` matches `len`.
        let ok = unsafe { FindNextFileNameW(handle.0, &mut len, buf.as_mut_ptr()) };
        if ok == 0 {
            let err = unsafe { GetLastError() };
            if err == ERROR_MORE_DATA {
                buf.resize(len as usize, 0);
                continue;
            }
            if win_find_next_exhausted(err) {
                break;
            }
            return Err(std::io::Error::from_raw_os_error(err as i32));
        }
        names.push(wide_to_os(&buf, len as usize));
    }
    Ok(names)
}

#[cfg(windows)]
struct WinHandleInfo {
    volume: u32,
    index: u64,
    nlink: u32,
}

#[cfg(windows)]
fn win_path_by_handle(path: &Path) -> std::io::Result<WinHandleInfo> {
    use std::os::windows::ffi::OsStrExt;

    type Handle = *mut core::ffi::c_void;
    type Dword = u32;
    const INVALID_HANDLE_VALUE: Handle = -1isize as Handle;
    const FILE_READ_ATTRIBUTES: Dword = 0x0080;
    const FILE_SHARE_READ: Dword = 0x0001;
    const FILE_SHARE_WRITE: Dword = 0x0002;
    const FILE_SHARE_DELETE: Dword = 0x0004;
    const OPEN_EXISTING: Dword = 3;
    const FILE_FLAG_BACKUP_SEMANTICS: Dword = 0x0200_0000;
    const FILE_FLAG_OPEN_REPARSE_POINT: Dword = 0x0020_0000;

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn CreateFileW(
            lp_file_name: *const u16,
            dw_desired_access: Dword,
            dw_share_mode: Dword,
            lp_security_attributes: *mut core::ffi::c_void,
            dw_creation_disposition: Dword,
            dw_flags_and_attributes: Dword,
            h_template_file: Handle,
        ) -> Handle;
        fn CloseHandle(h_object: Handle) -> i32;
        fn GetLastError() -> Dword;
    }

    let wide: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    // SAFETY: `wide` is a NUL-terminated path.
    let handle = unsafe {
        CreateFileW(
            wide.as_ptr(),
            FILE_READ_ATTRIBUTES,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            core::ptr::null_mut(),
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
            core::ptr::null_mut(),
        )
    };
    if handle == INVALID_HANDLE_VALUE {
        let err = unsafe { GetLastError() };
        return Err(std::io::Error::from_raw_os_error(err as i32));
    }
    let info = win_handle_info(handle);
    unsafe {
        CloseHandle(handle);
    }
    info
}

#[cfg(windows)]
fn win_handle_info(handle: *mut core::ffi::c_void) -> std::io::Result<WinHandleInfo> {
    type Dword = u32;

    #[repr(C)]
    struct ByHandleFileInformation {
        dw_file_attributes: Dword,
        ft_creation_time_lo: Dword,
        ft_creation_time_hi: Dword,
        ft_last_access_time_lo: Dword,
        ft_last_access_time_hi: Dword,
        ft_last_write_time_lo: Dword,
        ft_last_write_time_hi: Dword,
        dw_volume_serial_number: Dword,
        n_file_size_high: Dword,
        n_file_size_low: Dword,
        n_number_of_links: Dword,
        n_file_index_high: Dword,
        n_file_index_low: Dword,
    }

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn GetFileInformationByHandle(
            h_file: *mut core::ffi::c_void,
            lp_file_information: *mut ByHandleFileInformation,
        ) -> i32;
        fn GetLastError() -> Dword;
    }

    let mut info = ByHandleFileInformation {
        dw_file_attributes: 0,
        ft_creation_time_lo: 0,
        ft_creation_time_hi: 0,
        ft_last_access_time_lo: 0,
        ft_last_access_time_hi: 0,
        ft_last_write_time_lo: 0,
        ft_last_write_time_hi: 0,
        dw_volume_serial_number: 0,
        n_file_size_high: 0,
        n_file_size_low: 0,
        n_number_of_links: 0,
        n_file_index_high: 0,
        n_file_index_low: 0,
    };
    // SAFETY: `handle` is an open file handle; `info` is the Win32 layout.
    let ok = unsafe { GetFileInformationByHandle(handle, &mut info) };
    if ok == 0 {
        let err = unsafe { GetLastError() };
        return Err(std::io::Error::from_raw_os_error(err as i32));
    }
    Ok(WinHandleInfo {
        volume: info.dw_volume_serial_number,
        index: (u64::from(info.n_file_index_high) << 32) | u64::from(info.n_file_index_low),
        nlink: info.n_number_of_links,
    })
}

fn peel_shell_meta(s: &str) -> &str {
    s.trim_matches(|c: char| matches!(c, ';' | '|' | '&' | ')' | '(' | '<' | '>' | '`' | ','))
}

fn peel_shell_parts(s: &str) -> impl Iterator<Item = &str> {
    s.split([';', '|', '&', ')', '(', '<', '>', '`', ','])
        .map(peel_shell_meta)
        .filter(|p| !p.is_empty())
}

fn candidate_is_denied(candidate: &str, policy: &DenyPolicy) -> bool {
    for peeled in peel_shell_parts(candidate) {
        if peeled.starts_with('-') {
            continue;
        }
        if is_path_denied(Path::new(peeled), policy) {
            return true;
        }
        if let Some(value) = assignment_dest_value(peeled)
            && is_path_denied(Path::new(value), policy)
        {
            return true;
        }
        if let Some((_, after)) = peeled.rsplit_once(':') {
            let after = peel_shell_meta(after);
            if !after.is_empty()
                && !after.starts_with('-')
                && is_path_denied(Path::new(after), policy)
            {
                return true;
            }
        }
    }
    false
}

fn command_path_tokens(command: &str) -> Vec<(String, String)> {
    let mut out = Vec::new();
    collect_function_calls(command, &mut out);
    collect_quoted_and_words(command, &mut out);
    out
}

fn collect_function_calls(s: &str, out: &mut Vec<(String, String)>) {
    let mut pos = 0;
    while let Some((end, display, path)) = next_function_call(s, pos) {
        out.push((display, path));
        pos = end;
    }
}

fn next_function_call(s: &str, from: usize) -> Option<(usize, String, String)> {
    let bytes = s.as_bytes();
    let mut i = from;
    while i < bytes.len() {
        if is_ident_start(bytes[i]) {
            let start = i;
            i += 1;
            while i < bytes.len() && is_ident_cont(bytes[i]) {
                i += 1;
            }
            let ident_end = i;
            while i < bytes.len() && bytes[i].is_ascii_whitespace() {
                i += 1;
            }
            if i < bytes.len() && bytes[i] == b'(' {
                i += 1;
                while i < bytes.len() && bytes[i].is_ascii_whitespace() {
                    i += 1;
                }
                if i < bytes.len() && (bytes[i] == b'\'' || bytes[i] == b'"') {
                    let q = bytes[i];
                    i += 1;
                    let path_start = i;
                    while i < bytes.len() && bytes[i] != q {
                        i += 1;
                    }
                    if i < bytes.len() && bytes[i] == q {
                        let path = s[path_start..i].to_string();
                        i += 1;
                        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
                            i += 1;
                        }
                        if i < bytes.len() && bytes[i] == b')' {
                            i += 1;
                            let display = s[start..i].to_string();
                            return Some((i, display, path));
                        }
                    }
                }
            }
            i = ident_end.max(start + 1);
            continue;
        }
        i += 1;
    }
    None
}

fn is_ident_start(b: u8) -> bool {
    b.is_ascii_alphabetic() || b == b'_'
}

fn is_ident_cont(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

fn collect_quoted_and_words(s: &str, out: &mut Vec<(String, String)>) {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i].is_ascii_whitespace() {
            i += 1;
            continue;
        }
        if bytes[i] == b'\'' || bytes[i] == b'"' {
            let q = bytes[i];
            i += 1;
            let start = i;
            while i < bytes.len() && bytes[i] != q {
                i += 1;
            }
            let inner = &s[start..i];
            if i < bytes.len() {
                i += 1;
            }
            collect_function_calls(inner, out);
            collect_quoted_and_words(inner, out);
            out.push((inner.to_string(), inner.to_string()));
            continue;
        }
        let start = i;
        while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        let raw = &s[start..i];
        let peeled = peel_shell_meta(raw);
        out.push((raw.to_string(), peeled.to_string()));
        if let Some((_, after)) = peeled.rsplit_once(':') {
            out.push((raw.to_string(), after.to_string()));
        }
    }
}

/// v1 list is byte-identical to Bline `default_secret_denies()`.
/// Do not add `**/.azure/**` or `**/.config/gh/**`.
pub fn default_secret_denies() -> Vec<String> {
    vec![
        "**/.env".into(),
        "**/.env.*".into(),
        "**/*.pem".into(),
        "**/*.key".into(),
        "**/*.p12".into(),
        "**/*.pfx".into(),
        "**/id_rsa".into(),
        "**/id_ed25519".into(),
        "**/id_ecdsa".into(),
        "**/id_dsa".into(),
        "**/id_eddsa".into(),
        "**/.npmrc".into(),
        "**/.pypirc".into(),
        "**/.docker/config.json".into(),
        "**/kubeconfig".into(),
        "**/.kube/config".into(),
        "**/secrets.json".into(),
        "**/service-account*.json".into(),
        "**/.ssh/**".into(),
        "**/token.json".into(),
        "**/secring.gpg".into(),
        "**/.gnupg/private-keys-v1.d/**".into(),
        "**/credentials.json".into(),
        "**/.aws/credentials".into(),
        "**/.netrc".into(),
        "**/secrets/**".into(),
        "**/credentials/**".into(),
        "**/gateway/pairing.json".into(),
        "**/auth.json".into(),
        "**/auth-*.json".into(),
    ]
}

#[cfg(test)]
mod classify_hardlink_tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn hardlink_denied_when_canon_is_missing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let env = dir.path().join(".env");
        std::fs::write(&env, "API_KEY=secret\n").expect("write .env");
        let sibling = dir.path().join("notes.txt");
        std::fs::hard_link(&env, &sibling).expect("hardlink");
        let policy = DenyPolicy::default();
        assert!(
            hardlink_sibling_denied(&sibling, None, &policy),
            "nlink > 1 must dest-deny when canonicalize is unavailable"
        );
        assert!(!hardlink_sibling_denied(
            Path::new("no-such-workpen-hardlink-xyz"),
            None,
            &policy
        ));
    }

    #[cfg(unix)]
    #[test]
    fn hardlink_directory_is_scanned_once_inside_a_collect_scope() {
        let dir = tempfile::tempdir().expect("tempdir");
        let plain = dir.path().join("plain.txt");
        std::fs::write(&plain, b"ok").expect("plain");
        for i in 0..24 {
            std::fs::hard_link(&plain, dir.path().join(format!("link-{i}"))).expect("link");
        }
        std::fs::hard_link(&plain, dir.path().join(".env")).expect("secret name");
        let policy = DenyPolicy::default();
        reset_hardlink_dir_reads();
        {
            let _scope = HardlinkScanScope::new();
            for i in 0..24 {
                let path = dir.path().join(format!("link-{i}"));
                assert!(
                    hardlink_sibling_denied(&path, None, &policy),
                    "link-{i} shares an inode with .env"
                );
            }
        }
        let scoped = hardlink_dir_reads();
        assert!(
            scoped <= 2,
            "one collect scans the directory once, got {scoped}"
        );
        // A slash glob that is not `**/` is suppressed while the path is
        // outside `root`, and matches the absolute path with no root.
        // The cached directory must be ranked again for that second root.
        // The scan stores the canonical parent, so the glob uses that spelling.
        let outside = tempfile::tempdir().expect("outside root");
        let canon_dir = std::fs::canonicalize(dir.path()).expect("canon dir");
        let slash = path_as_glob(&canon_dir.join(".env"));
        let custom = DenyPolicy::new(vec![slash]);
        reset_hardlink_dir_reads();
        {
            let _scope = HardlinkScanScope::new();
            assert!(
                classify_dest_hit_root(&plain, &custom, Some(outside.path())).is_none(),
                "outside a non-** slash glob the hardlink is not a secret yet"
            );
            let reads = hardlink_dir_reads();
            assert!(
                classify_dest_hit_root(&plain, &custom, None).is_some(),
                "the same scan must dest-deny plain.txt once the root is unset"
            );
            assert_eq!(
                hardlink_dir_reads(),
                reads,
                "the second root reuses the directory read"
            );
        }
        reset_hardlink_dir_reads();
        for i in 0..24 {
            let path = dir.path().join(format!("link-{i}"));
            assert!(hardlink_sibling_denied(&path, None, &policy));
        }
        let unscoped = hardlink_dir_reads();
        assert!(
            unscoped >= 24,
            "without a collect scope each name scans the directory, got {unscoped}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn multicall_names_in_another_directory_are_not_a_denied_sibling() {
        let dir = tempfile::tempdir().expect("tempdir");
        let lib = dir.path().join("coreutils");
        let bin = dir.path().join("bin");
        std::fs::create_dir(&lib).expect("lib");
        std::fs::create_dir(&bin).expect("bin");
        let echo_lib = lib.join("echo");
        std::fs::write(&echo_lib, b"echo").expect("echo");
        std::fs::hard_link(&echo_lib, lib.join("sleep")).expect("sleep");
        std::fs::hard_link(&echo_lib, lib.join("printenv")).expect("printenv");
        let echo_bin = bin.join("echo");
        std::fs::hard_link(&echo_lib, &echo_bin).expect("bin echo");
        let policy = DenyPolicy::default();
        assert_eq!(
            classify_dest(&echo_bin, &policy),
            Some(DestDenyKind::HardlinkSibling),
            "unseen multicall names must still fail closed"
        );
        TEST_LINK_DIRS.with(|dirs| dirs.borrow_mut().push(lib.clone()));
        struct ClearHook;
        impl Drop for ClearHook {
            fn drop(&mut self) {
                TEST_LINK_DIRS.with(|dirs| dirs.borrow_mut().clear());
            }
        }
        let _clear = ClearHook;
        assert_eq!(
            classify_dest(&echo_bin, &policy),
            None,
            "scanning the other multicall directory must allow echo"
        );
        std::fs::hard_link(&echo_lib, lib.join(".env")).expect("secret name");
        assert_eq!(
            classify_dest(&echo_bin, &policy),
            Some(DestDenyKind::HardlinkSibling),
            "a .env name on the multicall inode must stay denied"
        );
    }

    #[cfg(unix)]
    #[test]
    fn program_link_dirs_include_cargo_coreutils() {
        let dirs = extra_link_dirs();
        assert!(
            dirs.iter()
                .any(|dir| dir == Path::new("/usr/lib/cargo/bin/coreutils")),
            "ubuntu multicall dir missing from the hardlink scan"
        );
    }

    #[test]
    fn win_find_next_exhausted_is_eof_not_other_errors() {
        assert!(win_find_next_exhausted(WIN_ERROR_NO_MORE_FILES));
        assert!(win_find_next_exhausted(WIN_ERROR_HANDLE_EOF));
        assert!(!win_find_next_exhausted(5));
        assert!(!win_find_next_exhausted(234));
    }

    #[test]
    fn win_names_shorter_than_nlink_is_hardlink_sibling() {
        let policy = DenyPolicy::default();
        let names = [std::ffi::OsString::from(r"C:\ws\notes.txt")];
        match hardlink_hit_from_win_names(&names, 2, &policy, None) {
            HardlinkHit::Denied { sibling: None } => {}
            other => panic!("incomplete name list must deny, got {other:?}"),
        }
    }

    #[test]
    fn win_names_matching_nlink_without_deny_glob_is_allowed() {
        let policy = DenyPolicy::default();
        let names = [std::ffi::OsString::from(r"C:\ws\notes.txt")];
        match hardlink_hit_from_win_names(&names, 1, &policy, None) {
            HardlinkHit::Allowed => {}
            other => panic!("single name and nlink 1 must allow, got {other:?}"),
        }
        let two = [
            std::ffi::OsString::from(r"C:\ws\a.txt"),
            std::ffi::OsString::from(r"C:\ws\b.txt"),
        ];
        match hardlink_hit_from_win_names(&two, 2, &policy, None) {
            HardlinkHit::Allowed => {}
            other => panic!("listed names with no deny glob must allow, got {other:?}"),
        }
    }

    #[test]
    fn win_names_denied_glob_reports_sibling_basename() {
        let policy = DenyPolicy::default();
        let names = [
            std::ffi::OsString::from(r"C:\ws\.env"),
            std::ffi::OsString::from(r"C:\ws\notes.txt"),
        ];
        match hardlink_hit_from_win_names(&names, 2, &policy, None) {
            HardlinkHit::Denied {
                sibling: Some(name),
            } => assert_eq!(name, ".env"),
            other => panic!("hardlink of .env must name sibling, got {other:?}"),
        }
    }

    #[test]
    fn win_names_prefer_earlier_deny_glob_over_list_order() {
        let policy = DenyPolicy::default();
        let names = [
            std::ffi::OsString::from(r"C:\ws\.env.example-link"),
            std::ffi::OsString::from(r"C:\ws\notes.txt"),
            std::ffi::OsString::from(r"C:\ws\.env"),
        ];
        match hardlink_hit_from_win_names(&names, 3, &policy, None) {
            HardlinkHit::Denied {
                sibling: Some(name),
            } => assert_eq!(name, ".env"),
            other => panic!("earlier deny glob must win, got {other:?}"),
        }
    }
}