newt-core 0.8.0

Newt-Agent core types, errors, and the NeMoCode-style tier router
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
//! `ConstrainedExecutor` — the single confined-subprocess seam (P4 /
//! `p4-constrained-executor`).
//!
//! # Why this exists
//!
//! Attacker-influenced subprocesses — a model-authored `run_command`, a
//! repository-configured `build_check_cmd`, a roadmap `verify` string, a crew
//! formatter — historically each reached the OS through a *raw* `sh -c` /
//! `Command::spawn` that inherited newt's full environment and ran with no
//! kernel confinement. That is one whole class of confused-deputy escapes, one
//! per spawn site. This module makes the escape *unrepresentable* by giving
//! every such spawn ONE typed door.
//!
//! An [`ExecRequest`] declares, explicitly and up front, everything the child
//! is allowed: its `program` + `args`, its `cwd`, the [`Caveats`] fence
//! (fs / net / exec authority), the exact environment grants (nothing else — the
//! child starts env-EMPTY), and its [`ExecOrigin`] trust class. The executor
//! then mints the confinement through the SAME audited path
//! [`newt-mcp-client`](../../newt_mcp_client) already uses for MCP stdio servers
//! —  `agent_bridle::ConfinedCommand` + the `Gate` — so a single, reviewed
//! implementation confines them all.
//!
//! # The fail-closed law (targets #7–#10)
//!
//! An [`ExecOrigin::AgentInfluenced`] request is minted under a **`Kernel`
//! strength floor**. `agent_bridle::ConfinedCommand::spawn` then refuses
//! (`confinement_unenforceable`) whenever a restricted fs axis cannot be
//! *kernel*-enforced — on Linux without Landlock, or on any platform without a
//! kernel fs backend at all. So:
//!
//! - **#7** no attacker-influenced child runs outside this executor (raw spawns
//!   are migrated away and inventory-gated),
//! - **#8** the child cannot inherit credentials or authority switches — its
//!   environment is EMPTY plus only the explicit grants,
//! - **#9** an empty `net` fence requires deny-all enforcement. A platform whose
//!   complete network authority is unknown refuses the spawn (including current
//!   Seatbelt restricted-net admission), rather than imply a proved boundary,
//! - **#10** where the required kernel enforcement is unavailable the spawn is
//!   **refused**, never silently downgraded to an unconfined run.
//!
//! Linux is the normative fully-supported platform; on a platform that cannot
//! kernel-confine, an `AgentInfluenced` spawn fails closed rather than pretend.
//! ([`ExecOrigin::TrustedInfra`] carries the default floor for the small set of
//! fixed-argv internal helpers that are *not* attacker-influenced; it is here
//! for signature completeness and is not used by the agent-exec paths.)
//!
//! # The per-axis exception (`ExecOrigin::BrokerMediated`, issue #2693)
//!
//! `AgentInfluenced`'s **scalar** `Kernel` floor demands `Kernel` on *every*
//! axis, including `exec`. Under Landlock a restricted `exec` axis can only
//! ever report `Interceptor` — the loader/interpreter trampoline is a
//! documented, permanent residual (agent-bridle `exec-behavior-bound` /
//! ADR 0011 D7), not a bug — so an `AgentInfluenced` spawn with a restricted
//! `exec` scope refuses unconditionally on Linux, for every caller, forever.
//! [`NativeGitBroker`](crate::native_git_broker) hit exactly this: its own
//! host-side re-dispatch of `git` (`exec: Scope::only(["git"])`) always
//! refused, so a governed commit could never land in a default-permission
//! session (#2693).
//!
//! [`ExecOrigin::BrokerMediated`] is the honest per-axis floor for that case:
//! `agent_bridle::EnforcementFloor::CONFINED` (`fs_read`/`fs_write`/`net` =
//! `Kernel`, `exec` = `Interceptor`). It is **not** a widening of
//! `AgentInfluenced` — the filesystem and network axes still fail closed
//! exactly as before. It accepts the Interceptor-level exec residual ONLY
//! where a host-side broker (not the model) already decides, by its own
//! policy, which fixed program and argv may run — `NativeGitBroker`'s
//! `RepositoryProbe` re-dispatch, never a model-chosen command. Recorded as a
//! named deviation: `docs/security/ocap-deviations.md` §
//! `native-git-broker-exec-floor`.

use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use agent_bridle::{
    AxisEnforcement, ConfinedCommand, EnforcementFloor, Gate, Tool, ToolContext, ToolError,
};

use crate::caveats::{Caveats, Scope};

/// The trust class of the code being executed — the axis that decides how hard
/// the executor must confine before it will run anything.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExecOrigin {
    /// The program, its argv, or its behavior is influenced by the model or by
    /// repository-authored content (a build-check command, a formatter, a
    /// roadmap verify string, a model `run_command`). Minted under a `Kernel`
    /// strength floor: the spawn is **refused** if the fs fence cannot be
    /// kernel-enforced (fail-closed, #10).
    AgentInfluenced,
    /// A fixed-argv internal helper the operator authored (not model/repo
    /// influenced). Carries the default strength floor. Reserved for helpers the
    /// spawn inventory classifies `trusted-*`; the attacker-influenced paths
    /// always use [`ExecOrigin::AgentInfluenced`].
    TrustedInfra,
    /// A fixed-program, policy-mediated re-dispatch issued by a HOST-SIDE
    /// broker that already bounds which program/argv may run — not a raw
    /// model `run_command` (see the module doc's "per-axis exception").
    /// Minted under [`agent_bridle::EnforcementFloor::CONFINED`]: `fs`/`net`
    /// still require `Kernel` (fail-closed, #10 unchanged), `exec` accepts
    /// the `Interceptor` tier Landlock actually provides. Currently used only
    /// by [`crate::native_git_broker::NativeGitBroker`]'s own `git`
    /// re-dispatch.
    BrokerMediated,
}

impl ExecOrigin {
    /// The `Gate` an origin authorizes through — `AgentInfluenced` raises the
    /// enforcement floor to `Kernel` so an un-kernel-enforceable fence refuses;
    /// `BrokerMediated` raises it to the per-axis `CONFINED` floor instead,
    /// which keeps fs/net at `Kernel` but accepts `Interceptor` for exec.
    fn gate(self) -> Gate {
        match self {
            Self::AgentInfluenced => Gate::new(0).with_strength_floor(AxisEnforcement::Kernel),
            Self::TrustedInfra => Gate::new(0),
            Self::BrokerMediated => Gate::new(0).with_enforcement_floor(EnforcementFloor::CONFINED),
        }
    }
}

/// The network floor a confined child runs under. The `Caveats.net` allow-list
/// is a hostname-level intent; this decides the *kernel* mechanism that backs it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NetGrant {
    /// The child's `Caveats.net` is honored by whatever the fs/net sandbox
    /// provides (Landlock TCP-deny, Seatbelt SBPL, …) with no extra floor. The
    /// historical default — kept for spawns that are not yet migrated to the
    /// full egress floor.
    #[default]
    Unrestricted,
    /// **Deny all egress**, by the strongest kernel mechanism the platform has:
    ///
    /// * **Linux** — the child is wrapped in `newt-net-guard`, which installs
    ///   the seccomp `socket()`-family deny (TCP/UDP/DNS/raw) *in addition to*
    ///   the inherited Landlock fs fence.
    /// * **macOS** — the child's `net` caveat is narrowed to deny-all. Current
    ///   Bridle admission refuses every restricted Seatbelt net scope because
    ///   OS-deputy egress is not proven bounded. Generated direct-socket rules
    ///   are defense in depth, not evidence of a complete network boundary.
    ///
    /// On a platform with neither floor the spawn is **refused**
    /// (`ExecRefused::ConfinementUnenforceable`), never run with a weaker net
    /// floor — and macOS refuses the same way if the Seatbelt backend
    /// (`sandbox-exec`) is unavailable.
    DenyAll,
}

/// A fully-specified request to run one confined subprocess. Every field is
/// explicit: there is no ambient default that could widen the child's
/// authority. The child starts env-EMPTY — [`env`](Self::env) grants are the
/// child's *entire* environment.
#[derive(Debug, Clone)]
pub struct ExecRequest {
    origin: ExecOrigin,
    program: String,
    args: Vec<String>,
    cwd: PathBuf,
    caveats: Caveats,
    env: Vec<(String, String)>,
    /// The kernel network floor (see [`NetGrant`]).
    net_grant: NetGrant,
    /// Explicit path to the `newt-net-guard` wrapper (tests set this; production
    /// resolves it next to the running executable). Only consulted for
    /// [`NetGrant::DenyAll`].
    net_guard_bin: Option<PathBuf>,
    /// A wall-clock bound on the child. `None` = unbounded (the historical
    /// behavior, kept for long legitimate builds). When set, the executor
    /// SIGKILLs the child's whole process group at the deadline so a hostile
    /// child cannot hang the harness indefinitely.
    timeout: Option<Duration>,
    /// Per-run scratch directories (a build's `TMPDIR`): created fresh and
    /// owner-only just before spawning, removed when the run ends, so building
    /// a request never touches the filesystem.
    scratch_dirs: Vec<PathBuf>,
    /// Read roots the caller holds as directory descriptors: the Landlock
    /// fence anchors on them instead of re-opening the root by path.
    held_read_roots: Vec<agent_bridle::HeldReadRoot>,
}

impl ExecRequest {
    /// A request to run `program` with `args` in `cwd`, confined by `caveats`.
    /// The environment starts empty; add grants with [`env`](Self::env).
    #[must_use]
    pub fn new(
        origin: ExecOrigin,
        program: impl Into<String>,
        args: impl IntoIterator<Item = impl Into<String>>,
        cwd: impl Into<PathBuf>,
        caveats: Caveats,
    ) -> Self {
        Self {
            origin,
            program: program.into(),
            args: args.into_iter().map(Into::into).collect(),
            cwd: cwd.into(),
            caveats,
            env: Vec::new(),
            timeout: None,
            net_grant: NetGrant::Unrestricted,
            net_guard_bin: None,
            scratch_dirs: Vec::new(),
            held_read_roots: Vec::new(),
        }
    }

    /// Anchor the fence's read rules for these roots on the descriptors the
    /// caller holds ([`agent_bridle::HeldReadRoot`]), so a root swapped at
    /// its pathname after the caller's check is outside the fence. Each root
    /// must also be in `caveats.fs_read`; this changes how the fence is
    /// built, never what is admitted.
    #[must_use]
    pub fn held_read_roots(
        mut self,
        roots: impl IntoIterator<Item = agent_bridle::HeldReadRoot>,
    ) -> Self {
        self.held_read_roots.extend(roots);
        self
    }

    /// Add validated build metadata reads together with their held objects.
    /// Plain caveats alone cannot carry descriptor-bound authority.
    #[must_use]
    pub fn with_build_git_reads(mut self, workspace: &Path) -> Self {
        let (paths, held) = crate::git_hardening::build_git_reads(workspace);
        if let Scope::Only(reads) = &mut self.caveats.fs_read {
            reads.extend(paths);
            self.held_read_roots.extend(held);
        }
        self
    }

    pub(crate) fn build_held_read_roots(&self) -> Vec<agent_bridle::HeldReadRoot> {
        self.held_read_roots.clone()
    }

