workpen 0.7.7

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
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
//! Process-jail wrap. Feature `nono`.
//!
//! Unix uses pinned nono (Landlock / Seatbelt). Windows uses a
//! write-restricted token. Never grant filesystem root (`/` or a
//! Windows drive root) or the current user's home directory. Inspect
//! [`KernelPolicy::grants`]; do not parse nono internals. Do not call
//! [`KernelPolicy::apply`] from unit tests (`Sandbox::apply_auto` is
//! irreversible). [`KernelPolicy::apply_pre_exec`] only installs a Unix
//! child hook. Hosts that need a jail on every OS call
//! [`KernelPolicy::run_child`], which errors instead of spawning when
//! the kernel cannot apply. The default crate (`default = []`) does not
//! compile this module. nono is pinned with `default-features = false`.
//! That build does not depend on `reqwest`. nono still depends on
//! `sigstore-verify`, which links `aws-lc-sys`. There is no nono feature
//! that drops `aws-lc-sys`. Do not enable nono's default features, and
//! do not fork nono.

use std::ffi::{OsStr, OsString};
#[cfg(unix)]
use std::os::fd::AsRawFd;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};
#[cfg(unix)]
use std::sync::Arc;
#[cfg(unix)]
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
#[cfg(unix)]
use std::time::Instant;

use crate::deny::{
    CheckDestError, DenyPolicy, DestDeny, DestDenyKind, dest_deny_at, dest_deny_at_root,
    dest_deny_glob_only,
};

#[cfg(target_os = "linux")]
mod linux;
#[cfg(unix)]
mod pty;
#[cfg(unix)]
mod reaper;
#[cfg(windows)]
mod windows;

/// Access granted for one path. Hosts branch on this; do not parse messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KernelAccess {
    Read,
    ReadWrite,
}

/// One grant we will hand to the kernel backend.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KernelGrant {
    pub path: PathBuf,
    pub access: KernelAccess,
}

/// Process-jail policy. Workspace RW, extra roots RW, existing system dirs Read.
///
/// Dest-deny names are a second list, not a grant of `/`. Linux Landlock
/// cannot dest-deny a file inside an allowed tree
/// ([nono #1592](https://github.com/nolabs-ai/nono/discussions/1592)).
/// macOS `run_child` applies Seatbelt `(deny file-read* / file-write* /
/// network-outbound)` literals (and `subpath` for directories) via nono
/// `add_platform_rule`. `network-outbound` covers `connect(2)` to a Unix
/// socket, which Seatbelt does not treat as a file operation.
/// Linux `run_child` bind-overs dest-deny paths in a private mount ns
/// when unprivileged user namespaces are available. If `unshare` is
/// denied, remount is skipped and Landlock still applies (in-tree
/// dest-deny stays a hole). Windows `run_child` adds a DENY ACE on
/// dest-deny paths for the Restricted SID.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KernelPolicy {
    grants: Vec<KernelGrant>,
    dest_denies: Vec<DestDeny>,
    deny_policy: DenyPolicy,
    network_blocked: bool,
    /// Read by [`Self::require_spawn`] on Unix. Windows has no remount.
    #[cfg_attr(not(unix), allow(dead_code))]
    require_dest_hide: bool,
}

/// Result of applying the jail. Hosts match the variant, not English.
///
/// New variants are breaking for exhaustive hosts even in 0.x. See
/// [`crate::threat_model`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KernelApply {
    /// Kernel jail is active in this process, or hooked/spawned for the child.
    /// Linux remount ran when dest-deny paths existed. Windows WFP ran
    /// when [`KernelPolicy::network_blocked`] and the token could add
    /// filters.
    Applied,
    /// Landlock/Seatbelt applied. Dest-deny remount was skipped
    /// (unshare / maps / `MS_PRIVATE` denied). In-tree dest-deny is
    /// userspace argv only. Extra-root dests still fail-closed.
    RemountSkipped,
    /// Write-restricted token and AppContainer applied. WFP filters
    /// were skipped (`ERROR_ACCESS_DENIED`, win32 5). AppContainer
    /// network deny is still on.
    WfpSkipped,
    /// Platform has no kernel backend. Userspace dest-deny + PathGuard only.
    UserspaceOnly,
}

/// Hosts match the variant, not English. New variants are breaking
/// for exhaustive hosts even in 0.x.
#[derive(Debug, thiserror::Error)]
pub enum KernelError {
    #[error("kernel wrap root is not usable: {0}")]
    Root(String),
    #[error("kernel wrap refused filesystem root {0}; use a subdirectory, not `/`")]
    FsRoot(PathBuf),
    #[error("kernel wrap refused home directory {0}; use a project subdirectory, not $HOME")]
    Home(PathBuf),
    #[error("kernel wrap apply failed: {0}")]
    Apply(String),
    /// Argv dest-deny before spawn. Hosts match [`CheckDestError`] /
    /// [`crate::DestDenyError`], not English.
    #[error("kernel wrap dest-deny: {0}")]
    DestDeny(#[from] CheckDestError),
    /// The child was killed after the deadline.
    #[error("kernel wrap child was killed after the deadline")]
    Timeout,
    /// Child finished; DACL restore failed. Hosts match this, not English.
    #[error("kernel wrap restore failed: {0}")]
    Restore(String),
    /// A descendant pid did not fit in the recorded set, or macOS left
    /// a recorded pid running. macOS also returns this when a live
    /// session leader with the command's name is outside that set.
    /// That session leader called `setsid`.
    /// [`KernelPolicy::run_child`] returns this instead of the child
    /// status. Hosts that spawn after [`KernelPolicy::apply_pre_exec`]
    /// get it from [`KernelPolicy::finish_pre_exec`] on that same thread.
    /// Hosts that wait on another thread, including after `.await`, get
    /// it from [`PreExecReport::finish`]. The CLI exits 4.
    #[error("kernel wrap did not track every descendant")]
    Descendants,
}

/// Owns the reaper report for one [`KernelPolicy::apply_pre_exec_report`].
///
/// `Send`, so the host can move it across an `.await` or onto another
/// thread with the child wait. [`Self::finish`] reads the pipe.
/// [`Self::discard`] and `Drop` close it, so a cancelled task does not
/// leave the descriptor open. This value is not the thread-local report
/// used by [`KernelPolicy::finish_pre_exec`].
#[must_use = "finish the report or drop it to close the reaper pipe"]
pub struct PreExecReport {
    #[cfg(unix)]
    pipe: reaper::ReportPipe,
    #[cfg(not(unix))]
    _private: (),
}

impl PreExecReport {
    #[cfg(unix)]
    fn from_pipe(pipe: reaper::ReportPipe) -> Self {
        Self { pipe }
    }

    fn unarmed() -> Self {
        #[cfg(unix)]
        {
            Self {
                pipe: reaper::unarmed_report(),
            }
        }
        #[cfg(not(unix))]
        {
            Self { _private: () }
        }
    }

    /// Keep an armed pipe for [`KernelPolicy::finish_pre_exec`].
    /// An unarmed pipe is not a report, so it is not stored.
    fn stash(self) {
        #[cfg(unix)]
        {
            let pipe = self.pipe;
            if pipe.armed {
                reaper::stash_report(pipe);
            }
        }
        #[cfg(not(unix))]
        {
            let _ = self;
        }
    }

    /// Read the descendant report.
    ///
    /// `Ok(status)` means every descendant was tracked, or no reaper was
    /// installed. [`KernelError::Descendants`] means the reaper reported
    /// a miss, the pipe was missing, or it wrote nothing. Pass
    /// `timed_out: true` when the host deadline already fired. The
    /// deadline wins and this returns `Ok(status)`.
    pub fn finish(self, status: ExitStatus, timed_out: bool) -> Result<ExitStatus, KernelError> {
        #[cfg(unix)]
        {
            if self.pipe.tracked(timed_out) {
                Ok(status)
            } else {
                Err(KernelError::Descendants)
            }
        }
        #[cfg(not(unix))]
        {
            let _ = (self, timed_out);
            Ok(status)
        }
    }

