workpen 0.7.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
//! Process-jail wrap. Feature `nono`.
//!
//! Unix uses pinned nono (Landlock / Seatbelt). Windows uses a
//! write-restricted token. Never grant filesystem root (`/` or a
//! Windows drive root) or the current user's home directory. Inspect
//! [`KernelPolicy::grants`]; do not parse nono internals. Do not call
//! [`KernelPolicy::apply`] from unit tests (`Sandbox::apply_auto` is
//! irreversible). [`KernelPolicy::apply_pre_exec`] only installs a Unix
//! child hook. Hosts that need a jail on every OS call
//! [`KernelPolicy::run_child`], which errors instead of spawning when
//! the kernel cannot apply. The default crate (`default = []`) does not
//! compile this module.

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

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

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

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

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

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

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

/// Hosts match the variant, not English. New variants are breaking
/// for exhaustive hosts even in 0.x.
#[derive(Debug, thiserror::Error)]
pub enum KernelError {
    #[error("kernel wrap root is not usable: {0}")]
    Root(String),
    #[error("kernel wrap refused filesystem root {0}; use a subdirectory, not `/`")]
    FsRoot(PathBuf),
    #[error("kernel wrap refused home directory {0}; use a project subdirectory, not $HOME")]
    Home(PathBuf),
    #[error("kernel wrap apply failed: {0}")]
    Apply(String),
    /// Argv dest-deny before spawn. Hosts match [`CheckDestError`] /
    /// [`crate::DestDenyError`], not English.
    #[error("kernel wrap dest-deny: {0}")]
    DestDeny(#[from] CheckDestError),
    /// The child was killed after the deadline.
    #[error("kernel wrap child was killed after the deadline")]
    Timeout,
    /// Child finished; DACL restore failed. Hosts match this, not English.
    #[error("kernel wrap restore failed: {0}")]
    Restore(String),
}

/// 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 = timeout.map(|limit| Instant::now() + limit);
    loop {
        if kill_group_if_zombie(pid) {
            let status = child
                .wait()
                .map_err(|e| KernelError::Apply(e.to_string()))?;
            return Ok((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 = child
                        .wait()
                        .map_err(|e| KernelError::Apply(e.to_string()))?;
                    return Ok((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 = child
                        .wait()
                        .map_err(|e| KernelError::Apply(e.to_string()))?;
                    return Ok((status, true));
                }
                std::thread::sleep(Duration::from_millis(10));
            }
        }
        std::thread::sleep(Duration::from_millis(10));
    }
}

#[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 stdout = child.stdout.take().map(|p| copy_pipe(p, std::io::stdout()));
    let stderr = child.stderr.take().map(|p| copy_pipe(p, std::io::stderr()));
    let (status, timed_out) = wait_until_deadline(&mut child, timeout)?;
    join_copy(stdout);
    join_copy(stderr);
    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 copy_pipe(
    mut src: impl std::io::Read + Send + 'static,
    mut dst: impl std::io::Write + Send + 'static,
) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || {
        let mut buf = [0u8; 16 * 1024];
        loop {
            match std::io::Read::read(&mut src, &mut buf) {
                Ok(0) => break,
                Ok(n) => {
                    if std::io::Write::write_all(&mut dst, &buf[..n]).is_err() {
                        break;
                    }
                }
                Err(_) => break,
            }
        }
        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();
    }
}

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

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

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

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

struct RemoveProbeDir(PathBuf);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /// Install Landlock/Seatbelt in the child `pre_exec` hook.
    ///
    /// Dest-denies `cmd` argv first ([`Self::dest_deny_command`]), same
    /// rules as [`Self::run_child`]. Builds the capability set in the
    /// parent (allocation is not safe after fork). Uses
    /// `SignalMode::Isolated` so the child cannot signal the parent.
    /// Does not jail this process. Windows has no `pre_exec`; this stays
    /// [`KernelApply::UserspaceOnly`]. Use [`Self::run_child`] to jail a child.
    ///
    /// On Linux, dest-deny remount skip is [`KernelApply::RemountSkipped`]
    /// when dest-deny paths exist and a private mount ns cannot be
    /// entered. Extra-root dests still fail-closed. If the parent probe
    /// returned [`KernelApply::Applied`], the child fail-closes when
    /// enter fails.
    pub fn apply_pre_exec(&self, cmd: &mut Command) -> Result<KernelApply, KernelError> {
        self.apply_pre_exec_dests(cmd, Vec::new())
    }