    /// Give the run a private scratch `dir`: created just before spawning
    /// (owner-only, refused if anything already exists there, symlink
    /// included) and removed when the run ends. See [`ScratchDir`].
    #[must_use]
    pub fn scratch_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.scratch_dirs.push(dir.into());
        self
    }

    /// Set the kernel network floor. [`NetGrant::DenyAll`] wraps the child in
    /// `newt-net-guard` (seccomp egress deny); if that floor cannot be
    /// established the spawn is refused.
    #[must_use]
    pub fn net_grant(mut self, grant: NetGrant) -> Self {
        self.net_grant = grant;
        self
    }

    /// Override the `newt-net-guard` binary path (tests point this at the
    /// Cargo-built guard; production resolves it next to the executor binary).
    #[must_use]
    pub fn net_guard_bin(mut self, path: impl Into<PathBuf>) -> Self {
        self.net_guard_bin = Some(path.into());
        self
    }

    /// Bound the child to `duration` of wall-clock time. At the deadline the
    /// executor SIGKILLs the child's entire process group and returns with
    /// [`ConfinedOutput::timed_out`] set — a hostile child that hangs (or spins)
    /// cannot stall the harness. Unset by default (unbounded, for long builds).
    #[must_use]
    pub fn timeout(mut self, duration: Duration) -> Self {
        self.timeout = Some(duration);
        self
    }

    /// Grant one environment variable to the child. Absent any grant the child
    /// runs with an EMPTY environment — no inherited credentials or authority
    /// switches (#8).
    #[must_use]
    pub fn env(mut self, key: impl Into<String>, val: impl Into<String>) -> Self {
        self.env.push((key.into(), val.into()));
        self
    }

    /// Grant several environment variables at once.
    #[must_use]
    pub fn envs(mut self, vars: impl IntoIterator<Item = (String, String)>) -> Self {
        self.env.extend(vars);
        self
    }

    /// The environment grants (test/inspection accessor). This is the child's
    /// entire environment — anything not listed here is unset in the child.
    #[must_use]
    pub fn env_grants(&self) -> &[(String, String)] {
        &self.env
    }

    /// The exact prepared fence, for admission before this request is spawned.
    #[must_use]
    pub fn caveats(&self) -> &Caveats {
        &self.caveats
    }

    /// Acquire this request's private scratch only after admission. The guards
    /// keep the same cleanup lifetime for native argv and confined shell runs.
    pub(crate) fn prepare_scratch(&self) -> std::io::Result<Vec<ScratchDir>> {
        self.scratch_dirs
            .iter()
            .map(|dir| {
                crate::scratch::validate_build_grant(dir, &self.caveats.fs_write)?;
                ScratchDir::create(dir)
            })
            .collect()
    }
}

/// Why a confined spawn did not run. Every variant is a refusal to weaken the
/// claim: the executor never falls back to an unconfined run.
#[derive(Debug)]
pub enum ExecRefused {
    /// The fence could not be kernel-enforced on this platform/kernel, so the
    /// spawn was refused rather than run unconfined (#10). Carries the honest
    /// reason from `agent-bridle`.
    ConfinementUnenforceable(String),
    /// The gate refused to mint the confinement (e.g. the program is outside the
    /// exec allow-list, or the call budget is exhausted).
    Authorize(String),
    /// The program was confined successfully but the OS failed to start or wait
    /// on it (spawn error, I/O error draining its output).
    Spawn(std::io::Error),
}

impl std::fmt::Display for ExecRefused {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ConfinementUnenforceable(why) => write!(
                f,
                "refused (fail-closed): confinement cannot be kernel-enforced here — {why}"
            ),
            Self::Authorize(why) => write!(f, "refused: {why}"),
            Self::Spawn(e) => write!(f, "confined spawn failed: {e}"),
        }
    }
}

impl std::error::Error for ExecRefused {}

/// The result of a completed confined run: the child's exit outcome, its
/// captured output, and the OS sandbox that was ACTUALLY applied (honest — never
/// over-claimed; [`agent_bridle::SandboxKind::None`] means advisory only).
#[derive(Debug)]
pub struct ConfinedOutput {
    /// True iff the child exited with a success status.
    pub success: bool,
    /// The exit code, if the process exited with one.
    pub code: Option<i32>,
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
    /// The OS sandbox actually applied to the child.
    pub sandbox_kind: agent_bridle::SandboxKind,
    /// True iff the child hit its [`ExecRequest::timeout`] and was killed. A
    /// timed-out run is never reported as `success`.
    pub timed_out: bool,
}

/// A throwaway [`Tool`] used only to mint the spawn [`ToolContext`] through the
/// gate. The confined spawn admission-checks the *program*, not this tool's
/// name, so the identity is immaterial. Module-scoped (mirrors
/// `newt-mcp-client`'s `McpSpawnTool`) so its trivial impl is unit-testable.
struct ExecSpawnTool;

#[async_trait::async_trait]
impl Tool for ExecSpawnTool {
    fn name(&self) -> &str {
        "confined_exec"
    }
    fn schema(&self) -> serde_json::Value {
        serde_json::json!({})
    }
    async fn invoke(
        &self,
        _args: serde_json::Value,
        _cx: &ToolContext,
    ) -> agent_bridle::ToolResult<serde_json::Value> {
        Ok(serde_json::Value::Null)
    }
}

/// Mint the spawn [`ToolContext`] the only legitimate way — through the gate —
/// bounded by `caveats` and the origin's strength floor.
fn mint_context(origin: ExecOrigin, caveats: &Caveats) -> Result<ToolContext, ExecRefused> {
    origin
        .gate()
        .authorize(&ExecSpawnTool, caveats)
        .map_err(|e| ExecRefused::Authorize(e.to_string()))
}

/// Whether this platform can actually **kernel-enforce** the workspace fs fence
/// an [`ExecOrigin::AgentInfluenced`] spawn requires. When `false`, such a spawn
/// FAILS CLOSED ([`ExecRefused::ConfinementUnenforceable`]) rather than running
/// unconfined — the honest signal a caller (or a test) uses to know whether the
/// executor will confine or refuse on this host.
///
/// Linux uses Landlock; macOS uses Seatbelt (A3, operator-accepted 2026-09-30,
/// verified on a remote macOS test runner — see `docs/security/ocap-deviations.md`).
#[must_use]
pub fn kernel_fs_fence_available() -> bool {
    #[cfg(target_os = "linux")]
    {
        agent_bridle::landlock_is_supported()
    }
    #[cfg(target_os = "macos")]
    {
        agent_bridle::seatbelt_is_supported()
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        false
    }
}

/// The single confined-subprocess executor. Every attacker-influenced spawn in
/// newt routes through [`run`](Self::run); there is no other confined-spawn
/// implementation to keep in sync.
pub struct ConstrainedExecutor;

impl ConstrainedExecutor {
    /// Run `req` to completion, confined. Blocks until the child exits (like the
    /// raw `Command::output` it replaces); returns [`ExecRefused`] without ever
    /// running the child unconfined.
    ///
    /// On `AgentInfluenced` origin the `Kernel` strength floor makes
    /// `agent_bridle::ConfinedCommand::spawn` refuse when the fs fence cannot be
    /// kernel-enforced — so a platform/kernel without Landlock (or any OS fs
    /// backend) fails closed here rather than running the child unconfined.
    pub fn run(req: &ExecRequest) -> Result<ConfinedOutput, ExecRefused> {
        Self::run_until_cancelled(req, None)
    }

    /// The same executor for model-visible async tools. Dropping this future
    /// signals the existing wait loop to kill/reap the confined process group;
    /// dropping a bare spawn_blocking handle alone would leave it running.
    pub async fn run_async(req: ExecRequest) -> Result<ConfinedOutput, ExecRefused> {
        use std::sync::{
            atomic::{AtomicBool, Ordering},
            Arc,
        };
        struct CancelOnDrop(Arc<AtomicBool>);
        impl Drop for CancelOnDrop {
            fn drop(&mut self) {
                self.0.store(true, Ordering::Release);
            }
        }
        let cancel = CancelOnDrop(Arc::new(AtomicBool::new(false)));
        let flag = Arc::clone(&cancel.0);
        let result =
            tokio::task::spawn_blocking(move || Self::run_until_cancelled(&req, Some(&flag)))
                .await
                .map_err(|error| ExecRefused::Spawn(std::io::Error::other(error)))?;
        drop(cancel);
        result
    }