    /// Close the reaper pipe without reading it.
    ///
    /// Same as dropping the report. Use this when spawn failed.
    pub fn discard(self) {
        drop(self);
    }
}

/// Merge spawn and DACL-restore results. Timeout stays Timeout.
/// A successful child plus restore failure is Restore that names the exit.
#[cfg(any(windows, test))]
pub(crate) fn combine_spawn_restore(
    result: Result<(KernelApply, ExitStatus), KernelError>,
    restore: Result<(), KernelError>,
) -> Result<(KernelApply, ExitStatus), KernelError> {
    match (result, restore) {
        (ok, Ok(())) => ok,
        (Err(KernelError::Timeout), Err(_)) => Err(KernelError::Timeout),
        (Err(spawn), Err(restore_err)) => Err(KernelError::Apply(format!(
            "{}; {}",
            apply_detail(&spawn),
            apply_detail(&restore_err)
        ))),
        (Ok((_, status)), Err(restore_err)) => {
            let code = status
                .code()
                .map(|c| c.to_string())
                .unwrap_or_else(|| "signal".into());
            Err(KernelError::Restore(format!(
                "child exited {code}; {}",
                apply_detail(&restore_err)
            )))
        }
    }
}

#[cfg(any(windows, test))]
fn apply_detail(err: &KernelError) -> String {
    match err {
        KernelError::Apply(msg) | KernelError::Restore(msg) => msg.clone(),
        KernelError::DestDeny(err) => err.to_string(),
        other => other.to_string(),
    }
}

/// Drain stdout/stderr on helper threads while waiting so a chatty child
/// cannot fill the pipe (~64KiB) and block until the deadline.
///
/// The bool is `timed_out`. Deadline still returns the drained bytes so
/// callers can write them before GNU timeout 124. [`KernelError::Timeout`]
/// stays a unit variant on [`KernelPolicy::run_child_timeout`].
/// The child is an unreaped zombie (`WNOWAIT`), so its pid cannot be
/// recycled. Signal its process group before the reap when this pid
/// leads that group. A `setsid` grandchild is stopped by the pre_exec
/// reaper, not by this `killpg`.
#[cfg(unix)]
fn kill_group_if_zombie(pid: libc::pid_t) -> bool {
    let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
    let rc = unsafe {
        libc::waitid(
            libc::P_PID,
            pid as libc::id_t,
            &mut info,
            libc::WEXITED | libc::WNOWAIT | libc::WNOHANG,
        )
    };
    if rc != 0 || info.si_signo != libc::SIGCHLD {
        return false;
    }
    if reaper::is_group_leader(pid) {
        unsafe {
            libc::killpg(pid, libc::SIGKILL);
        }
    }
    true
}

/// Wait until the direct child exits or `timeout` elapses, then signal
/// its process group. `true` means the deadline fired.
#[cfg(unix)]
fn reap_process_group(
    child: &mut std::process::Child,
    timeout: Option<Duration>,
) -> Result<(ExitStatus, bool), KernelError> {
    use std::time::Instant;

    let pid = child.id() as libc::pid_t;
    let deadline = match timeout {
        None => None,
        Some(limit) => match timeout_deadline(limit) {
            Ok(end) => Some(end),
            Err(err) => {
                unsafe {
                    libc::kill(pid, libc::SIGKILL);
                }
                if reaper::is_group_leader(pid) {
                    unsafe {
                        libc::killpg(pid, libc::SIGKILL);
                    }
                }
                let _ = wait_reaped(child);
                reaper::discard_report();
                return Err(err);
            }
        },
    };
    loop {
        if kill_group_if_zombie(pid) {
            let status = wait_reaped(child)?;
            return finish_reap(status, false);
        }
        if deadline.is_some_and(|end| Instant::now() >= end) {
            // Ask the reaper to kill the command and any `setsid`
            // descendant, then exit. SIGKILL would skip that cleanup.
            unsafe {
                libc::kill(pid, libc::SIGTERM);
            }
            let grace = Instant::now() + Duration::from_millis(300);
            loop {
                if kill_group_if_zombie(pid) {
                    let status = wait_reaped(child)?;
                    return finish_reap(status, true);
                }
                if Instant::now() >= grace {
                    unsafe {
                        libc::kill(pid, libc::SIGKILL);
                    }
                    if reaper::is_group_leader(pid) {
                        unsafe {
                            libc::killpg(pid, libc::SIGKILL);
                        }
                    }
                    let status = wait_reaped(child)?;
                    return finish_reap(status, true);
                }
                std::thread::sleep(Duration::from_millis(10));
            }
        }
        std::thread::sleep(Duration::from_millis(10));
    }
}

/// `Instant + duration` panics when the sum does not fit.
#[cfg(unix)]
fn timeout_deadline(limit: Duration) -> Result<std::time::Instant, KernelError> {
    std::time::Instant::now()
        .checked_add(limit)
        .ok_or_else(|| KernelError::Apply("timeout does not fit on the clock".into()))
}

#[cfg(unix)]
fn wait_reaped(child: &mut std::process::Child) -> Result<ExitStatus, KernelError> {
    child.wait().map_err(|err| {
        reaper::discard_report();
        KernelError::Apply(err.to_string())
    })
}

#[cfg(unix)]
fn finish_reap(status: ExitStatus, timed_out: bool) -> Result<(ExitStatus, bool), KernelError> {
    let outcome = reaper::take_report(timed_out);
    if outcome == reaper::ReportOutcome::Miss {
        return Err(KernelError::Descendants);
    }
    let timed_out = timed_out || outcome == reaper::ReportOutcome::PreexecDeadline;
    Ok((status, timed_out))
}

#[cfg(unix)]
fn spawn_jailed(cmd: &mut Command) -> Result<std::process::Child, KernelError> {
    spawn_jailed_deadline(cmd, None)
}

/// `timeout` is copied into the forked reaper so a pre-exec stall
/// cannot outlive it. The guard drops on this thread after spawn.
#[cfg(unix)]
fn spawn_jailed_deadline(
    cmd: &mut Command,
    timeout: Option<Duration>,
) -> Result<std::process::Child, KernelError> {
    let _guard = timeout.map(reaper::arm_spawn_deadline);
    match cmd.spawn() {
        Ok(child) => {
            reaper::close_parent_report_write();
            Ok(child)
        }
        Err(err) => {
            reaper::discard_report();
            Err(KernelError::Apply(err.to_string()))
        }
    }
}

#[cfg(unix)]
fn wait_until_deadline(
    child: &mut std::process::Child,
    timeout: Duration,
) -> Result<(ExitStatus, bool), KernelError> {
    reap_process_group(child, Some(timeout))
}

#[cfg(unix)]
fn wait_child_timeout_output(
    mut child: std::process::Child,
    timeout: Duration,
) -> Result<(std::process::Output, bool), KernelError> {
    let stdout = child.stdout.take().map(drain_pipe);
    let stderr = child.stderr.take().map(drain_pipe);
    let (status, timed_out) = wait_until_deadline(&mut child, timeout)?;
    Ok((
        std::process::Output {
            status,
            stdout: join_drain(stdout),
            stderr: join_drain(stderr),
        },
        timed_out,
    ))
}

/// Copy child pipes to this process as bytes arrive. No unbounded `Vec`.
#[cfg(unix)]
fn wait_child_timeout_forward(
    mut child: std::process::Child,
    timeout: Duration,
) -> Result<(std::process::ExitStatus, bool), KernelError> {
    let started = Instant::now();
    let stop = forward_stop();
    let stdout = child
        .stdout
        .take()
        .map(|p| copy_pipe(p, std::io::stdout(), Arc::clone(&stop)));
    let stderr = child
        .stderr
        .take()
        .map(|p| copy_pipe(p, std::io::stderr(), Arc::clone(&stop)));
    let (status, mut timed_out) = wait_until_deadline(&mut child, timeout)?;
    // The child can exit while the last chunk is still stuck on a
    // reader that stopped. Joining that write would ignore the deadline.
    if finish_copies(&stop, stdout, stderr, started + timeout) {
        timed_out = true;
    }
    Ok((status, timed_out))
}

#[cfg(unix)]
fn drain_pipe(mut pipe: impl std::io::Read + Send + 'static) -> std::thread::JoinHandle<Vec<u8>> {
    std::thread::spawn(move || {
        let mut buf = Vec::new();
        let _ = std::io::Read::read_to_end(&mut pipe, &mut buf);
        buf
    })
}

#[cfg(unix)]
fn forward_stop() -> Arc<AtomicBool> {
    Arc::new(AtomicBool::new(false))
}

/// Stdout's buffer flushes 8KiB. Linux also reports `POLLOUT` when a
/// single byte is free, so a blocking `PIPE_BUF` write can still wait.
#[cfg(unix)]
fn forward_chunk(fd: std::os::fd::RawFd) -> usize {
    let mut stat = unsafe { std::mem::zeroed::<libc::stat>() };
    // SAFETY: stat is a live object. A regular file never blocks a
    // short write, so the copy can keep the previous 16KiB chunk.
    let rc = unsafe { libc::fstat(fd, &mut stat) };
    if rc == 0 && stat.st_mode & libc::S_IFMT == libc::S_IFREG {
        16 * 1024
    } else {
        512
    }
}

#[cfg(unix)]
enum PollOut {
    Ready,
    Later,
    Stop,
}

/// One poll. `Later` means the caller should drop any write lock and
/// try again, so the other stream can use the pipe.
#[cfg(unix)]
fn poll_out_once(fd: std::os::fd::RawFd, stop: &AtomicBool) -> PollOut {
    if stop.load(Ordering::Relaxed) {
        return PollOut::Stop;
    }
    let mut poll_fd = libc::pollfd {
        fd,
        events: libc::POLLOUT,
        revents: 0,
    };
    // SAFETY: poll_fd is a live one-slot array. The 50ms cap lets the
    // deadline flag win over a reader that stopped.
    let rc = unsafe { libc::poll(&mut poll_fd, 1, 50) };
    if stop.load(Ordering::Relaxed) {
        return PollOut::Stop;
    }
    if rc == 0 {
        return PollOut::Later;
    }
    if rc < 0 {
        let err = std::io::Error::last_os_error();
        if err.kind() == std::io::ErrorKind::Interrupted {
            return PollOut::Later;
        }
        return PollOut::Stop;
    }
    // macOS kqueue reports `POLLNVAL` for `/dev/null`. The write itself
    // still succeeds, so treat that as writable.
    if poll_fd.revents & (libc::POLLNVAL | libc::POLLOUT) != 0 {
        return PollOut::Ready;
    }
    let bad = libc::POLLERR | libc::POLLHUP;
    if poll_fd.revents & bad != 0 {
        return PollOut::Stop;
    }
    PollOut::Later
}

/// The deadline line. A full `2>&1` pipe must not block this write.
pub fn write_timeout_notice() {
    #[cfg(not(unix))]
    {
        eprintln!("child killed after the deadline");
    }
    #[cfg(unix)]
    {
        let msg = b"child killed after the deadline\n";
        let fd = std::io::stderr().as_raw_fd();
        // SAFETY: stderr is open for the life of the process.
        if unsafe { libc::isatty(fd) } == 1 {
            eprintln!("child killed after the deadline");
            return;
        }
        let idle = AtomicBool::new(false);
        for &byte in msg {
            if !matches!(poll_out_once(fd, &idle), PollOut::Ready) {
                return;
            }
            let buf = [byte];
            // SAFETY: `buf` is one live byte.
            let rc = unsafe { libc::write(fd, buf.as_ptr().cast(), 1) };
            if rc <= 0 {
                return;
            }
        }
    }
}

#[cfg(unix)]
enum ForwardWrite {
    Wrote(usize),
    /// `O_NONBLOCK` refused the write. The pipe has some space, not enough
    /// for this chunk. Callers must wait before retrying the same bytes.
    Again,
}

/// One `write`. `EINTR` retries. `WouldBlock` asks the caller to wait.
#[cfg(unix)]
fn write_once(fd: std::os::fd::RawFd, buf: &[u8]) -> Option<ForwardWrite> {
    loop {
        // SAFETY: `buf` is a live slice. The length is the byte count.
        let rc = unsafe { libc::write(fd, buf.as_ptr().cast(), buf.len()) };
        if rc > 0 {
            return Some(ForwardWrite::Wrote(rc as usize));
        }
        if rc == 0 {
            return None;
        }
        let err = std::io::Error::last_os_error();
        if err.kind() == std::io::ErrorKind::Interrupted {
            continue;
        }
        if err.kind() == std::io::ErrorKind::WouldBlock {
            return Some(ForwardWrite::Again);
        }
        return None;
    }
}

/// `write` while this fd is non-blocking, then put the old flags back.
///
/// `toggle` stays false for a terminal. Its stdin and stdout share one
/// open-file description, so `O_NONBLOCK` on stdout would make stdin
/// return `EAGAIN`. Pipe ends do not share that description.
/// Callers hold [`forward_write_lock`] across the poll and this write.
/// Two threads that both saw `POLLOUT` would otherwise block in `write`
/// when the pipe has room for only one `PIPE_BUF`.
#[cfg(unix)]
fn forward_write_lock() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    LOCK.lock().unwrap_or_else(|err| err.into_inner())
}

#[cfg(unix)]
fn write_fd(fd: std::os::fd::RawFd, buf: &[u8], toggle: bool) -> Option<ForwardWrite> {
    if !toggle {
        return write_once(fd, buf);
    }
    // SAFETY: `F_GETFL` reads this fd's status flags.
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
    if flags < 0 {
        return None;
    }
    let added = flags & libc::O_NONBLOCK == 0;
    if added {
        // SAFETY: `flags` came from `F_GETFL` on this fd.
        let rc = unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) };
        if rc < 0 {
            return None;
        }
    }
    let write_result = write_once(fd, buf);
    if added {
        // SAFETY: restore the flags this function observed.
        unsafe { libc::fcntl(fd, libc::F_SETFL, flags) };
    }
    write_result
}

/// A second open of the tty. Its `O_NONBLOCK` is not the shell's stdin.
#[cfg(unix)]
struct PrivateOut(std::os::fd::RawFd);

#[cfg(unix)]
impl Drop for PrivateOut {
    fn drop(&mut self) {
        // SAFETY: this fd came from `open` below and is still open.
        unsafe { libc::close(self.0) };
    }
}

/// Linux `/proc/self/fd` opens a new description. If this platform
/// instead shares flags with `fd`, restore them and give up.
#[cfg(target_os = "linux")]
fn open_private_nonblock(fd: std::os::fd::RawFd) -> Option<PrivateOut> {
    let mut stat = unsafe { std::mem::zeroed::<libc::stat>() };
    // SAFETY: `stat` is a live object. A regular file must keep its
    // offset, so only pipes and sockets get a second description.
    let rc = unsafe { libc::fstat(fd, &mut stat) };
    if rc != 0 {
        return None;
    }
    let kind = stat.st_mode & libc::S_IFMT;
    if kind != libc::S_IFIFO && kind != libc::S_IFSOCK {
        return None;
    }
    let path = std::ffi::CString::new(format!("/proc/self/fd/{fd}")).ok()?;
    // SAFETY: `F_GETFL` reads this fd's status flags.
    let before = unsafe { libc::fcntl(fd, libc::F_GETFL) };
    if before < 0 {
        return None;
    }
    // SAFETY: `path` is a NUL-terminated `/proc/self/fd/N`.
    let opened = unsafe {
        libc::open(
            path.as_ptr(),
            libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
        )
    };
    if opened < 0 {
        return None;
    }
    // SAFETY: same fd as `before`.
    let after = unsafe { libc::fcntl(fd, libc::F_GETFL) };
    if before & libc::O_NONBLOCK == 0 && after & libc::O_NONBLOCK != 0 {
        unsafe {
            libc::fcntl(fd, libc::F_SETFL, before);
            libc::close(opened);
        }
        return None;
    }
    Some(PrivateOut(opened))
}

#[cfg(unix)]
fn open_private_tty(fd: std::os::fd::RawFd) -> Option<PrivateOut> {
    // SAFETY: `isatty` only reads the fd type.
    if unsafe { libc::isatty(fd) } != 1 {
        return None;
    }
    let mut name = [0 as libc::c_char; 1024];
    // SAFETY: `name` is a live buffer of that length.
    let rc = unsafe { libc::ttyname_r(fd, name.as_mut_ptr(), name.len()) };
    if rc != 0 {
        return None;
    }
    let path = unsafe { std::ffi::CStr::from_ptr(name.as_ptr()) };
    // SAFETY: `path` is the NUL-terminated tty name just written.
    let opened = unsafe {
        libc::open(
            path.as_ptr(),
            libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
        )
    };
    if opened < 0 {
        None
    } else {
        Some(PrivateOut(opened))
    }
}

#[cfg(unix)]
fn copy_pipe(
    mut src: impl std::io::Read + Send + 'static,
    mut dst: impl std::io::Write + AsRawFd + Send + 'static,
    stop: Arc<AtomicBool>,
) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || {
        let fd = dst.as_raw_fd();
        #[cfg(target_os = "linux")]
        let private = open_private_tty(fd).or_else(|| open_private_nonblock(fd));
        #[cfg(not(target_os = "linux"))]
        let private = open_private_tty(fd);
        let out_fd = private.as_ref().map(|out| out.0).unwrap_or(fd);
        // macOS `POLLOUT` already means a 512-byte write will not block,
        // so pipes there do not need `O_NONBLOCK`. Linux falls back to
        // the toggle only when a private descriptor is unavailable.
        // SAFETY: `fd` is the destination stdout or stderr handle.
        let toggle =
            cfg!(target_os = "linux") && private.is_none() && unsafe { libc::isatty(fd) } != 1;
        let chunk = forward_chunk(out_fd);
        // Push any prefix already sitting in the stdout buffer. Later
        // writes go to the fd, so a drop flush cannot block after stop.
        let _ = std::io::Write::flush(&mut dst);
        let mut buf = [0u8; 16 * 1024];
        loop {
            if stop.load(Ordering::Relaxed) {
                return;
            }
            let n = match std::io::Read::read(&mut src, &mut buf) {
                Ok(0) | Err(_) => break,
                Ok(n) => n,
            };
            let mut off = 0;
            while off < n {
                let _guard = forward_write_lock();
                match poll_out_once(out_fd, &stop) {
                    PollOut::Stop => return,
                    PollOut::Later => continue,
                    PollOut::Ready => {
                        let end = off + (n - off).min(chunk);
                        match write_fd(out_fd, &buf[off..end], toggle) {
                            Some(ForwardWrite::Wrote(wrote)) if wrote > 0 => off += wrote,
                            Some(ForwardWrite::Again) => continue,
                            _ => return,
                        }
                    }
                }
            }
        }
        if !stop.load(Ordering::Relaxed) {
            let _ = std::io::Write::flush(&mut dst);
        }
    })
}

#[cfg(unix)]
fn join_drain(handle: Option<std::thread::JoinHandle<Vec<u8>>>) -> Vec<u8> {
    handle.and_then(|h| h.join().ok()).unwrap_or_default()
}

#[cfg(unix)]
fn join_copy(handle: Option<std::thread::JoinHandle<()>>) {
    if let Some(h) = handle {
        let _ = h.join();
    }
}

#[cfg(unix)]
fn copy_finished(handle: &Option<std::thread::JoinHandle<()>>) -> bool {
    match handle {
        None => true,
        Some(handle) => handle.is_finished(),
    }
}

