workpen 0.11.0

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

/// Drop the process-wide Windows AppContainer cache.
///
/// Dynamic WFP filters die with the session handle. The profile is
/// deleted here. Other platforms do nothing. `run_child` for a
/// workspace jail does not create this cache.
pub fn shutdown_process_jail() {
    #[cfg(windows)]
    windows::shutdown_jail_cache();
}

/// How many times this process called `CreateAppContainerProfile`.
/// Tests reset this. Not a stable host metric.
#[doc(hidden)]
#[cfg(windows)]
pub fn windows_appcontainer_creates() -> u32 {
    windows::appcontainer_creates()
}

/// Zero the `CreateAppContainerProfile` counter. Tests only.
#[doc(hidden)]
#[cfg(windows)]
pub fn reset_windows_appcontainer_creates() {
    windows::reset_appcontainer_creates();
}

/// 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,
    /// Parent directories of one-file grants and create-files directories.
    /// The bool is true for that parent (the ACE is required) and false
    /// for higher ancestors (access denied is skipped).
    #[cfg(windows)]
    traverse_dirs: Vec<(PathBuf, bool)>,
    /// Files this builder created. Removed on a hard grant failure.
    created: Vec<CreatedGrant>,
    /// Directories where the child may create regular files. Not a
    /// read-write root and not a dest-deny walk.
    create_files: Vec<CreateFiles>,
}

/// 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,
    /// One-file grant failed. Hosts match [`FileGrantReason`], not the sentence.
    #[error("kernel wrap file grant failed for {path}: {reason}")]
    FileGrant {
        path: PathBuf,
        reason: FileGrantReason,
    },
}

/// Why a one-file grant did not add that path.
///
/// Hosts match this. The `Display` text is for logs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileGrantReason {
    /// `create` was false, or the read grant's file is not there.
    Missing,
    /// The path exists and is not a regular file.
    NotRegular,
    /// The final component is a symlink. The parent may still be a junction.
    Symlink,
    /// Windows reserved device, including `NUL.txt`. `notes.NUL` is not one.
    ReservedDevice,
    /// The immediate parent does not exist. The grant does not create it.
    ParentMissing,
    /// The immediate parent exists and is not a directory.
    ParentNotDirectory,
    /// This kernel cannot grant new names in one directory without also
    /// granting the files beneath it. Linux Landlock is that kernel.
    Unsupported,
}

impl std::fmt::Display for FileGrantReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Missing => "file does not exist",
            Self::NotRegular => "is not a regular file",
            Self::Symlink => "is a symlink",
            Self::ReservedDevice => "is a reserved device name",
            Self::ParentMissing => "parent directory does not exist",
            Self::ParentNotDirectory => "parent is not a directory",
            Self::Unsupported => {
                "this kernel cannot create new files in one directory without granting the files beneath it"
            }
        })
    }
}

/// Result of [`KernelPolicy::try_write_file`] or [`KernelPolicy::try_read_file`].
///
/// [`FileGrantAttempt::Skipped`] keeps files this builder already created.
/// [`FileGrantAttempt::Failed`] has removed them. Dropping a [`Granted`](Self::Granted)
/// policy does not remove them: a failed spawn still leaves the new lock,
/// with mode 0600 on Unix and an owner-only DACL on Windows.
#[derive(Debug)]
pub enum FileGrantAttempt {
    Granted(KernelPolicy),
    Skipped {
        policy: KernelPolicy,
        path: PathBuf,
        reason: FileGrantReason,
    },
    Failed(KernelError),
}

/// One directory the child may create regular files in.
///
/// Not a read-write root. [`KernelPolicy::grants`] does not list it.
/// Dest-deny does not walk it. `prefix` limits names on macOS.
/// Windows allows any new file name in the directory and does not
/// open files that were already there. Linux returns
/// [`FileGrantReason::Unsupported`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateFiles {
    pub directory: PathBuf,
    pub prefix: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct CreatedGrant {
    path: PathBuf,
    id: FileId,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct FileId {
    #[cfg(unix)]
    dev: u64,
    #[cfg(unix)]
    ino: u64,
    #[cfg(windows)]
    volume: u32,
    #[cfg(windows)]
    index_high: u32,
    #[cfg(windows)]
    index_low: u32,
}

impl FileGrantAttempt {
    /// Turn a skip or a failure into [`KernelError::FileGrant`].
    ///
    /// A skip removes files this builder created. A failure already did.
    pub fn strict(self) -> Result<KernelPolicy, KernelError> {
        match self {
            Self::Granted(policy) => Ok(policy),
            Self::Skipped {
                mut policy,
                path,
                reason,
            } => {
                policy.rollback_created();
                Err(KernelError::FileGrant { path, reason })
            }
            Self::Failed(err) => Err(err),
        }
    }
}

/// 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. Linux `POLLOUT` means one byte
    /// fits, so retrying this chunk spins. Callers write one byte or wait.
    Again,
}

#[cfg(unix)]
enum PushNonblock {
    Wrote(usize),
    Wait,
    Stop,
}

/// Write up to `chunk` bytes. On `EAGAIN`, write one byte. A second
/// refusal waits. It does not retry the same chunk.
#[cfg(unix)]
fn push_nonblock(
    buf: &[u8],
    chunk: usize,
    mut write: impl FnMut(&[u8]) -> Option<ForwardWrite>,
) -> PushNonblock {
    if buf.is_empty() {
        return PushNonblock::Wrote(0);
    }
    let take = buf.len().min(chunk.max(1));
    match write(&buf[..take]) {
        Some(ForwardWrite::Wrote(n)) if n > 0 => PushNonblock::Wrote(n),
        Some(ForwardWrite::Again) if take > 1 => match write(&buf[..1]) {
            Some(ForwardWrite::Wrote(n)) if n > 0 => PushNonblock::Wrote(n),
            Some(ForwardWrite::Again) => PushNonblock::Wait,
            _ => PushNonblock::Stop,
        },
        Some(ForwardWrite::Again) => PushNonblock::Wait,
        _ => PushNonblock::Stop,
    }
}

#[cfg(all(test, unix))]
mod push_nonblock_tests {
    use super::{ForwardWrite, PushNonblock, push_nonblock};

    #[test]
    fn short_pipe_writes_one_byte_instead_of_retrying_the_chunk() {
        let data = vec![7u8; 2_000];
        let mut off = 0;
        let mut big_writes = 0u32;
        let mut steps = 0u32;
        while off < data.len() {
            steps += 1;
            assert!(steps < 10_000, "forward spun without progress");
            match push_nonblock(&data[off..], 512, |slice| {
                if slice.len() > 1 {
                    big_writes += 1;
                    Some(ForwardWrite::Again)
                } else {
                    Some(ForwardWrite::Wrote(1))
                }
            }) {
                PushNonblock::Wrote(n) => off += n,
                PushNonblock::Wait => panic!("one free byte must be written"),
                PushNonblock::Stop => panic!("forward stopped"),
            }
        }
        assert_eq!(off, data.len());
        assert!(big_writes < 5_000, "chunk retries ran away: {big_writes}");
    }

    #[test]
    fn one_byte_refusal_waits_instead_of_another_chunk() {
        let mut calls = 0u32;
        let step = push_nonblock(&[0u8; 512], 512, |slice| {
            calls += 1;
            assert!(slice.len() <= 512);
            Some(ForwardWrite::Again)
        });
        assert!(matches!(step, PushNonblock::Wait));
        assert_eq!(calls, 2, "one chunk attempt, then one byte, then wait");
    }
}

/// 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 => {
                        match push_nonblock(&buf[off..n], chunk, |slice| {
                            write_fd(out_fd, slice, toggle)
                        }) {
                            // A match guard is not exhaustive, so zero is its own arm.
                            PushNonblock::Wrote(0) | PushNonblock::Stop => return,
                            PushNonblock::Wait => continue,
                            PushNonblock::Wrote(wrote) => off += wrote,
                        }
                    }
                }
            }
        }
        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);
    }
}