    fn run_until_cancelled(
        req: &ExecRequest,
        cancel: Option<&std::sync::atomic::AtomicBool>,
    ) -> Result<ConfinedOutput, ExecRefused> {
        if cancel.is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Acquire)) {
            return Err(ExecRefused::Spawn(std::io::Error::new(
                std::io::ErrorKind::Interrupted,
                "confined execution cancelled before spawn",
            )));
        }
        let _scratch = req.prepare_scratch().map_err(ExecRefused::Spawn)?;
        // For a guarded (DenyAll) child, place it in a fresh cgroup-v2 subtree so
        // the whole descendant TREE — including a setsid / double-fork daemon that
        // escapes the process group — can be terminated with one `cgroup.kill`.
        // Best-effort: `None` where cgroup delegation is unavailable (killpg
        // fallback + the b1 residual).
        #[cfg(target_os = "linux")]
        let cgroup = if req.net_grant == NetGrant::DenyAll {
            CgroupHandle::create()
        } else {
            None
        };
        #[cfg(target_os = "linux")]
        let cgroup_procs = cgroup.as_ref().map(CgroupHandle::procs);
        #[cfg(not(target_os = "linux"))]
        let cgroup_procs: Option<PathBuf> = None;

        // Apply the network floor: NetGrant::DenyAll rewrites the child to run
        // under `newt-net-guard` (seccomp egress deny) with the guard's dir added
        // to the fs fence's read set so it can be exec'd. Refuses if the floor
        // cannot be established (never a weaker net floor).
        let (program, args, caveats) = Self::resolve_net_floor(req, cgroup_procs.as_deref())?;
        let cx = mint_context(req.origin, &caveats)?;

        let mut cmd = ConfinedCommand::new(&program)
            .sandbox_policy(std::sync::Arc::new(runtime_sandbox_policy()))
            .args(&args)
            .current_dir(&req.cwd)
            // A fresh process group so a supervisor could kill the whole
            // descendant tree (the executor's own cancellation is a follow-up;
            // the group is set up now so it is available without a re-spawn).
            .new_process_group()
            // `ConfinedStdio::Null`/`Piped` (not a bare `Stdio`) so this
            // `AgentInfluenced`/`Kernel`-floor spawn can honestly claim the
            // audited stdio shape ADR 0015 amendment E6 requires for the
            // Seatbelt net:none Kernel witness (agent-bridle#416 round-2
            // review, item 1) — this is the exact route
            // `seatbelt_net_deny_all_runs_kernel_denied` exercises.
            .stdin(agent_bridle::ConfinedStdio::Null)
            .stdout(agent_bridle::ConfinedStdio::Piped)
            .stderr(agent_bridle::ConfinedStdio::Piped)
            .held_read_roots(req.held_read_roots.iter().cloned());
        // The child's ENTIRE environment: the explicit grants and nothing else
        // (ConfinedCommand starts env-empty). No inherited credentials/switches.
        for (k, v) in &req.env {
            cmd = cmd.env(k, v);
        }

        let mut child = cmd.spawn(&cx).map_err(|e| match e {
            // A `Denied` from spawn is the fail-closed refusal: the fence could
            // not be kernel-enforced (confinement_unenforceable) — do NOT fall
            // back to an unconfined run.
            ToolError::Denied { .. } => ExecRefused::ConfinementUnenforceable(e.to_string()),
            other => ExecRefused::Authorize(other.to_string()),
        })?;

        let sandbox_kind = child.sandbox_kind;
        // The child leads its own process group (`new_process_group`, pgid ==
        // pid), so one `killpg` reaps the child AND any descendants it left in
        // the group — the child-lifetime containment the raw `Command`s lacked.
        let pgid = child.child.id();
        #[cfg(target_os = "windows")]
        let windows_job = WindowsJob::for_child(&child.child);

        // Drain stdout/stderr on their own threads so a child that fills a pipe
        // buffer cannot deadlock the wait (matches `wait_with_output`).
        let out_pipe = child.child.stdout.take();
        let err_pipe = child.child.stderr.take();
        let out_thread = std::thread::spawn(move || drain_pipe(out_pipe));
        let err_thread = std::thread::spawn(move || drain_pipe(err_pipe));

        // Bounded wait: poll for exit until the optional deadline. At the
        // deadline (leader still alive → pgid valid, no pid-reuse race) SIGKILL
        // the whole group so a hostile child cannot hang the harness.
        let deadline = req.timeout.map(|t| Instant::now() + t);
        let mut timed_out = false;
        let status = loop {
            if let Some(s) = child.child.try_wait().map_err(ExecRefused::Spawn)? {
                break s;
            }
            let deadline_reached = deadline.is_some_and(|dl| Instant::now() >= dl);
            let cancelled =
                cancel.is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Acquire));
            if deadline_reached || cancelled {
                #[cfg(target_os = "linux")]
                if let Some(cg) = &cgroup {
                    cg.kill();
                }
                #[cfg(target_os = "windows")]
                kill_child_tree(&mut child.child, pgid, windows_job.as_ref());
                #[cfg(not(target_os = "windows"))]
                kill_child_tree(&mut child.child, pgid);
                timed_out = deadline_reached;
                break child.child.wait().map_err(ExecRefused::Spawn)?;
            }
            std::thread::sleep(Duration::from_millis(20));
        };

        // Sweep the whole descendant tree. `cgroup.kill` catches a setsid /
        // double-fork daemon that escaped the process group; `killpg` is the
        // fallback where cgroup delegation was unavailable.
        #[cfg(target_os = "linux")]
        if let Some(cg) = &cgroup {
            cg.kill();
        }
        #[cfg(target_os = "windows")]
        kill_child_tree(&mut child.child, pgid, windows_job.as_ref());
        #[cfg(not(target_os = "windows"))]
        kill_child_tree(&mut child.child, pgid);

        let stdout = out_thread.join().unwrap_or_default();
        let stderr = err_thread.join().unwrap_or_default();

        Ok(ConfinedOutput {
            // A killed/timed-out run is never a success even if the reaped status
            // is a signal-death the OS reports oddly.
            success: status.success() && !timed_out,
            code: status.code(),
            stdout,
            stderr,
            sandbox_kind,
            timed_out,
        })
    }

    /// Compute the effective `(program, args, caveats)` after applying the
    /// request's [`NetGrant`]. [`NetGrant::DenyAll`] wraps the real program in
    /// `newt-net-guard` and grants the fs fence read+exec on the guard's dir; if
    /// the seccomp floor cannot be established it refuses (fail-closed). When
    /// `cgroup_procs` is `Some`, the guard is told to join that cgroup (its
    /// `cgroup.procs` is added to the write fence) before it execs.
    fn resolve_net_floor(
        req: &ExecRequest,
        cgroup_procs: Option<&Path>,
    ) -> Result<(String, Vec<String>, Caveats), ExecRefused> {
        // Only the Linux `DenyAll` arm reads `cgroup_procs`; on other platforms
        // that arm is `#[cfg]`'d out and `DenyAll` fails closed, so the parameter
        // is genuinely unused there. Consume it to keep `-D warnings` happy
        // without weakening the Linux signature both callers share.
        #[cfg(not(target_os = "linux"))]
        let _ = cgroup_procs;
        match req.net_grant {
            NetGrant::Unrestricted => {
                Ok((req.program.clone(), req.args.clone(), req.caveats.clone()))
            }
            #[cfg(target_os = "linux")]
            NetGrant::DenyAll => {
                // `(guard_program, prefix_args)`: a standalone `newt-net-guard`
                // (tests) has no prefix; the production self-exec is
                // `current_exe __net-guard`, so the guard rides in a released
                // `newt`. Either way the child inherits the fs fence + gets the
                // seccomp egress floor before the real program runs.
                let (guard, prefix) = Self::resolve_net_guard(req)?;
                let mut caveats = req.caveats.clone();
                if let Some(dir) = Path::new(&guard).parent() {
                    extend_read_root(&mut caveats, dir.to_string_lossy().into_owned());
                }
                let mut args: Vec<String> = prefix;
                if let Some(procs) = cgroup_procs {
                    // Grant write to the single cgroup.procs file so the guard can
                    // join the subtree under Landlock (it cannot escape to another
                    // cgroup — only its own procs file is writable).
                    let procs = procs.to_string_lossy().into_owned();
                    extend_write_root(&mut caveats, procs.clone());
                    args.push("--cgroup-procs".to_string());
                    args.push(procs);
                }
                args.push("--".to_string());
                args.push(req.program.clone());
                args.extend(req.args.iter().cloned());
                Ok((guard, args, caveats))
            }
            #[cfg(target_os = "macos")]
            NetGrant::DenyAll => {
                // Preserve the requested deny-all scope for Bridle admission.
                // Seatbelt availability alone does not prove the network floor:
                // current Bridle reports restricted macOS networking as
                // unenforceable and refuses it before spawning. Never weaken
                // the requested boundary merely because sandbox-exec exists.
                if !agent_bridle::seatbelt_is_supported() {
                    return Err(ExecRefused::ConfinementUnenforceable(
                        "NetGrant::DenyAll needs a kernel egress floor; the Seatbelt \
                         backend (sandbox-exec) is unavailable on this host"
                            .into(),
                    ));
                }
                Ok((
                    req.program.clone(),
                    req.args.clone(),
                    deny_all_net(&req.caveats),
                ))
            }
            #[cfg(not(any(target_os = "linux", target_os = "macos")))]
            NetGrant::DenyAll => Err(ExecRefused::ConfinementUnenforceable(
                "NetGrant::DenyAll needs a kernel egress floor (Linux seccomp guard or \
                 macOS Seatbelt), unavailable on this platform"
                    .into(),
            )),
        }
    }

    /// Resolve how to invoke the child-side network guard as `(program,
    /// prefix_args)`, in three tiers:
    ///
    /// 1. an explicit `net_guard_bin` override (the crate's real-resource tests
    ///    point it at the Cargo-built `newt-net-guard`) — standalone, no prefix;
    /// 2. a co-located `newt-net-guard` helper next to the running exe or one dir
    ///    up (the cargo dev/test layout builds it there) — standalone, no prefix.
    ///    Preferred in tests/dev so the guard is always a *real, correct* binary,
    ///    never a re-exec of a non-`newt` harness;
    /// 3. **self-exec** `current_exe __net-guard …` — production, where only
    ///    `newt` ships and carries the guard, so nothing separate can fall out of
    ///    the release archive / `cargo install` / package payload.
    ///
    /// Tier 3 self-exec fires **only when the running exe is `newt`**: re-exec'ing
    /// an arbitrary binary that lacks the `__net-guard` dispatch (a test harness,
    /// say) would run neither the guard nor the intended child — so when the exe
    /// is not `newt` and no helper was found, refuse (fail-closed) rather than
    /// re-exec something that cannot enforce the floor.
    #[cfg(target_os = "linux")]
    fn resolve_net_guard(req: &ExecRequest) -> Result<(String, Vec<String>), ExecRefused> {
        // Tier 1: explicit override.
        if let Some(p) = &req.net_guard_bin {
            return if p.is_file() {
                Ok((p.to_string_lossy().into_owned(), Vec::new()))
            } else {
                Err(ExecRefused::ConfinementUnenforceable(format!(
                    "net-guard binary not found at {}",
                    p.display()
                )))
            };
        }
        let exe = std::env::current_exe().map_err(|e| {
            ExecRefused::ConfinementUnenforceable(format!(
                "cannot resolve current executable to locate the net guard: {e}"
            ))
        })?;
        // Tier 2: a sibling `newt-net-guard` (exe dir, or one dir up for the
        // cargo `deps/` test layout).
        for cand in [
            exe.parent().map(|d| d.join("newt-net-guard")),
            exe.parent()
                .and_then(Path::parent)
                .map(|d| d.join("newt-net-guard")),
        ]
        .into_iter()
        .flatten()
        {
            if cand.is_file() {
                return Ok((cand.to_string_lossy().into_owned(), Vec::new()));
            }
        }
        // Tier 3: self-exec — only if the running exe actually IS `newt` (the
        // binary that carries the hidden `__net-guard` dispatch).
        if exe.file_name().and_then(|n| n.to_str()) == Some("newt") {
            return Ok((
                exe.to_string_lossy().into_owned(),
                vec!["__net-guard".to_string()],
            ));
        }
        Err(ExecRefused::ConfinementUnenforceable(format!(
            "no net guard: no `newt-net-guard` next to {} and it is not the `newt` \
             binary, so the `__net-guard` self-exec dispatch is unavailable",
            exe.display()
        )))
    }
}

/// Whether the [`NetGrant::DenyAll`] network guard can be resolved in the current
/// process WITHOUT an explicit override — mirroring tiers 2–3 of
/// [`ConstrainedExecutor::resolve_net_guard`]: a co-located `newt-net-guard`
/// helper (the cargo dev/test layout), or the running exe being `newt` (which
/// carries the `__net-guard` self-exec dispatch).
///
/// Tests gate their "the confined verify actually runs" assertions on this:
/// where the guard cannot be established the `DenyAll` spawn correctly FAILS
/// CLOSED (it never runs the repo-controlled command unconfined), so a test that
/// needs the verify to run must skip rather than assert a pass. A `-p <crate>`
/// build that does not compile the `newt-net-guard` bin and runs from a test
/// harness (not `newt`) is exactly that case. Always `false` off Linux (DenyAll
/// is unsupported there and fails closed).
#[must_use]
pub fn net_guard_available() -> bool {
    #[cfg(target_os = "linux")]
    {
        let Ok(exe) = std::env::current_exe() else {
            return false;
        };
        for cand in [
            exe.parent().map(|d| d.join("newt-net-guard")),
            exe.parent()
                .and_then(Path::parent)
                .map(|d| d.join("newt-net-guard")),
        ]
        .into_iter()
        .flatten()
        {
            if cand.is_file() {
                return true;
            }
        }
        exe.file_name().and_then(|n| n.to_str()) == Some("newt")
    }
    #[cfg(not(target_os = "linux"))]
    {
        false
    }
}

/// Narrow a caveat set's `net` axis to deny-all (a pure attenuation — never
/// widens). This is the macOS [`NetGrant::DenyAll`] floor: an empty net scope
/// makes the Seatbelt profile `(deny network*)`.
#[cfg(any(target_os = "macos", test))]
fn deny_all_net(caveats: &Caveats) -> Caveats {
    let mut narrowed = caveats.clone();
    narrowed.net = Scope::only([] as [String; 0]);
    narrowed
}

/// Add one read root to a caveats fs-read scope (the `lock_fs_to_workspace`
/// pattern); `All` stays `All`.
#[cfg(target_os = "linux")]
fn extend_read_root(caveats: &mut Caveats, dir: String) {
    caveats.fs_read = match &caveats.fs_read {
        Scope::All => Scope::All,
        Scope::Only(set) => Scope::only(set.iter().cloned().chain(std::iter::once(dir))),
    };
}

/// Add one write path to a caveats fs-write scope; `All` stays `All`.
#[cfg(target_os = "linux")]
fn extend_write_root(caveats: &mut Caveats, path: String) {
    caveats.fs_write = match &caveats.fs_write {
        Scope::All => Scope::All,
        Scope::Only(set) => Scope::only(set.iter().cloned().chain(std::iter::once(path))),
    };
}

/// A child-lifetime cgroup-v2 subtree: the confined child (and EVERY descendant,
/// including a `setsid` / double-fork daemon that escapes the process group) is
/// placed in it, so one write to `cgroup.kill` terminates the whole tree —
/// containment `killpg` alone cannot provide.
///
/// Best-effort and unprivileged: [`create`](Self::create) makes a fresh directory
/// under this process's OWN delegated cgroup and returns `None` where cgroup-v2
/// delegation is unavailable (the executor then keeps the killpg fallback and the
/// full-tree containment stays a `b1` residual). Dropping it kills + removes the
/// subtree.
#[cfg(target_os = "linux")]
pub struct CgroupHandle {
    dir: PathBuf,
}

/// Whether a delegated cgroup-v2 subtree with `cgroup.kill` can be created on
/// this host (the mechanism that contains a `setsid` / double-fork escape).
/// `false` where cgroup-v2 delegation is unavailable — e.g. an unprivileged
/// container/pod without a delegated subtree — in which case the executor falls
/// back to `killpg` and full-tree containment stays a `b1` residual. Real-resource
/// tests use this to skip the stronger assertion where the primitive is absent.
#[must_use]
pub fn cgroup_subtree_kill_available() -> bool {
    #[cfg(target_os = "linux")]
    {
        CgroupHandle::create().is_some()
    }
    #[cfg(not(target_os = "linux"))]
    {
        false
    }
}