/// Stop the copies at `deadline` if a stalled reader is still blocking
/// them. True means the deadline, not the child, ended the forward.
#[cfg(unix)]
fn finish_copies(
    stop: &AtomicBool,
    stdout: Option<std::thread::JoinHandle<()>>,
    stderr: Option<std::thread::JoinHandle<()>>,
    deadline: Instant,
) -> bool {
    let mut forced = false;
    loop {
        if copy_finished(&stdout) && copy_finished(&stderr) {
            break;
        }
        if Instant::now() >= deadline {
            stop.store(true, Ordering::Relaxed);
            forced = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    join_copy(stdout);
    join_copy(stderr);
    forced
}

/// Inputs for [`doctor_fails`]. Remount is Linux-only. WFP is Windows-only.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DoctorFacts {
    pub kernel_supported: bool,
    /// `Some` only on Linux. `false` means `workpen run` will not start a child.
    pub remount_available: Option<bool>,
    /// `Some(true)` when Windows WFP returned access denied. `None` off Windows.
    pub wfp_skipped: Option<bool>,
    /// Probe setup failed, so a child would not start.
    pub setup_failed: bool,
}

/// Exit 1 when the kernel is missing, Linux remount is unavailable, or
/// Windows jail setup failed. WFP skip alone is not a failure.
#[must_use]
pub fn doctor_fails(facts: DoctorFacts) -> bool {
    !facts.kernel_supported || facts.setup_failed || facts.remount_available == Some(false)
}

/// Probe this machine. Uses a private temp directory, not the user
/// workspace, and does not plant `.env` or start a user command.
pub fn collect_doctor_facts() -> DoctorFacts {
    let kernel_supported = kernel_supported();
    let dir = private_probe_dir().ok();
    let _remove = dir.as_ref().map(|path| RemoveProbeDir(path.clone()));
    #[cfg(target_os = "linux")]
    let remount_available = Some(linux::dest_remount_available());
    #[cfg(not(target_os = "linux"))]
    let remount_available = None;
    #[cfg(windows)]
    let (wfp_skipped, setup_failed) = if kernel_supported {
        match dir.as_deref() {
            Some(path) => match windows::probe_wfp_skipped(path) {
                Ok(skipped) => (Some(skipped), false),
                Err(_) => (None, true),
            },
            None => (None, true),
        }
    } else {
        (None, false)
    };
    #[cfg(not(windows))]
    let (wfp_skipped, setup_failed) = (None, false);
    DoctorFacts {
        kernel_supported,
        remount_available,
        wfp_skipped,
        setup_failed,
    }
}

fn private_probe_dir() -> std::io::Result<PathBuf> {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let dir = std::env::temp_dir().join(format!("workpen-doctor-{}-{nanos}", std::process::id()));
    std::fs::create_dir(&dir)?;
    Ok(dir)
}

struct RemoveProbeDir(PathBuf);

impl Drop for RemoveProbeDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// Whether this OS can apply a kernel jail.
#[must_use]
pub fn kernel_supported() -> bool {
    #[cfg(unix)]
    {
        nono::Sandbox::is_supported()
    }
    #[cfg(windows)]
    {
        windows::write_restricted_supported()
    }
    #[cfg(not(any(unix, windows)))]
    {
        false
    }
}

/// Build a process-jail policy. Does not apply it.
///
/// Refuses filesystem root and the current user's home directory as the
/// workspace or as an extra-root. Extra-roots may still be an explicit
/// `/tmp` or a subdirectory of home.
///
/// Dest-deny names default to [`crate::default_secret_denies()`] plus
/// workspace `agent.lock` extras, resolved under the workspace and
/// each extra-root (except `/tmp` / `/var/tmp`; those trees are too
/// large to walk). An extra-root with a cache dir name
/// (`target`, `node_modules`, `.venv`, `dist`, `__pycache__`)
/// in any path component uses the glob-name cache walk, same as a
/// workspace `target/` (no hardlink sibling scan of rustc
/// artifacts). That includes `--extra-root …/target/debug`.
/// Missing lock equals defaults. Invalid
/// lock is [`KernelError::Apply`]. Hosts match [`crate::DestDenyKind`],
/// not English.
pub fn process_jail(
    workspace: impl AsRef<Path>,
    extra: impl IntoIterator<Item = impl AsRef<Path>>,
) -> Result<KernelPolicy, KernelError> {
    let workspace = workspace.as_ref();
    let policy =
        DenyPolicy::from_workspace(workspace).map_err(|err| KernelError::Apply(err.to_string()))?;
    process_jail_with_policy(workspace, extra, &policy)
}

/// Same as [`process_jail`] with a host [`DenyPolicy`].
///
/// The host policy wins. Hosts that pass a policy own the merge,
/// including whether to load workspace `agent.lock`. This function
/// does not read the lock.
pub fn process_jail_with_policy(
    workspace: impl AsRef<Path>,
    extra: impl IntoIterator<Item = impl AsRef<Path>>,
    policy: &DenyPolicy,
) -> Result<KernelPolicy, KernelError> {
    refuse_home_workspace(workspace.as_ref())?;
    let extras: Vec<PathBuf> = extra
        .into_iter()
        .map(|p| p.as_ref().to_path_buf())
        .collect();
    let mut grants = Vec::new();
    add_rw(&mut grants, workspace.as_ref())?;
    for extra in &extras {
        add_rw(&mut grants, extra)?;
    }
    for dir in system_read_dirs() {
        add_read_if_dir(&mut grants, &dir);
    }
    let mut dest_denies = collect_workspace_dest_denies(workspace.as_ref(), policy)?;
    let mut remaining = DEST_DENY_WALK_LIMIT;
    for extra in &extras {
        append_extra_dest_denies(extra, policy, &mut dest_denies, &mut remaining)?;
    }
    if let Some(null_dev) = null_device_grant() {
        push_grant(&mut grants, null_dev, KernelAccess::ReadWrite);
    }
    Ok(KernelPolicy {
        grants,
        dest_denies,
        deny_policy: policy.clone(),
        network_blocked: true,
        require_dest_hide: false,
    })
}

/// Read-write on the null device file only, when that path is still a
/// character device. Missing path and a symlink to a regular file get
/// no grant. `/dev` itself stays a read grant.
fn null_device_grant() -> Option<PathBuf> {
    #[cfg(unix)]
    {
        let path = PathBuf::from("/dev/null");
        if crate::deny::is_null_device(&path) {
            return Some(path);
        }
    }
    None
}

impl KernelPolicy {
    pub fn grants(&self) -> &[KernelGrant] {
        &self.grants
    }

    /// Dest-deny paths collected under the workspace and extra-roots.
    /// Not a filesystem grant.
    pub fn dest_denies(&self) -> &[DestDeny] {
        &self.dest_denies
    }

    /// When `blocked` is false, Unix `to_capability_set` does not call
    /// `block_network()`. The default from [`process_jail`] stays blocked.
    #[must_use]
    pub fn with_network(mut self, blocked: bool) -> Self {
        self.network_blocked = blocked;
        self
    }

    /// Read-only grant for one extra directory. Home and filesystem root
    /// are refused the same way as a read-write extra root. Dest-deny for
    /// that tree is recorded after the allow.
    pub fn with_read_root(mut self, path: &Path) -> Result<Self, KernelError> {
        add_read_grant(&mut self.grants, path)?;
        let mut remaining = DEST_DENY_WALK_LIMIT;
        append_extra_dest_denies(
            path,
            &self.deny_policy,
            &mut self.dest_denies,
            &mut remaining,
        )?;
        Ok(self)
    }

    /// Fail closed when Linux dest-deny remount is skipped.
    ///
    /// Default `run_child` still starts the child and returns
    /// [`KernelApply::RemountSkipped`]. `workpen run` uses this so a
    /// child that can open in-tree secrets is not started.
    #[must_use]
    pub fn with_require_dest_hide(mut self) -> Self {
        self.require_dest_hide = true;
        self
    }

    #[cfg(unix)]
    fn require_spawn(&self, applied: KernelApply) -> Result<KernelApply, KernelError> {
        if self.require_dest_hide {
            require_dest_hide(applied)
        } else {
            require_applied(applied)
        }
    }

    /// Add host dest-deny paths. Existing files are classified (glob or
    /// hardlink). Missing paths are still recorded as [`DestDenyKind::DenyGlob`].
    pub fn with_dest_deny_paths(
        mut self,
        paths: impl IntoIterator<Item = impl AsRef<Path>>,
    ) -> Self {
        for path in paths {
            push_dest_deny(
                &mut self.dest_denies,
                dest_deny_from_path(path.as_ref(), &self.deny_policy),
            );
        }
        self
    }

    /// True when the policy asked the kernel backend to block sockets.
    ///
    /// Unix `run_child` passes this to nono `block_network()`. Windows
    /// `run_child` wraps the command in a unique helper PE, launches
    /// that helper in an AppContainer with no network capabilities, and
    /// adds a dynamic WFP BLOCK on the package SID (and the helper
    /// APP_ID) when the token can add filters. Fail closed if
    /// AppContainer cannot apply. WFP `ERROR_ACCESS_DENIED` (win32 5)
    /// is skipped: package filters need an elevated token. The child
    /// still starts with AppContainer network deny.
    pub fn network_blocked(&self) -> bool {
        self.network_blocked
    }

    /// Apply Landlock/Seatbelt for this process. Irreversible. Not for tests.
    ///
    /// Uses `SignalMode::AllowAll` so a jailed parent can still signal children.
    /// Windows cannot retoken the current process; this stays
    /// [`KernelApply::UserspaceOnly`].
    pub fn apply(&self) -> Result<KernelApply, KernelError> {
        if !kernel_supported() {
            return Ok(KernelApply::UserspaceOnly);
        }
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        {
            let caps = self.to_capability_set(nono::SignalMode::AllowAll)?;
            nono::Sandbox::apply_auto(&caps).map_err(|e| KernelError::Apply(e.to_string()))?;
            Ok(KernelApply::Applied)
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
        {
            Ok(KernelApply::UserspaceOnly)
        }
    }

    /// Install Landlock/Seatbelt in the child `pre_exec` hook.
    ///
    /// Dest-denies `cmd` argv first ([`Self::dest_deny_command`]), same
    /// rules as [`Self::run_child`]. Builds the capability set in the
    /// parent (allocation is not safe after fork). Uses
    /// `SignalMode::Isolated` so the child cannot signal the parent.
    /// Does not jail this process. Windows has no `pre_exec`; this stays
    /// [`KernelApply::UserspaceOnly`]. Use [`Self::run_child`] to jail a child.
    ///
    /// On Linux, dest-deny remount skip is [`KernelApply::RemountSkipped`]
    /// when dest-deny paths exist and a private mount ns cannot be
    /// entered. Extra-root dests still fail-closed. If the parent probe
    /// returned [`KernelApply::Applied`], the child fail-closes when
    /// enter fails.
    ///
    /// The hook forks a reaper. After the host waits for the spawned
    /// child, call [`Self::finish_pre_exec`] on this same thread. A miss
    /// is [`KernelError::Descendants`], not the child status. Call
    /// [`Self::discard_pre_exec`] when spawn fails or the host does not
    /// wait. [`Self::run_child`] waits and finishes itself.
    ///
    /// The report is one pipe per thread, not per policy value. A second
    /// `apply_pre_exec` on this thread drops an unread report. A wait
    /// that resumes on another thread, including after `.await`, must
    /// use [`Self::apply_pre_exec_report`] instead. [`Self::finish_pre_exec`]
    /// on that other thread is [`KernelError::Descendants`] even when
    /// the command had no grandchildren.
    pub fn apply_pre_exec(&self, cmd: &mut Command) -> Result<KernelApply, KernelError> {
        let (applied, report) = self.apply_pre_exec_dests(cmd, Vec::new())?;
        report.stash();
        Ok(applied)
    }

    /// Same hook as [`Self::apply_pre_exec`]. The [`PreExecReport`] owns
    /// the reaper pipe and is `Send`.
    ///
    /// Move the report with the child. [`PreExecReport::finish`] reads
    /// it on whichever thread resumed. [`PreExecReport::discard`] and
    /// `Drop` close the pipe. This does not store a thread-local, and it
    /// does not drop a report the host still holds.
    pub fn apply_pre_exec_report(
        &self,
        cmd: &mut Command,
    ) -> Result<(KernelApply, PreExecReport), KernelError> {
        self.apply_pre_exec_dests(cmd, Vec::new())
    }

    /// Read the descendant report for a child spawned after
    /// [`Self::apply_pre_exec`] on this same thread.
    ///
    /// Call this once, after the host's own wait. `Ok(status)` means the
    /// reaper tracked every descendant. [`KernelError::Descendants`]
    /// means it did not: the report was a miss, the pipe was missing, or
    /// the reaper wrote nothing. That includes calling this on a
    /// different thread from [`Self::apply_pre_exec`]. Use
    /// [`PreExecReport::finish`] to read a report that moved. Pass
    /// `timed_out: true` when the host's deadline already fired. The
    /// deadline wins and this returns `Ok(status)`, same as
    /// [`Self::run_child_timeout`].
    ///
    /// Closes the report pipe. Leaving it unread holds that pipe until
    /// the next [`Self::apply_pre_exec`] on this thread.
    pub fn finish_pre_exec(
        &self,
        status: ExitStatus,
        timed_out: bool,
    ) -> Result<ExitStatus, KernelError> {
        let _ = self;
        #[cfg(unix)]
        {
            finish_reap(status, timed_out).map(|(status, _)| status)
        }
        #[cfg(not(unix))]
        {
            let _ = timed_out;
            Ok(status)
        }
    }

    /// Drop the thread-local descendant report without reading it.
    ///
    /// Use this when [`Self::apply_pre_exec`] succeeded but the host did
    /// not wait (spawn failed, or the host gave up). The next
    /// `apply_pre_exec` also drops an unread pipe. A later
    /// [`Self::finish_pre_exec`] on this thread then has no report.
    /// [`PreExecReport::discard`] is the same close for a report the
    /// host holds.
    pub fn discard_pre_exec(&self) {
        let _ = self;
        #[cfg(unix)]
        reaper::discard_report();
    }

    fn apply_pre_exec_dests(
        &self,
        cmd: &mut Command,
        extra_dests: Vec<PathBuf>,
    ) -> Result<(KernelApply, PreExecReport), KernelError> {
        self.dest_deny_command(cmd)?;
        if !kernel_supported() {
            return Ok((KernelApply::UserspaceOnly, PreExecReport::unarmed()));
        }
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        {
            let caps = self.to_capability_set(nono::SignalMode::Isolated)?;
            let mut dests: Vec<PathBuf> = self.dest_denies.iter().map(|d| d.path.clone()).collect();
            dests.extend(extra_dests);
            let workspace = self
                .grants
                .iter()
                .find(|g| g.access == KernelAccess::ReadWrite)
                .map(|g| g.path.clone())
                .unwrap_or_default();
            #[cfg(target_os = "linux")]
            let remount = linux::remount_status(&dests, &workspace)?;
            #[cfg(not(target_os = "linux"))]
            let remount = KernelApply::Applied;
            #[cfg(target_os = "linux")]
            let require_remount = remount == KernelApply::Applied;
            // Safety: the set and dest list are built in the parent; the hook
            // only applies them and maps failure to io::Error.
            // The write fd is captured by value. The parent keeps the
            // `OwnedFd`. `fork` gives the child its own copy.
            let report = reaper::open_report();
            let report_fd = report.write_raw();
            let expected_comm = reaper::expected_comm_bytes(cmd.get_program());
            unsafe {
                use std::os::unix::process::CommandExt;
                cmd.pre_exec(move || {
                    // Mark inherited descriptors before the reaper fork so a
                    // soft limit that cannot be covered fails spawn here.
                    reaper::cloexec_inherited_fds()?;
                    reaper::supervise_or_continue(report_fd, expected_comm)?;
                    #[cfg(target_os = "linux")]
                    linux::apply_dest_deny_remounts(&dests, &workspace, require_remount)?;
                    #[cfg(not(target_os = "linux"))]
                    let _ = (&dests, &workspace);
                    apply_child_hardening()?;
                    nono::Sandbox::apply_auto(&caps)
                        .map_err(|e| std::io::Error::other(e.to_string()))?;
                    Ok(())
                });
            }
            Ok((remount, PreExecReport::from_pipe(report)))
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
        {
            let _ = extra_dests;
            Ok((KernelApply::UserspaceOnly, PreExecReport::unarmed()))
        }
    }

    /// Spawn `cmd` under the kernel jail and wait for it.
    ///
    /// Dest-denies the `Command` program plus args with
    /// [`crate::check_command_argv`] (same rules as `workpen run`)
    /// before spawn. Invalid `-EncodedCommand` is
    /// [`crate::DestDenyError::EncodedCommand`] via
    /// [`KernelError::DestDeny`]. The child is not started.
    ///
    /// Unix installs `pre_exec` then `status`. Windows creates a
    /// write-restricted token and `CreateProcessAsUserW`. When
    /// [`Self::network_blocked`] is set, Windows also wraps the command
    /// through a unique helper PE in an AppContainer and a package-SID
    /// WFP BLOCK when the token can add filters. WFP win32 5 is skipped
    /// (needs admin). If AppContainer or the kernel cannot apply, this
    /// returns [`KernelError::Apply`] and does not start the child.
    /// [`KernelApply::UserspaceOnly`] stays on [`Self::apply`] /
    /// [`Self::apply_pre_exec`] inspect paths only.
    ///
    /// Windows spawn inherits parent stdio or grants NUL so console
    /// children do not block on null handles. [`Command`]
    /// [`std::process::Stdio::piped`] is not readable after this wait.
    /// Hosts that need captured stdout call [`Self::run_child_output`].
    ///
    /// Blocking wait has no host-visible kill; use
    /// [`Self::run_child_timeout`]. Hosts that need captured stdout use
    /// [`Self::run_child_output`].
    #[cfg(target_os = "linux")]
    fn occupy_and_hook(
        &self,
        cmd: &mut Command,
    ) -> Result<(KernelApply, linux::OccupiedDests), KernelError> {
        let occupy = linux::occupy_missing(&self.occupy_roots(), self.deny_policy.globs())
            .map_err(|e| KernelError::Apply(e.to_string()))?;
        let extra = occupy.paths().to_vec();
        let (applied, report) = self.apply_pre_exec_dests(cmd, extra)?;
        report.stash();
        let applied = self
            .require_spawn(applied)
            .inspect_err(|_| reaper::discard_report())?;
        Ok((applied, occupy))
    }

    #[cfg(all(unix, not(target_os = "linux")))]
    fn hook_ready(&self, cmd: &mut Command) -> Result<KernelApply, KernelError> {
        let applied = self.apply_pre_exec(cmd)?;
        self.require_spawn(applied)
            .inspect_err(|_| reaper::discard_report())
    }

    #[cfg(target_os = "linux")]
    fn occupy_roots(&self) -> Vec<PathBuf> {
        self.grants
            .iter()
            .filter(|g| g.access == KernelAccess::ReadWrite && !is_system_temp_root(&g.path))
            .map(|g| g.path.clone())
            .collect()
    }

    pub fn run_child(&self, cmd: Command) -> Result<(KernelApply, ExitStatus), KernelError> {
        self.dest_deny_command(&cmd)?;
        #[cfg(unix)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "kernel jail is not available; child was not started".into(),
                ));
            }
            use std::os::unix::process::CommandExt;

            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            #[cfg(target_os = "linux")]
            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
            #[cfg(not(target_os = "linux"))]
            let applied = self.hook_ready(&mut cmd)?;
            cmd.process_group(0);
            let mut child = spawn_jailed(&mut cmd)?;
            let (status, _) = reap_process_group(&mut child, None)?;
            Ok((applied, status))
        }
        #[cfg(windows)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "write-restricted token is not available".into(),
                ));
            }
            windows::spawn_write_restricted(self, &cmd, None)
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = cmd;
            Err(KernelError::Apply(
                "no kernel backend on this platform".into(),
            ))
        }
    }

    /// Spawn `cmd` under the kernel jail and collect stdout/stderr.
    ///
    /// Same dest-deny and fail-closed setup as [`Self::run_child`].
    /// Windows creates anonymous pipes. Unix inherits stdin and pipes
    /// stdout/stderr (`Command::output` would close stdin).
    pub fn run_child_output(
        &self,
        cmd: Command,
    ) -> Result<(KernelApply, std::process::Output), KernelError> {
        self.dest_deny_command(&cmd)?;
        #[cfg(unix)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "kernel jail is not available; child was not started".into(),
                ));
            }
            use std::os::unix::process::CommandExt;

            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            #[cfg(target_os = "linux")]
            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
            #[cfg(not(target_os = "linux"))]
            let applied = self.hook_ready(&mut cmd)?;
            cmd.stdin(std::process::Stdio::inherit());
            cmd.stdout(std::process::Stdio::piped());
            cmd.stderr(std::process::Stdio::piped());
            cmd.process_group(0);
            let mut child = spawn_jailed(&mut cmd)?;
            let stdout = child.stdout.take().map(drain_pipe);
            let stderr = child.stderr.take().map(drain_pipe);
            let (status, _) = reap_process_group(&mut child, None)?;
            let output = std::process::Output {
                status,
                stdout: join_drain(stdout),
                stderr: join_drain(stderr),
            };
            Ok((applied, output))
        }
        #[cfg(windows)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "write-restricted token is not available".into(),
                ));
            }
            windows::spawn_write_restricted_output(self, &cmd, None).map(|(a, o, _)| (a, o))
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = cmd;
            Err(KernelError::Apply(
                "no kernel backend on this platform".into(),
            ))
        }
    }

    /// Same as [`Self::run_child_output`] with a deadline.
    ///
    /// Stdout and stderr are drained while waiting so a chatty child
    /// cannot fill the pipe and block until this deadline.
    ///
    /// Returns `(applied, output, timed_out)`. When `timed_out` is true,
    /// `output` still holds drained stdout/stderr. [`KernelError::Timeout`]
    /// stays a unit variant on [`Self::run_child_timeout`].
    pub fn run_child_timeout_output(
        &self,
        cmd: Command,
        timeout: Duration,
    ) -> Result<(KernelApply, std::process::Output, bool), KernelError> {
        self.dest_deny_command(&cmd)?;
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;

            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "kernel jail is not available; child was not started".into(),
                ));
            }
            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            #[cfg(target_os = "linux")]
            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
            #[cfg(not(target_os = "linux"))]
            let applied = self.hook_ready(&mut cmd)?;
            cmd.stdout(std::process::Stdio::piped());
            cmd.stderr(std::process::Stdio::piped());
            cmd.process_group(0);
            let child = spawn_jailed_deadline(&mut cmd, Some(timeout))?;
            let (output, timed_out) = wait_child_timeout_output(child, timeout)?;
            Ok((applied, output, timed_out))
        }
        #[cfg(windows)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "write-restricted token is not available".into(),
                ));
            }
            windows::spawn_write_restricted_output(self, &cmd, Some(timeout))
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = (cmd, timeout);
            Err(KernelError::Apply(
                "no kernel backend on this platform".into(),
            ))
        }
    }

    /// Spawn `cmd` and copy stdout/stderr to this process as they arrive.
    ///
    /// Unlike [`Self::run_child_output`], this does not buffer the whole
    /// stream in a `Vec`. The CLI uses it so a chatty child cannot grow
    /// parent RSS without bound. Redirects outside `--root` stay parent
    /// writes (Seatbelt/DACL).
    pub fn run_child_forward(
        &self,
        cmd: Command,
    ) -> Result<(KernelApply, ExitStatus), KernelError> {
        self.dest_deny_command(&cmd)?;
        #[cfg(unix)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "kernel jail is not available; child was not started".into(),
                ));
            }
            use std::os::unix::process::CommandExt;

            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            #[cfg(target_os = "linux")]
            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
            #[cfg(not(target_os = "linux"))]
            let applied = self.hook_ready(&mut cmd)?;
            cmd.stdin(std::process::Stdio::inherit());
            cmd.stdout(std::process::Stdio::piped());
            cmd.stderr(std::process::Stdio::piped());
            cmd.process_group(0);
            let mut child = spawn_jailed(&mut cmd)?;
            let stop = forward_stop();
            let stdout = child
                .stdout
                .take()
                .map(|p| copy_pipe(p, std::io::stdout(), Arc::clone(&stop)));
            let stderr = child
                .stderr
                .take()
                .map(|p| copy_pipe(p, std::io::stderr(), Arc::clone(&stop)));
            let (status, _) = reap_process_group(&mut child, None)?;
            join_copy(stdout);
            join_copy(stderr);
            Ok((applied, status))
        }
        #[cfg(windows)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "write-restricted token is not available".into(),
                ));
            }
            windows::spawn_write_restricted_forward(self, &cmd, None).map(|(a, s, _)| (a, s))
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = cmd;
            Err(KernelError::Apply(
                "no kernel backend on this platform".into(),
            ))
        }
    }

    /// Same as [`Self::run_child_forward`] with a deadline.
    ///
    /// Returns `(applied, status, timed_out)`. Bytes are copied to this
    /// process as they arrive. [`KernelError::Timeout`] stays a unit
    /// variant on [`Self::run_child_timeout`].
    pub fn run_child_timeout_forward(
        &self,
        cmd: Command,
        timeout: Duration,
    ) -> Result<(KernelApply, ExitStatus, bool), KernelError> {
        self.dest_deny_command(&cmd)?;
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;

            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "kernel jail is not available; child was not started".into(),
                ));
            }
            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            #[cfg(target_os = "linux")]
            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
            #[cfg(not(target_os = "linux"))]
            let applied = self.hook_ready(&mut cmd)?;
            cmd.stdin(std::process::Stdio::inherit());
            cmd.stdout(std::process::Stdio::piped());
            cmd.stderr(std::process::Stdio::piped());
            cmd.process_group(0);
            let child = spawn_jailed_deadline(&mut cmd, Some(timeout))?;
            let (status, timed_out) = wait_child_timeout_forward(child, timeout)?;
            Ok((applied, status, timed_out))
        }
        #[cfg(windows)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "write-restricted token is not available".into(),
                ));
            }
            windows::spawn_write_restricted_forward(self, &cmd, Some(timeout))
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = (cmd, timeout);
            Err(KernelError::Apply(
                "no kernel backend on this platform".into(),
            ))
        }
    }

    /// Same as [`Self::run_child_forward`] with a PTY for the child.
    ///
    /// Unix only. Windows returns [`KernelError::Apply`]. stdin/stdout/
    /// stderr are the slave. The parent copies the master to this
    /// process. `setsid` is the child's process group (no extra
    /// `process_group(0)`).
    pub fn run_child_forward_pty(
        &self,
        cmd: Command,
    ) -> Result<(KernelApply, ExitStatus), KernelError> {
        self.run_child_pty(cmd, None).map(|(a, s, _)| (a, s))
    }

    /// Same as [`Self::run_child_timeout_forward`] with a PTY.
    pub fn run_child_timeout_forward_pty(
        &self,
        cmd: Command,
        timeout: Duration,
    ) -> Result<(KernelApply, ExitStatus, bool), KernelError> {
        self.run_child_pty(cmd, Some(timeout))
    }

    fn run_child_pty(
        &self,
        cmd: Command,
        timeout: Option<Duration>,
    ) -> Result<(KernelApply, ExitStatus, bool), KernelError> {
        self.dest_deny_command(&cmd)?;
        #[cfg(unix)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "kernel jail is not available; child was not started".into(),
                ));
            }
            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            let pty = pty::open_pty().map_err(|e| KernelError::Apply(e.to_string()))?;
            // unshare/Landlock before setsid/TIOCSCTTY. Linux userns
            // after a controlling TTY can stop the child on SIGTTIN.
            #[cfg(target_os = "linux")]
            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
            #[cfg(not(target_os = "linux"))]
            let applied = self.hook_ready(&mut cmd)?;
            pty::attach_pty(&mut cmd, pty.slave).map_err(|e| {
                reaper::discard_report();
                KernelError::Apply(e.to_string())
            })?;
            let mut child = spawn_jailed_deadline(&mut cmd, timeout)?;
            // The spawned pid is the reaper. Foreground the command
            // after it becomes a session leader. The child also calls
            // tcsetpgrp; this covers the Linux race the other way.
            #[cfg(unix)]
            if let Some(leader) = reaper::leader_pid(child.id() as libc::pid_t) {
                let _ = unsafe { libc::tcsetpgrp(pty.master.as_raw_fd(), leader) };
            }
            // Command keeps the slave File after spawn. Linux master
            // read does not EOF while that fd stays open in the parent.
            drop(cmd);
            let started = Instant::now();
            let stop = forward_stop();
            // Linux sends SIGHUP when the last PTY master closes. The
            // copy thread can drop its master before wait records the
            // child's exit, which turns a finished `cat` into 129.
            let master_hold = pty.master.try_clone().map_err(|e| {
                reaper::discard_report();
                KernelError::Apply(e.to_string())
            })?;
            let (out_th, master_write) = pty::pump_master(pty.master, &stop).map_err(|e| {
                reaper::discard_report();
                KernelError::Apply(e.to_string())
            })?;
            let _stdin_th = pty::pump_stdin(master_write);
            let (status, mut timed_out) = reap_process_group(&mut child, timeout)?;
            drop(master_hold);
            if let Some(limit) = timeout {
                if finish_copies(&stop, Some(out_th), None, started + limit) {
                    timed_out = true;
                }
            } else {
                join_copy(Some(out_th));
            }
            Ok((applied, status, timed_out))
        }
        #[cfg(windows)]
        {
            let _ = (cmd, timeout);
            Err(KernelError::Apply(
                "tty is not available on Windows; child was not started".into(),
            ))
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = (cmd, timeout);
            Err(KernelError::Apply(
                "tty is not available on this platform; child was not started".into(),
            ))
        }
    }

    /// Spawn `cmd` under the kernel jail and kill it after `timeout`.
    ///
    /// On macOS the deadline includes pre-exec. A command that has not
    /// reached exec by then is killed, and this returns
    /// [`KernelError::Timeout`].
    ///
    /// Same fail-closed setup as [`Self::run_child`]. Unix places the
    /// child in its own process group and `killpg`s that group when the
    /// leader exits and again on the deadline. A grandchild that called
    /// `setsid` is stopped by the pre_exec reaper before this wait
    /// returns. A pid that was not stored is
    /// [`KernelError::Descendants`] instead of the child status.
    /// Windows waits with a bounded `WaitForSingleObject` and
    /// closes the job so `KILL_ON_JOB_CLOSE` stops the child.
    pub fn run_child_timeout(
        &self,
        cmd: Command,
        timeout: Duration,
    ) -> Result<(KernelApply, ExitStatus), KernelError> {
        self.dest_deny_command(&cmd)?;
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;

            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "kernel jail is not available; child was not started".into(),
                ));
            }
            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            #[cfg(target_os = "linux")]
            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
            #[cfg(not(target_os = "linux"))]
            let applied = self.hook_ready(&mut cmd)?;
            cmd.process_group(0);
            let mut child = spawn_jailed_deadline(&mut cmd, Some(timeout))?;
            let (status, timed_out) = reap_process_group(&mut child, Some(timeout))?;
            if timed_out {
                return Err(KernelError::Timeout);
            }
            Ok((applied, status))
        }
        #[cfg(windows)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "write-restricted token is not available".into(),
                ));
            }
            windows::spawn_write_restricted(self, &cmd, Some(timeout))
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = (cmd, timeout);
            Err(KernelError::Apply(
                "no kernel backend on this platform".into(),
            ))
        }
    }

    #[cfg(unix)]
    fn to_capability_set(
        &self,
        signal: nono::SignalMode,
    ) -> Result<nono::CapabilitySet, KernelError> {
        let mut caps = nono::CapabilitySet::new();
        for grant in &self.grants {
            let mode = match grant.access {
                KernelAccess::Read => nono::AccessMode::Read,
                KernelAccess::ReadWrite => nono::AccessMode::ReadWrite,
            };
            caps = if grant.path.is_dir() {
                caps.allow_path(&grant.path, mode)
            } else {
                caps.allow_file(&grant.path, mode)
            }
            .map_err(|e| KernelError::Apply(e.to_string()))?;
        }
        #[cfg(target_os = "macos")]
        {
            let rw: Vec<&Path> = self
                .grants
                .iter()
                .filter(|g| g.access == KernelAccess::ReadWrite)
                .map(|g| g.path.as_path())
                .collect();
            add_macos_dest_deny_rules(&mut caps, &self.dest_denies, &rw, self.deny_policy.globs())?;
        }
        let caps = if self.network_blocked {
            caps.block_network()
        } else {
            caps
        };
        Ok(caps.set_signal_mode(signal))
    }

    /// Dest-deny `cmd` argv with the jail [`DenyPolicy`] before spawn.
    ///
    /// Relative dests resolve against `cmd.current_dir()` when set, else
    /// the first ReadWrite grant. Same rules as
    /// [`crate::check_command_argv`] on program plus args. A program or
    /// argument that is not valid UTF-8 is [`KernelError::DestDeny`]
    /// of [`CheckDestError::NonUtf8`] before spawn. Hosts that
    /// jail writes in a capture dir still dest-deny argv against the
    /// user cwd when they set `current_dir`. Hosts that cannot use
    /// [`Self::run_child`] call this, then [`Self::apply_pre_exec`]
    /// (which also calls it) or their own spawn. Hosts match
    /// [`KernelError::DestDeny`], not English.
    pub fn dest_deny_command(&self, cmd: &Command) -> Result<(), KernelError> {
        let from_cwd = cmd.get_current_dir();
        let from_grant = self
            .grants
            .iter()
            .find(|g| g.access == KernelAccess::ReadWrite)
            .map(|g| g.path.as_path());
        let workspace = from_cwd.or(from_grant).ok_or_else(|| {
            KernelError::Apply("dest-deny argv needs a current_dir or ReadWrite grant".into())
        })?;
        let argv = command_argv(cmd)?;
        crate::check_command_argv(&argv, workspace, &self.deny_policy)?;
        Ok(())
    }
}