/// How many times this process created the Windows re-exec AppContainer.
///
/// A second [`KernelPolicy::spawn_reexec`] in the same process does not
/// increment this. Other platforms stay at zero. `run_child` does not
/// increment it.
#[must_use]
pub fn reexec_profile_creates() -> u64 {
    #[cfg(windows)]
    {
        windows::reexec_profile_creates()
    }
    #[cfg(not(windows))]
    {
        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);
    }
    // One hardlink-directory scan for the workspace and every extra root.
    #[cfg(unix)]
    let _hardlink_scans = crate::deny::HardlinkScanScope::new();
    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,
        #[cfg(windows)]
        traverse_dirs: Vec::new(),
        created: Vec::new(),
        create_files: Vec::new(),
    })
}

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

fn file_grant(path: &Path, reason: FileGrantReason) -> KernelError {
    KernelError::FileGrant {
        path: path.to_path_buf(),
        reason,
    }
}

fn require_grant_file_name(path: &Path) -> Result<(), KernelError> {
    match path.file_name() {
        Some(name) if !name.is_empty() && name != "." && name != ".." => Ok(()),
        _ => Err(file_grant(path, FileGrantReason::NotRegular)),
    }
}

/// The immediate parent must be a directory. A symlink or junction is
/// followed. A missing parent is not created.
fn require_grant_parent_dir(path: &Path) -> Result<(), KernelError> {
    let parent = match path.parent() {
        Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
        Some(_) => PathBuf::from("."),
        None => return Err(file_grant(path, FileGrantReason::ParentMissing)),
    };
    match std::fs::symlink_metadata(&parent) {
        Ok(meta) if meta.file_type().is_symlink() => match std::fs::metadata(&parent) {
            Ok(followed) if followed.is_dir() => Ok(()),
            Ok(_) => Err(file_grant(path, FileGrantReason::ParentNotDirectory)),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                Err(file_grant(path, FileGrantReason::ParentMissing))
            }
            Err(_) => Err(file_grant(path, FileGrantReason::ParentNotDirectory)),
        },
        Ok(meta) if meta.is_dir() => Ok(()),
        Ok(_) => Err(file_grant(path, FileGrantReason::ParentNotDirectory)),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            Err(file_grant(path, FileGrantReason::ParentMissing))
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotADirectory => {
            Err(file_grant(path, FileGrantReason::ParentNotDirectory))
        }
        Err(err) => Err(KernelError::Root(format!("{}: {err}", path.display()))),
    }
}

enum GrantAdd {
    Added,
    Skip(FileGrantReason),
}

enum FileMode {
    Write { create: bool },
    Read,
}

impl FileMode {
    fn access(self) -> KernelAccess {
        match self {
            Self::Write { .. } => KernelAccess::ReadWrite,
            Self::Read => KernelAccess::Read,
        }
    }
}

fn create_empty_grant_file(path: &Path) -> Result<Option<CreatedGrant>, KernelError> {
    #[cfg(unix)]
    {
        create_empty_grant_file_unix(path)
    }
    #[cfg(windows)]
    {
        windows::create_owner_file(path)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = path;
        Err(KernelError::Apply(
            "file grants are not available on this platform".into(),
        ))
    }
}

#[cfg(unix)]
fn create_empty_grant_file_unix(path: &Path) -> Result<Option<CreatedGrant>, KernelError> {
    use std::os::unix::fs::OpenOptionsExt;
    let mut opts = std::fs::OpenOptions::new();
    opts.write(true).read(true).create_new(true).mode(0o600);
    let file = match opts.open(path) {
        Ok(file) => file,
        Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => return Ok(None),
        Err(err) => {
            return Err(KernelError::Root(format!("{}: {err}", path.display())));
        }
    };
    let rc = unsafe { libc::fchmod(file.as_raw_fd(), 0o600) };
    if rc != 0 {
        let err = std::io::Error::last_os_error();
        if let Ok(id) = unix_file_id(&file) {
            remove_created(&CreatedGrant {
                path: path.to_path_buf(),
                id,
            });
        }
        return Err(KernelError::Root(format!("{}: {err}", path.display())));
    }
    let id = unix_file_id(&file)?;
    if path_file_id(path) != Some(id) {
        return Err(file_grant(path, FileGrantReason::NotRegular));
    }
    Ok(Some(CreatedGrant {
        path: path.to_path_buf(),
        id,
    }))
}

#[cfg(unix)]
fn unix_file_id(file: &std::fs::File) -> Result<FileId, KernelError> {
    use std::os::unix::fs::MetadataExt;
    let meta = file
        .metadata()
        .map_err(|err| KernelError::Root(format!("grant file: {err}")))?;
    Ok(FileId {
        dev: meta.dev(),
        ino: meta.ino(),
    })
}

fn path_file_id(path: &Path) -> Option<FileId> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        let meta = std::fs::symlink_metadata(path).ok()?;
        if meta.file_type().is_symlink() || !meta.is_file() {
            return None;
        }
        Some(FileId {
            dev: meta.dev(),
            ino: meta.ino(),
        })
    }
    #[cfg(windows)]
    {
        windows::path_grant_file_id(path).ok().flatten()
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = path;
        None
    }
}