#[cfg(target_os = "linux")]
impl CgroupHandle {
    /// Create a fresh sub-cgroup under this process's delegated cgroup, or `None`
    /// if cgroup-v2 delegation (`cgroup.kill`) is unavailable here.
    fn create() -> Option<Self> {
        let self_cg = std::fs::read_to_string("/proc/self/cgroup").ok()?;
        // The unified (v2) line is `0::<relative-path>`.
        let rel = self_cg
            .lines()
            .find_map(|l| l.strip_prefix("0::"))?
            .trim()
            .trim_start_matches('/');
        let pid = std::process::id();
        // A per-process counter disambiguates concurrent runs (no rng available).
        static SEQ: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let dir = PathBuf::from(format!("/sys/fs/cgroup/{rel}/newt-exec-{pid}-{n}"));
        std::fs::create_dir(&dir).ok()?;
        if dir.join("cgroup.kill").exists() {
            Some(Self { dir })
        } else {
            let _ = std::fs::remove_dir(&dir);
            None
        }
    }

    /// The `cgroup.procs` file a joining child writes its pid into.
    fn procs(&self) -> PathBuf {
        self.dir.join("cgroup.procs")
    }

    /// Kill every process in the subtree (setsid escapes included). Best-effort.
    fn kill(&self) {
        let _ = std::fs::write(self.dir.join("cgroup.kill"), "1");
    }
}