fn command_argv(cmd: &Command) -> Result<Vec<String>, CheckDestError> {
    let mut out = Vec::with_capacity(1 + cmd.get_args().len());
    out.push(utf8_arg(cmd.get_program())?);
    for arg in cmd.get_args() {
        out.push(utf8_arg(arg)?);
    }
    Ok(out)
}

fn utf8_arg(arg: &OsStr) -> Result<String, CheckDestError> {
    arg.to_str()
        .map(str::to_owned)
        .ok_or(CheckDestError::NonUtf8)
}

/// Win32 `ERROR_ACCESS_DENIED`. Package WFP filters need an elevated token.
#[cfg(any(windows, test))]
pub(crate) const WFP_ERROR_ACCESS_DENIED: u32 = 5;

/// True when a WFP engine or filter call returned access denied.
#[cfg(any(windows, test))]
#[must_use]
pub(crate) fn wfp_skip_access_denied(code: u32) -> bool {
    code == WFP_ERROR_ACCESS_DENIED
}

/// Names `run_child` strips from the child environment.
#[must_use]
pub fn child_env_deny_names() -> &'static [&'static str] {
    &[
        "LD_PRELOAD",
        "DYLD_INSERT_LIBRARIES",
        "DYLD_LIBRARY_PATH",
        "BASH_ENV",
        "ENV",
        "NODE_OPTIONS",
        "NODE_PATH",
        "PYTHONPATH",
        "PYTHONHOME",
        "PYTHONSTARTUP",
        "PERL5OPT",
        "RUBYOPT",
        "LD_LIBRARY_PATH",
        "XAI_API_KEY",
        "ANTHROPIC_API_KEY",
        "OPENAI_API_KEY",
        "AWS_SECRET_ACCESS_KEY",
        "AWS_ACCESS_KEY_ID",
        "TMPDIR",
        "TEMP",
        "TMP",
    ]
}