    fn apply_pre_exec_dests(
        &self,
        cmd: &mut Command,
        extra_dests: Vec<PathBuf>,
    ) -> Result<KernelApply, KernelError> {
        self.dest_deny_command(cmd)?;
        if !kernel_supported() {
            return Ok(KernelApply::UserspaceOnly);
        }
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        {
            let caps = self.to_capability_set(nono::SignalMode::Isolated)?;
            let mut dests: Vec<PathBuf> = self.dest_denies.iter().map(|d| d.path.clone()).collect();
            dests.extend(extra_dests);
            let workspace = self
                .grants
                .iter()
                .find(|g| g.access == KernelAccess::ReadWrite)
                .map(|g| g.path.clone())
                .unwrap_or_default();
            #[cfg(target_os = "linux")]
            let remount = linux::remount_status(&dests, &workspace)?;
            #[cfg(not(target_os = "linux"))]
            let remount = KernelApply::Applied;
            #[cfg(target_os = "linux")]
            let require_remount = remount == KernelApply::Applied;
            // Safety: the set and dest list are built in the parent; the hook
            // only applies them and maps failure to io::Error.
            unsafe {
                use std::os::unix::process::CommandExt;
                cmd.pre_exec(move || {
                    reaper::supervise_or_continue()?;
                    #[cfg(target_os = "linux")]
                    linux::apply_dest_deny_remounts(&dests, &workspace, require_remount)?;
                    #[cfg(not(target_os = "linux"))]
                    let _ = (&dests, &workspace);
                    apply_child_hardening()?;
                    nono::Sandbox::apply_auto(&caps)
                        .map_err(|e| std::io::Error::other(e.to_string()))?;
                    Ok(())
                });
            }
            Ok(remount)
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
        {
            let _ = extra_dests;
            Ok(KernelApply::UserspaceOnly)
        }
    }

    /// 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 = self.require_spawn(self.apply_pre_exec_dests(cmd, extra)?)?;
        Ok((applied, occupy))
    }

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

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

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

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

            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            #[cfg(target_os = "linux")]
            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
            #[cfg(not(target_os = "linux"))]
            let applied = self.require_spawn(self.apply_pre_exec(&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 = cmd.spawn().map_err(|e| KernelError::Apply(e.to_string()))?;
            let stdout = child.stdout.take().map(drain_pipe);
            let stderr = child.stderr.take().map(drain_pipe);
            let (status, _) = reap_process_group(&mut child, None)?;
            let output = std::process::Output {
                status,
                stdout: join_drain(stdout),
                stderr: join_drain(stderr),
            };
            Ok((applied, output))
        }
        #[cfg(windows)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "write-restricted token is not available".into(),
                ));
            }
            windows::spawn_write_restricted_output(self, &cmd, None).map(|(a, o, _)| (a, o))
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = cmd;
            Err(KernelError::Apply(
                "no kernel backend on this platform".into(),
            ))
        }
    }

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

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

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

            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            #[cfg(target_os = "linux")]
            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
            #[cfg(not(target_os = "linux"))]
            let applied = self.require_spawn(self.apply_pre_exec(&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 = cmd.spawn().map_err(|e| KernelError::Apply(e.to_string()))?;
            let stdout = child.stdout.take().map(|p| copy_pipe(p, std::io::stdout()));
            let stderr = child.stderr.take().map(|p| copy_pipe(p, std::io::stderr()));
            let (status, _) = reap_process_group(&mut child, None)?;
            join_copy(stdout);
            join_copy(stderr);
            Ok((applied, status))
        }
        #[cfg(windows)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "write-restricted token is not available".into(),
                ));
            }
            windows::spawn_write_restricted_forward(self, &cmd, None).map(|(a, s, _)| (a, s))
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = cmd;
            Err(KernelError::Apply(
                "no kernel backend on this platform".into(),
            ))
        }
    }

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

            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "kernel jail is not available; child was not started".into(),
                ));
            }
            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            #[cfg(target_os = "linux")]
            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
            #[cfg(not(target_os = "linux"))]
            let applied = self.require_spawn(self.apply_pre_exec(&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 = cmd.spawn().map_err(|e| KernelError::Apply(e.to_string()))?;
            let (status, timed_out) = wait_child_timeout_forward(child, timeout)?;
            Ok((applied, status, timed_out))
        }
        #[cfg(windows)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "write-restricted token is not available".into(),
                ));
            }
            windows::spawn_write_restricted_forward(self, &cmd, Some(timeout))
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = (cmd, timeout);
            Err(KernelError::Apply(
                "no kernel backend on this platform".into(),
            ))
        }
    }

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

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

    fn run_child_pty(
        &self,
        cmd: Command,
        timeout: Option<Duration>,
    ) -> Result<(KernelApply, ExitStatus, bool), KernelError> {
        self.dest_deny_command(&cmd)?;
        #[cfg(unix)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "kernel jail is not available; child was not started".into(),
                ));
            }
            let mut cmd = cmd;
            scrub_child_command(&mut cmd);
            let pty = pty::open_pty().map_err(|e| KernelError::Apply(e.to_string()))?;
            // unshare/Landlock before setsid/TIOCSCTTY. Linux userns
            // after a controlling TTY can stop the child on SIGTTIN.
            #[cfg(target_os = "linux")]
            let (applied, _occupy) = self.occupy_and_hook(&mut cmd)?;
            #[cfg(not(target_os = "linux"))]
            let applied = self.require_spawn(self.apply_pre_exec(&mut cmd)?)?;
            pty::attach_pty(&mut cmd, pty.slave).map_err(|e| KernelError::Apply(e.to_string()))?;
            let mut child = cmd.spawn().map_err(|e| KernelError::Apply(e.to_string()))?;
            // 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 (out_th, master_write) =
                pty::pump_master(pty.master).map_err(|e| KernelError::Apply(e.to_string()))?;
            let _stdin_th = pty::pump_stdin(master_write);
            let (status, timed_out) = reap_process_group(&mut child, timeout)?;
            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`.
    ///
    /// 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. 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.require_spawn(self.apply_pre_exec(&mut cmd)?)?;
            cmd.process_group(0);
            let mut child = cmd.spawn().map_err(|e| KernelError::Apply(e.to_string()))?;
            let (status, timed_out) = reap_process_group(&mut child, Some(timeout))?;
            if timed_out {
                return Err(KernelError::Timeout);
            }
            Ok((applied, status))
        }
        #[cfg(windows)]
        {
            if !kernel_supported() {
                return Err(KernelError::Apply(
                    "write-restricted token is not available".into(),
                ));
            }
            windows::spawn_write_restricted(self, &cmd, Some(timeout))
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = (cmd, timeout);
            Err(KernelError::Apply(
                "no kernel backend on this platform".into(),
            ))
        }
    }

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

    /// Dest-deny `cmd` argv with the jail [`DenyPolicy`] before spawn.
    ///
    /// Relative dests resolve against `cmd.current_dir()` when set, else
    /// the first ReadWrite grant. Same rules as
    /// [`crate::check_command_argv`] on program plus args. 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) -> Vec<String> {
    let mut out = vec![cmd.get_program().to_string_lossy().into_owned()];
    out.extend(cmd.get_args().map(|a| a.to_string_lossy().into_owned()));
    out
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// Same as [`collect_workspace_dest_denies`] with a host-chosen entry cap.
pub fn collect_workspace_dest_denies_limited(
    workspace: &Path,
    policy: &DenyPolicy,
    limit: usize,
) -> Result<Vec<DestDeny>, KernelError> {
    let mut out = Vec::new();
    let mut remaining = limit;
    walk_dest_denies(workspace, 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>,
) -> bool {
    if !ft.is_dir() || ft.is_symlink() {
        return false;
    }
    if let Some(deny) = dest_deny_at(path, path.display().to_string(), policy) {
        push_dest_deny(out, deny);
    }
    true
}

fn walk_dest_denies(
    dir: &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) {
            walk_dest_denies(&path, policy, out, remaining, limit)?;
            continue;
        }
        if let Some(deny) = dest_deny_at(&path, path.display().to_string(), policy) {
            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) {
            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) {
            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) {
            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) {
            walk_cache_dest_denies(&path, policy, out, remaining, limit)?;
            continue;
        }
        if let Some(deny) = dest_deny_glob_only(&path, path.display().to_string(), policy) {
            if *remaining == 0 {
                return Err(dest_deny_walk_cap(dir, limit));
            }
            *remaining -= 1;
            push_dest_deny(out, deny);
        }
    }
    Ok(())
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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