#[cfg(target_os = "linux")]
impl Drop for CgroupHandle {
    fn drop(&mut self) {
        self.kill();
        // rmdir needs the cgroup empty; the kill above drains it, but reaping is
        // asynchronous, so retry briefly.
        for _ in 0..50 {
            if std::fs::remove_dir(&self.dir).is_ok() {
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
    }
}

/// Read a captured pipe to EOF (best-effort). Runs on its own thread so the
/// wait loop cannot deadlock behind a full pipe buffer.
fn drain_pipe(pipe: Option<impl Read>) -> Vec<u8> {
    let mut buf = Vec::new();
    if let Some(mut p) = pipe {
        let _ = p.read_to_end(&mut buf);
    }
    buf
}

#[cfg(target_os = "windows")]
pub(crate) struct WindowsJob {
    handle: windows_sys::Win32::Foundation::HANDLE,
}

#[cfg(target_os = "windows")]
impl WindowsJob {
    fn for_child(child: &std::process::Child) -> Option<Self> {
        use std::os::windows::io::AsRawHandle;
        Self::for_process(child.as_raw_handle())
    }

    pub(crate) fn for_process(process: std::os::windows::io::RawHandle) -> Option<Self> {
        use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
        use windows_sys::Win32::System::JobObjects::{
            AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,
            SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
            JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
        };

        // SAFETY: all pointers are null or point to initialized Win32 structs for
        // the duration of the call. The returned handle is owned by `WindowsJob`.
        let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
        if handle.is_null() {
            return None;
        }

        let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
        limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
        // SAFETY: `limits` has the exact type requested by
        // `JobObjectExtendedLimitInformation`.
        let configured = unsafe {
            SetInformationJobObject(
                handle,
                JobObjectExtendedLimitInformation,
                (&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
                std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
            )
        } != 0;
        if !configured {
            // SAFETY: `handle` is a live handle returned by CreateJobObjectW.
            unsafe {
                CloseHandle(handle);
            }
            return None;
        }

        let process = process as HANDLE;
        // SAFETY: both handles are live. Failure is possible when the host has
        // already assigned the process to a non-breakaway job; in that case the
        // executor keeps the immediate-child kill fallback.
        let assigned = unsafe { AssignProcessToJobObject(handle, process) } != 0;
        if !assigned {
            // SAFETY: `handle` is a live handle returned by CreateJobObjectW.
            unsafe {
                CloseHandle(handle);
            }
            return None;
        }

        Some(Self { handle })
    }

    fn terminate(&self) {
        use windows_sys::Win32::System::JobObjects::TerminateJobObject;
        // SAFETY: `handle` is owned by this RAII wrapper. Termination is
        // best-effort; an already-empty job simply reports failure, which is fine.
        unsafe {
            let _ = TerminateJobObject(self.handle, 1);
        }
    }
}

#[cfg(target_os = "windows")]
impl Drop for WindowsJob {
    fn drop(&mut self) {
        use windows_sys::Win32::Foundation::CloseHandle;
        // KILL_ON_JOB_CLOSE makes a dropped job object a final cleanup sweep.
        // SAFETY: `handle` is owned by this wrapper.
        unsafe {
            CloseHandle(self.handle);
        }
    }
}

#[cfg(target_os = "windows")]
fn kill_child_tree(child: &mut std::process::Child, _pgid: u32, job: Option<&WindowsJob>) {
    if let Some(job) = job {
        job.terminate();
    }
    // If job assignment failed because the host runner already placed the child
    // in a job object, still kill the immediate launcher so the wait is bounded.
    let _ = child.kill();
}

#[cfg(not(target_os = "windows"))]
fn kill_child_tree(_child: &mut std::process::Child, pgid: u32) {
    #[cfg(unix)]
    kill_process_group(pgid);
    #[cfg(not(unix))]
    {
        let _ = pgid;
        let _ = _child.kill();
    }
}

/// SIGKILL an entire process group (`pgid`). Best-effort: `ESRCH` (the group is
/// already gone) is fine. On non-unix this is a no-op — the confined executor is
/// the Linux-normative path; other platforms fail closed before reaching here.
/// Public so the eval harness's unconfined runner reaps with the same call.
#[cfg(unix)]
pub fn kill_process_group(pgid: u32) {
    // SAFETY: `killpg` with a valid pgid and SIGKILL has no memory effects; a
    // stale pgid returns ESRCH which we ignore.
    unsafe {
        let _ = libc::killpg(pgid as libc::pid_t, libc::SIGKILL);
    }
}

/// System runtime reads shared by shell execution, build execution, and frame
/// admission. macOS's /usr/bin/git is an xcrun shim; its selected developer
/// directory can live outside Bridle's default /Library runtime roots.
pub(crate) fn runtime_sandbox_policy() -> agent_bridle::SandboxPolicy {
    // agent-bridle 0.8's L3 admission bound (`AdmittedFence::admit`) only
    // resolves a RESTRICTED `net` axis when `child_network == DenyDirect`;
    // under the default `LandlockOnly` the axis is `Unknown` and every
    // `ConstrainedExecutor` spawn fails closed with "not decidable against
    // the delegated grant ∪ declared runtime closure (L3 BOUND)". This
    // STRENGTHENS the fence (adds the seccomp `socket()` + io_uring deny on
    // top of Landlock's TCP-only rule) — it widens nothing. Matches the
    // floor `b1_run_command_sandbox_policy` already applies to the
    // run_command lane (see its doc comment).
    let policy = agent_bridle::SandboxPolicy {
        child_network: agent_bridle::ChildNetworkPolicy::DenyDirect,
        macos_private_ptys: cfg!(target_os = "macos"),
        ..agent_bridle::SandboxPolicy::default()
    };
    #[cfg(target_os = "macos")]
    {
        let mut policy = policy;
        if let Some(developer) = selected_developer_directory() {
            policy.base_read_paths.extra.push(developer.to_owned());
            // Xcode's launchers load libraries beside Contents/Developer.
            // Reading the selected tools without these sibling frameworks
            // admits the executable but leaves dyld unable to start it.
            if let Some(contents) = Path::new(developer).parent() {
                for name in ["Frameworks", "SharedFrameworks"] {
                    let frameworks = contents.join(name);
                    if frameworks.is_dir() {
                        policy
                            .base_read_paths
                            .extra
                            .push(frameworks.to_string_lossy().into_owned());
                    }
                }
            }
        }
        policy
    }
    #[cfg(not(target_os = "macos"))]
    policy
}

/// The Xcode binaries a bare-name exec grant already reaches: for each granted
/// name whose `/usr/bin/<name>` is present, `<developer>/usr/bin/<name>`.
///
/// On macOS `/usr/bin/python3`, `/usr/bin/git`, `/usr/bin/clang` and the rest
/// are xcrun shims that only forward to that binary, and the shell lane puts
/// `<developer>/usr/bin` first on the child's PATH so the shim's per-user xcrun
/// cache is never needed. A bare grant resolves only against the system dirs,
/// though, so without the twin the kernel refused the very binary PATH chose
/// (`execvp() of 'python3' failed: Operation not permitted`). Admitting it is
/// the grant the operator already made, as agent-bridle admits `/bin/bash` for
/// a granted `/bin/sh`. Empty off macOS or with no selected developer dir.
#[must_use]
pub(crate) fn developer_exec_twins<'a>(exec: impl IntoIterator<Item = &'a String>) -> Vec<String> {
    #[cfg(target_os = "macos")]
    if let Some(developer) = selected_developer_directory() {
        return exec
            .into_iter()
            .filter(|name| !name.contains('/') && Path::new("/usr/bin").join(name).is_file())
            .map(|name| Path::new(developer).join("usr/bin").join(name))
            .filter_map(|twin| twin.canonicalize().ok())
            .filter(|twin| twin.is_file())
            .flat_map(|twin| {
                // A framework build's `Versions/<v>/bin/<name>` is itself a
                // launcher that re-spawns a companion inside its bundle.
                let companions: Vec<PathBuf> = twin
                    .parent()
                    .and_then(Path::parent)
                    .map(|version| {
                        FRAMEWORK_LAUNCHER_COMPANIONS
                            .iter()
                            .map(|relative| version.join(relative))
                            .filter(|companion| companion.is_file())
                            .collect()
                    })
                    .unwrap_or_default();
                std::iter::once(twin).chain(companions)
            })
            .map(|path| path.to_string_lossy().into_owned())
            .collect();
    }
    let _ = exec;
    Vec::new()
}

/// What a macOS framework launcher (`<Name>.framework/Versions/<v>/bin/<tool>`)
/// re-spawns, relative to its `Versions/<v>` directory. Python's framework build
/// runs its interpreter from an app bundle so it gets a bundle identity.
#[cfg(target_os = "macos")]
const FRAMEWORK_LAUNCHER_COMPANIONS: &[&str] = &["Resources/Python.app/Contents/MacOS/Python"];

/// The system's selected toolchain, resolved once without repository env/cwd.
#[cfg(target_os = "macos")]
pub(crate) fn selected_developer_directory() -> Option<&'static str> {
    static DEVELOPER: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
    DEVELOPER
        .get_or_init(|| {
            let output = std::process::Command::new("/usr/bin/xcode-select")
                .arg("-p")
                .env_clear()
                .current_dir("/")
                .stdin(std::process::Stdio::null())
                .output()
                .ok()?;
            if !output.status.success() {
                return None;
            }
            let path = std::path::PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
            if !path.is_absolute() || !path.is_dir() {
                return None;
            }
            path.canonicalize().ok()?.to_str().map(str::to_owned)
        })
        .as_deref()
}

/// A `Caveats` fence for an attacker-influenced subprocess confined to
/// `workspace`: it may read and write **only** beneath the workspace root, run
/// any program (an interpreter's *identity* is admitted; its behavior is bounded
/// by the fs/net axes — see [`AxisEnforcement::Kernel`]'s doc), and reach **no**
/// network (empty `net` → kernel deny-all). Built axis-by-axis so a headless
/// dispatch path never even mentions `Caveats::top()` (the `#94` no-top-leak
/// guard).
#[must_use]
pub fn workspace_confined_caveats(workspace: &Path) -> Caveats {
    let root = workspace.to_string_lossy().into_owned();
    Caveats {
        fs_read: Scope::only([root.clone()]),
        fs_write: Scope::only([root]),
        exec: Scope::All,
        // Empty net allow-list → a kernel deny-all under Landlock ABI-v4 /
        // Seatbelt. Untrusted code has no network without an explicit grant (#9).
        net: Scope::none(),
        max_calls: crate::caveats::CountBound::Unlimited,
        valid_for_generation: Scope::All,
    }
}

/// Prepare a build under the existing calibrated fence. Resolve operator
/// tool homes before replacing HOME; no shell credentials or global target /
/// compiler-cache authority are inherited. Cargo build scripts and tests inherit
/// the same kernel fence as the compiler.
/// `network` is the caller's existing operator-granted scope, never authority
/// acquired by approving a build. Host lists narrow to deny-all for the child,
/// just as in ordinary dispatch; the caller's session authority is unchanged.
#[must_use]
pub fn build_tool_request(
    workspace: &Path,
    cwd: &Path,
    program: impl Into<String>,
    args: impl IntoIterator<Item = impl Into<String>>,
    network: &Scope<String>,
) -> ExecRequest {
    let mut caveats = build_tool_caveats(workspace);
    caveats.net = crate::caveats::spawn_net_scope(network);
    let net_grant = if caveats.net == Scope::none() {
        NetGrant::DenyAll
    } else {
        NetGrant::Unrestricted
    };
    toolchain_request(
        ExecOrigin::AgentInfluenced,
        workspace,
        cwd,
        program,
        args,
        caveats,
    )
    .net_grant(net_grant)
    .env("CARGO_NET_OFFLINE", "true")
}

/// A build's unique temporary directory under a private managed base outside
/// Git worktrees, or the explicit operator override. The Build gate admits its
/// workspace-specific root before the executor creates anything. The existing
/// execution lease retains scratch through completion and cancellation.
#[must_use]
pub fn build_scratch_dir(workspace: &Path) -> PathBuf {
    scratch_dir_under(workspace, Some(crate::scratch::build_scratch_base()))
}

/// The stable per-workspace scratch root used by Build requests and their run
/// directories. This only plans a path; allocation remains after admission.
/// An explicit operator Build scratch override is reflected in this path and
/// still needs coverage by the caller's authority.
#[must_use]
pub fn build_scratch_root(workspace: &Path) -> PathBuf {
    operator_build_scratch_root(workspace, Some(crate::scratch::build_scratch_base()))
        .expect("the Build scratch base is always configured or managed")
}

fn scratch_dir_under(workspace: &Path, base: Option<PathBuf>) -> PathBuf {
    use std::sync::atomic::{AtomicU64, Ordering};
    static NEXT: AtomicU64 = AtomicU64::new(0);
    operator_build_scratch_root(workspace, base)
        .unwrap_or_else(|| workspace.join("target").join("tmp"))
        .join(format!(
            "{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        ))
}

/// Stable per-workspace root, so the fence can grant it before any run exists.
/// Managed defaults use a compact locator; explicit bases retain the full CID.
fn operator_build_scratch_root(workspace: &Path, base: Option<PathBuf>) -> Option<PathBuf> {
    base.map(|base| {
        let identity =
            content_addressable::RawContentId::from_content(workspace.to_string_lossy().as_bytes());
        crate::scratch::managed_build_partition(&base, &identity)
            .unwrap_or_else(|| base.join(identity.to_string()))
    })
}

/// A run's private scratch directory. [`ScratchDir::create`] makes it owner-only
/// and refuses if the path already exists (so a pre-planted directory or
/// symlink is never followed or reused); `Drop` removes exactly that directory,
/// then the `tmp` and `target` parents only if they are left empty.
pub(crate) struct ScratchDir {
    path: PathBuf,
    /// `target/` did not exist before this run created it.
    created_target: bool,
    managed: Option<crate::scratch::ManagedRun>,
}

impl ScratchDir {
    fn create(path: &Path) -> std::io::Result<Self> {
        if let Some(managed) = crate::scratch::acquire_build_run(path)? {
            return Ok(Self {
                path: path.to_owned(),
                created_target: false,
                managed: Some(managed),
            });
        }
        let tmp = path.parent().unwrap_or(path);
        let target = tmp.parent().unwrap_or(tmp);
        let created_target = !target.exists();
        // `create_dir`, not `create_dir_all`: the workspace (or the operator's
        // base) must already exist. A missing one is a refusal, never created.
        match std::fs::create_dir(target) {
            Err(error) if error.kind() != std::io::ErrorKind::AlreadyExists => return Err(error),
            _ => {}
        }
        Self::private_dir(tmp, false)?;
        Self::private_dir(path, true)?;
        Ok(Self {
            path: path.to_path_buf(),
            created_target,
            managed: None,
        })
    }

    /// Make one directory, owner-only on unix. `exclusive`: fail if it exists.
    fn private_dir(dir: &Path, exclusive: bool) -> std::io::Result<()> {
        #[cfg(unix)]
        let builder = {
            let mut builder = std::fs::DirBuilder::new();
            std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
            builder
        };
        #[cfg(not(unix))]
        let builder = std::fs::DirBuilder::new();
        match builder.create(dir) {
            Err(error) if !exclusive && error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
            other => other,
        }
    }
}

impl Drop for ScratchDir {
    fn drop(&mut self) {
        if self.managed.is_some() {
            return;
        }
        // Never follow a link: only a real directory is removed.
        if std::fs::symlink_metadata(&self.path).is_ok_and(|m| m.is_dir()) {
            let _ = std::fs::remove_dir_all(&self.path);
        }
        if let Some(tmp) = self.path.parent() {
            let _ = std::fs::remove_dir(tmp);
            if self.created_target {
                if let Some(target) = tmp.parent() {
                    let _ = std::fs::remove_dir(target);
                }
            }
        }
    }
}

/// The crates.io hosts `cargo fetch` reaches: the sparse index and the
/// download CDN. These are the destinations the dependency-fetch gate asks for.
pub const CRATES_IO_FETCH_HOSTS: &[&str] = &["index.crates.io", "static.crates.io"];

/// Fill the operator's Cargo package cache with the crates `Cargo.lock` pins, so
/// the offline build lane ([`build_tool_request`]) can resolve them.
///
/// `cargo fetch --locked` compiles nothing and runs no build script, and
/// `--locked` binds every download to the lockfile's checksums. The argv is
/// fixed here, never model-supplied, so it runs as [`ExecOrigin::TrustedInfra`]:
/// host restrictions remain subject to Bridle's platform admission checks.
/// The fetch path is registered as `dependency-fetch-egress` in
/// `docs/security/ocap-deviations.md`; callers must hold the operator's `net`
/// grant for [`CRATES_IO_FETCH_HOSTS`] before running this. `network` carries
/// that authority (including an explicit unrestricted grant); this builder
/// never grants a host the caller did not provide.
#[must_use]
pub fn dependency_fetch_request(
    workspace: &Path,
    cwd: &Path,
    network: &Scope<String>,
) -> ExecRequest {
    let writes: Vec<String> = operator_tool_home("CARGO_HOME", ".cargo")
        .map(|home| cargo_home_fetch_write_roots(&home))
        .unwrap_or_default();
    let mut caveats = build_tool_caveats_with_writes(workspace, &writes);
    caveats.net = network.clone();
    toolchain_request(
        ExecOrigin::TrustedInfra,
        workspace,
        cwd,
        "cargo",
        ["fetch", "--locked"],
        caveats,
    )
}

/// What a fetch writes under `$CARGO_HOME`: the registry (index cache, `.crate`
/// files, extracted sources) and cargo's package-cache lock files. Not the
/// whole directory, which holds `credentials.toml`.
fn cargo_home_fetch_write_roots(cargo_home: &str) -> Vec<String> {
    let base = Path::new(cargo_home);
    [
        "registry",
        ".package-cache",
        ".package-cache-mutate",
        ".global-cache",
        ".global-cache-journal",
        ".global-cache-wal",
        ".global-cache-shm",
    ]
    .into_iter()
    .map(|entry| base.join(entry).to_string_lossy().into_owned())
    .collect()
}

/// The environment every toolchain child shares: an env-empty start, a private
/// scratch HOME, a workspace target, operator tool homes, and a PATH that finds
/// the real compiler. HOME and temporary files share the admitted run lease;
/// developer-tool caches and Linux dot directories cannot dirty the checkout.
/// Network policy is the caller's.
fn toolchain_request(
    origin: ExecOrigin,
    workspace: &Path,
    cwd: &Path,
    program: impl Into<String>,
    args: impl IntoIterator<Item = impl Into<String>>,
    caveats: Caveats,
) -> ExecRequest {
    let scratch = build_scratch_dir(workspace);
    let mut request = ExecRequest::new(origin, program, args, cwd, caveats)
        .env("HOME", scratch.to_string_lossy())
        .env("TMPDIR", scratch.to_string_lossy())
        .env("TMP", scratch.to_string_lossy())
        .env("TEMP", scratch.to_string_lossy())
        .scratch_dir(scratch)
        .env(
            "CARGO_TARGET_DIR",
            workspace.join("target").to_string_lossy(),
        )
        // Operator Cargo config may name an out-of-fence compiler cache daemon.
        // A confined build uses the compiler directly, not that ambient deputy.
        .env("RUSTC_WRAPPER", "")
        .env("RUSTC_WORKSPACE_WRAPPER", "");
    for (name, default) in [("CARGO_HOME", ".cargo"), ("RUSTUP_HOME", ".rustup")] {
        if let Some(path) = operator_tool_home(name, default) {
            request = request.env(name, path);
        }
    }
    let mut paths = Vec::new();
    #[cfg(target_os = "macos")]
    if let Some(developer) = selected_developer_directory() {
        // Xcode's Developer/usr/bin/cc is another xcrun shim. Prefer its
        // actual compiler, which needs no per-user xcrun cache/frameworks.
        paths.push(PathBuf::from(developer).join("Toolchains/XcodeDefault.xctoolchain/usr/bin"));
        paths.push(PathBuf::from(developer).join("usr/bin"));
        if let Some(sdk) = selected_macos_sdk() {
            request = request.env("SDKROOT", sdk);
        }
    }
    if let Some(path) = std::env::var_os("PATH") {
        paths.extend(std::env::split_paths(&path));
    }
    if let Ok(path) = std::env::join_paths(paths) {
        request = request.env("PATH", path.to_string_lossy());
    }
    request.with_build_git_reads(workspace)
}

fn operator_tool_home(name: &str, default: &str) -> Option<String> {
    std::env::var_os(name)
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(default)))
        .filter(|path| path.is_absolute())
        .map(|path| path.to_string_lossy().into_owned())
}

#[cfg(target_os = "macos")]
fn selected_macos_sdk() -> Option<String> {
    let developer = Path::new(selected_developer_directory()?);
    [
        "Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk",
        "SDKs/MacOSX.sdk",
    ]
    .into_iter()
    .filter_map(|relative| developer.join(relative).canonicalize().ok())
    .find(|path| path.is_dir() && path.starts_with(developer))
    .map(|path| path.to_string_lossy().into_owned())
}

/// A `Caveats` fence for a repo-configured **build / test / format tool** run on
/// the model's edits (`build_check_cmd`, crew formatters, roadmap `verify`).
///
/// It widens [`workspace_confined_caveats`]'s reads to the **toolchain + package
/// cache** a real build tool needs (so `cargo`/`rustc` resolve and cached deps
/// are found) but NOT `$HOME` broadly — `~/.ssh`, `~/.aws`, `/etc/shadow`, and
/// arbitrary secrets stay unreadable. That closes a read-then-disclose path: a
/// hostile `build_check_cmd = "cat ~/.ssh/id_rsa"` would otherwise surface the
/// key in the tool output the model sees, and the net fence alone (which stops
/// the *child* exfiltrating) does not close the child→output→model channel.
///
/// Writes cover the workspace and its private build scratch partition, never
/// the shared cache or shared temporary parent. The baseline denies networking;
/// build requests narrow the caller's network scope using ordinary spawn policy.
/// Descendants inherit the same filesystem fence.
#[must_use]
pub fn build_tool_caveats(workspace: &Path) -> Caveats {
    build_tool_caveats_with_writes(workspace, &[])
}

/// [`build_tool_caveats`] plus additional writable roots — for a build tool that
/// legitimately writes OUTSIDE the workspace to an operator-configured location,
/// e.g. crew's shared `CARGO_TARGET_DIR` (one incremental target across the
/// sequential worktrees). Each extra root is an explicit, reviewed grant; `net`
/// stays denied and the read set stays the calibrated toolchain/cache set. Only
/// add roots the OPERATOR configured, not anything the repository controls.
#[must_use]
pub fn build_tool_caveats_with_writes(workspace: &Path, extra_write_roots: &[String]) -> Caveats {
    build_caveats_with_scratch(
        workspace,
        extra_write_roots,
        Some(crate::scratch::build_scratch_base()),
    )
}

fn build_caveats_with_scratch(
    workspace: &Path,
    extra_write_roots: &[String],
    scratch_base: Option<PathBuf>,
) -> Caveats {
    let scratch = operator_build_scratch_root(workspace, scratch_base)
        .map(|root| root.to_string_lossy().into_owned());
    let mut write_roots = vec![workspace.to_string_lossy().into_owned()];
    write_roots.extend(extra_write_roots.iter().cloned());
    write_roots.extend(scratch.clone());
    let mut read_roots = build_tool_read_roots(workspace);
    read_roots.extend(scratch);
    Caveats {
        // Calibrated reads: workspace + the toolchain/package-cache roots build
        // tools need — NOT all of `$HOME` (so ~/.ssh etc. stay unreadable). The
        // system dirs (/usr, /lib, loaders) are covered by the sandbox backend's
        // base read paths; here we add the workspace and the per-user caches.
        fs_read: Scope::only(read_roots),
        fs_write: Scope::only(write_roots),
        exec: Scope::All,
        net: Scope::none(),
        max_calls: crate::caveats::CountBound::Unlimited,
        valid_for_generation: Scope::All,
    }
}

/// The read roots a build tool needs beyond the sandbox backend's base system
/// paths: the workspace and per-user toolchain / package caches — resolved
/// from the operator's environment, never
/// `$HOME` as a whole. Deliberately excludes credential dirs (`~/.ssh`, `~/.aws`,
/// `~/.gnupg`): a build tool has no reason to read those, and granting them would
/// reopen the read-then-disclose path.
fn build_tool_read_roots(workspace: &Path) -> Vec<String> {
    let mut roots = vec![workspace.to_string_lossy().into_owned()];
    roots.extend(toolchain_read_roots());
    roots
}

/// The per-user toolchain / package-cache roots alone (no workspace), derived
/// from the operator's environment. Shared by [`build_tool_read_roots`] and by
/// [`crate::agentic::permissions::widen_caveats`]'s build-tool exec arm — an
/// `exec` grant for `cargo`/`just`/`make` carries the same calibrated reads a
/// lifecycle build gets, one derivation, not two (dec1-build-grant, F35).
///
/// dec1-build-grant round 3 (architect review, PR #2579): every root here is
/// non-secret by construction — narrow this list rather than the callers, and
/// every caller inherits the fix. `$CARGO_HOME` is narrowed to
/// [`cargo_home_read_roots`] (never the whole directory — that grant let
/// `cargo --version; cat $CARGO_HOME/credentials.toml` read the secret
/// straight through it), and `$XDG_CACHE_HOME` is dropped entirely: nothing
/// in this repo has shown a build needs it, and it can hold arbitrary
/// per-tool state (an ML CLI's auth token cache, for one). If a real build
/// ever needs a specific cache subdirectory, grant that subdirectory with a
/// comment naming why — never the whole cache root.
#[must_use]
pub fn toolchain_read_roots() -> Vec<String> {
    let mut roots = Vec::new();
    if let Some(home) = operator_tool_home("CARGO_HOME", ".cargo") {
        roots.extend(cargo_home_read_roots(&home));
    }
    if let Some(path) = operator_tool_home("RUSTUP_HOME", ".rustup") {
        roots.push(path);
    }
    // System C toolchain headers: world-readable OS files with zero
    // disclosure value (P0 U6e) — this is a read-then-disclose fence, and
    // headers carry nothing worth disclosing. macOS is covered by the
    // SDK/Developer roots added above instead.
    #[cfg(all(unix, not(target_os = "macos")))]
    {
        roots.push("/usr/include".to_string());
        roots.push("/usr/local/include".to_string());
    }
    // The exact `~/.local/bin` root only — never a wider `~/.local` or
    // `$HOME` grant. `$XDG_BIN_HOME`, if set, overrides it; XDG_BIN_HOME is
    // a proposed, not ratified, XDG variable, so this is deliberately not
    // presented as a standard default.
    if let Some(path) = operator_tool_home("XDG_BIN_HOME", ".local/bin") {
        roots.push(path);
    }
    roots
}

/// `$CARGO_HOME`'s narrow, non-secret read set (dec1-build-grant round 3):
/// `bin/` (cached toolchain binaries), `registry/` (downloaded crate
/// sources), `git/` (vendored git dependencies) — what `cargo build`/`cargo
/// test` reads to resolve dependencies with the network denied — plus the
/// config file, if the operator has one. NEVER `credentials.toml` /
/// `credentials`: those hold registry auth tokens, and the whole-directory
/// grant this replaces handed them to ANY confined command whose leading
/// token merely looked like a build tool. A subdir that doesn't exist yet is
/// a harmless no-op grant, so this never probes the filesystem — same style
/// as the rest of this module's root derivation.
fn cargo_home_read_roots(cargo_home: &str) -> Vec<String> {
    let base = Path::new(cargo_home);
    let mut roots: Vec<String> = ["bin", "registry", "git"]
        .into_iter()
        .map(|subdir| base.join(subdir).to_string_lossy().into_owned())
        .collect();
    roots.push(base.join("config.toml").to_string_lossy().into_owned());
    roots.push(base.join("config").to_string_lossy().into_owned());
    roots
}

/// Build-tool exec names whose grant carries the toolchain read roots and, in
/// the TUI danger table, is covered by an existing session build grant —
/// pure DATA (three-Cs), not a `match` arm, so a new build tool is a data
/// edit. Compared against the target's file-name component, so a pathful
/// `/usr/bin/cargo` matches too.
pub const BUILD_TOOL_EXEC: &[&str] = &["cargo", "just", "make"];

/// Is `target` a build-tool exec name (see [`BUILD_TOOL_EXEC`])? Compares the
/// file-name component, matching the danger table's `is_interpreter` convention.
#[must_use]
pub fn is_build_tool_exec(target: &str) -> bool {
    let trimmed = target.trim();
    let name = Path::new(trimmed)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(trimmed);
    BUILD_TOOL_EXEC.contains(&name)
}

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