/// True when `name` must not be inherited by the child.
///
/// Exact denylist names, plus a final `_TOKEN` / `_SECRET` / `_PASSWORD`
/// segment and a final `_API_KEY`. The underscore is required.
/// `_KEY` alone is not enough: `CACHE_KEY` and `GIT_CONFIG_KEY_0` stay.
/// A `_KEY` name that contains `_PUBLIC_` or `_ANON_`, or that ends with
/// `_PUBLIC_KEY` or `_PUB_KEY`, stays. `_TOKEN` stays denied even then.
#[must_use]
pub fn is_denied_child_env(name: impl AsRef<OsStr>) -> bool {
    let raw = name.as_ref().to_string_lossy();
    if raw.is_empty() {
        return false;
    }
    if child_env_deny_names()
        .iter()
        .any(|n| raw.eq_ignore_ascii_case(n))
    {
        return true;
    }
    let upper = raw.to_ascii_uppercase();
    let last = upper.rsplit('_').next().unwrap_or(upper.as_str());
    if matches!(last, "TOKEN" | "SECRET" | "PASSWORD") {
        return true;
    }
    upper.ends_with("_API_KEY") && !public_key_env_exception(&upper)
}

fn public_key_env_exception(upper: &str) -> bool {
    upper.contains("_PUBLIC_")
        || upper.contains("_ANON_")
        || upper.ends_with("_PUBLIC_KEY")
        || upper.ends_with("_PUB_KEY")
}

/// Loader and script-execution names. `--env` cannot put these back.
pub(crate) fn is_child_env_loader(name: &OsStr) -> bool {
    let raw = name.to_string_lossy();
    const LOADERS: &[&str] = &[
        "LD_PRELOAD",
        "DYLD_INSERT_LIBRARIES",
        "DYLD_LIBRARY_PATH",
        "BASH_ENV",
        "ENV",
        "NODE_OPTIONS",
        "NODE_PATH",
        "PYTHONPATH",
        "PYTHONHOME",
        "PYTHONSTARTUP",
        "PERL5OPT",
        "RUBYOPT",
        "LD_LIBRARY_PATH",
    ];
    LOADERS.iter().any(|n| raw.eq_ignore_ascii_case(n))
}

/// Remove denied inherited names. An explicit `cmd.env` is kept, except loaders.
pub fn scrub_child_command(cmd: &mut Command) {
    let explicit: Vec<(OsString, bool)> = cmd
        .get_envs()
        .map(|(key, value)| (key.to_os_string(), value.is_some()))
        .collect();
    let kept: Vec<OsString> = explicit
        .iter()
        .filter(|(_, set)| *set)
        .map(|(key, _)| key.clone())
        .filter(|key| !is_child_env_loader(key))
        .collect();
    for (key, _) in std::env::vars_os() {
        if is_denied_child_env(&key) && !kept.iter().any(|kept| kept == &key) {
            cmd.env_remove(&key);
        }
    }
    for (key, set) in &explicit {
        if *set && is_child_env_loader(key) {
            cmd.env_remove(key);
        }
    }
}

/// Insert `--noprofile` and `--norc` after argv0 when the program is bash.
///
/// When argv0 is `env`/`env.exe`, drop `NAME=value` assignments whose name
/// is on the child-env denylist, including leftover tokens inside a `-S` /
/// `--split-string` operand, then insert after the first non-flag operand
/// that is bash. Walks clustered shorts (`-iC /tmp`) and value flags
/// (`-u NAME`, `-f FILE`, `--file FILE`). Attached forms stay one token.
///
/// When argv0 is `timeout`/`nohup`/`nice`/`time`/`stdbuf` (or `.exe`),
/// skip wrapper flags plus the timeout duration or `nice -n N`. If the
/// remaining argv starts with env, drop denylist assignments on that env
/// argv, then insert after the first bash operand (wrapper bash or env
/// bash). An `env`/`env.exe` token after any other prefix is walked the
/// same way. Non-bash commands (`timeout 30 echo hi`) stay unchanged.
#[must_use]
pub fn with_bash_noprofile(
    program: impl AsRef<OsStr>,
    args: impl IntoIterator<Item = impl AsRef<OsStr>>,
) -> (OsString, Vec<OsString>) {
    let program = program.as_ref().to_os_string();
    let mut args: Vec<OsString> = args
        .into_iter()
        .map(|a| a.as_ref().to_os_string())
        .collect();
    if is_env_argv0(&program) {
        drop_denied_env_assignments(&mut args, 0);
    } else if let Some(i) = first_env_arg(&args) {
        drop_denied_env_assignments(&mut args, i + 1);
    }
    if is_bash_argv0(&program) {
        insert_bash_noprofile(&mut args, 0);
    } else if is_env_argv0(&program)
        && let Some(idx) = first_env_bash_operand(&args)
    {
        insert_bash_noprofile(&mut args, idx + 1);
    } else if let Some(kind) = cmd_wrapper(&program)
        && let Some(idx) = first_wrapper_bash_operand(kind, &args)
    {
        insert_bash_noprofile(&mut args, idx + 1);
    } else if let Some(env_i) = first_env_arg(&args)
        && let Some(idx) = first_env_bash_operand(&args[env_i + 1..])
    {
        insert_bash_noprofile(&mut args, env_i + 1 + idx + 1);
    }
    (program, args)
}

fn drop_denied_env_assignments(args: &mut Vec<OsString>, mut i: usize) {
    let mut options_done = false;
    while i < args.len() {
        let raw = args[i].to_string_lossy().into_owned();
        if !options_done {
            if raw == "--" {
                options_done = true;
                i += 1;
                continue;
            }
            if let Some(skip) = env_flag_skip(&raw) {
                rewrite_denied_in_env_s(args, i);
                i = i.saturating_add(skip);
                continue;
            }
        }
        if let Some(eq) = raw.find('=') {
            let name = &raw[..eq];
            if !name.is_empty() && is_denied_child_env(name) {
                args.remove(i);
                continue;
            }
            i += 1;
            continue;
        }
        break;
    }
}

fn rewrite_denied_in_env_s(args: &mut [OsString], i: usize) {
    let raw = args[i].to_string_lossy().into_owned();
    if let Some(value) = raw.strip_prefix("--split-string=") {
        let dropped = drop_denied_from_split_string(value);
        args[i] = OsString::from(format!("--split-string={dropped}"));
        return;
    }
    if raw == "--split-string" {
        rewrite_next_s_operand(args, i);
        return;
    }
    if let Some((prefix, attached)) = env_s_cluster(&raw) {
        if attached.is_empty() {
            rewrite_next_s_operand(args, i);
        } else {
            let dropped = drop_denied_from_split_string(attached);
            args[i] = OsString::from(format!("{prefix}{dropped}"));
        }
    }
}

fn rewrite_next_s_operand(args: &mut [OsString], i: usize) {
    if let Some(op) = args.get_mut(i + 1) {
        let dropped = drop_denied_from_split_string(&op.to_string_lossy());
        *op = OsString::from(dropped);
    }
}

/// Clustered `-*S` / `-S` (not `--`). Prefix includes `S`; rest is attached.
fn env_s_cluster(arg: &str) -> Option<(&str, &str)> {
    if !arg.starts_with('-') || arg.starts_with("--") || arg == "-" {
        return None;
    }
    let rest = &arg[1..];
    let mut idx = 0;
    for c in rest.chars() {
        if c == 'S' {
            let prefix_end = 1 + idx + c.len_utf8();
            return Some((&arg[..prefix_end], &arg[prefix_end..]));
        }
        if crate::deny::env_takes_value(c) {
            return None;
        }
        idx += c.len_utf8();
    }
    None
}