fn remove_created(created: &CreatedGrant) {
    if path_file_id(&created.path) == Some(created.id) {
        let _ = std::fs::remove_file(&created.path);
    }
}

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

    /// Directories the child may create regular files in.
    ///
    /// These are not [`Self::grants`] and they are not dest-deny walks.
    pub fn create_files(&self) -> &[CreateFiles] {
        &self.create_files
    }

    /// Remove files this builder created and keep files that were already there.
    pub fn discard_created_files(mut self) {
        self.rollback_created();
    }

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

    /// Downgrade read-write grants to read. The null device stays writable.
    ///
    /// On Windows this is the read-only jail: no write ACE is added, so
    /// the restricting SID denies creates in the workspace. Network is
    /// unchanged. Call [`Self::with_network`] when the profile should
    /// also block sockets. This does not remove [`Self::with_create_files`]
    /// entries. A status check starts a new policy and calls
    /// [`Self::with_read_file`].
    #[must_use]
    pub fn read_only(mut self) -> Self {
        for grant in &mut self.grants {
            #[cfg(unix)]
            if crate::deny::is_null_device(&grant.path) {
                continue;
            }
            if grant.access == KernelAccess::ReadWrite {
                grant.access = KernelAccess::Read;
            }
        }
        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)
    }

    /// Read-write grant for one regular file.
    ///
    /// A missing name whose parent directory already exists is created
    /// empty, mode 0600 on Unix, and then granted. The parent is not
    /// created. An existing regular file is not truncated and keeps its
    /// mode and ACL. A symlink or a directory is refused, as is a
    /// Windows reserved device name, including `NUL.txt`.
    ///
    /// Same as [`Self::with_write_file_create`] with `create` true.
    /// Pass `create` false to grant a file that must already exist.
    /// [`Self::try_write_file`] returns the policy when the host should
    /// skip that path and keep going. A hard failure removes every file
    /// this builder created and leaves files that were already there.
    ///
    /// Does not walk the parent, so a sibling tree such as
    /// `~/.grok/sessions` is not charged against the dest-deny
    /// entry cap. The parent is not a read-write root. A symlink or
    /// junction parent is followed, and only the canonical file is
    /// granted. Windows adds traverse on that parent and a write ACE
    /// on the file. A file this call created gets an owner-only DACL
    /// before the call returns, so a failed spawn does not leave the
    /// parent directory's ACL on it. Linux adds execute on each
    /// ancestor directory in the same Landlock ruleset. Landlock has
    /// no access right that walks a directory without that execute. A
    /// path-beneath rule with that right also allows executing other
    /// files beneath the directory. That does not grant listing or
    /// reading children. Siblings stay outside the grant.
    ///
    /// A deny glob that matches this file (`**/auth.json`) is not
    /// applied to it. The host asked for this file.
    pub fn with_write_file(self, path: &Path) -> Result<Self, KernelError> {
        self.with_write_file_create(path, true)
    }

    /// [`Self::with_write_file`] when `create` is true.
    ///
    /// When `create` is false, a missing file is
    /// [`FileGrantReason::Missing`] and nothing is created.
    pub fn with_write_file_create(self, path: &Path, create: bool) -> Result<Self, KernelError> {
        self.try_write_file(path, create).strict()
    }

    /// Grant one file, or skip a path the host can ignore.
    ///
    /// [`FileGrantReason::Symlink`], [`FileGrantReason::ReservedDevice`],
    /// and [`FileGrantReason::Missing`] (when `create` is false) keep the
    /// policy and the files already created. [`FileGrantReason::ParentMissing`]
    /// does too, so the host can create that one directory and retry.
    /// [`FileGrantReason::ParentNotDirectory`] and other errors remove
    /// files this builder created.
    pub fn try_write_file(self, path: &Path, create: bool) -> FileGrantAttempt {
        self.try_one_file(path, FileMode::Write { create })
    }

    /// Read-only grant for one existing regular file.
    ///
    /// Does not create a missing file. Does not walk the parent and does
    /// not grant it. The same ancestor execute rule as
    /// [`Self::with_write_file`] applies on Linux. Landlock has no access
    /// right that walks a directory without that execute.
    pub fn with_read_file(self, path: &Path) -> Result<Self, KernelError> {
        self.try_read_file(path).strict()
    }

    /// [`Self::with_read_file`] that keeps the policy when the file is
    /// missing, a symlink, or a reserved device name.
    pub fn try_read_file(self, path: &Path) -> FileGrantAttempt {
        self.try_one_file(path, FileMode::Read)
    }

    /// Let the child create regular files directly in `dir`.
    ///
    /// The directory is not a read-write root and is not dest-deny
    /// walked. Subdirectories are not granted, so `sessions` cannot be
    /// created and files already inside it are not opened. Existing
    /// siblings such as `notes.txt` are not granted. `prefix` limits
    /// the name on macOS (`auth` allows `auth.json` and not
    /// `notes.txt`). Windows allows any new file name in that directory
    /// and still does not open files that were already there. Linux
    /// returns [`FileGrantReason::Unsupported`].
    ///
    /// A missing directory is [`FileGrantReason::ParentMissing`]. This
    /// call does not create it.
    pub fn with_create_files(self, dir: &Path, prefix: Option<&str>) -> Result<Self, KernelError> {
        self.try_create_files(dir, prefix).strict()
    }

    /// [`Self::with_create_files`] that keeps earlier files when the
    /// directory is missing or this kernel cannot express the grant.
    pub fn try_create_files(self, dir: &Path, prefix: Option<&str>) -> FileGrantAttempt {
        self.try_add_create_files(dir, prefix)
    }

    fn try_one_file(mut self, path: &Path, mode: FileMode) -> FileGrantAttempt {
        match self.grant_one_file(path, mode) {
            Ok(GrantAdd::Added) => FileGrantAttempt::Granted(self),
            Ok(GrantAdd::Skip(reason)) => FileGrantAttempt::Skipped {
                policy: self,
                path: path.to_path_buf(),
                reason,
            },
            Err(err) => {
                self.rollback_created();
                FileGrantAttempt::Failed(err)
            }
        }
    }

    fn try_add_create_files(self, dir: &Path, prefix: Option<&str>) -> FileGrantAttempt {
        #[cfg(target_os = "linux")]
        {
            let _ = prefix;
            FileGrantAttempt::Skipped {
                policy: self,
                path: dir.to_path_buf(),
                reason: FileGrantReason::Unsupported,
            }
        }
        #[cfg(not(target_os = "linux"))]
        {
            let mut policy = self;
            match policy.add_create_files(dir, prefix) {
                Ok(()) => FileGrantAttempt::Granted(policy),
                Err(err) => match err {
                    KernelError::FileGrant {
                        reason: FileGrantReason::ParentMissing,
                        path,
                    } => FileGrantAttempt::Skipped {
                        policy,
                        path,
                        reason: FileGrantReason::ParentMissing,
                    },
                    err => {
                        policy.rollback_created();
                        FileGrantAttempt::Failed(err)
                    }
                },
            }
        }
    }

    fn grant_one_file(&mut self, path: &Path, mode: FileMode) -> Result<GrantAdd, KernelError> {
        if crate::deny::is_reserved_grant_device(path) {
            return Ok(GrantAdd::Skip(FileGrantReason::ReservedDevice));
        }
        require_grant_file_name(path)?;
        if let Err(err) = require_grant_parent_dir(path) {
            if let KernelError::FileGrant {
                reason: FileGrantReason::ParentMissing,
                ..
            } = err
            {
                return Ok(GrantAdd::Skip(FileGrantReason::ParentMissing));
            }
            return Err(err);
        }
        let create = match mode {
            FileMode::Write { create } => create,
            FileMode::Read => false,
        };
        match std::fs::symlink_metadata(path) {
            Ok(meta) if meta.file_type().is_symlink() => {
                Ok(GrantAdd::Skip(FileGrantReason::Symlink))
            }
            Ok(meta) if !meta.is_file() => Err(file_grant(path, FileGrantReason::NotRegular)),
            Ok(_) => {
                self.push_file_grant(path, mode.access())?;
                Ok(GrantAdd::Added)
            }
            Err(err) if err.kind() == std::io::ErrorKind::NotFound && !create => {
                Ok(GrantAdd::Skip(FileGrantReason::Missing))
            }
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                match create_empty_grant_file(path)? {
                    Some(created) => {
                        let granted = self.push_file_grant(path, mode.access());
                        if granted.is_err() {
                            remove_created(&created);
                            return granted.map(|_| GrantAdd::Added);
                        }
                        self.created.push(created);
                        Ok(GrantAdd::Added)
                    }
                    None => match std::fs::symlink_metadata(path) {
                        Ok(meta) if meta.file_type().is_symlink() => {
                            Ok(GrantAdd::Skip(FileGrantReason::Symlink))
                        }
                        Ok(meta) if meta.is_file() => {
                            self.push_file_grant(path, mode.access())?;
                            Ok(GrantAdd::Added)
                        }
                        _ => Err(file_grant(path, FileGrantReason::NotRegular)),
                    },
                }
            }
            Err(err) => Err(KernelError::Root(format!("{}: {err}", path.display()))),
        }
    }

    fn push_file_grant(&mut self, path: &Path, access: KernelAccess) -> Result<(), KernelError> {
        let resolved = std::fs::canonicalize(path)
            .map_err(|err| KernelError::Root(format!("{}: {err}", path.display())))?;
        if is_fs_root(&resolved) || is_drive_root(&resolved) {
            return Err(KernelError::FsRoot(resolved));
        }
        let resolved_meta = std::fs::symlink_metadata(&resolved)
            .map_err(|err| KernelError::Root(format!("{}: {err}", resolved.display())))?;
        if resolved_meta.file_type().is_symlink() || !resolved_meta.is_file() {
            return Err(file_grant(path, FileGrantReason::NotRegular));
        }
        self.dest_denies.retain(|deny| {
            !same_existing_path(&deny.path, path) && !same_existing_path(&deny.path, &resolved)
        });
        #[cfg(windows)]
        {
            record_file_traverse(&mut self.traverse_dirs, &resolved);
            if path != resolved.as_path() {
                record_file_traverse(&mut self.traverse_dirs, path);
            }
        }
        push_grant(&mut self.grants, resolved, access);
        Ok(())
    }

    #[cfg(not(target_os = "linux"))]
    fn add_create_files(&mut self, dir: &Path, prefix: Option<&str>) -> Result<(), KernelError> {
        if let Some(prefix) = prefix {
            if prefix.is_empty()
                || prefix.contains('/')
                || prefix.contains('\\')
                || prefix.contains('\0')
                || prefix == "."
                || prefix == ".."
            {
                return Err(KernelError::Apply(format!(
                    "create-files prefix is not a single name: {prefix}"
                )));
            }
        }
        // The reported path is the directory. A synthetic child would
        // make the host create `dir/name` when it retries.
        if let Err(err) = require_grant_parent_dir(&dir.join("name")) {
            return Err(match err {
                KernelError::FileGrant { reason, .. } => file_grant(dir, reason),
                other => other,
            });
        }
        let resolved = std::fs::canonicalize(dir)
            .map_err(|err| KernelError::Root(format!("{}: {err}", dir.display())))?;
        if is_fs_root(&resolved) || is_drive_root(&resolved) {
            return Err(KernelError::FsRoot(resolved));
        }
        let meta = std::fs::symlink_metadata(&resolved)
            .map_err(|err| KernelError::Root(format!("{}: {err}", resolved.display())))?;
        if meta.file_type().is_symlink() || !meta.is_dir() {
            return Err(file_grant(dir, FileGrantReason::ParentNotDirectory));
        }
        if self
            .create_files
            .iter()
            .any(|grant| grant.directory == resolved)
        {
            return Ok(());
        }
        #[cfg(windows)]
        {
            record_file_traverse(&mut self.traverse_dirs, &resolved.join("name"));
            if dir != resolved.as_path() {
                record_file_traverse(&mut self.traverse_dirs, &dir.join("name"));
            }
        }
        self.create_files.push(CreateFiles {
            directory: resolved,
            prefix: prefix.map(str::to_string),
        });
        Ok(())
    }

    fn rollback_created(&mut self) {
        for created in self.created.drain(..) {
            remove_created(&created);
        }
    }

    /// 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 helper PE and an AppContainer
    /// with no network capabilities. One profile and one dynamic WFP
    /// session are reused for every network-blocked command in this
    /// process. Fail closed if the AppContainer cannot be created.
    /// WFP `ERROR_ACCESS_DENIED` (win32 5) is skipped: package filters
    /// need an elevated token. The child still starts with AppContainer
    /// network deny. `workspace` (`with_network(false)`) does not create
    /// that profile.
    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)?;
            apply_kernel_caps(&caps)?;
            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)?;
            #[cfg(target_os = "linux")]
            let file_ancestors = uncovered_file_ancestors(&caps);
            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()?;
                    #[cfg(target_os = "linux")]
                    {
                        if file_ancestors.is_empty() {
                            let _ = nono::Sandbox::apply_auto(&caps)
                                .map_err(|err| std::io::Error::other(err.to_string()))?;
                        } else {
                            linux_landlock::apply_landlock_with_ancestors(&caps, &file_ancestors)
                                .map_err(|err| std::io::Error::other(err.to_string()))?;
                        }
                    }
                    #[cfg(not(target_os = "linux"))]
                    {
                        nono::Sandbox::apply_auto(&caps)
                            .map_err(|err| std::io::Error::other(err.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()
    }

    /// Spawn `cmd` into a long-lived Windows jail with outbound network.
    ///
    /// Read and read-write roots come from this policy.
    /// [`process_jail`] adds `SystemRoot` and `ProgramFiles` as read
    /// roots and refuses filesystem root and the user home as a
    /// read-write root. [`Self::with_read_root`] refuses those too.
    ///
    /// Network stays open. The AppContainer has the internet client
    /// capability and this function does not add a WFP BLOCK. That is
    /// not [`Self::network_blocked`]. [`Self::run_child`] is unchanged:
    /// `workspace` stays on the write-restricted token when network is
    /// left open, and `network_blocked` still builds a per-command
    /// container with no network capability.
    ///
    /// When `.ssh`, `.aws`, `.gnupg`, `.azure`, `.config\gh`, `.docker`,
    /// or `.kube` exist under the user profile, they get a package-SID
    /// deny. The deny is not Everyone. Missing directories are skipped.
    /// The profile is not walked.
    ///
    /// The AppContainer is created once in this process and reused.
    /// [`reexec_profile_creates`] counts that create. The profile name is
    /// per Windows user, so a second process derives the same container.
    /// It lives until this process exits. [`KernelApply::Applied`] means the
    /// container is active. It does not mean WFP ran. A denied open of
    /// `\BaseNamedObjects` skips that ACE and is not printed.
    ///
    /// Unix returns [`KernelError::Apply`] and does not start `cmd`.
    /// Windows does the same when the container cannot be created.
    /// The corpus test accepts a loopback connect to the parent, or
    /// TCP to `1.1.1.1` port 443, as proof that outbound network works.
    pub fn spawn_reexec(&self, cmd: Command) -> Result<(KernelApply, ExitStatus), KernelError> {
        self.spawn_reexec_io(cmd, false)
            .map(|(applied, status, _)| (applied, status))
    }

    /// [`Self::spawn_reexec`] with stdout and stderr collected.
    pub fn spawn_reexec_output(
        &self,
        cmd: Command,
    ) -> Result<(KernelApply, std::process::Output), KernelError> {
        self.spawn_reexec_io(cmd, true)
            .and_then(|(applied, status, output)| {
                output.map(|output| (applied, output)).ok_or_else(|| {
                    KernelError::Apply(format!(
                        "re-exec child produced no output (status {status})"
                    ))
                })
            })
    }

    fn spawn_reexec_io(
        &self,
        cmd: Command,
        capture: bool,
    ) -> Result<(KernelApply, ExitStatus, Option<std::process::Output>), KernelError> {
        self.dest_deny_command(&cmd)?;
        #[cfg(windows)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "write-restricted token is not available".into(),
                ));
            }
            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            if capture {
                windows::spawn_reexec_output(self, &mut cmd)
                    .map(|(applied, output)| (applied, output.status, Some(output)))
            } else {
                windows::spawn_reexec(self, &mut cmd)
                    .map(|(applied, status)| (applied, status, None))
            }
        }
        #[cfg(not(windows))]
        {
            let _ = (cmd, capture);
            Err(KernelError::Apply(
                "long-lived re-exec jail is Windows-only; child was not started".into(),
            ))
        }
    }

    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(),
                ));
            }
            let mut cmd = cmd;
            windows::spawn_write_restricted(self, &mut 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(),
                ));
            }
            let mut cmd = cmd;
            windows::spawn_write_restricted_output(self, &mut 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(),
                ));
            }
            let mut cmd = cmd;
            windows::spawn_write_restricted_output(self, &mut 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(),
                ));
            }
            let mut cmd = cmd;
            windows::spawn_write_restricted_forward(self, &mut 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(),
                ));
            }
            let mut cmd = cmd;
            windows::spawn_write_restricted_forward(self, &mut 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(),
                ));
            }
            let mut cmd = cmd;
            windows::spawn_write_restricted(self, &mut 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())?;
            for grant in &self.create_files {
                add_macos_create_file_rules(&mut caps, grant)?;
            }
        }
        let caps = if self.network_blocked {
            caps.block_network()
        } else {
            caps
        };
        Ok(caps.set_signal_mode(signal))
    }
}