    /// dec1-build-grant: the build-tool predicate matches a bare name and a
    /// pathful target on its file-name component, and rejects an unrelated
    /// command — the same convention `DangerTable::is_interpreter` uses.
    #[test]
    fn is_build_tool_exec_matches_known_names_only() {
        assert!(is_build_tool_exec("cargo"));
        assert!(is_build_tool_exec("just"));
        assert!(is_build_tool_exec("make"));
        assert!(is_build_tool_exec("/usr/bin/cargo"));
        assert!(!is_build_tool_exec("rm"));
        assert!(!is_build_tool_exec("bash"));
    }

    /// RAII guard that restores an env var to its value at construction on
    /// drop, so a failed assertion mid-test does not leak the fake `HOME` (or
    /// a cleared `XDG_BIN_HOME`) into every later test in the process.
    struct EnvRestore {
        key: &'static str,
        saved: Option<std::ffi::OsString>,
    }

    impl EnvRestore {
        fn capture(key: &'static str) -> Self {
            Self {
                key,
                saved: std::env::var_os(key),
            }
        }
    }

    impl Drop for EnvRestore {
        fn drop(&mut self) {
            crate::process_env::set_or_remove(
                self.key,
                self.saved.as_deref().and_then(|v| v.to_str()),
            );
        }
    }

    /// Regression for the P0 U6e build-lane read fence: the lane could not
    /// compile any crate with a C build script (`stdc-predef.h: Permission
    /// denied`) or resolve `just` from `~/.local/bin` (`Permission denied`).
    ///
    /// Deterministic (holds `process_env::lock`, pins `HOME` to a fake path,
    /// clears `XDG_BIN_HOME` for the default case) rather than reading the
    /// ambient environment — a runner with `XDG_BIN_HOME` set or no `HOME`
    /// must not flip or skip this assertion.
    ///
    /// The forbidden check reuses [`crate::caveats::permits_path`] — the same
    /// containment logic the fence itself enforces — so it is an
    /// ancestor-or-equal check, not string equality: a root of `$HOME` itself
    /// would pass an equality check against `$HOME/.newt` but must fail this
    /// one, since it would still disclose everything under it.
    #[test]
    fn build_tool_read_roots_include_c_headers_and_local_bin() {
        let _env = crate::process_env::lock();
        let _restore_home = EnvRestore::capture("HOME");
        let _restore_xdg_bin = EnvRestore::capture("XDG_BIN_HOME");
        // Built from temp_dir so it is absolute on every platform: a bare
        // `/fake-…` has no drive prefix on Windows, and operator_tool_home
        // (correctly) drops a non-absolute root.
        let fake_home = std::env::temp_dir().join("fake-home-for-build-tool-read-roots-test");
        let abs_bin_home = std::env::temp_dir()
            .join("abs-bin-home")
            .to_string_lossy()
            .into_owned();
        crate::process_env::set_var("HOME", fake_home.to_str().unwrap());
        crate::process_env::remove_var("XDG_BIN_HOME");

        let roots = build_tool_read_roots(Path::new("/workspace"));
        #[cfg(all(unix, not(target_os = "macos")))]
        {
            assert!(roots.iter().any(|r| r == "/usr/include"));
            assert!(roots.iter().any(|r| r == "/usr/local/include"));
        }
        let local_bin = fake_home.join(".local/bin").to_string_lossy().into_owned();
        assert!(roots.contains(&local_bin));

        // Ancestor-or-equal, not equality: no root may CONTAIN these HOME
        // subtrees (or HOME itself) via the same prefix logic the fs fence
        // enforces in production.
        let read_scope = Scope::only(roots.clone());
        for forbidden in [
            fake_home.clone(),
            fake_home.join(".newt"),
            fake_home.join(".config"),
            fake_home.join(".local/share"),
            fake_home.join(".ssh"),
        ] {
            let forbidden = forbidden.to_string_lossy().into_owned();
            assert!(
                !crate::caveats::permits_path(&read_scope, &forbidden),
                "a build-lane root must not grant read over {forbidden}"
            );
        }

        // An absolute XDG_BIN_HOME override replaces the default.
        crate::process_env::set_var("XDG_BIN_HOME", &abs_bin_home);
        let roots_abs = build_tool_read_roots(Path::new("/workspace"));
        assert!(roots_abs.contains(&abs_bin_home));
        assert!(!roots_abs.contains(&local_bin));

        // A relative XDG_BIN_HOME must be skipped, per operator_tool_home,
        // not silently fall back to the default `~/.local/bin`.
        crate::process_env::set_var("XDG_BIN_HOME", "relative/bin");
        let roots_relative = build_tool_read_roots(Path::new("/workspace"));
        assert!(!roots_relative.iter().any(|r| r == "relative/bin"));
        assert!(!roots_relative.contains(&local_bin));
    }

    /// dec1-build-grant round 3 (architect review, PR #2579), red test (a):
    /// the whole `$CARGO_HOME` directory is no longer a root — a hostile
    /// `cargo --version; cat $CARGO_HOME/credentials.toml` read the secret
    /// straight through that grant. `toolchain_read_roots` now narrows
    /// `$CARGO_HOME` to `bin/`/`registry/`/`git/` + a config file, and drops
    /// `$XDG_CACHE_HOME` entirely. Would fail before the fix: `roots`
    /// contained the bare `$CARGO_HOME` and `$XDG_CACHE_HOME` strings, which
    /// `permits_path` (ancestor-or-equal, the same check the fence itself
    /// uses) would have found to cover `credentials.toml` and
    /// `huggingface/token`.
    #[test]
    fn toolchain_read_roots_narrows_cargo_home_and_drops_the_cache_dir() {
        let _env = crate::process_env::lock();
        let _restore_home = EnvRestore::capture("HOME");
        let _restore_cargo = EnvRestore::capture("CARGO_HOME");
        let _restore_xdg_cache = EnvRestore::capture("XDG_CACHE_HOME");
        let fake_home = std::env::temp_dir().join("fake-home-for-toolchain-read-roots-test");
        crate::process_env::set_var("HOME", fake_home.to_str().unwrap());
        crate::process_env::remove_var("CARGO_HOME");
        crate::process_env::remove_var("XDG_CACHE_HOME");

        let roots = toolchain_read_roots();
        let cargo_home = fake_home.join(".cargo");

        // The narrow subdirs a real build needs ARE granted.
        for subdir in ["bin", "registry", "git"] {
            let expected = cargo_home.join(subdir).to_string_lossy().into_owned();
            assert!(roots.contains(&expected), "missing {expected} in {roots:?}");
        }
        for config in ["config.toml", "config"] {
            let expected = cargo_home.join(config).to_string_lossy().into_owned();
            assert!(roots.contains(&expected), "missing {expected} in {roots:?}");
        }
        // The whole CARGO_HOME directory itself is never a root — a
        // directory grant would also cover credentials.toml.
        assert!(!roots
            .iter()
            .any(|r| r == cargo_home.to_string_lossy().as_ref()));

        // The credential files are never covered — ancestor-or-equal check,
        // the same containment logic the fence itself enforces.
        let read_scope = Scope::only(roots.clone());
        for secret in ["credentials.toml", "credentials"] {
            let forbidden = cargo_home.join(secret).to_string_lossy().into_owned();
            assert!(
                !crate::caveats::permits_path(&read_scope, &forbidden),
                "toolchain_read_roots must never grant read over {forbidden}"
            );
        }

        // $XDG_CACHE_HOME is dropped entirely — not a root, and no path
        // beneath the default cache dir is covered either.
        let default_cache = fake_home.join(".cache").to_string_lossy().into_owned();
        assert!(!roots.iter().any(|r| r == &default_cache));
        let hf_token = fake_home
            .join(".cache/huggingface/token")
            .to_string_lossy()
            .into_owned();
        assert!(!crate::caveats::permits_path(&read_scope, &hf_token));
    }