fn drop_denied_from_split_string(s: &str) -> String {
    let tokens: Vec<&str> = s.split_whitespace().collect();
    let mut out = Vec::new();
    let mut i = 0;
    while i < tokens.len() {
        let raw = tokens[i];
        if raw == "--" || raw == "-" {
            out.extend_from_slice(&tokens[i..]);
            break;
        }
        if let Some(skip) = env_flag_skip(raw) {
            let end = (i + skip).min(tokens.len());
            out.extend_from_slice(&tokens[i..end]);
            i = end;
            continue;
        }
        if let Some(eq) = raw.find('=') {
            let name = &raw[..eq];
            if !name.is_empty() && is_denied_child_env(name) {
                i += 1;
                continue;
            }
            out.push(raw);
            i += 1;
            continue;
        }
        out.extend_from_slice(&tokens[i..]);
        break;
    }
    out.join(" ")
}

fn insert_bash_noprofile(args: &mut Vec<OsString>, at: usize) {
    let has_noprofile = args[at..].iter().any(|a| a == "--noprofile");
    let has_norc = args[at..].iter().any(|a| a == "--norc");
    if !has_noprofile {
        args.insert(at, OsString::from("--noprofile"));
    }
    if !has_norc {
        let idx = args[at..]
            .iter()
            .position(|a| a == "--noprofile")
            .map(|i| at + i + 1)
            .unwrap_or(at);
        args.insert(idx, OsString::from("--norc"));
    }
}

fn is_bash_argv0(program: &OsStr) -> bool {
    let raw = program.to_string_lossy();
    let name = raw.rsplit(['/', '\\']).next().unwrap_or(raw.as_ref());
    name.eq_ignore_ascii_case("bash") || name.eq_ignore_ascii_case("bash.exe")
}

fn is_env_argv0(program: &OsStr) -> bool {
    crate::deny::is_env_program(program)
}

fn first_env_arg(args: &[OsString]) -> Option<usize> {
    args.iter().position(|a| is_env_argv0(a.as_os_str()))
}

fn first_env_bash_operand(args: &[OsString]) -> Option<usize> {
    let mut i = 0;
    while i < args.len() {
        let raw = args[i].to_string_lossy();
        if raw == "--" {
            return args
                .get(i + 1)
                .filter(|a| is_bash_argv0(a.as_os_str()))
                .map(|_| i + 1);
        }
        if let Some(skip) = env_flag_skip(&raw) {
            i = i.saturating_add(skip);
            continue;
        }
        if raw.contains('=') {
            i += 1;
            continue;
        }
        if is_bash_argv0(args[i].as_os_str()) {
            return Some(i);
        }
        return None;
    }
    None
}

fn cmd_wrapper(program: &OsStr) -> Option<crate::deny::CmdWrapper> {
    crate::deny::cmd_wrapper(program)
}

fn skip_wrapper_os(kind: crate::deny::CmdWrapper, args: &[OsString]) -> usize {
    let raws: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    crate::deny::skip_wrapper_prefix(kind, &raws)
}

fn first_wrapper_bash_operand(kind: crate::deny::CmdWrapper, args: &[OsString]) -> Option<usize> {
    let start = skip_wrapper_os(kind, args);
    let rest = args.get(start..)?;
    if rest.first().is_some_and(|a| is_bash_argv0(a.as_os_str())) {
        return Some(start);
    }
    if rest.first().is_some_and(|a| is_env_argv0(a.as_os_str())) {
        return first_env_bash_operand(&rest[1..]).map(|i| start + 1 + i);
    }
    None
}

fn env_flag_skip(arg: &str) -> Option<usize> {
    crate::deny::env_flag_skip(arg)
}

/// Call `spawn` only when token or job setup succeeded.
pub fn spawn_after_setup<T>(
    setup: Result<T, KernelError>,
    spawn: impl FnOnce(T) -> Result<(KernelApply, ExitStatus), KernelError>,
) -> Result<(KernelApply, ExitStatus), KernelError> {
    spawn(setup?)
}

/// Refuse a userspace-only inspect result on the spawn path.
///
/// [`KernelApply::RemountSkipped`] and [`KernelApply::WfpSkipped`] still
/// start the child. Hosts that require remount or WFP match those
/// variants themselves, or call [`require_dest_hide`].
pub fn require_applied(applied: KernelApply) -> Result<KernelApply, KernelError> {
    match applied {
        KernelApply::Applied | KernelApply::RemountSkipped | KernelApply::WfpSkipped => Ok(applied),
        KernelApply::UserspaceOnly => Err(KernelError::Apply(
            "kernel jail did not apply; child was not started".into(),
        )),
    }
}

/// Refuse a spawn when Linux dest-deny remount did not hide in-tree dests.
///
/// [`KernelApply::WfpSkipped`] still starts the child (AppContainer is
/// the Windows net deny). [`KernelApply::RemountSkipped`] does not.
pub fn require_dest_hide(applied: KernelApply) -> Result<KernelApply, KernelError> {
    match applied {
        KernelApply::Applied | KernelApply::WfpSkipped => Ok(applied),
        KernelApply::RemountSkipped => Err(KernelError::Apply(
            "dest-deny remount unavailable (unshare, user-namespace id map, or private remount of /); child was not started".into(),
        )),
        KernelApply::UserspaceOnly => Err(KernelError::Apply(
            "kernel jail did not apply; child was not started".into(),
        )),
    }
}

const DEST_DENY_WALK_LIMIT: usize = 65_536;
/// Duplicated from gc (feature-gated). Do not import `gc::CACHE_DIR_NAMES`.
const DEST_DENY_CACHE_DIR_NAMES: &[&str] =
    &["target", "node_modules", ".venv", "dist", "__pycache__"];

/// Existing dest-deny files and glob directories under `workspace`,
/// including hardlink siblings.
///
/// Does not apply the jail. Does not follow directory symlinks. Does
/// not descend `.git`. Cache trees are walked for dest-deny glob names
/// only (no hardlink sibling scan); non-deny rustc artifacts do not
/// count toward the entry cap. Walk failure or an entry cap is
/// [`KernelError::Root`].
pub fn collect_workspace_dest_denies(
    workspace: &Path,
    policy: &DenyPolicy,
) -> Result<Vec<DestDeny>, KernelError> {
    collect_workspace_dest_denies_limited(workspace, policy, DEST_DENY_WALK_LIMIT)
}

/// Same as [`collect_workspace_dest_denies`] with a host-chosen entry cap.
pub fn collect_workspace_dest_denies_limited(
    workspace: &Path,
    policy: &DenyPolicy,
    limit: usize,
) -> Result<Vec<DestDeny>, KernelError> {
    let mut out = Vec::new();
    let mut remaining = limit;
    walk_dest_denies(
        workspace,
        Some(workspace),
        policy,
        &mut out,
        &mut remaining,
        limit,
    )?;
    Ok(out)
}

fn dest_deny_walk_cap(dir: &Path, limit: usize) -> KernelError {
    KernelError::Root(format!(
        "dest-deny walk exceeded {limit} entries under {}",
        dir.display()
    ))
}

fn dest_deny_walk_io(dir: &Path, err: std::io::Error) -> KernelError {
    KernelError::Root(format!("dest-deny walk {}: {err}", dir.display()))
}

fn entry_file_name(path: &Path) -> &str {
    path.file_name().and_then(|n| n.to_str()).unwrap_or("")
}

fn is_git_dir_name(name: &str) -> bool {
    name.eq_ignore_ascii_case(".git")
}

fn is_dest_deny_cache_dir_name(name: &str) -> bool {
    DEST_DENY_CACHE_DIR_NAMES
        .iter()
        .any(|n| name.eq_ignore_ascii_case(n))
}

/// Extra-root is a cache tree when any path component is a cache
/// dir name. Basename-only misses `--extra-root …/target/debug`.
fn extra_root_is_cache_tree(path: &Path) -> bool {
    path.components().any(|c| match c {
        std::path::Component::Normal(s) => is_dest_deny_cache_dir_name(&s.to_string_lossy()),
        _ => false,
    })
}

/// Dest-deny a real directory. Directory symlinks are not followed
/// (`false`). Shared so every walk dest-denies the dir before recurse.
fn dest_deny_if_real_dir(
    path: &Path,
    ft: std::fs::FileType,
    policy: &DenyPolicy,
    out: &mut Vec<DestDeny>,
    glob_root: Option<&Path>,
) -> bool {
    if !ft.is_dir() || ft.is_symlink() {
        return false;
    }
    if let Some(deny) = dest_deny_at_root(path, path.display().to_string(), policy, glob_root) {
        push_dest_deny(out, deny);
    }
    true
}

fn walk_dest_denies(
    dir: &Path,
    glob_root: Option<&Path>,
    policy: &DenyPolicy,
    out: &mut Vec<DestDeny>,
    remaining: &mut usize,
    limit: usize,
) -> Result<(), KernelError> {
    if *remaining == 0 {
        return Err(dest_deny_walk_cap(dir, limit));
    }
    let rd = std::fs::read_dir(dir).map_err(|e| dest_deny_walk_io(dir, e))?;
    for ent in rd {
        let ent = ent.map_err(|e| dest_deny_walk_io(dir, e))?;
        let path = ent.path();
        let name = entry_file_name(&path);
        if is_git_dir_name(name) {
            continue;
        }
        let ft = ent.file_type().map_err(|e| dest_deny_walk_io(&path, e))?;
        if is_dest_deny_cache_dir_name(name) && ft.is_dir() && !ft.is_symlink() {
            walk_cache_dest_denies(&path, policy, out, remaining, limit)?;
            continue;
        }
        if *remaining == 0 {
            return Err(dest_deny_walk_cap(dir, limit));
        }
        *remaining -= 1;
        if dest_deny_if_real_dir(&path, ft, policy, out, glob_root) {
            walk_dest_denies(&path, glob_root, policy, out, remaining, limit)?;
            continue;
        }
        if let Some(deny) = dest_deny_at_root(&path, path.display().to_string(), policy, glob_root)
        {
            push_dest_deny(out, deny);
        }
    }
    Ok(())
}

fn is_system_read_extra(path: &Path) -> bool {
    system_read_dirs()
        .iter()
        .any(|d| path == d || path.starts_with(d))
}

/// Dest-deny scan of `/tmp` (and host temp). Immediate dest-deny names
/// plus dest-deny directory names. Ordinary subdirectories are walked
/// for dest-deny names only (same as cache walk). Do not follow
/// directory symlinks. Do not walk every file under `/tmp`.
fn collect_system_temp_dest_denies(
    extra: &Path,
    policy: &DenyPolicy,
    out: &mut Vec<DestDeny>,
    remaining: &mut usize,
    limit: usize,
) -> Result<(), KernelError> {
    let rd = std::fs::read_dir(extra).map_err(|e| dest_deny_walk_io(extra, e))?;
    for ent in rd {
        let ent = ent.map_err(|e| dest_deny_walk_io(extra, e))?;
        let path = ent.path();
        let name = entry_file_name(&path);
        if is_git_dir_name(name) {
            continue;
        }
        let ft = ent.file_type().map_err(|e| dest_deny_walk_io(&path, e))?;
        if dest_deny_if_real_dir(&path, ft, policy, out, None) {
            if is_dest_deny_dir_name(name) {
                walk_temp_dest_denies(&path, policy, out, remaining, limit)?;
            } else {
                collect_temp_dir_dest_names(&path, policy, out, remaining, limit)?;
            }
            continue;
        }
        if let Some(deny) = dest_deny_at(&path, path.display().to_string(), policy) {
            if *remaining == 0 {
                return Err(dest_deny_walk_cap(extra, limit));
            }
            *remaining -= 1;
            push_dest_deny(out, deny);
        }
    }
    Ok(())
}

fn is_dest_deny_dir_name(name: &str) -> bool {
    matches!(
        name,
        ".ssh" | ".aws" | ".kube" | ".gnupg" | ".docker" | "secrets" | "credentials" | "gateway"
    )
}

fn is_system_temp_root(path: &Path) -> bool {
    let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
        return false;
    };
    if !name.eq_ignore_ascii_case("tmp") && !name.eq_ignore_ascii_case("temp") {
        return false;
    }
    let Some(parent) = path.parent() else {
        return true;
    };
    parent == Path::new("/")
        || parent == Path::new("\\")
        || parent.ends_with("private")
        || parent.ends_with("var")
}

/// One extra level under an ordinary `/tmp` subdirectory. Catches
/// `/tmp/proj/.env` without walking `/tmp/proj/node_modules`. Dest-deny
/// directory names still recurse. Skip unreadable entries.
fn collect_temp_dir_dest_names(
    dir: &Path,
    policy: &DenyPolicy,
    out: &mut Vec<DestDeny>,
    remaining: &mut usize,
    limit: usize,
) -> Result<(), KernelError> {
    let rd = match std::fs::read_dir(dir) {
        Ok(rd) => rd,
        Err(_) => return Ok(()),
    };
    for ent in rd {
        let ent = match ent {
            Ok(ent) => ent,
            Err(_) => continue,
        };
        let path = ent.path();
        let name = entry_file_name(&path);
        if is_git_dir_name(name) {
            continue;
        }
        let ft = match ent.file_type() {
            Ok(ft) => ft,
            Err(_) => continue,
        };
        if dest_deny_if_real_dir(&path, ft, policy, out, None) {
            if is_dest_deny_dir_name(name) {
                walk_temp_dest_denies(&path, policy, out, remaining, limit)?;
            }
            continue;
        }
        if ft.is_dir() {
            continue;
        }
        if let Some(deny) = dest_deny_at(&path, path.display().to_string(), policy) {
            if *remaining == 0 {
                return Err(dest_deny_walk_cap(dir, limit));
            }
            *remaining -= 1;
            push_dest_deny(out, deny);
        }
    }
    Ok(())
}