#[cfg(unix)]
fn apply_kernel_caps(caps: &nono::CapabilitySet) -> Result<(), KernelError> {
    #[cfg(target_os = "linux")]
    {
        let ancestors = uncovered_file_ancestors(caps);
        if ancestors.is_empty() {
            match nono::Sandbox::apply_auto(caps) {
                Ok(_) => Ok(()),
                Err(err) => Err(KernelError::Apply(err.to_string())),
            }
        } else {
            linux_landlock::apply_landlock_with_ancestors(caps, &ancestors)
        }
    }
    #[cfg(not(target_os = "linux"))]
    {
        nono::Sandbox::apply_auto(caps).map_err(|err| KernelError::Apply(err.to_string()))
    }
}

/// Ancestor directories of file grants that no directory grant already covers.
///
/// A directory grant includes execute for that directory and everything
/// beneath it. Higher directories still need their own execute right, or
/// an absolute open stops there. Landlock has no access right that walks
/// a directory without that execute. `/` is omitted: executing `/bin/sh`
/// already works without a rule on the filesystem root.
#[cfg(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn uncovered_file_ancestors(caps: &nono::CapabilitySet) -> Vec<PathBuf> {
    let dirs: Vec<&Path> = caps
        .fs_capabilities()
        .iter()
        .filter(|cap| !cap.is_file)
        .map(|cap| cap.resolved.as_path())
        .collect();
    let mut out = Vec::new();
    for cap in caps.fs_capabilities() {
        if !cap.is_file {
            continue;
        }
        let mut cursor = cap.resolved.parent();
        while let Some(dir) = cursor {
            if is_fs_root(dir) {
                break;
            }
            let covered = dirs
                .iter()
                .any(|root| dir == *root || dir.starts_with(root));
            if !covered && !out.iter().any(|got| got == dir) {
                out.push(dir.to_path_buf());
            }
            cursor = dir.parent();
        }
    }
    out
}