    #[test]
    fn already_cancelled_request_never_attempts_spawn() {
        let request = ExecRequest::new(
            ExecOrigin::AgentInfluenced,
            "missing-program",
            ["unused"],
            "/missing",
            workspace_confined_caveats(Path::new("/missing")),
        );
        let cancel = std::sync::atomic::AtomicBool::new(true);
        assert!(
            matches!(ConstrainedExecutor::run_until_cancelled(&request, Some(&cancel)), Err(ExecRefused::Spawn(error)) if error.kind() == std::io::ErrorKind::Interrupted)
        );
    }

    #[test]
    fn dependency_fetch_is_online_to_crates_io_only_and_never_writes_credentials() {
        let _env = crate::process_env::lock();
        let network = Scope::only(CRATES_IO_FETCH_HOSTS.iter().map(|host| (*host).to_owned()));
        let request = dependency_fetch_request(Path::new("/ws"), Path::new("/ws/sub"), &network);
        assert_eq!(request.origin, ExecOrigin::TrustedInfra);
        assert_eq!(request.net_grant, NetGrant::Unrestricted);
        assert_eq!(request.args, ["fetch", "--locked"]);
        assert_eq!(
            request.caveats.net,
            Scope::only(CRATES_IO_FETCH_HOSTS.iter().map(|host| (*host).to_owned()))
        );
        assert!(request
            .env_grants()
            .iter()
            .all(|(name, _)| name != "CARGO_NET_OFFLINE"));
        if let Some(home) = operator_tool_home("CARGO_HOME", ".cargo") {
            let home = Path::new(&home);
            let registry = home.join("registry").to_string_lossy().into_owned();
            let credentials = home.join("credentials.toml").to_string_lossy().into_owned();
            assert!(crate::caveats::permits_path(
                &request.caveats.fs_write,
                &registry
            ));
            assert!(!crate::caveats::permits_path(
                &request.caveats.fs_write,
                &credentials
            ));
            assert!(!crate::caveats::permits_path(
                &request.caveats.fs_read,
                &credentials
            ));
        }
    }

    #[test]
    fn dependency_fetch_network_grant_does_not_expand_filesystem_authority() {
        let _env = crate::process_env::lock();
        let ws = Path::new("/ws");
        let narrow = Scope::only(CRATES_IO_FETCH_HOSTS.iter().map(|host| (*host).to_owned()));
        let baseline = dependency_fetch_request(ws, ws, &narrow);
        let request = dependency_fetch_request(ws, ws, &Scope::All);
        assert_eq!(request.caveats.net, Scope::All);
        assert_eq!(request.caveats.fs_read, baseline.caveats.fs_read);
        assert_eq!(request.caveats.fs_write, baseline.caveats.fs_write);
        assert_eq!(request.args, baseline.args);
        let denied = dependency_fetch_request(ws, ws, &Scope::none());
        assert_eq!(denied.caveats.net, Scope::none());
    }

    #[test]
    fn build_request_discovers_toolchain_before_replacing_home() {
        let _env = crate::process_env::lock();
        let request = build_tool_request(
            Path::new("/ws"),
            Path::new("/ws"),
            "cargo",
            ["test"],
            &Scope::none(),
        );
        let env: std::collections::BTreeMap<_, _> = request.env_grants().iter().cloned().collect();
        assert_eq!(
            env.get("HOME").map(Path::new),
            Some(request.scratch_dirs[0].as_path())
        );
        assert_eq!(
            env.get("CARGO_TARGET_DIR").map(std::path::Path::new),
            Some(Path::new("/ws").join("target").as_path())
        );
        // `RUSTUP_HOME` env matches an operator override and is fully
        // readable (never a secret; toolchains only).
        if let Some(path) = operator_tool_home("RUSTUP_HOME", ".rustup") {
            assert_eq!(env.get("RUSTUP_HOME"), Some(&path));
            assert!(crate::caveats::permits_path(
                &request.caveats.fs_read,
                &path
            ));
            assert!(!crate::caveats::permits_path(
                &request.caveats.fs_write,
                &path
            ));
        }
        // `CARGO_HOME` env still resolves to the whole home (cargo itself
        // needs that to find its own layout) — but the READ grant is the
        // narrowed `cargo_home_read_roots` set (round 3, PR #2579): the
        // subdirs a build needs are readable, `credentials.toml` is not.
        if let Some(path) = operator_tool_home("CARGO_HOME", ".cargo") {
            assert_eq!(env.get("CARGO_HOME"), Some(&path));
            for subdir in ["bin", "registry", "git"] {
                assert!(crate::caveats::permits_path(
                    &request.caveats.fs_read,
                    &Path::new(&path).join(subdir).to_string_lossy()
                ));
            }
            assert!(!crate::caveats::permits_path(
                &request.caveats.fs_read,
                &Path::new(&path).join("credentials.toml").to_string_lossy()
            ));
            assert!(!crate::caveats::permits_path(
                &request.caveats.fs_write,
                &path
            ));
        }
        assert!(env.keys().all(|name| [
            "HOME",
            "TMPDIR",
            "TMP",
            "TEMP",
            "PATH",
            "CARGO_HOME",
            "RUSTUP_HOME",
            "CARGO_TARGET_DIR",
            "CARGO_NET_OFFLINE",
            "RUSTC_WRAPPER",
            "RUSTC_WORKSPACE_WRAPPER",
            "SDKROOT"
        ]
        .contains(&name.as_str())));
        assert_eq!(request.net_grant, NetGrant::DenyAll);
        assert_eq!(request.caveats.exec, Scope::All);
        // The proposed Build fence includes only this workspace's private
        // scratch partition, not its shared temporary parent.
        assert_eq!(
            request.caveats.fs_write,
            build_tool_caveats(Path::new("/ws")).fs_write
        );
        let scratch = &request.scratch_dirs[0];
        assert_eq!(request.scratch_dirs.len(), 1);
        assert_eq!(env.get("TMPDIR").map(Path::new), Some(scratch.as_path()));
        assert!(!scratch.starts_with("/ws"), "{scratch:?}");
        assert!(crate::caveats::permits_path(
            &request.caveats.fs_write,
            &scratch.to_string_lossy()
        ));
        assert!(crate::caveats::permits_path(
            &request.caveats.fs_read,
            &scratch.to_string_lossy()
        ));
    }

    /// Build and fetch must isolate HOME writes without losing toolchain homes.
    #[test]
    fn toolchain_requests_keep_home_outside_the_workspace() {
        let _env = crate::process_env::lock();
        let workspace = Path::new("/ws");
        for request in [
            build_tool_request(workspace, workspace, "cargo", ["check"], &Scope::none()),
            dependency_fetch_request(workspace, workspace, &Scope::none()),
        ] {
            let env: std::collections::BTreeMap<_, _> =
                request.env_grants().iter().cloned().collect();
            let home = Path::new(&env["HOME"]);
            assert!(
                !home.starts_with(workspace),
                "HOME must not pollute the repo"
            );
            assert_eq!(home, request.scratch_dirs[0]);
            assert_eq!(env["HOME"], env["TMPDIR"]);
            for (name, default) in [("CARGO_HOME", ".cargo"), ("RUSTUP_HOME", ".rustup")] {
                assert_eq!(env.get(name).cloned(), operator_tool_home(name, default));
            }
            assert!(crate::caveats::permits_path(
                &request.caveats.fs_write,
                &home.to_string_lossy()
            ));
            assert!(!crate::caveats::permits_path(
                &request.caveats.fs_write,
                &home.parent().unwrap().parent().unwrap().to_string_lossy()
            ));
        }
    }

    #[test]
    fn each_build_scratch_dir_is_unique() {
        let ws = Path::new("/ws");
        assert_ne!(build_scratch_dir(ws), build_scratch_dir(ws));
    }

    #[test]
    fn build_network_authority_narrows_hosts_and_preserves_filesystem_fence() {
        let _env = crate::process_env::lock();
        let ws = Path::new("/ws");
        let baseline = build_tool_caveats(ws);
        // #2729: derive the native grant from the effective child scope.
        for (network, expected) in [
            (Scope::none(), Scope::none()),
            (Scope::only(["example.test".into()]), Scope::none()),
            (Scope::All, Scope::All),
        ] {
            let request = build_tool_request(ws, ws, "cargo", ["test"], &network);
            assert_eq!(request.caveats.net, expected);
            assert_eq!(request.caveats.fs_read, baseline.fs_read);
            assert_eq!(request.caveats.fs_write, baseline.fs_write);
            assert_eq!(request.caveats.exec, baseline.exec);
            assert_eq!(request.origin, ExecOrigin::AgentInfluenced);
            assert_eq!(
                request.net_grant,
                if expected == Scope::none() {
                    NetGrant::DenyAll
                } else {
                    NetGrant::Unrestricted
                }
            );
            assert!(request
                .env_grants()
                .contains(&("CARGO_NET_OFFLINE".into(), "true".into())));
        }
    }