/// Like [`walk_cache_dest_denies`], but skip unreadable dirs. `/tmp`
/// has other-user 0700 trees; those are not a dest-deny walk failure.
fn walk_temp_dest_denies(
    dir: &Path,
    policy: &DenyPolicy,
    out: &mut Vec<DestDeny>,
    remaining: &mut usize,
    limit: usize,
) -> Result<(), KernelError> {
    let rd = match std::fs::read_dir(dir) {
        Ok(rd) => rd,
        Err(_) => return Ok(()),
    };
    for ent in rd {
        let ent = match ent {
            Ok(ent) => ent,
            Err(_) => continue,
        };
        let path = ent.path();
        let name = entry_file_name(&path);
        if is_git_dir_name(name) {
            continue;
        }
        let ft = match ent.file_type() {
            Ok(ft) => ft,
            Err(_) => continue,
        };
        if dest_deny_if_real_dir(&path, ft, policy, out, None) {
            walk_temp_dest_denies(&path, policy, out, remaining, limit)?;
            continue;
        }
        if let Some(deny) = dest_deny_at(&path, path.display().to_string(), policy) {
            if *remaining == 0 {
                return Err(dest_deny_walk_cap(dir, limit));
            }
            *remaining -= 1;
            push_dest_deny(out, deny);
        }
    }
    Ok(())
}

/// Walk a cache tree for dest-deny glob names only. Non-deny files are
/// not charged to the entry cap. Does not follow directory symlinks.
/// Does not canonicalize or hardlink-scan rustc artifacts (`nlink` in
/// `target/debug/deps` is O(entries^2) and stalls `run --root` on a
/// populated cargo tree).
fn walk_cache_dest_denies(
    dir: &Path,
    policy: &DenyPolicy,
    out: &mut Vec<DestDeny>,
    remaining: &mut usize,
    limit: usize,
) -> Result<(), KernelError> {
    let rd = std::fs::read_dir(dir).map_err(|e| dest_deny_walk_io(dir, e))?;
    for ent in rd {
        let ent = ent.map_err(|e| dest_deny_walk_io(dir, e))?;
        let path = ent.path();
        let name = entry_file_name(&path);
        if is_git_dir_name(name) {
            continue;
        }
        let ft = ent.file_type().map_err(|e| dest_deny_walk_io(&path, e))?;
        if dest_deny_if_real_dir(&path, ft, policy, out, None) {
            walk_cache_dest_denies(&path, policy, out, remaining, limit)?;
            continue;
        }
        if let Some(deny) = dest_deny_glob_only(&path, path.display().to_string(), policy) {
            if *remaining == 0 {
                return Err(dest_deny_walk_cap(dir, limit));
            }
            *remaining -= 1;
            push_dest_deny(out, deny);
        }
    }
    Ok(())
}

fn dest_deny_from_path(path: &Path, policy: &DenyPolicy) -> DestDeny {
    dest_deny_at(path, path.display().to_string(), policy).unwrap_or(DestDeny {
        kind: DestDenyKind::DenyGlob,
        path: path.to_path_buf(),
        display: path.display().to_string(),
        matched: None,
    })
}

fn push_dest_deny(out: &mut Vec<DestDeny>, deny: DestDeny) {
    if out
        .iter()
        .any(|d| d.path == deny.path && d.kind == deny.kind)
    {
        return;
    }
    out.push(deny);
}

/// Seatbelt dest-deny of workspace secrets. Platform rules emit last so
/// they win over the workspace ReadWrite allow (nono last-rule-wins).
/// Do not use `require-not` inside deny (invalid SBPL).
#[cfg(target_os = "macos")]
fn add_macos_dest_deny_rules(
    caps: &mut nono::CapabilitySet,
    denies: &[DestDeny],
    rw_roots: &[&Path],
    globs: &[String],
) -> Result<(), KernelError> {
    for deny in denies {
        for path in dest_deny_rule_paths(&deny.path) {
            let Some(raw) = path.to_str() else {
                return Err(KernelError::Apply(format!(
                    "dest-deny path is not UTF-8: {}",
                    path.display()
                )));
            };
            let escaped = escape_sbpl_literal(raw);
            let filter = if path.is_dir() {
                format!("subpath \"{escaped}\"")
            } else {
                format!("literal \"{escaped}\"")
            };
            for action in macos_dest_deny_actions() {
                let rule = format!("(deny {action} ({filter}))");
                caps.add_platform_rule(&rule)
                    .map_err(|e| KernelError::Apply(e.to_string()))?;
            }
        }
    }
    for root in rw_roots {
        add_macos_post_create_rules(caps, root, globs)?;
    }
    Ok(())
}

/// Name-based denies so a child `touch .env` then `cat .env` is still blocked.
#[cfg(target_os = "macos")]
fn add_macos_post_create_rules(
    caps: &mut nono::CapabilitySet,
    workspace: &Path,
    globs: &[String],
) -> Result<(), KernelError> {
    for workspace in dest_deny_rule_paths(workspace) {
        let Some(raw) = workspace.to_str() else {
            return Err(KernelError::Apply(format!(
                "workspace path is not UTF-8: {}",
                workspace.display()
            )));
        };
        let prefix = escape_regex_literal(raw);
        // One filter only. Combined (subpath)(regex) denied the whole tree.
        let mut regexes = macos_post_create_env_regexes(&prefix);
        for glob in globs {
            // Default `**/.env.*` is replaced by the template-aware segment
            // regexes. Any other glob, including a custom dotenv pattern,
            // still becomes a Seatbelt regex.
            if crate::deny::is_default_env_star_glob(glob) {
                continue;
            }
            if let Some(re) = crate::dest_deny_glob_regex(&prefix, glob) {
                regexes.push(re);
            }
        }
        for regex in regexes {
            let regex = escape_sbpl_literal(&regex);
            for action in macos_dest_deny_actions() {
                let rule = format!("(deny {action} (regex \"{regex}\"))");
                caps.add_platform_rule(&rule)
                    .map_err(|e| KernelError::Apply(e.to_string()))?;
            }
        }
    }
    Ok(())
}

/// As-given path, canonicalize, and `/private` firmlink aliases.
/// Used for Seatbelt literals and Linux remount dests under `/tmp` /
/// `/var` / `/etc`.
#[cfg(any(unix, test))]
fn dest_deny_rule_paths(path: &Path) -> Vec<PathBuf> {
    let mut out = vec![path.to_path_buf()];
    if let Ok(canon) = dunce::canonicalize(path)
        && canon != path
    {
        out.push(canon);
    }
    let aliases: Vec<PathBuf> = out.iter().filter_map(|p| firmlink_alias(p)).collect();
    for alias in aliases {
        if !out.iter().any(|p| p == &alias) {
            out.push(alias);
        }
    }
    out
}

/// `/tmp` ↔ `/private/tmp`, `/var` ↔ `/private/var`, `/etc` ↔ `/private/etc`.
#[cfg(any(unix, test))]
fn firmlink_alias(path: &Path) -> Option<PathBuf> {
    let raw = path.to_str()?;
    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
}

#[cfg(target_os = "macos")]
fn macos_post_create_env_regexes(prefix: &str) -> Vec<String> {
    let star = env_star_segment();
    vec![
        format!("^{prefix}/[.][Ee][Nn][Vv]$"),
        format!("^{prefix}/.*/[.][Ee][Nn][Vv]$"),
        format!("^{prefix}/{star}$"),
        format!("^{prefix}/.*/{star}$"),
    ]
}

/// One path segment: `.env` or `.env.<tail>` where the tail's last
/// dot-segment is not exactly `example`, `sample`, or `template`.
#[cfg(target_os = "macos")]
fn env_star_segment() -> String {
    let last = format!(
        "({one}|{two}|{three}|{four}|{five}|{sample}|{example}|{template}|{nine})",
        one = "[^.]",
        two = "[^.][^.]?",
        three = "[^.][^.][^.]?",
        four = "[^.][^.][^.][^.]?",
        five = "[^.][^.][^.][^.][^.]?",
        sample = not_exact_segment("sample"),
        example = not_exact_segment("example"),
        template = not_exact_segment("template"),
        nine = "[^.][^.][^.][^.][^.][^.][^.][^.][^.][^.]*",
    );
    format!(
        "[.][Ee][Nn][Vv]([.]([^.]{plus}\\.)*{last_seg})?",
        plus = "+",
        last_seg = last
    )
}

#[cfg(target_os = "macos")]
fn not_exact_segment(word: &str) -> String {
    let mut alts = Vec::new();
    let chars: Vec<char> = word.chars().collect();
    for (i, ch) in chars.iter().enumerate() {
        let mut part = String::new();
        for prev in &chars[..i] {
            part.push_str(&letter_class(*prev));
        }
        part.push_str(&neg_letter(*ch));
        for _ in 0..(chars.len() - i - 1) {
            part.push_str("[^.]");
        }
        alts.push(part);
    }
    format!("({})", alts.join("|"))
}

#[cfg(target_os = "macos")]
fn letter_class(ch: char) -> String {
    format!("[{}{}]", ch.to_ascii_uppercase(), ch.to_ascii_lowercase())
}

#[cfg(target_os = "macos")]
fn neg_letter(ch: char) -> String {
    format!("[^{}{}.]", ch.to_ascii_uppercase(), ch.to_ascii_lowercase())
}

/// File operations plus `network-outbound`. Seatbelt treats `connect(2)`
/// to a Unix socket as network, so a file deny alone still allows it.
/// `--net` must not open a socket under a dest-denied path.
#[cfg(target_os = "macos")]
fn macos_dest_deny_actions() -> &'static [&'static str] {
    &[
        "file-read*",
        "file-write*",
        "file-write-data",
        "file-write-create",
        "file-write-unlink",
        "file-write-mode",
        "file-write-owner",
        "network-outbound",
    ]
}

/// Child-only hardening after remount, before Landlock and exec.
/// `RLIMIT_CORE=0` survives exec. Linux dumpable does not.
#[cfg(unix)]
fn apply_child_hardening() -> std::io::Result<()> {
    #[cfg(unix)]
    {
        let zero = libc::rlimit {
            rlim_cur: 0,
            rlim_max: 0,
        };
        // SAFETY: RLIMIT_CORE on this thread, which is the forked child.
        if unsafe { libc::setrlimit(libc::RLIMIT_CORE, &zero) } != 0 {
            return Err(std::io::Error::last_os_error());
        }
    }
    #[cfg(target_os = "linux")]
    {
        // SAFETY: PR_SET_DUMPABLE on this thread, the forked child.
        if unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) } != 0 {
            return Err(std::io::Error::last_os_error());
        }
    }
    #[cfg(target_os = "macos")]
    {
        const PT_DENY_ATTACH: libc::c_int = 31;
        // SAFETY: ptrace PT_DENY_ATTACH on this process, the forked child.
        if unsafe { libc::ptrace(PT_DENY_ATTACH, 0, std::ptr::null_mut(), 0) } != 0 {
            return Err(std::io::Error::last_os_error());
        }
    }
    Ok(())
}