impl KernelPolicy {
    /// 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);
        }
    }
}

/// Pairs for the Windows environment block.
///
/// `Command::get_envs` omits inherited names after `env_clear`, and
/// `env_remove` after `env_clear` does not record the name. A fresh
/// `env_remove` is listed only when the child still inherits.
#[cfg(any(windows, test))]
fn child_env_pairs(cmd: &mut Command) -> Vec<(OsString, OsString)> {
    let cleared = command_clears_env(cmd);
    let mut pairs: Vec<(OsString, OsString)> = if cleared {
        Vec::new()
    } else {
        std::env::vars_os().collect()
    };
    let mut explicit_keep = Vec::new();
    for (key, value) in cmd.get_envs() {
        pairs.retain(|(existing, _)| !env_key_eq(existing, key));
        if let Some(value) = value
            && !is_child_env_loader(key)
        {
            explicit_keep.push(key.to_os_string());
            pairs.push((key.to_os_string(), value.to_os_string()));
        }
    }
    pairs.retain(|(key, _)| {
        !is_denied_child_env(key) || explicit_keep.iter().any(|keep| env_key_eq(keep, key))
    });
    pairs
}

#[cfg(any(windows, test))]
fn command_clears_env(cmd: &mut Command) -> bool {
    let sentinel = fresh_clear_probe(cmd);
    cmd.env_remove(&sentinel);
    !cmd.get_envs().any(|(key, _)| env_key_eq(key, &sentinel))
}

#[cfg(any(windows, test))]
fn fresh_clear_probe(cmd: &Command) -> OsString {
    let mut n = 0u32;
    loop {
        let name = OsString::from(format!("WP_ENV_CLEAR_PROBE_{n}"));
        let in_cmd = cmd.get_envs().any(|(key, _)| env_key_eq(key, &name));
        let in_parent = std::env::vars_os().any(|(key, _)| env_key_eq(&key, &name));
        if !in_cmd && !in_parent {
            return name;
        }
        n += 1;
    }
}

#[cfg(any(windows, test))]
fn env_key_eq(left: &OsStr, right: &OsStr) -> bool {
    left.to_string_lossy()
        .eq_ignore_ascii_case(&right.to_string_lossy())
}

/// 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. Each directory is read once per call,
/// not once per hardlinked name.
///
/// 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> {
    #[cfg(unix)]
    let _hardlink_scans = crate::deny::HardlinkScanScope::new();
    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);
}

/// New files directly in `dir`. A prefix limits the name. No subpath.
#[cfg(target_os = "macos")]
fn add_macos_create_file_rules(
    caps: &mut nono::CapabilitySet,
    grant: &CreateFiles,
) -> Result<(), KernelError> {
    let Some(raw) = grant.directory.to_str() else {
        return Err(KernelError::Apply(format!(
            "create-files path is not UTF-8: {}",
            grant.directory.display()
        )));
    };
    let escaped_dir = escape_sbpl_literal(raw);
    for action in ["file-read-metadata", "file-write-create"] {
        let rule = format!("(allow {action} (literal \"{escaped_dir}\"))");
        caps.add_platform_rule(&rule)
            .map_err(|err| KernelError::Apply(err.to_string()))?;
    }
    let dir = escape_regex_literal(raw);
    let name = match grant.prefix.as_deref() {
        Some(prefix) => format!("{}[^/]*", escape_regex_literal(prefix)),
        None => "[^/]+".to_string(),
    };
    let regex = escape_sbpl_literal(&format!("^{dir}/{name}$"));
    // The dest-deny list allows `file-write*` and `file-write-create`
    // separately, so creation is its own allow. Without a prefix the
    // regex is every direct child, including `notes.txt`.
    let mut actions = vec!["file-write*", "file-write-create", "file-write-data"];
    if grant.prefix.is_some() {
        actions.push("file-read*");
    } else {
        actions.push("file-read-metadata");
    }
    for action in actions {
        let rule = format!("(allow {action} (regex \"{regex}\"))");
        caps.add_platform_rule(&rule)
            .map_err(|err| KernelError::Apply(err.to_string()))?;
    }
    Ok(())
}

/// 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> {
    #[cfg(unix)]
    let _hardlink_scans = crate::deny::HardlinkScanScope::new();
    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(),
    }
}

/// `C:\` and `\\?\C:\`. Those are not file parents we can jail.
fn is_drive_root(path: &Path) -> bool {
    let text = path.to_string_lossy().replace('/', "\\");
    let text = text
        .strip_prefix("\\\\?\\")
        .unwrap_or(text.as_str())
        .trim_end_matches('\\');
    text.len() == 2 && text.as_bytes().get(1) == Some(&b':')
}

fn same_existing_path(left: &Path, right: &Path) -> bool {
    if left == right {
        return true;
    }
    match (std::fs::canonicalize(left), std::fs::canonicalize(right)) {
        (Ok(left), Ok(right)) => left == right,
        _ => false,
    }
}

/// The file's parent only.
///
/// Higher directories such as the user profile are not rewritten.
/// `SetNamedSecurityInfo` on those trees is slow, and a jail that can
/// already open a temp workspace can traverse them.
#[cfg(windows)]
fn file_ancestor_dirs(file: &Path) -> Vec<PathBuf> {
    match file.parent() {
        Some(dir) if !is_fs_root(dir) && !is_drive_root(dir) && !dir.as_os_str().is_empty() => {
            vec![dir.to_path_buf()]
        }
        _ => Vec::new(),
    }
}

#[cfg(windows)]
fn record_file_traverse(dirs: &mut Vec<(PathBuf, bool)>, file: &Path) {
    let mut required = true;
    for dir in file_ancestor_dirs(file) {
        if let Some(existing) = dirs.iter_mut().find(|(path, _)| path == &dir) {
            if required {
                existing.1 = true;
            }
        } else {
            dirs.push((dir, required));
        }
        required = false;
    }
}

#[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 child_env_pairs_tests {
    use super::{child_env_pairs, is_denied_child_env};
    use std::ffi::OsString;
    use std::process::Command;

    fn inherited_marker() -> Option<(OsString, OsString)> {
        std::env::vars_os().find(|(name, value)| {
            !value.is_empty()
                && !is_denied_child_env(name)
                && !name.to_string_lossy().eq_ignore_ascii_case("PATH")
                && !name.to_string_lossy().eq_ignore_ascii_case("SystemRoot")
        })
    }

    fn has_key(pairs: &[(OsString, OsString)], key: &str) -> bool {
        pairs
            .iter()
            .any(|(name, _)| name.to_string_lossy().eq_ignore_ascii_case(key))
    }

    #[test]
    fn env_clear_drops_inherited_names_and_keeps_explicit_inserts() {
        let Some((key, _)) = inherited_marker() else {
            return;
        };
        let name = key.to_string_lossy().into_owned();
        let mut cmd = Command::new("cmd");
        cmd.env_clear();
        if let Some(path) = std::env::var_os("PATH") {
            cmd.env("PATH", path);
        }
        cmd.env("CUSTOM_API_KEY", "kept-explicit");
        cmd.env("LD_PRELOAD", "/tmp/nope");
        let pairs = child_env_pairs(&mut cmd);
        assert!(!has_key(&pairs, &name), "{name} stayed after env_clear");
        assert!(
            !has_key(&pairs, "SystemRoot"),
            "SystemRoot stayed without being set again"
        );
        if std::env::var_os("PATH").is_some() {
            assert!(has_key(&pairs, "PATH"), "explicit PATH was dropped");
        }
        assert!(
            pairs
                .iter()
                .any(|(k, v)| k == "CUSTOM_API_KEY" && v == "kept-explicit"),
            "explicit CUSTOM_API_KEY was dropped after env_clear"
        );
        assert!(
            !has_key(&pairs, "LD_PRELOAD"),
            "loader must stay dropped after env_clear"
        );
    }

    #[test]
    fn inherited_name_stays_without_env_clear() {
        let Some(path) = std::env::var_os("PATH") else {
            return;
        };
        let mut cmd = Command::new("cmd");
        let pairs = child_env_pairs(&mut cmd);
        assert!(
            pairs.iter().any(
                |(key, value)| key.to_string_lossy().eq_ignore_ascii_case("PATH") && value == &path
            ),
            "PATH was dropped from an inheriting command"
        );
    }
}

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