    #[cfg(unix)]
    #[test]
    fn scratch_dir_is_owner_only_and_gone_after_the_run() {
        use std::os::unix::fs::PermissionsExt;
        let ws = tempfile::tempdir().unwrap();
        let path = build_scratch_dir(ws.path());
        let guard = ScratchDir::create(&path).unwrap();
        let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode(&path), 0o700);
        assert_eq!(mode(path.parent().unwrap()), 0o700);
        std::fs::write(path.join("cc.tmp"), b"x").unwrap();
        drop(guard);
        assert!(!path.exists(), "scratch dir must be removed");
        assert!(
            !ws.path().join("target").exists(),
            "an empty target/ this run created is removed too"
        );
    }

    #[cfg(unix)]
    #[test]
    fn scratch_cleanup_deletes_nothing_else() {
        let ws = tempfile::tempdir().unwrap();
        let target = ws.path().join("target");
        std::fs::create_dir_all(target.join("debug")).unwrap();
        std::fs::write(target.join("debug/keep"), b"k").unwrap();
        let other = ScratchDir::create(&build_scratch_dir(ws.path())).unwrap();
        let path = build_scratch_dir(ws.path());
        drop(ScratchDir::create(&path).unwrap());
        assert!(target.join("debug/keep").is_file());
        assert!(other.path.is_dir(), "a concurrent run's dir is untouched");
        drop(other);
        assert!(target.join("debug/keep").is_file());
    }

    /// A pre-existing symlink (or anything) at the scratch path is refused,
    /// never followed into another place, and its target is left alone.
    #[cfg(unix)]
    #[test]
    fn a_symlink_at_the_scratch_path_is_refused() {
        let ws = tempfile::tempdir().unwrap();
        let elsewhere = tempfile::tempdir().unwrap();
        let path = scratch_dir_under(ws.path(), None);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::os::unix::fs::symlink(elsewhere.path(), &path).unwrap();
        assert!(ScratchDir::create(&path).is_err());
        assert!(std::fs::symlink_metadata(&path)
            .unwrap()
            .file_type()
            .is_symlink());
        assert!(elsewhere.path().is_dir());
    }

    /// A missing workspace is a refusal: the scratch guard creates `target/`
    /// and below, never the workspace itself or its ancestors.
    #[test]
    fn a_missing_workspace_is_refused_not_created() {
        let root = tempfile::tempdir().unwrap();
        let ws = root.path().join("missing").join("ws");
        assert!(ScratchDir::create(&scratch_dir_under(&ws, None)).is_err());
        assert!(!root.path().join("missing").exists());
    }

    /// End to end: the child's TMPDIR is the scratch dir, and it is gone once
    /// the lane returns, whether or not this host can enforce the fence.
    #[cfg(unix)]
    #[test]
    fn a_build_lane_run_leaves_no_scratch_behind() {
        let ws = tempfile::tempdir().unwrap();
        let ws = ws.path().canonicalize().unwrap();
        let req = build_tool_request(
            &ws,
            &ws,
            "sh",
            ["-c", "printf %s \"$TMPDIR\"; touch \"$TMPDIR/x\""],
            &Scope::none(),
        );
        let scratch = req.scratch_dirs[0].clone();
        if let Ok(out) = ConstrainedExecutor::run(&req) {
            if out.success {
                assert_eq!(
                    String::from_utf8_lossy(&out.stdout),
                    scratch.to_string_lossy()
                );
            }
        }
        assert!(!scratch.exists());
    }

    #[test]
    fn agent_influenced_mints_under_a_kernel_strength_floor() {
        // #10 foundation: an AgentInfluenced context carries the Kernel floor,
        // which is what makes `spawn` fail closed when the fence can't be
        // kernel-enforced. TrustedInfra carries the default (advisory) floor.
        let caveats = workspace_confined_caveats(Path::new("/ws"));
        let agent_cx = mint_context(ExecOrigin::AgentInfluenced, &caveats).unwrap();
        assert_eq!(agent_cx.strength_floor().exec(), AxisEnforcement::Kernel);
        assert_eq!(agent_cx.strength_floor().net(), AxisEnforcement::Kernel);
        let trusted_cx = mint_context(ExecOrigin::TrustedInfra, &caveats).unwrap();
        assert_ne!(trusted_cx.strength_floor().exec(), AxisEnforcement::Kernel);
        assert_ne!(trusted_cx.strength_floor().net(), AxisEnforcement::Kernel);
    }

    /// #2693: `BrokerMediated` is the per-axis fix for `NativeGitBroker`'s own
    /// git re-dispatch — fs/net stay at the SAME `Kernel` floor `AgentInfluenced`
    /// requires (no widening there), but exec is accepted at `Interceptor`
    /// instead of demanding `Kernel` (which Landlock's restricted-exec axis can
    /// never report — see the module doc). Mutation: if this ever regressed to
    /// `AgentInfluenced`'s scalar floor, `exec()` here would equal `Kernel` and
    /// this assertion would fail.
    #[test]
    fn broker_mediated_mints_under_the_per_axis_confined_floor() {
        let caveats = workspace_confined_caveats(Path::new("/ws"));
        let agent_cx = mint_context(ExecOrigin::AgentInfluenced, &caveats).unwrap();
        let broker_cx = mint_context(ExecOrigin::BrokerMediated, &caveats).unwrap();
        assert_eq!(
            broker_cx.strength_floor().fs_read(),
            agent_cx.strength_floor().fs_read()
        );
        assert_eq!(
            broker_cx.strength_floor().fs_write(),
            agent_cx.strength_floor().fs_write()
        );
        assert_eq!(
            broker_cx.strength_floor().net(),
            agent_cx.strength_floor().net()
        );
        assert_eq!(
            broker_cx.strength_floor().fs_read(),
            AxisEnforcement::Kernel
        );
        assert_eq!(broker_cx.strength_floor().net(), AxisEnforcement::Kernel);
        assert_eq!(
            broker_cx.strength_floor().exec(),
            AxisEnforcement::Interceptor
        );
        assert_ne!(
            broker_cx.strength_floor().exec(),
            agent_cx.strength_floor().exec()
        );
    }

    #[test]
    fn deny_all_net_is_a_pure_attenuation_of_the_net_axis_only() {
        // The macOS DenyAll floor rests on this narrowing: the net axis becomes
        // deny-all (→ Seatbelt `(deny network*)`), and NOTHING else moves — a
        // widened fs/exec axis here would be authority the caller never asked
        // for. Grounded by `macos_seatbelt_adversarial::
        // seatbelt_net_deny_all_runs_kernel_denied` (the real Seatbelt run).
        let base = workspace_confined_caveats(Path::new("/ws"));
        let narrowed = deny_all_net(&base);
        assert_eq!(narrowed.net, Scope::only([] as [String; 0]));
        assert_eq!(narrowed.fs_read, base.fs_read);
        assert_eq!(narrowed.fs_write, base.fs_write);
        assert_eq!(narrowed.exec, base.exec);
        // Idempotent, and already-deny-all stays deny-all.
        assert_eq!(deny_all_net(&narrowed), narrowed);
    }

    #[test]
    fn request_env_is_exactly_the_grants_nothing_inherited() {
        // #8: the child's environment is the explicit grants only — there is no
        // path by which an ambient credential/switch reaches it.
        let req = ExecRequest::new(
            ExecOrigin::AgentInfluenced,
            "sh",
            ["-c", "true"],
            "/ws",
            workspace_confined_caveats(Path::new("/ws")),
        )
        .env("HOME", "/ws")
        .envs([("LANG".into(), "C".into())]);
        assert_eq!(
            req.env_grants(),
            &[
                ("HOME".to_string(), "/ws".to_string()),
                ("LANG".to_string(), "C".to_string())
            ]
        );
    }

    #[test]
    fn timeout_builder_sets_the_bound_default_is_unbounded() {
        // #1598: the bound is opt-in (unbounded by default so long legitimate
        // builds are not killed), and `.timeout()` records it — the field the
        // real-resource `confined_exec_lifetime` tests exercise for real.
        let base = ExecRequest::new(
            ExecOrigin::AgentInfluenced,
            "sh",
            ["-c", "true"],
            "/ws",
            workspace_confined_caveats(Path::new("/ws")),
        );
        assert_eq!(base.timeout, None);
        let bounded = base.timeout(Duration::from_secs(5));
        assert_eq!(bounded.timeout, Some(Duration::from_secs(5)));
    }

    #[test]
    fn build_tool_caveats_calibrated_reads_fenced_writes_no_net() {
        // A build/test tool reads the workspace + toolchain caches, but NOT
        // arbitrary secrets; it must not write outside the workspace fence, and
        // must not reach the network.
        use crate::caveats::ScopeExt;
        let cav = build_tool_caveats(Path::new("/ws"));
        // Reads: the workspace is granted; an arbitrary credential path is not.
        assert!(cav.fs_read.permits(&"/ws".to_string()));
        assert!(
            !cav.fs_read
                .permits(&"/home/someone-else/.ssh/id_rsa".to_string()),
            "a build tool must not be able to READ arbitrary secrets (disclosure via output)"
        );
        assert!(
            matches!(cav.fs_read, Scope::Only(_)),
            "reads are a calibrated set, never open"
        );
        // Writes: workspace only.
        assert!(cav.fs_write.permits(&"/ws".to_string()));
        assert!(
            !cav.fs_write.permits(&"/home/user/.cargo".to_string()),
            "no write to the shared package cache (poisoning) outside the fence"
        );
        assert!(!cav.fs_write.permits(&"/etc".to_string()));
        assert!(
            !cav.fs_write.permits(&"/tmp".to_string()),
            "no write to shared /tmp — only the private workspace scratch partition"
        );
        assert!(
            !cav.net.permits(&"evil.example".to_string()),
            "no network — the exfil channel is closed"
        );
    }

    /// Grounds `build_scratch_dir` against a real build-lane child: its
    /// `TMPDIR` is writable under the fence and lies outside the workspace.
    #[cfg(target_os = "macos")]
    #[test]
    fn a_build_lane_child_gets_a_writable_scratch_dir_outside_the_workspace() {
        let ws = tempfile::tempdir().unwrap();
        let ws = ws.path().canonicalize().unwrap();
        let script = "import os, tempfile\n\
            d = tempfile.mkdtemp(); open(os.path.join(d, 'x'), 'w').write('ok'); print(d)\n";
        // Exercise scratch filesystem confinement; macOS cannot enforce restricted net.
        let req = build_tool_request(&ws, &ws, "python3", ["-c", script], &Scope::All);
        let out = ConstrainedExecutor::run(&req).expect("the build lane spawns");
        let stdout = String::from_utf8_lossy(&out.stdout);
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(out.success, "stdout: {stdout}\nstderr: {stderr}");
        assert!(
            !std::path::Path::new(stdout.trim()).starts_with(&ws),
            "{stdout}"
        );
    }

    /// #2604 escape hatch: an operator build scratch base moves the run out of
    /// the repo, to `<base>/<workspace id>/<run>`, and the fence grants exactly
    /// that per-workspace root. With no base, nothing is added.
    #[test]
    fn an_operator_build_scratch_base_moves_the_run_and_is_granted() {
        let ws = Path::new("/ws");
        let base = std::env::temp_dir().join("operator-build-scratch");
        let root = operator_build_scratch_root(ws, Some(base.clone())).unwrap();
        assert_eq!(root.parent(), Some(base.as_path()));
        assert_eq!(
            Some(root.clone()),
            operator_build_scratch_root(ws, Some(base.clone()))
        );
        assert_ne!(
            Some(root.clone()),
            operator_build_scratch_root(Path::new("/other"), Some(base.clone()))
        );

        let run = scratch_dir_under(ws, Some(base.clone()));
        assert_eq!(run.parent(), Some(root.as_path()));
        assert!(
            !run.starts_with(ws),
            "an operator base leaves the workspace"
        );

        let root = root.to_string_lossy().into_owned();
        let cav = build_caveats_with_scratch(ws, &[], Some(base));
        assert!(crate::caveats::permits_path(
            &cav.fs_write,
            &run.to_string_lossy()
        ));
        assert!(crate::caveats::permits_path(&cav.fs_read, &root));

        let default = build_caveats_with_scratch(ws, &[], None);
        assert_eq!(default.fs_write, Scope::only(["/ws".to_owned()]));
        assert!(scratch_dir_under(ws, None).starts_with("/ws/target/tmp"));
    }

    #[test]
    fn build_tool_caveats_with_writes_grants_only_the_named_extra_root() {
        use crate::caveats::ScopeExt;
        let cav = build_tool_caveats_with_writes(Path::new("/ws"), &["/crew/target".to_string()]);
        assert!(cav.fs_write.permits(&"/ws".to_string()));
        assert!(
            cav.fs_write.permits(&"/crew/target".to_string()),
            "the explicitly-granted extra write root is permitted"
        );
        assert!(!cav.fs_write.permits(&"/crew/other".to_string()));
    }

    #[test]
    fn workspace_caveats_fence_reads_writes_to_workspace_and_denies_net() {
        // #9: net is an empty allow-list (deny-all). fs_read/fs_write name only
        // the workspace root; exec stays open (interpreter identity, not behavior).
        use crate::caveats::ScopeExt;
        let cav = workspace_confined_caveats(Path::new("/ws"));
        assert!(cav.fs_write.permits(&"/ws".to_string()));
        assert!(!cav.fs_write.permits(&"/etc".to_string()));
        assert!(cav.fs_read.permits(&"/ws".to_string()));
        assert!(!cav.fs_read.permits(&"/etc/passwd".to_string()));
        // Empty net allow-list permits nothing.
        assert!(!cav.net.permits(&"example.com".to_string()));
        assert!(matches!(cav.net, Scope::Only(ref s) if s.is_empty()));
    }

    #[test]
    fn exec_spawn_tool_declares_no_special_ceiling() {
        // The throwaway tool must not narrow authority: it declares `top()` so
        // the effective caveats are exactly the request's fence.
        let tool = ExecSpawnTool;
        assert_eq!(tool.name(), "confined_exec");
        assert_eq!(tool.required(), Caveats::top());
    }

    #[test]
    fn refusal_displays_are_honest_about_fail_closed() {
        let r = ExecRefused::ConfinementUnenforceable("no Landlock".into());
        assert!(r.to_string().contains("fail-closed"));
    }
}

#[cfg(all(test, target_os = "linux"))]
#[path = "confined_exec_git_tests.rs"]
mod git_read_race_tests;