#[cfg(target_os = "macos")]
fn escape_sbpl_literal(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

#[cfg(target_os = "macos")]
fn escape_regex_literal(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if matches!(
            c,
            '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '^' | '$'
        ) {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

fn refuse_home_workspace(workspace: &Path) -> Result<(), KernelError> {
    let resolved = match std::fs::canonicalize(workspace) {
        Ok(p) => p,
        Err(_) => return Ok(()),
    };
    if crate::guard::is_user_home_dir(&resolved) {
        return Err(KernelError::Home(resolved));
    }
    Ok(())
}

fn system_read_dirs() -> Vec<PathBuf> {
    #[cfg(unix)]
    {
        [
            "/usr",
            "/bin",
            "/lib",
            "/lib64",
            "/sbin",
            "/System",
            "/Library",
            "/dev",
            "/proc",
            "/etc",
            "/opt/homebrew",
            "/usr/local",
            "/var/select",
            "/private/var/select",
        ]
        .into_iter()
        .map(PathBuf::from)
        .collect()
    }
    #[cfg(windows)]
    {
        let mut dirs = Vec::new();
        if let Some(root) = std::env::var_os("SystemRoot") {
            let root = PathBuf::from(root);
            dirs.push(root.join("System32"));
            dirs.push(root);
        }
        if let Some(pf) = std::env::var_os("ProgramFiles") {
            dirs.push(PathBuf::from(pf));
        }
        dirs
    }
    #[cfg(not(any(unix, windows)))]
    {
        Vec::new()
    }
}

fn append_extra_dest_denies(
    extra: &Path,
    policy: &DenyPolicy,
    dest_denies: &mut Vec<DestDeny>,
    remaining: &mut usize,
) -> Result<(), KernelError> {
    if is_system_read_extra(extra) {
        return Ok(());
    }
    if is_system_temp_root(extra) {
        collect_system_temp_dest_denies(
            extra,
            policy,
            dest_denies,
            remaining,
            DEST_DENY_WALK_LIMIT,
        )?;
        return Ok(());
    }
    if extra_root_is_cache_tree(extra) {
        walk_cache_dest_denies(extra, policy, dest_denies, remaining, DEST_DENY_WALK_LIMIT)?;
        return Ok(());
    }
    walk_dest_denies(
        extra,
        None,
        policy,
        dest_denies,
        remaining,
        DEST_DENY_WALK_LIMIT,
    )
}

fn add_read_grant(grants: &mut Vec<KernelGrant>, path: &Path) -> Result<(), KernelError> {
    let resolved = canonicalize_dir(path)?;
    if crate::guard::is_user_home_dir(&resolved) {
        return Err(KernelError::Home(resolved));
    }
    if !is_fs_root(path) && path != resolved.as_path() {
        push_grant(grants, path.to_path_buf(), KernelAccess::Read);
    }
    if let Some(alias) = macos_public_alias(&resolved)
        && !is_fs_root(&alias)
        && alias != resolved
    {
        push_grant(grants, alias, KernelAccess::Read);
    }
    push_grant(grants, resolved, KernelAccess::Read);
    Ok(())
}

fn add_rw(grants: &mut Vec<KernelGrant>, path: &Path) -> Result<(), KernelError> {
    let resolved = canonicalize_dir(path)?;
    if crate::guard::is_user_home_dir(&resolved) {
        return Err(KernelError::Home(resolved));
    }
    // Grant the path as given so symlink lookups (`/tmp` -> `/private/tmp`) work.
    if !is_fs_root(path) && path != resolved.as_path() {
        push_grant(grants, path.to_path_buf(), KernelAccess::ReadWrite);
    }
    // CLI resolve_workspace_root returns canon only. On macOS, `/tmp/ws`
    // and `/var/folders/...` still appear on argv as the unprefixed form.
    if let Some(alias) = macos_public_alias(&resolved)
        && !is_fs_root(&alias)
        && alias != resolved
    {
        push_grant(grants, alias, KernelAccess::ReadWrite);
    }
    push_grant(grants, resolved, KernelAccess::ReadWrite);
    Ok(())
}

#[cfg(target_os = "macos")]
fn macos_public_alias(path: &Path) -> Option<PathBuf> {
    let s = path.to_str()?;
    s.strip_prefix("/private/")
        .map(|rest| PathBuf::from(format!("/{rest}")))
}

#[cfg(not(target_os = "macos"))]
fn macos_public_alias(_path: &Path) -> Option<PathBuf> {
    None
}

fn add_read_if_dir(grants: &mut Vec<KernelGrant>, path: &Path) {
    let Ok(meta) = std::fs::metadata(path) else {
        return;
    };
    if !meta.is_dir() {
        return;
    }
    let resolved = std::fs::canonicalize(path).ok();
    if resolved.as_ref().is_some_and(|p| is_fs_root(p)) {
        return;
    }
    // Grant the path as given so symlink lookups (`/etc` -> `/private/etc`) work.
    if !is_fs_root(path) {
        push_grant(grants, path.to_path_buf(), KernelAccess::Read);
    }
    if let Some(resolved) = resolved {
        push_grant(grants, resolved, KernelAccess::Read);
    }
}

fn push_grant(grants: &mut Vec<KernelGrant>, path: PathBuf, access: KernelAccess) {
    if let Some(existing) = grants.iter_mut().find(|g| g.path == path) {
        if access == KernelAccess::ReadWrite {
            existing.access = KernelAccess::ReadWrite;
        }
        return;
    }
    grants.push(KernelGrant { path, access });
}

fn canonicalize_dir(path: &Path) -> Result<PathBuf, KernelError> {
    let resolved = std::fs::canonicalize(path)
        .map_err(|e| KernelError::Root(format!("{}: {e}", path.display())))?;
    if !resolved.is_dir() {
        return Err(KernelError::Root(format!(
            "{} is not a directory",
            path.display()
        )));
    }
    if is_fs_root(&resolved) {
        return Err(KernelError::FsRoot(resolved));
    }
    Ok(resolved)
}

fn is_fs_root(path: &Path) -> bool {
    match path.parent() {
        None => true,
        Some(parent) => parent.as_os_str().is_empty(),
    }
}

#[cfg(all(test, unix))]
mod timeout_deadline_tests {
    use std::time::Duration;

    use super::{KernelError, timeout_deadline};

    #[test]
    fn one_second_fits() {
        assert!(timeout_deadline(Duration::from_secs(1)).is_ok());
    }

    #[test]
    fn max_seconds_does_not_fit() {
        let err = timeout_deadline(Duration::from_secs(u64::MAX)).expect_err("overflow");
        assert!(
            matches!(err, KernelError::Apply(ref msg) if msg.contains("does not fit")),
            "{err:?}"
        );
    }
}

#[cfg(test)]
mod noprofile_tests {
    use super::with_bash_noprofile;

    #[test]
    fn env_after_unknown_prefix_inserts_after_bash() {
        let (_got, args) = with_bash_noprofile("watch", ["env", "bash", "-c", "true"]);
        assert_eq!(args, ["env", "bash", "--noprofile", "--norc", "-c", "true"]);
        let (_got, args) =
            with_bash_noprofile("watch", ["env", "BASH_ENV=.env", "bash", "-c", "true"]);
        assert_eq!(args, ["env", "bash", "--noprofile", "--norc", "-c", "true"]);
        let (_got, args) = with_bash_noprofile("watch", ["bash", "-c", "true"]);
        assert_eq!(
            args,
            ["bash", "-c", "true"],
            "watch bash without env must not invent noprofile"
        );
    }
}

#[cfg(test)]
mod combine_spawn_restore_tests {
    #[cfg(target_os = "macos")]
    use super::macos_post_create_env_regexes;
    use super::{
        KernelApply, KernelError, WFP_ERROR_ACCESS_DENIED, combine_spawn_restore,
        dest_deny_rule_paths, process_jail, require_applied, require_dest_hide,
        wfp_skip_access_denied,
    };
    use std::path::Path;
    use std::process::ExitStatus;

    fn status(code: i32) -> ExitStatus {
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt;
            ExitStatus::from_raw(code << 8)
        }
        #[cfg(windows)]
        {
            use std::os::windows::process::ExitStatusExt;
            ExitStatus::from_raw(code as u32)
        }
    }

    #[test]
    fn timeout_wins_over_restore_failure() {
        let err = combine_spawn_restore(
            Err(KernelError::Timeout),
            Err(KernelError::Apply("restore DACL failed (win32 5)".into())),
        )
        .expect_err("timeout must stay timeout");
        assert!(
            matches!(err, KernelError::Timeout),
            "Timeout plus restore failure must stay Timeout, got {err}"
        );
    }

    #[test]
    fn spawn_apply_keeps_apply_and_names_restore() {
        let err = combine_spawn_restore(
            Err(KernelError::Apply(
                "CreateProcessAsUserW failed (win32 5)".into(),
            )),
            Err(KernelError::Apply("restore DACL failed (win32 5)".into())),
        )
        .expect_err("combined apply");
        let KernelError::Apply(msg) = err else {
            panic!("expected Apply, got {err}");
        };
        assert!(
            msg.contains("CreateProcessAsUserW"),
            "spawn Apply must not be dropped: {msg}"
        );
        assert!(
            msg.contains("restore DACL"),
            "restore failure must be named: {msg}"
        );
    }

    #[test]
    fn successful_child_plus_restore_failure_names_exit() {
        let err = combine_spawn_restore(
            Ok((KernelApply::Applied, status(0))),
            Err(KernelError::Apply("restore DACL failed (win32 5)".into())),
        )
        .expect_err("restore after success");
        let KernelError::Restore(msg) = err else {
            panic!("expected Restore, got {err}");
        };
        assert!(
            msg.contains("child exited 0"),
            "successful child must name exit: {msg}"
        );
        assert!(
            msg.contains("restore DACL"),
            "restore failure must be named: {msg}"
        );
    }

    #[test]
    fn wfp_access_denied_is_skip_and_other_codes_are_not() {
        assert!(wfp_skip_access_denied(WFP_ERROR_ACCESS_DENIED));
        assert!(wfp_skip_access_denied(5));
        assert!(!wfp_skip_access_denied(0));
        assert!(!wfp_skip_access_denied(2));
        assert!(!wfp_skip_access_denied(87));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_post_create_env_regexes_match_dot_env_any_case() {
        let got = macos_post_create_env_regexes("/ws");
        assert_eq!(got.len(), 4, "{got:?}");
        assert!(got[0].contains("[.][Ee][Nn][Vv]$"), "{got:?}");
        assert!(got[2].contains("[.][Ee][Nn][Vv]"), "{got:?}");
        assert!(
            !got[2].contains("[.].*$"),
            "star regex must not be an open .env.* : {got:?}"
        );
        assert_env_star_regex_skips_templates(&got[2]);
    }

    #[cfg(target_os = "macos")]
    fn assert_env_star_regex_skips_templates(star_anchored: &str) {
        let mut re = unsafe { std::mem::zeroed::<libc::regex_t>() };
        let c = std::ffi::CString::new(star_anchored).expect("regex");
        let rc =
            unsafe { libc::regcomp(&mut re, c.as_ptr(), libc::REG_EXTENDED | libc::REG_NOSUB) };
        assert_eq!(rc, 0, "seatbelt env-star regex must compile");
        let check = |name: &str, want: bool| {
            let path = std::ffi::CString::new(format!("/ws/{name}")).expect("path");
            let hit = unsafe { libc::regexec(&re, path.as_ptr(), 0, std::ptr::null_mut(), 0) } == 0;
            assert_eq!(
                hit, want,
                "{name} match={hit} want={want} re={star_anchored}"
            );
        };
        check(".env.local", true);
        check(".env.production", true);
        check(".ENV.LOCAL", true);
        check(".env.example", false);
        check(".env.EXAMPLE", false);
        check(".env.sample", false);
        check(".env.template", false);
        check(".env.local.example", false);
        check("readme.md", false);
        unsafe { libc::regfree(&mut re) };
    }

    #[test]
    fn dest_deny_rule_paths_emits_firmlink_aliases() {
        let got = dest_deny_rule_paths(Path::new("/tmp/.env"));
        assert!(
            got.iter().any(|p| p == Path::new("/tmp/.env")),
            "as-given /tmp/.env must stay: {got:?}"
        );
        assert!(
            got.iter().any(|p| p == Path::new("/private/tmp/.env")),
            "/tmp/.env must also deny /private/tmp/.env: {got:?}"
        );
        let got = dest_deny_rule_paths(Path::new("/private/var/folders/x/.env"));
        assert!(
            got.iter().any(|p| p == Path::new("/var/folders/x/.env")),
            "/private/var must also deny /var: {got:?}"
        );
        let got = dest_deny_rule_paths(Path::new("/etc/ssh/ssh_host_rsa_key"));
        assert!(
            got.iter()
                .any(|p| p == Path::new("/private/etc/ssh/ssh_host_rsa_key")),
            "/etc must also deny /private/etc: {got:?}"
        );
    }

    #[test]
    fn require_applied_accepts_remount_and_wfp_skip() {
        assert_eq!(
            require_applied(KernelApply::RemountSkipped).expect("remount skip"),
            KernelApply::RemountSkipped
        );
        assert_eq!(
            require_applied(KernelApply::WfpSkipped).expect("wfp skip"),
            KernelApply::WfpSkipped
        );
    }

    #[test]
    fn require_dest_hide_rejects_remount_skip() {
        let err = require_dest_hide(KernelApply::RemountSkipped).expect_err("remount skip");
        match err {
            KernelError::Apply(msg) => {
                assert!(
                    msg.contains("remount unavailable"),
                    "error must name remount: {msg}"
                );
                assert!(
                    msg.contains("child was not started"),
                    "error must say child was not started: {msg}"
                );
                for phrase in ["unshare", "user-namespace id map", "private remount of /"] {
                    assert!(
                        msg.contains(phrase),
                        "remount refusal must name {phrase}: {msg}"
                    );
                }
            }
            other => panic!("expected Apply, got {other}"),
        }
        assert_eq!(
            require_dest_hide(KernelApply::Applied).expect("Applied"),
            KernelApply::Applied
        );
        assert_eq!(
            require_dest_hide(KernelApply::WfpSkipped).expect("wfp skip"),
            KernelApply::WfpSkipped
        );
    }

    #[test]
    fn extra_root_temp_collects_nested_dest_deny_names() {
        let ws = tempfile::TempDir::new().expect("ws");
        let extra = tempfile::TempDir::new().expect("extra");
        let tmp = extra.path().join("private").join("tmp");
        let proj = tmp.join("proj");
        std::fs::create_dir_all(&proj).expect("proj");
        std::fs::write(proj.join(".env"), "SECRET=1\n").expect(".env");
        std::fs::write(tmp.join("readme.md"), "ok\n").expect("readme");
        let policy = process_jail(ws.path(), [tmp.as_path()]).expect("jail");
        assert!(
            policy
                .dest_denies()
                .iter()
                .any(|d| d.path.ends_with(Path::new("proj/.env"))
                    || d.path.ends_with(Path::new("proj\\.env"))),
            "nested extra-root /tmp dest-deny name must be collected: {:?}",
            policy.dest_denies()
        );
        assert!(
            !policy
                .dest_denies()
                .iter()
                .any(|d| d.path.ends_with("readme.md")),
            "non-deny extra-root file must not be collected"
        );
    }

    #[test]
    fn extra_root_temp_collects_ssh_directory() {
        let ws = tempfile::TempDir::new().expect("ws");
        let extra = tempfile::TempDir::new().expect("extra");
        let tmp = extra.path().join("private").join("tmp");
        let proj = tmp.join("proj");
        let ssh = proj.join(".ssh");
        std::fs::create_dir_all(&ssh).expect("proj/.ssh");
        std::fs::write(ssh.join("id_ed25519"), "SECRET=1\n").expect("key");
        let policy = process_jail(ws.path(), [tmp.as_path()]).expect("jail");
        assert!(
            policy.dest_denies().iter().any(|d| d.path == ssh),
            "extra-root /tmp proj/.ssh directory must dest-deny: {:?}",
            policy.dest_denies()
        );
        assert!(
            policy
                .dest_denies()
                .iter()
                .any(|d| d.path == ssh.join("id_ed25519")),
            "nested extra-root .ssh file must still dest-deny: {:?}",
            policy.dest_denies()
        );
    }
}

#[cfg(test)]
mod doctor_facts_tests {
    use super::{DoctorFacts, doctor_fails};

    fn facts(
        kernel_supported: bool,
        remount_available: Option<bool>,
        wfp_skipped: Option<bool>,
        setup_failed: bool,
    ) -> DoctorFacts {
        DoctorFacts {
            kernel_supported,
            remount_available,
            wfp_skipped,
            setup_failed,
        }
    }

    #[test]
    fn unsupported_kernel_fails() {
        assert!(doctor_fails(facts(false, None, None, false)));
    }

    #[test]
    fn wfp_skip_alone_succeeds() {
        assert!(!doctor_fails(facts(true, None, Some(true), false)));
    }

    #[test]
    fn wfp_applied_succeeds() {
        assert!(!doctor_fails(facts(true, None, Some(false), false)));
    }

    #[test]
    fn linux_remount_unavailable_fails_even_when_kernel_works() {
        assert!(doctor_fails(facts(true, Some(false), None, false)));
    }

    #[test]
    fn linux_remount_available_succeeds() {
        assert!(!doctor_fails(facts(true, Some(true), None, false)));
    }

    #[test]
    fn setup_failure_fails() {
        assert!(doctor_fails(facts(true, None, None, true)));
    }
}