#[cfg(test)]
mod write_file_grant_tests {
    use std::path::Path;

    use super::{KernelAccess, process_jail};

    fn grant_is_file(policy: &super::KernelPolicy, file: &Path) -> bool {
        grant_has(policy, file, KernelAccess::ReadWrite)
    }

    fn grant_has(policy: &super::KernelPolicy, file: &Path, access: KernelAccess) -> bool {
        let want = std::fs::canonicalize(file).ok();
        policy.grants().iter().any(|grant| {
            grant.access == access
                && (grant.path == file || want.as_ref().is_some_and(|p| grant.path == *p))
        })
    }

    fn file_grant_reason(err: super::KernelError) -> super::FileGrantReason {
        match err {
            super::KernelError::FileGrant { reason, .. } => reason,
            other => panic!("expected FileGrant, got {other}"),
        }
    }

    fn only_canonical(policy: &super::KernelPolicy, spelled: &Path) -> bool {
        let canon = std::fs::canonicalize(spelled).expect("canon");
        let hits: Vec<_> = policy
            .grants()
            .iter()
            .filter(|grant| grant.path == spelled || grant.path == canon)
            .map(|grant| grant.path.clone())
            .collect();
        hits == vec![canon]
    }

    #[test]
    fn write_file_does_not_grant_or_walk_the_parent() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        let sessions = grok.join("sessions");
        std::fs::create_dir_all(&sessions).expect("sessions");
        std::fs::create_dir_all(&workspace).expect("ws");
        let auth = grok.join("auth.json");
        std::fs::write(&auth, b"{}\n").expect("auth");
        std::fs::write(sessions.join("one.log"), b"log\n").expect("log");
        let policy = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&auth)
            .expect("file grant");
        assert!(grant_is_file(&policy, &auth), "auth.json must be writable");
        let grok_canon = std::fs::canonicalize(&grok).expect("grok");
        assert!(
            policy
                .grants()
                .iter()
                .all(|grant| grant.path != grok && grant.path != grok_canon),
            "the parent directory must not be a grant: {:?}",
            policy.grants()
        );
        assert!(
            policy
                .dest_denies()
                .iter()
                .all(|deny| !deny.path.starts_with(&sessions) && !deny.path.ends_with("auth.json")),
            "sessions and auth.json must not be dest-deny walked: {:?}",
            policy.dest_denies()
        );
        #[cfg(windows)]
        {
            assert!(
                policy
                    .traverse_dirs
                    .iter()
                    .any(|(dir, required)| dir == &grok_canon && *required),
                "the parent needs traverse, not a write root"
            );
        }
        let err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&grok)
            .expect_err("a directory is not a file grant");
        assert_eq!(
            file_grant_reason(err),
            super::FileGrantReason::NotRegular,
            "a directory is not a regular file"
        );
    }

    #[test]
    fn write_file_clears_a_deny_glob_on_that_file() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        std::fs::create_dir_all(&workspace).expect("ws");
        let auth = workspace.join("auth.json");
        std::fs::write(&auth, b"{}\n").expect("auth");
        let walked = process_jail(&workspace, std::iter::empty::<&Path>()).expect("jail");
        assert!(
            walked
                .dest_denies()
                .iter()
                .any(|deny| deny.path.ends_with("auth.json")),
            "workspace walk must still dest-deny auth.json before the file grant"
        );
        let granted = walked.with_write_file(&auth).expect("file grant");
        assert!(
            granted
                .dest_denies()
                .iter()
                .all(|deny| !deny.path.ends_with("auth.json")),
            "the explicit file grant must drop the auth.json deny: {:?}",
            granted.dest_denies()
        );
        assert!(grant_is_file(&granted, &auth));
    }

    #[test]
    fn write_file_refuses_a_symlink() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        std::fs::create_dir_all(&workspace).expect("ws");
        let auth = workspace.join("auth.json");
        std::fs::write(&auth, b"{}\n").expect("auth");
        let link = workspace.join("link.json");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&auth, &link).expect("symlink");
        #[cfg(windows)]
        std::os::windows::fs::symlink_file(&auth, &link).expect("symlink");
        #[cfg(not(any(unix, windows)))]
        return;
        let err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&link)
            .expect_err("symlink");
        assert_eq!(file_grant_reason(err), super::FileGrantReason::Symlink);
    }

    #[cfg(unix)]
    #[test]
    fn write_file_traverse_dirs_are_not_grants() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        let auth = grok.join("auth.json");
        std::fs::write(&auth, b"{}\n").expect("auth");
        let policy = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&auth)
            .expect("file grant");
        let caps = policy
            .to_capability_set(nono::SignalMode::Isolated)
            .expect("caps");
        let extra = super::uncovered_file_ancestors(&caps);
        let grok_canon = std::fs::canonicalize(&grok).expect("grok");
        assert!(
            extra.iter().any(|dir| dir == &grok_canon),
            "the parent directory needs traverse: {extra:?}"
        );
        assert!(
            extra
                .iter()
                .all(|dir| policy.grants().iter().all(|grant| grant.path != *dir)),
            "traverse directories must not be grants: {extra:?} {:?}",
            policy.grants()
        );
    }

    #[test]
    fn write_file_creates_a_missing_name_and_leaves_the_parent_closed() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        std::fs::write(grok.join("notes.txt"), b"sibling\n").expect("notes");
        let auth = grok.join("auth.json");
        let policy = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&auth)
            .expect("missing file grant");
        assert!(grant_is_file(&policy, &auth), "auth.json must be writable");
        assert_eq!(std::fs::read(&auth).expect("auth bytes"), b"");
        let grok_canon = std::fs::canonicalize(&grok).expect("grok");
        assert!(
            policy
                .grants()
                .iter()
                .all(|grant| grant.path != grok && grant.path != grok_canon),
            "the parent directory must not be a grant: {:?}",
            policy.grants()
        );
        assert!(
            policy.grants().iter().all(|grant| {
                grant.path != grok.join("notes.txt") && grant.path != grok_canon.join("notes.txt")
            }),
            "a sibling must stay outside the grant: {:?}",
            policy.grants()
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&auth).expect("meta").permissions().mode() & 0o777;
            assert_eq!(
                mode, 0o600,
                "a new grant file must be owner read-write only"
            );
        }
        #[cfg(windows)]
        {
            assert!(
                policy
                    .traverse_dirs
                    .iter()
                    .any(|(dir, required)| dir == &grok_canon && *required),
                "the parent needs traverse, not a write root"
            );
        }
    }

    #[test]
    fn write_file_refuses_a_missing_parent() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        std::fs::create_dir_all(&workspace).expect("ws");
        let parent = root.path().join("missing");
        let auth = parent.join("auth.json");
        let err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&auth)
            .expect_err("missing parent");
        assert_eq!(
            file_grant_reason(err),
            super::FileGrantReason::ParentMissing
        );
        assert!(!parent.exists(), "the parent directory must not be created");
        assert!(!auth.exists(), "the file must not be created");
    }

    #[cfg(windows)]
    #[test]
    fn write_file_refuses_a_reserved_device_name() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        for name in ["NUL", "CON"] {
            let path = grok.join(name);
            let err = process_jail(&workspace, std::iter::empty::<&Path>())
                .expect("jail")
                .with_write_file(&path)
                .expect_err(name);
            assert_eq!(
                file_grant_reason(err),
                super::FileGrantReason::ReservedDevice,
                "{name}"
            );
        }
        let listed: Vec<_> = std::fs::read_dir(&grok)
            .expect("list")
            .map(|entry| entry.expect("entry").file_name())
            .collect();
        assert!(
            listed.is_empty(),
            "device names must not create files: {listed:?}"
        );
    }

    #[test]
    fn write_file_create_false_does_not_plant_a_missing_login() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        let auth = grok.join("auth.json");
        let err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file_create(&auth, false)
            .expect_err("missing login");
        assert_eq!(file_grant_reason(err), super::FileGrantReason::Missing);
        assert!(!auth.exists(), "a missing login file must not be created");
        std::fs::write(&auth, b"{token}\n").expect("auth");
        let policy = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file_create(&auth, false)
            .expect("existing login");
        assert!(grant_is_file(&policy, &auth));
        assert_eq!(std::fs::read(&auth).expect("bytes"), b"{token}\n");
    }

    #[test]
    fn write_file_failure_removes_only_files_this_builder_created() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        let auth = grok.join("auth.json");
        std::fs::write(&auth, b"{token}\n").expect("auth");
        let lock = grok.join("auth.lock");
        let link = grok.join("auth-work.lock");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&auth, &link).expect("symlink");
        #[cfg(windows)]
        std::os::windows::fs::symlink_file(&auth, &link).expect("symlink");
        #[cfg(not(any(unix, windows)))]
        return;
        let err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&lock)
            .expect("create lock")
            .with_write_file(&link)
            .expect_err("symlink lock");
        assert_eq!(file_grant_reason(err), super::FileGrantReason::Symlink);
        assert!(!lock.exists(), "the new lock must be removed");
        assert_eq!(std::fs::read(&auth).expect("auth"), b"{token}\n");
        assert!(
            link.symlink_metadata()
                .expect("link")
                .file_type()
                .is_symlink()
        );
    }

    #[test]
    fn try_write_file_skips_a_symlink_and_keeps_the_new_lock() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        let auth = grok.join("auth.json");
        std::fs::write(&auth, b"{token}\n").expect("auth");
        let lock = grok.join("auth.lock");
        let link = grok.join("auth-work.lock");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&auth, &link).expect("symlink");
        #[cfg(windows)]
        std::os::windows::fs::symlink_file(&auth, &link).expect("symlink");
        #[cfg(not(any(unix, windows)))]
        return;
        let started = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&lock)
            .expect("create lock");
        let skipped = started.try_write_file(&link, true);
        let super::FileGrantAttempt::Skipped { policy, reason, .. } = skipped else {
            panic!("symlink lock should be skipped");
        };
        assert_eq!(reason, super::FileGrantReason::Symlink);
        assert!(lock.exists(), "a skipped path must not remove the new lock");
        assert!(grant_is_file(&policy, &lock));
    }

    #[test]
    fn try_write_file_reports_a_missing_parent_without_creating_it() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        std::fs::create_dir_all(&workspace).expect("ws");
        let grok = root.path().join("grok");
        let auth = grok.join("auth.json");
        let attempt = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .try_write_file(&auth, true);
        let super::FileGrantAttempt::Skipped { reason, .. } = attempt else {
            panic!("missing parent should be skipped so the host can retry");
        };
        assert_eq!(reason, super::FileGrantReason::ParentMissing);
        assert!(!grok.exists());
        assert!(!auth.exists());
    }

    #[test]
    fn write_file_follows_a_directory_link_and_grants_one_file() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let real = root.path().join("real");
        let link = root.path().join("link");
        std::fs::create_dir_all(&real).expect("real");
        std::fs::create_dir_all(&workspace).expect("ws");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&real, &link).expect("symlink dir");
        #[cfg(windows)]
        std::os::windows::fs::symlink_dir(&real, &link).expect("junction");
        #[cfg(not(any(unix, windows)))]
        return;
        let spelled = link.join("auth.lock");
        let policy = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&spelled)
            .expect("grant through the directory link");
        assert!(only_canonical(&policy, &spelled));
        assert_eq!(std::fs::read(real.join("auth.lock")).expect("bytes"), b"");
    }

    #[test]
    fn read_file_does_not_create_or_walk_or_grant_write() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        let sessions = grok.join("sessions");
        std::fs::create_dir_all(&sessions).expect("sessions");
        std::fs::create_dir_all(&workspace).expect("ws");
        std::fs::write(sessions.join("one.log"), b"log\n").expect("log");
        std::fs::write(grok.join("notes.txt"), b"notes\n").expect("notes");
        let missing = grok.join("auth.json");
        let err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_read_file(&missing)
            .expect_err("missing");
        assert_eq!(file_grant_reason(err), super::FileGrantReason::Missing);
        assert!(!missing.exists());
        let dir_err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_read_file(&grok)
            .expect_err("directory");
        assert_eq!(
            file_grant_reason(dir_err),
            super::FileGrantReason::NotRegular
        );
        std::fs::write(&missing, b"{exp}\n").expect("auth");
        let policy = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_read_file(&missing)
            .expect("read");
        assert!(grant_has(&policy, &missing, KernelAccess::Read));
        assert!(
            !grant_is_file(&policy, &missing),
            "read must not grant write"
        );
        assert_eq!(std::fs::read(&missing).expect("bytes"), b"{exp}\n");
        let link = grok.join("link.json");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&missing, &link).expect("symlink");
        #[cfg(windows)]
        std::os::windows::fs::symlink_file(&missing, &link).expect("symlink");
        #[cfg(any(unix, windows))]
        {
            let link_err = process_jail(&workspace, std::iter::empty::<&Path>())
                .expect("jail")
                .with_read_file(&link)
                .expect_err("symlink");
            assert_eq!(file_grant_reason(link_err), super::FileGrantReason::Symlink);
        }
        let grok_canon = std::fs::canonicalize(&grok).expect("grok");
        assert!(policy.grants().iter().all(|grant| {
            grant.path != grok
                && grant.path != grok_canon
                && grant.path != grok.join("notes.txt")
                && !grant.path.starts_with(&sessions)
        }));
        assert!(policy.dest_denies().iter().all(|deny| {
            !deny.path.starts_with(&sessions) && !deny.path.ends_with("notes.txt")
        }));
    }

    #[test]
    fn create_files_does_not_walk_or_grant_the_directory() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        let sessions = grok.join("sessions");
        std::fs::create_dir_all(&sessions).expect("sessions");
        std::fs::create_dir_all(&workspace).expect("ws");
        std::fs::write(grok.join("notes.txt"), b"notes\n").expect("notes");
        for index in 0..8 {
            std::fs::write(sessions.join(format!("f{index}.log")), b"x").expect("log");
        }
        let missing = root.path().join("absent");
        let missing_err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_create_files(&missing, Some("auth"))
            .expect_err("missing dir");
        let super::KernelError::FileGrant { path, reason } = &missing_err else {
            panic!("expected FileGrant, got {missing_err}");
        };
        assert_eq!(path, &missing, "the error path is the directory");
        #[cfg(target_os = "linux")]
        assert_eq!(*reason, super::FileGrantReason::Unsupported);
        #[cfg(not(target_os = "linux"))]
        assert_eq!(*reason, super::FileGrantReason::ParentMissing);
        assert!(!missing.exists());
        let result = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_create_files(&grok, Some("auth"));
        #[cfg(target_os = "linux")]
        {
            assert_eq!(
                file_grant_reason(result.expect_err("landlock")),
                super::FileGrantReason::Unsupported
            );
        }
        #[cfg(not(target_os = "linux"))]
        {
            let policy = result.expect("create files");
            let grok_canon = std::fs::canonicalize(&grok).expect("grok");
            assert!(policy.grants().iter().all(|grant| {
                grant.path != grok
                    && grant.path != grok_canon
                    && grant.path != grok.join("notes.txt")
            }));
            assert!(policy.dest_denies().iter().all(|deny| {
                !deny.path.starts_with(&sessions) && !deny.path.ends_with("notes.txt")
            }));
            assert_eq!(policy.create_files().len(), 1);
            assert_eq!(policy.create_files()[0].directory, grok_canon);
            assert_eq!(policy.create_files()[0].prefix.as_deref(), Some("auth"));
        }
    }

    #[cfg(windows)]
    #[test]
    fn write_file_refuses_a_reserved_device_name_with_an_extension() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        for name in ["NUL.txt", "AUX.json", "COM1.txt"] {
            let path = grok.join(name);
            let err = process_jail(&workspace, std::iter::empty::<&Path>())
                .expect("jail")
                .with_write_file(&path)
                .expect_err(name);
            assert_eq!(
                file_grant_reason(err),
                super::FileGrantReason::ReservedDevice,
                "{name}"
            );
        }
        let notes = grok.join("notes.NUL");
        process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&notes)
            .expect("notes.NUL is not a device");
        assert!(notes.is_file());
        let _ = std::fs::remove_file(&notes);
        let listed: Vec<_> = std::fs::read_dir(&grok)
            .expect("list")
            .map(|entry| entry.expect("entry").file_name())
            .collect();
        assert!(
            listed.is_empty(),
            "extended device names must not create files: {listed:?}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn write_file_sets_an_owner_only_dacl_on_a_new_file() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        let lock = grok.join("auth.lock");
        process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&lock)
            .expect("lock");
        assert!(
            super::windows::dacl_is_protected(&lock).expect("dacl"),
            "a new lock must not keep the parent ACL"
        );
        assert_eq!(std::fs::read(&lock).expect("lock bytes"), b"");
        std::fs::write(grok.join("auth.json"), b"{token}\n").expect("auth");
        let auth = grok.join("auth.json");
        process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file_create(&auth, false)
            .expect("existing");
        assert_eq!(std::fs::read(&auth).expect("bytes"), b"{token}\n");
        assert!(
            !super::windows::dacl_is_protected(&auth).expect("existing dacl"),
            "an existing login file must keep its ACL"
        );
    }

    #[test]
    fn first_login_creates_the_file_after_the_host_creates_the_directory() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        std::fs::create_dir_all(&workspace).expect("ws");
        let grok = root.path().join("grok");
        let auth = grok.join("auth.json");
        let sessions = grok.join("sessions");
        let err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&auth)
            .expect_err("no directory yet");
        assert_eq!(
            file_grant_reason(err),
            super::FileGrantReason::ParentMissing
        );
        assert!(!grok.exists());
        std::fs::create_dir(&grok).expect("host creates the directory");
        let policy = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&auth)
            .expect("login file");
        assert!(grant_is_file(&policy, &auth));
        assert_eq!(std::fs::read(&auth).expect("bytes"), b"");
        assert!(!sessions.exists(), "sessions must not be created");
        assert!(policy.grants().iter().all(|grant| {
            let canon = std::fs::canonicalize(&grok).expect("grok");
            grant.path != grok && grant.path != canon
        }));
    }

    #[test]
    fn later_missing_parent_removes_only_the_new_lock() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        let auth = grok.join("auth.json");
        std::fs::write(&auth, b"{token}\n").expect("auth");
        let lock = grok.join("auth.lock");
        let other = root.path().join("missing").join("auth.lock");
        let err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&lock)
            .expect("create lock")
            .with_write_file(&other)
            .expect_err("missing parent");
        assert_eq!(
            file_grant_reason(err),
            super::FileGrantReason::ParentMissing
        );
        assert!(!lock.exists(), "the new lock must be removed");
        assert!(!other.parent().expect("parent").exists());
        assert_eq!(std::fs::read(&auth).expect("auth"), b"{token}\n");
    }

    #[test]
    fn try_write_file_keeps_the_lock_when_the_next_parent_is_missing() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        let lock = grok.join("auth.lock");
        let other = root.path().join("missing").join("auth.lock");
        let started = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&lock)
            .expect("create lock");
        let skipped = started.try_write_file(&other, true);
        let super::FileGrantAttempt::Skipped { policy, reason, .. } = skipped else {
            panic!("missing parent should be skipped");
        };
        assert_eq!(reason, super::FileGrantReason::ParentMissing);
        assert!(lock.exists(), "a skipped path must not remove the new lock");
        assert!(grant_is_file(&policy, &lock));
        assert!(!other.parent().expect("parent").exists());
    }

    #[test]
    fn write_file_refuses_a_parent_that_is_a_file() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        let parent = grok.join("not-a-dir");
        std::fs::write(&parent, b"x").expect("file");
        let auth = parent.join("auth.json");
        let err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&auth)
            .expect_err("parent file");
        assert_eq!(
            file_grant_reason(err),
            super::FileGrantReason::ParentNotDirectory
        );
        assert!(!auth.exists());
        assert_eq!(std::fs::read(&parent).expect("bytes"), b"x");
    }

    #[cfg(not(target_os = "linux"))]
    #[test]
    fn create_files_rejects_a_file_and_an_empty_prefix() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        let notes = grok.join("notes.txt");
        std::fs::write(&notes, b"notes\n").expect("notes");
        let err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_create_files(&notes, Some("auth"))
            .expect_err("file");
        assert!(
            matches!(
                &err,
                super::KernelError::FileGrant { path, reason }
                    if path == &notes && *reason == super::FileGrantReason::ParentNotDirectory
            ),
            "{err}"
        );
        let bad = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_create_files(&grok, Some(""))
            .expect_err("prefix");
        assert!(
            matches!(bad, super::KernelError::Apply(ref msg) if msg.contains("prefix")),
            "{bad}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn write_file_follows_a_junction_and_grants_one_file() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let real = root.path().join("real");
        let link = root.path().join("link");
        std::fs::create_dir_all(&real).expect("real");
        std::fs::create_dir_all(&workspace).expect("ws");
        let status = std::process::Command::new("cmd")
            .args(["/c", "mklink", "/J"])
            .arg(&link)
            .arg(&real)
            .status()
            .expect("mklink");
        assert!(status.success(), "mklink /J");
        let spelled = link.join("auth.lock");
        let policy = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&spelled)
            .expect("grant through the junction");
        assert!(only_canonical(&policy, &spelled));
        assert_eq!(std::fs::read(real.join("auth.lock")).expect("bytes"), b"");
    }

    #[cfg(windows)]
    #[test]
    fn write_file_creates_a_verbatim_nul_as_a_literal_file() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        assert!(crate::deny::is_reserved_grant_device(std::path::Path::new(
            r"\\?\NUL"
        )));
        let grok_abs = std::fs::canonicalize(&grok).expect("canon");
        let text = grok_abs.display().to_string();
        let verbatim_dir = if text.starts_with(r"\\?\") {
            grok_abs
        } else {
            std::path::PathBuf::from(format!(r"\\?\{text}"))
        };
        let literal = verbatim_dir.join("NUL");
        assert!(!crate::deny::is_reserved_grant_device(&literal));
        let policy = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_write_file(&literal)
            .expect("literal NUL");
        assert!(only_canonical(&policy, &literal));
        assert!(std::fs::metadata(&literal).expect("meta").is_file());
        std::fs::remove_file(&literal).expect("remove literal");
    }

    #[cfg(windows)]
    #[test]
    fn read_file_refuses_an_extended_device_name() {
        let root = tempfile::tempdir().expect("temp");
        let workspace = root.path().join("ws");
        let grok = root.path().join("grok");
        std::fs::create_dir_all(&grok).expect("grok");
        std::fs::create_dir_all(&workspace).expect("ws");
        let path = grok.join("NUL.txt");
        let err = process_jail(&workspace, std::iter::empty::<&Path>())
            .expect("jail")
            .with_read_file(&path)
            .expect_err("NUL.txt");
        assert_eq!(
            file_grant_reason(err),
            super::FileGrantReason::ReservedDevice
        );
        assert!(!path.exists());
    }
}