harn-vm 0.10.131

Async bytecode virtual machine for the Harn programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
//! Process sandbox dispatch and per-platform OS confinement.
//!
//! The runtime exposes one stable surface — [`command_output`],
//! [`std_command_for`], [`tokio_command_for`], plus the
//! `enforce_*` helpers — and dispatches into a per-OS
//! [`SandboxBackend`] selected at compile time. The backend chooses
//! how to attach the active capability ceiling to the spawn:
//!
//! * **Linux** ([`linux::Backend`]): Landlock LSM filesystem scoping
//!   plus a default-deny seccomp-bpf syscall allowlist installed via
//!   `pre_exec`, gated behind `PR_SET_NO_NEW_PRIVS`.
//! * **macOS** ([`macos::Backend`]): a `sandbox-exec` profile rendered
//!   from the active capability set wraps the spawn.
//! * **Windows** ([`windows::Backend`]): an AppContainer plus a Job
//!   Object, launched directly through `CreateProcessW` with a
//!   `SECURITY_CAPABILITIES` attribute. There is no restricted token
//!   and no explicit integrity label: the AppContainer's own access
//!   check is what confines the child. A read or a write succeeds only
//!   where the object's DACL grants it to the container's package SID,
//!   one of its capability SIDs, or `ALL APPLICATION PACKAGES` — a user
//!   or group SID in the token never helps. That makes this the one
//!   backend that is read-*closed* by construction, so the read roots
//!   the other backends get for free have to be granted here with an
//!   explicit `icacls` ACE. Writes are confined by the same implicit
//!   deny rather than by a token restriction: every root this backend
//!   grants outside the workspace is granted read and execute only.
//! * **OpenBSD** ([`openbsd::Backend`]): pledge/unveil applied via
//!   `pre_exec` on top of the standard `Command` plumbing.
//!
//! The [`SandboxProfile`] selected by the active [`CapabilityPolicy`]
//! controls how strictly the backend is required:
//!
//! * `Unrestricted` — bypass everything (path enforcement and OS
//!   confinement).
//! * `Worktree` — workspace path enforcement; OS confinement is
//!   best-effort (warn-and-skip when unavailable). Honors
//!   `HARN_HANDLER_SANDBOX={off,warn,enforce}`.
//! * `OsHardened` — workspace path enforcement; OS confinement is
//!   required. Spawns fail with `tool_rejected` if the platform
//!   mechanism is unavailable, regardless of `HARN_HANDLER_SANDBOX`.
//! * `Wasi` — testbench mode; subprocesses are intercepted by the
//!   process tape and resolved against recorded WASI modules.
//!
//! Per-platform capability → kernel-knob mappings are documented in
//! `docs/src/sandboxing.md`.

use std::cell::RefCell;
use std::collections::BTreeSet;
use std::io;
use std::io::Write as _;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Output};

#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
use crate::orchestration::ProcessSandboxPreset;
use crate::orchestration::{CapabilityPolicy, SandboxProfile};
use crate::value::{environment_io_error_thrown, ErrorCategory, VmError, VmValue};
use crate::vm::Vm;

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) use read_roots::developer_toolchain_cache_write_roots_for_home;
pub(crate) use read_roots::{
    developer_toolchain_read_roots_for_home, package_manager_config_read_roots_for_home,
    sandbox_user_home_dir,
};

use paths::{
    access_is_exempt_from_scope, is_standard_io_device_for_access, normalize_for_policy,
    normalize_io_device_path, path_is_within, relocated_runtime_roots,
};

mod backend;
#[cfg(all(test, target_os = "linux"))]
mod enforcement_report;
mod handler_env;
#[cfg(target_os = "linux")]
mod linux;
mod locked_append;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "openbsd")]
mod openbsd;
mod paths;
mod process_config;
mod process_output;
mod read_roots;
mod refusal;
use backend::ActiveBackend;
pub use backend::{
    active_backend_available, active_backend_filesystem_available,
    active_backend_filesystem_mechanism, active_backend_name,
};
pub(crate) use backend::{PrepareOutcome, SandboxBackend};
pub use process_config::apply_active_rustc_wrapper_policy;
use process_config::neutralize_rustc_wrapper;
pub use process_config::{ProcessCommandConfig, ProcessStdin};
use process_output::apply_process_config;
#[cfg(target_os = "windows")]
pub(crate) use process_output::windows_command_output;
pub use process_output::{deterministic_message_locale_env, MESSAGE_LOCALE_OVERRIDE_ENV};
pub(crate) mod process_cwd;
use process_cwd::enforce_process_cwd_for_policy;
pub(crate) use process_cwd::policy_process_cwd;
mod policy;
mod replace;

// Each backend uses exactly one of these: the platform helpers call
// `unavailable`, Linux installs confinement in `pre_exec` and warns directly.
#[cfg(target_os = "linux")]
pub(crate) use refusal::mechanism_skipped_warning;
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(crate) use refusal::unavailable;
pub(crate) use refusal::{path_is_denied, process_sandbox_read_deny_roots};
pub use refusal::{
    process_violation_error, SandboxMechanism, SandboxMechanismAvailability,
    SandboxMechanismUnavailable, SandboxRequirement,
};
#[cfg(any(target_os = "linux", target_os = "macos"))]
mod toolchain_cache;
#[cfg(target_os = "windows")]
mod windows;
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) use toolchain_cache::process_roots as process_sandbox_developer_toolchain_cache_roots;
pub(crate) mod workspace_env;
#[cfg(all(test, unix))]
mod workspace_env_integration;

pub(crate) use handler_env::effective_fallback;
#[cfg(test)]
pub(crate) use handler_env::handler_sandbox_test_guard;
pub(crate) use locked_append::AppendLockOptions;
pub(crate) use policy::allows_network as policy_allows_network;
pub(crate) use replace::{
    atomic_replace_scoped_at_open_unlocked, atomic_write_scoped_at_open,
    read_for_replace_scoped_at_open,
};
pub use workspace_env::active_workspace_process_env;
pub(crate) use workspace_env::{
    inject_workspace_process_env, workspace_local_tmpdir, WORKSPACE_TMPDIR_NAME,
};
#[cfg(test)]
pub(crate) use workspace_env::{inject_workspace_tmpdir, TMPDIR_ENV_KEYS};

const HANDLER_SANDBOX_ENV: &str = "HARN_HANDLER_SANDBOX";
#[cfg(any(unix, windows))]
const MAX_SCOPED_PATH_COMPONENTS: usize = 256;

thread_local! {
    static WARNED_KEYS: RefCell<BTreeSet<String>> = const { RefCell::new(BTreeSet::new()) };
}

/// The kind of filesystem access a path-scope check is guarding. This drives
/// the verb rendered in rejection messages and the narrow standard-device
/// exception; ordinary files are otherwise scoped by the same workspace roots.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FsAccess {
    Read,
    Write,
    Delete,
}

#[derive(Clone, Debug, Default)]
pub struct ProcessSandboxScope {
    pub workspace_roots: Vec<String>,
}

#[must_use]
pub struct ProcessSandboxScopeGuard {
    pushed: bool,
}

impl Drop for ProcessSandboxScopeGuard {
    fn drop(&mut self) {
        if self.pushed {
            crate::orchestration::pop_execution_policy();
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SandboxFallback {
    Off,
    Warn,
    Enforce,
}

pub(crate) fn reset_sandbox_state() {
    WARNED_KEYS.with(|keys| keys.borrow_mut().clear());
}

/// Register Harn-callable introspection builtins for the sandbox.
/// Intended for diagnostics, `harn doctor`, and conformance fixtures —
/// not as a way to mutate runtime sandbox behavior from a script.
pub fn register_sandbox_builtins(vm: &mut Vm) {
    for def in MODULE_BUILTINS {
        vm.register_builtin_def(def);
    }
    use harn_builtin_meta::CapabilityId;
    vm.register_capability_method(
        CapabilityId::System,
        "sandbox_active_backend",
        sandbox_active_backend_impl,
    );
    vm.register_capability_method(
        CapabilityId::System,
        "sandbox_backend_available",
        sandbox_backend_available_impl,
    );
    vm.register_capability_method(
        CapabilityId::System,
        "sandbox_active_profile",
        sandbox_active_profile_impl,
    );
}

pub(crate) const MODULE_BUILTINS: &[&crate::stdlib::macros::VmBuiltinDef] = &[
    &SANDBOX_ACTIVE_BACKEND_IMPL_DEF,
    &SANDBOX_BACKEND_AVAILABLE_IMPL_DEF,
    &SANDBOX_ACTIVE_PROFILE_IMPL_DEF,
];

#[crate::stdlib::macros::harn_builtin(
    exposure = "runtime_internal",
    effects = [],
    sig = "sandbox_active_backend() -> string",
    category = "sandbox"
)]
fn sandbox_active_backend_impl(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    Ok(VmValue::String(arcstr::ArcStr::from(active_backend_name())))
}

#[crate::stdlib::macros::harn_builtin(
    exposure = "runtime_internal",
    effects = [],
    sig = "sandbox_backend_available() -> bool",
    category = "sandbox"
)]
fn sandbox_backend_available_impl(
    _args: &[VmValue],
    _out: &mut String,
) -> Result<VmValue, VmError> {
    Ok(VmValue::Bool(active_backend_available()))
}

#[crate::stdlib::macros::harn_builtin(
    exposure = "runtime_internal",
    effects = [],
    sig = "sandbox_active_profile() -> string",
    category = "sandbox"
)]
fn sandbox_active_profile_impl(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let profile = crate::orchestration::current_execution_policy()
        .map(|policy| policy.sandbox_profile)
        .unwrap_or(SandboxProfile::Unrestricted);
    Ok(VmValue::String(arcstr::ArcStr::from(profile.as_str())))
}

/// A workspace-root scope violation: a path that resolved outside every
/// configured workspace root under a restricted [`SandboxProfile`].
///
/// This is the `VmError`-free shape returned by [`check_fs_path_scope`] so
/// that crates outside `harn-vm` (today: `harn-hostlib`) can enforce the
/// same scope policy and render the violation onto their own error type.
#[derive(Clone, Debug)]
pub struct SandboxViolation {
    /// The path the call attempted to touch, normalized against the
    /// active policy (CWD-relative paths resolved to absolute, `..`
    /// collapsed, symlinks canonicalized where the path exists).
    pub attempted: PathBuf,
    /// The writable workspace roots the path was checked against,
    /// normalized the same way as `attempted`.
    pub roots: Vec<PathBuf>,
    /// Whether the rejected access was a read, write, or delete.
    pub access: FsAccess,
    /// True when the path resolved *inside* a read-only root: it is in
    /// scope for reads, and only the attempted mutation is denied. False
    /// when the path fell outside every configured root entirely.
    pub read_only: bool,
}

impl SandboxViolation {
    /// Render the canonical rejection message. Matches the text produced
    /// by [`enforce_fs_path`] so the `harness.fs.*` and hostlib surfaces
    /// reject an out-of-root path identically.
    pub fn message(&self, builtin: &str) -> String {
        if self.read_only {
            return format!(
                "sandbox violation: builtin '{builtin}' attempted to {} '{}' under a read-only workspace root",
                self.access.verb(),
                self.attempted.display(),
            );
        }
        format!(
            "sandbox violation: builtin '{builtin}' attempted to {} '{}' outside workspace_roots [{}]",
            self.access.verb(),
            self.attempted.display(),
            self.roots
                .iter()
                .map(|root| root.display().to_string())
                .collect::<Vec<_>>()
                .join(", ")
        )
    }
}

/// Check whether `path` is inside the active policy's workspace roots.
///
/// Returns `Ok(())` when no execution policy is active, when the active
/// profile does not enforce path scope, when the normalized path
/// falls within a writable workspace root, or — for [`FsAccess::Read`]
/// only — when it falls within a read-only root. A write/delete that
/// resolves under a read-only root is rejected with `read_only` set, as
/// is any access that falls outside every configured root.
///
/// This is the public, `VmError`-free entry point embedders use to apply
/// workspace-root scoping to their own host calls. The in-crate
/// `harness.fs.*` builtins funnel through [`enforce_fs_path`], which wraps
/// this with a `VmError`; both share the same path normalization and
/// rejection text.
pub fn check_fs_path_scope(path: &Path, access: FsAccess) -> Result<(), SandboxViolation> {
    let Some(policy) = crate::orchestration::current_execution_policy() else {
        return Ok(());
    };
    if !policy.sandbox_profile.enforces_path_scope() {
        return Ok(());
    }
    // Standard process I/O device files are not workspace filesystem
    // mutations: writing to /dev/stdout, /dev/stderr, or /dev/null (and the
    // numeric /dev/fd/<N> descriptors they alias) targets the process's own
    // output streams, not the sandboxed tree. A pipeline that falls back to
    // /dev/stdout for debug output must not read as a sandbox violation, so
    // allow these regardless of the configured roots. Matched on the
    // lexically-normalized path (not the canonicalized form): canonicalize()
    // rewrites /dev/stdout to a per-process /dev/fd/<…>.output alias that no
    // longer looks like a standard device. Kept deliberately narrow — only
    // the well-known device files, no broader /dev access.
    if access_is_exempt_from_scope(path, access) {
        return Ok(());
    }
    let candidate = normalize_for_policy(path);
    let roots = normalized_workspace_roots(&policy);
    // The denylist is checked BEFORE any grant, because it must beat all of
    // them. A workspace root, a read-only root, and a preset are each a reason
    // to allow; this is the one reason to refuse, and a subtraction that ran
    // after the grants would never fire on the paths that matter (a credential
    // under a preset-granted `~/.config` is exactly that case).
    if access == FsAccess::Read
        && path_is_denied(&candidate, &process_sandbox_read_deny_roots(&policy))
    {
        return Err(SandboxViolation {
            attempted: candidate,
            roots,
            access,
            read_only: false,
        });
    }
    if roots.iter().any(|root| path_is_within(&candidate, root)) {
        return Ok(());
    }
    let read_only_roots = normalized_read_only_roots(&policy);
    let within_read_only = read_only_roots
        .iter()
        .any(|root| path_is_within(&candidate, root));
    if within_read_only && access == FsAccess::Read {
        return Ok(());
    }
    Err(SandboxViolation {
        attempted: candidate,
        roots,
        access,
        read_only: within_read_only,
    })
}

pub(crate) fn enforce_fs_path(builtin: &str, path: &Path, access: FsAccess) -> Result<(), VmError> {
    check_fs_path_scope(path, access)
        .map_err(|violation| sandbox_rejection(violation.message(builtin)))
}

pub(crate) fn append_scoped_at_open(builtin: &str, path: &Path, contents: &[u8]) -> io::Result<()> {
    let Some(target) = scoped_mutation_target(builtin, path, FsAccess::Write)? else {
        return append_unscoped(path, contents);
    };
    append_scoped_target(&target, contents)
}

pub(crate) fn append_locked_scoped_at_open(
    builtin: &str,
    path: &Path,
    contents: &[u8],
    options: AppendLockOptions,
) -> io::Result<()> {
    let Some(target) = scoped_mutation_target(builtin, path, FsAccess::Write)? else {
        return locked_append::append_locked_unscoped(path, contents, options);
    };
    locked_append::append_locked_scoped_target(&target, contents, options)
}

pub(crate) fn copy_scoped_at_open(builtin: &str, src: &Path, dst: &Path) -> io::Result<u64> {
    let Some(target) = scoped_mutation_target(builtin, dst, FsAccess::Write)? else {
        return std::fs::copy(src, dst);
    };
    copy_scoped_target(src, &target)
}

pub(crate) fn rename_scoped_at_open(builtin: &str, src: &Path, dst: &Path) -> io::Result<()> {
    let Some(src_target) = scoped_mutation_target(builtin, src, FsAccess::Delete)? else {
        return std::fs::rename(src, dst);
    };
    let dst_target = scoped_mutation_target(builtin, dst, FsAccess::Write)?.ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "sandbox violation: builtin '{builtin}' attempted to rename '{}' without an active destination sandbox scope",
                dst.display()
            ),
        )
    })?;
    rename_scoped_targets(&src_target, &dst_target)
}

pub(crate) fn create_dir_scoped_at_open(
    builtin: &str,
    path: &Path,
    recursive: bool,
) -> io::Result<()> {
    let Some(target) = scoped_mutation_target(builtin, path, FsAccess::Write)? else {
        return if recursive {
            std::fs::create_dir_all(path)
        } else {
            std::fs::create_dir(path)
        };
    };
    if recursive {
        create_dir_all_scoped_target(&target)
    } else {
        create_dir_scoped_target(&target)
    }
}

#[derive(Clone, Debug)]
struct ScopedMutationTarget {
    root: PathBuf,
    relative: PathBuf,
}

fn scoped_mutation_target(
    builtin: &str,
    path: &Path,
    access: FsAccess,
) -> io::Result<Option<ScopedMutationTarget>> {
    let Some(policy) = crate::orchestration::current_execution_policy() else {
        return Ok(None);
    };
    if !policy.sandbox_profile.enforces_path_scope() {
        return Ok(None);
    }
    if is_standard_io_device_for_access(&normalize_io_device_path(path), access) {
        return Ok(None);
    }
    check_fs_path_scope(path, access).map_err(|violation| {
        io::Error::new(io::ErrorKind::PermissionDenied, violation.message(builtin))
    })?;
    let candidate = normalize_for_policy(path);
    let roots = normalized_workspace_roots(&policy);
    let Some(root) = roots
        .into_iter()
        .find(|root| path_is_within(&candidate, root))
    else {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "sandbox violation: builtin '{builtin}' attempted to {} '{}' outside writable workspace_roots",
                access.verb(),
                candidate.display()
            ),
        ));
    };
    let relative = candidate.strip_prefix(&root).map_err(|_| {
        io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "sandbox violation: builtin '{builtin}' attempted to {} '{}' outside workspace root '{}'",
                access.verb(),
                candidate.display(),
                root.display()
            ),
        )
    })?;
    if relative.as_os_str().is_empty() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "sandbox violation: builtin '{builtin}' attempted to {} workspace root '{}'",
                access.verb(),
                root.display()
            ),
        ));
    }
    Ok(Some(ScopedMutationTarget {
        root,
        relative: relative.to_path_buf(),
    }))
}

fn append_unscoped(path: &Path, contents: &[u8]) -> io::Result<()> {
    // Match the `append_file` contract: appending to a new log in a
    // not-yet-created directory recreates the parent chain.
    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .and_then(|mut file| file.write_all(contents))
}

#[cfg(test)]
fn shared_atomic_write_unscoped(path: &Path, contents: &[u8]) -> io::Result<()> {
    crate::atomic_io::atomic_write(path, contents)
}

#[cfg(unix)]
fn append_scoped_target(target: &ScopedMutationTarget, contents: &[u8]) -> io::Result<()> {
    use std::os::fd::AsRawFd;

    // Append creates the file (and its parent chain) when absent, matching the
    // pre-hardening `append_file` contract (append-to-a-new-log-in-a-new-dir).
    let (parent, file_name) = ensure_parent_dirs_scoped(target)?;
    let mut file = openat_file(
        parent.as_raw_fd(),
        &file_name,
        libc::O_WRONLY | libc::O_CREAT | libc::O_APPEND | libc::O_CLOEXEC | libc::O_NOFOLLOW,
        0o666,
    )?;
    file.write_all(contents)
}

#[cfg(windows)]
fn append_scoped_target(target: &ScopedMutationTarget, contents: &[u8]) -> io::Result<()> {
    let (parent, file_name) = win_scoped_parent(target, true)?;
    let full = parent.join(&file_name);
    win_reject_reparse_leaf(&full)?;
    append_unscoped(&full, contents)
}

#[cfg(all(not(unix), not(windows)))]
fn append_scoped_target(target: &ScopedMutationTarget, contents: &[u8]) -> io::Result<()> {
    let full = target.root.join(&target.relative);
    if let Some(parent) = full.parent().filter(|p| !p.as_os_str().is_empty()) {
        std::fs::create_dir_all(parent)?;
    }
    append_unscoped(&full, contents)
}

#[cfg(unix)]
fn copy_scoped_target(src: &Path, target: &ScopedMutationTarget) -> io::Result<u64> {
    use std::os::fd::AsRawFd;

    let mut source = std::fs::File::open(src)?;
    let source_metadata = source.metadata().ok();
    let (parent, file_name) = open_parent_dir_scoped(target)?;
    let mut destination = openat_file(
        parent.as_raw_fd(),
        &file_name,
        libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC | libc::O_CLOEXEC | libc::O_NOFOLLOW,
        0o666,
    )?;
    let copied = io::copy(&mut source, &mut destination)?;
    destination.sync_all()?;
    if let Some(metadata) = source_metadata {
        let _ = destination.set_permissions(metadata.permissions());
    }
    sync_dir_fd(parent.as_raw_fd());
    Ok(copied)
}

#[cfg(windows)]
fn copy_scoped_target(src: &Path, target: &ScopedMutationTarget) -> io::Result<u64> {
    // Copy destinations keep the "parent must already exist" contract, so the
    // walk does not auto-create (create_parents = false), matching the unix
    // `open_parent_dir_scoped` path.
    let (parent, file_name) = win_scoped_parent(target, false)?;
    let full = parent.join(&file_name);
    win_reject_reparse_leaf(&full)?;
    std::fs::copy(src, full)
}

#[cfg(all(not(unix), not(windows)))]
fn copy_scoped_target(src: &Path, target: &ScopedMutationTarget) -> io::Result<u64> {
    std::fs::copy(src, target.root.join(&target.relative))
}

#[cfg(unix)]
fn rename_scoped_targets(src: &ScopedMutationTarget, dst: &ScopedMutationTarget) -> io::Result<()> {
    use std::os::fd::AsRawFd;

    let (src_parent, src_name) = open_parent_dir_scoped(src)?;
    let (dst_parent, dst_name) = open_parent_dir_scoped(dst)?;
    renameat_name(
        src_parent.as_raw_fd(),
        &src_name,
        dst_parent.as_raw_fd(),
        &dst_name,
    )?;
    sync_dir_fd(dst_parent.as_raw_fd());
    Ok(())
}

#[cfg(windows)]
fn rename_scoped_targets(src: &ScopedMutationTarget, dst: &ScopedMutationTarget) -> io::Result<()> {
    // No `win_reject_reparse_leaf` on the leaves here: rename operates on the
    // directory entry (the name), not by traversing through the target, and may
    // legitimately move/replace a reparse point. The junction-traversal defense
    // is the ancestor-chain validation in `win_scoped_parent`.
    let (src_parent, src_name) = win_scoped_parent(src, false)?;
    let (dst_parent, dst_name) = win_scoped_parent(dst, false)?;
    std::fs::rename(src_parent.join(&src_name), dst_parent.join(&dst_name))
}

#[cfg(all(not(unix), not(windows)))]
fn rename_scoped_targets(src: &ScopedMutationTarget, dst: &ScopedMutationTarget) -> io::Result<()> {
    std::fs::rename(src.root.join(&src.relative), dst.root.join(&dst.relative))
}

#[cfg(unix)]
fn create_dir_scoped_target(target: &ScopedMutationTarget) -> io::Result<()> {
    use std::os::fd::AsRawFd;

    let (parent, file_name) = open_parent_dir_scoped(target)?;
    mkdirat_name(parent.as_raw_fd(), &file_name)?;
    sync_dir_fd(parent.as_raw_fd());
    Ok(())
}

#[cfg(windows)]
fn create_dir_scoped_target(target: &ScopedMutationTarget) -> io::Result<()> {
    // Single `mkdir` keeps the "parent must already exist" contract; only the
    // leaf is created, after verifying no ancestor is a junction/symlink. No
    // `win_reject_reparse_leaf` on the leaf: `CreateDirectoryW` creates a NEW
    // name and fails `AlreadyExists` if anything (reparse point or not) already
    // occupies it — it never writes *through* an existing leaf — so the
    // ancestor-chain validation is the whole defense.
    let (parent, file_name) = win_scoped_parent(target, false)?;
    win_create_dir_raw(&parent.join(&file_name))
}

#[cfg(all(not(unix), not(windows)))]
fn create_dir_scoped_target(target: &ScopedMutationTarget) -> io::Result<()> {
    std::fs::create_dir(target.root.join(&target.relative))
}

#[cfg(unix)]
fn create_dir_all_scoped_target(target: &ScopedMutationTarget) -> io::Result<()> {
    use std::os::fd::AsRawFd;

    let root = open_dir_absolute(&target.root)?;
    let mut current = root;
    for component in clean_relative_components(&target.relative)? {
        match open_dir_at(current.as_raw_fd(), &component) {
            Ok(next) => current = next,
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                mkdirat_name(current.as_raw_fd(), &component)?;
                let next = open_dir_at(current.as_raw_fd(), &component)?;
                current = next;
            }
            Err(error) => return Err(error),
        }
    }
    Ok(())
}

#[cfg(windows)]
fn create_dir_all_scoped_target(target: &ScopedMutationTarget) -> io::Result<()> {
    // `mkdir -p`: every component (including the leaf) is created, and each is
    // verified not to be a reparse point (junction/symlink) as the walk descends.
    let components = win_clean_relative_components(&target.relative)?;
    win_walk_components(&target.root, &components, true)?;
    Ok(())
}

#[cfg(all(not(unix), not(windows)))]
fn create_dir_all_scoped_target(target: &ScopedMutationTarget) -> io::Result<()> {
    std::fs::create_dir_all(target.root.join(&target.relative))
}

#[cfg(unix)]
/// Create the ancestor directory chain of a scoped write/append target,
/// mirroring the pre-hardening `mkdir -p` behavior of the content-producing
/// filesystem builtins (`write_file`, `write_file_bytes`, `append_file`,
/// `append_file_locked`) and `http_download`. Only the ancestors are created —
/// the final path component
/// is the file the caller writes. Traversal stays scoped to `target.root` and
/// symlink-safe (each level is opened with `O_NOFOLLOW` via `open_dir_at`), so
/// this preserves the security properties #4147 added while restoring the
/// directory-autovivification contract downstream code depends on. Concurrent
/// creators are tolerated (a losing `mkdirat` that sees `EEXIST` is ignored).
///
/// The returned parent fd is the one content-producing callers must use for
/// their final `openat`/`renameat`, so the path is not resolved again between
/// mkdir-p and the write.
///
/// Structural operations (copy destination, rename, remove, single `mkdir`)
/// intentionally do NOT call this — they keep `open_parent_dir_scoped`'s
/// "parent must already exist" semantics.
#[cfg(unix)]
fn ensure_parent_dirs_scoped(
    target: &ScopedMutationTarget,
) -> io::Result<(std::os::fd::OwnedFd, String)> {
    use std::os::fd::AsRawFd;

    let mut components = clean_relative_components(&target.relative)?;
    let file_name = components.pop().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "sandbox scoped open requires a file name: {}",
                target.relative.display()
            ),
        )
    })?;
    let root = open_dir_absolute(&target.root)?;
    let mut current = root;
    for component in components {
        match open_dir_at(current.as_raw_fd(), &component) {
            Ok(next) => current = next,
            Err(error) if error.kind() == io::ErrorKind::NotFound => {
                if let Err(mkerr) = mkdirat_name(current.as_raw_fd(), &component) {
                    if mkerr.kind() != io::ErrorKind::AlreadyExists {
                        return Err(mkerr);
                    }
                }
                current = open_dir_at(current.as_raw_fd(), &component)?;
            }
            Err(error) => return Err(error),
        }
    }
    Ok((current, file_name))
}

#[cfg(unix)]
fn open_parent_dir_scoped(
    target: &ScopedMutationTarget,
) -> io::Result<(std::os::fd::OwnedFd, String)> {
    use std::os::fd::AsRawFd;

    let mut components = clean_relative_components(&target.relative)?;
    let file_name = components.pop().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "sandbox scoped open requires a file name: {}",
                target.relative.display()
            ),
        )
    })?;
    let root = open_dir_absolute(&target.root)?;
    let mut current = root;
    for component in components {
        current = open_dir_at(current.as_raw_fd(), &component)?;
    }
    Ok((current, file_name))
}

#[cfg(unix)]
fn clean_relative_components(path: &Path) -> io::Result<Vec<String>> {
    use std::os::unix::ffi::OsStrExt;

    let mut out = Vec::new();
    for component in path.components() {
        match component {
            Component::Normal(value) => {
                let bytes = value.as_bytes();
                if bytes.contains(&0) {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!("path component contains NUL: {}", path.display()),
                    ));
                }
                out.push(value.to_string_lossy().into_owned());
                if out.len() > MAX_SCOPED_PATH_COMPONENTS {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!(
                            "sandbox scoped path exceeds {MAX_SCOPED_PATH_COMPONENTS} components: {}",
                            path.display()
                        ),
                    ));
                }
            }
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("sandbox scoped path must stay relative: {}", path.display()),
                ));
            }
        }
    }
    Ok(out)
}

#[cfg(unix)]
fn open_dir_absolute(path: &Path) -> io::Result<std::os::fd::OwnedFd> {
    use std::os::fd::{FromRawFd, OwnedFd};
    use std::os::unix::ffi::OsStrExt;

    let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(|_| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("path contains NUL: {}", path.display()),
        )
    })?;
    let fd = unsafe {
        libc::open(
            c_path.as_ptr(),
            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
        )
    };
    if fd < 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}

#[cfg(unix)]
fn open_dir_at(parent_fd: libc::c_int, name: &str) -> io::Result<std::os::fd::OwnedFd> {
    use std::os::fd::{FromRawFd, OwnedFd};

    let c_name = c_name(name)?;
    let fd = unsafe {
        libc::openat(
            parent_fd,
            c_name.as_ptr(),
            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
        )
    };
    if fd < 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}

#[cfg(unix)]
fn openat_file(
    parent_fd: libc::c_int,
    name: &str,
    flags: libc::c_int,
    mode: libc::mode_t,
) -> io::Result<std::fs::File> {
    use std::os::fd::FromRawFd;

    let c_name = c_name(name)?;
    let fd = unsafe { libc::openat(parent_fd, c_name.as_ptr(), flags, mode as libc::c_uint) };
    if fd < 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}

#[cfg(unix)]
fn mkdirat_name(parent_fd: libc::c_int, name: &str) -> io::Result<()> {
    let c_name = c_name(name)?;
    let rc = unsafe { libc::mkdirat(parent_fd, c_name.as_ptr(), 0o777) };
    if rc != 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

#[cfg(unix)]
fn renameat_name(
    old_parent_fd: libc::c_int,
    old_name: &str,
    new_parent_fd: libc::c_int,
    new_name: &str,
) -> io::Result<()> {
    let old_name = c_name(old_name)?;
    let new_name = c_name(new_name)?;
    let rc = unsafe {
        libc::renameat(
            old_parent_fd,
            old_name.as_ptr(),
            new_parent_fd,
            new_name.as_ptr(),
        )
    };
    if rc != 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

#[cfg(unix)]
fn unlinkat_name(parent_fd: libc::c_int, name: &str, flags: libc::c_int) -> io::Result<()> {
    let c_name = c_name(name)?;
    let rc = unsafe { libc::unlinkat(parent_fd, c_name.as_ptr(), flags) };
    if rc != 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

#[cfg(unix)]
fn sync_dir_fd(fd: libc::c_int) -> bool {
    (unsafe { libc::fsync(fd) }) == 0
}

#[cfg(unix)]
fn c_name(name: &str) -> io::Result<std::ffi::CString> {
    std::ffi::CString::new(name).map_err(|_| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("path component contains NUL: {name:?}"),
        )
    })
}

// ---------------------------------------------------------------------------
// Windows scoped-walk primitives (junction/symlink-safe directory descent).
//
// Windows has no `openat`, and `O_NOFOLLOW` has no equivalent that a plain
// `std::fs` path open honors — worse, a *junction* (mount-point reparse point)
// IS a directory and is creatable by a non-admin user, so it slips past every
// "is this a symlink" check that only inspects the leaf. The unix path defends
// the whole chain by opening each component `O_NOFOLLOW`; the Windows path here
// mirrors that by opening each walked component with
// `FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS` (so the reparse
// point itself is opened, not its target) and refusing the walk the moment any
// component reports a mount-point or symlink reparse tag. See
// research/scoped-fs-mkdir-footguns (#12, RedirectionGuard) for the class.
//
// Residual, Windows-CI-only: because there is no handle-relative openat here,
// each component is re-resolved by string as the walk descends, so a
// concurrent attacker who swaps an *already-validated* ancestor for a junction
// between our check and the next open is not fully closed (the unix fd-walk is;
// the true fix is `NtCreateFile` with a `RootDirectory` handle). The
// intermediate-junction class the acceptance test covers IS closed.
// ---------------------------------------------------------------------------

/// Reparse tags Windows assigns to the two "traverses out of the tree"
/// reparse-point kinds the scoped walk must refuse. Defined locally so the
/// module does not need the `Win32_System_SystemServices` feature just for two
/// stable ABI constants.
#[cfg(windows)]
const IO_REPARSE_TAG_MOUNT_POINT: u32 = 0xA000_0003;
#[cfg(windows)]
const IO_REPARSE_TAG_SYMLINK: u32 = 0xA000_000C;

#[cfg(windows)]
fn win_wide(path: &Path) -> Vec<u16> {
    use std::os::windows::ffi::OsStrExt;
    path.as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect()
}

/// Refuse `path` if it is a mount-point or symlink reparse point. The handle is
/// opened with `FILE_FLAG_OPEN_REPARSE_POINT` so we inspect the reparse point
/// itself rather than following it, and `FILE_FLAG_BACKUP_SEMANTICS` so a
/// directory handle is permitted. A `NotFound` error is propagated unchanged so
/// callers can distinguish "does not exist yet" (create it) from "exists and is
/// hostile" (refuse).
#[cfg(windows)]
fn win_reject_reparse_point(path: &Path) -> io::Result<()> {
    use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
    use windows_sys::Win32::Storage::FileSystem::{
        CreateFileW, FileAttributeTagInfo, GetFileInformationByHandleEx,
        FILE_ATTRIBUTE_REPARSE_POINT, FILE_ATTRIBUTE_TAG_INFO, FILE_FLAG_BACKUP_SEMANTICS,
        FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
        OPEN_EXISTING,
    };

    // Query attributes only; no read/write access to the object is needed.
    const FILE_READ_ATTRIBUTES: u32 = 0x0080;

    let wide = win_wide(path);
    let handle = unsafe {
        CreateFileW(
            wide.as_ptr(),
            FILE_READ_ATTRIBUTES,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            std::ptr::null(),
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
            std::ptr::null_mut(),
        )
    };
    if handle == INVALID_HANDLE_VALUE {
        return Err(io::Error::last_os_error());
    }
    let mut info = FILE_ATTRIBUTE_TAG_INFO::default();
    let ok = unsafe {
        GetFileInformationByHandleEx(
            handle,
            FileAttributeTagInfo,
            std::ptr::from_mut(&mut info).cast(),
            std::mem::size_of::<FILE_ATTRIBUTE_TAG_INFO>() as u32,
        )
    };
    let result = if ok == 0 {
        Err(io::Error::last_os_error())
    } else if info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0
        && matches!(
            info.ReparseTag,
            IO_REPARSE_TAG_MOUNT_POINT | IO_REPARSE_TAG_SYMLINK
        )
    {
        Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "sandbox scoped walk refuses reparse-point (junction/symlink) component: {}",
                path.display()
            ),
        ))
    } else {
        Ok(())
    };
    unsafe {
        CloseHandle(handle);
    }
    result
}

/// A reparse point that squats on a *leaf* target name is refused; a leaf that
/// simply does not exist yet is fine (the caller is about to create it).
#[cfg(windows)]
fn win_reject_reparse_leaf(path: &Path) -> io::Result<()> {
    match win_reject_reparse_point(path) {
        Ok(()) => Ok(()),
        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(err) => Err(err),
    }
}

/// Low-level `CreateDirectoryW` used by the scoped walk. Kept raw (rather than
/// `std::fs::create_dir`) so the recurrence-guard lint can assert the scoped
/// Windows walk never reaches for a path-based `std::fs` mutation.
#[cfg(windows)]
fn win_create_dir_raw(path: &Path) -> io::Result<()> {
    use windows_sys::Win32::Storage::FileSystem::CreateDirectoryW;
    let wide = win_wide(path);
    let ok = unsafe { CreateDirectoryW(wide.as_ptr(), std::ptr::null()) };
    if ok == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

/// Windows analogue of [`clean_relative_components`]: reject `..`, absolute, and
/// drive-prefixed components, cap the depth, and refuse embedded NULs — keeping
/// the same invariants the unix walk enforces before descending.
#[cfg(windows)]
fn win_clean_relative_components(path: &Path) -> io::Result<Vec<std::ffi::OsString>> {
    use std::os::windows::ffi::OsStrExt;

    let mut out: Vec<std::ffi::OsString> = Vec::new();
    for component in path.components() {
        match component {
            Component::Normal(value) => {
                if value.encode_wide().any(|unit| unit == 0) {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!("path component contains NUL: {}", path.display()),
                    ));
                }
                out.push(value.to_os_string());
                if out.len() > MAX_SCOPED_PATH_COMPONENTS {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!(
                            "sandbox scoped path exceeds {MAX_SCOPED_PATH_COMPONENTS} components: {}",
                            path.display()
                        ),
                    ));
                }
            }
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("sandbox scoped path must stay relative: {}", path.display()),
                ));
            }
        }
    }
    Ok(out)
}

/// Descend `root` through `components`, refusing any component that is a
/// junction/symlink reparse point. When `create` is set, missing directories
/// are created (`mkdir -p`) and re-validated immediately, so a directory we
/// just made cannot be a reparse point. Returns the validated deepest path.
#[cfg(windows)]
fn win_walk_components(
    root: &Path,
    components: &[std::ffi::OsString],
    create: bool,
) -> io::Result<PathBuf> {
    // The configured workspace root is trusted, but verify it resolves to a real
    // directory and is not itself a reparse point, mirroring the unix
    // `open_dir_absolute` `O_NOFOLLOW` open of the root.
    win_reject_reparse_point(root)?;
    let mut current = root.to_path_buf();
    for component in components {
        current.push(component);
        match win_reject_reparse_point(&current) {
            Ok(()) => {}
            Err(err) if create && err.kind() == io::ErrorKind::NotFound => {
                match win_create_dir_raw(&current) {
                    Ok(()) => {}
                    // A concurrent creator won the race; tolerate and re-validate.
                    Err(mkerr) if mkerr.kind() == io::ErrorKind::AlreadyExists => {}
                    Err(mkerr) => return Err(mkerr),
                }
                win_reject_reparse_point(&current)?;
            }
            Err(err) => return Err(err),
        }
    }
    Ok(current)
}

/// Validate the ancestor chain of a scoped target on Windows and return the
/// verified `(parent_dir, leaf_name)`. With `create_parents`, missing ancestors
/// are created; without it, the parent must already exist (structural ops).
#[cfg(windows)]
fn win_scoped_parent(
    target: &ScopedMutationTarget,
    create_parents: bool,
) -> io::Result<(PathBuf, std::ffi::OsString)> {
    let mut components = win_clean_relative_components(&target.relative)?;
    let file_name = components.pop().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "sandbox scoped open requires a file name: {}",
                target.relative.display()
            ),
        )
    })?;
    let parent = win_walk_components(&target.root, &components, create_parents)?;
    Ok((parent, file_name))
}

pub fn enforce_process_cwd(path: &Path) -> Result<(), VmError> {
    let Some(policy) = crate::orchestration::current_execution_policy() else {
        return Ok(());
    };
    enforce_process_cwd_for_policy(path, &policy)
}

pub fn push_process_sandbox_scope(
    scope: ProcessSandboxScope,
) -> Result<ProcessSandboxScopeGuard, VmError> {
    let Some(mut policy) = crate::orchestration::current_execution_policy() else {
        return Ok(ProcessSandboxScopeGuard { pushed: false });
    };
    if !policy.sandbox_profile.enforces_path_scope() {
        return Ok(ProcessSandboxScopeGuard { pushed: false });
    }

    let requested_roots: Vec<PathBuf> = scope
        .workspace_roots
        .iter()
        .filter_map(|root| {
            let trimmed = root.trim();
            (!trimmed.is_empty()).then(|| normalize_for_policy(&resolve_policy_path(trimmed)))
        })
        .collect();
    if requested_roots.is_empty() {
        return Ok(ProcessSandboxScopeGuard { pushed: false });
    }

    if !policy.workspace_roots.is_empty() {
        let ceiling_roots = normalized_workspace_roots(&policy);
        if let Some(rejected) = requested_roots.iter().find(|root| {
            !ceiling_roots
                .iter()
                .any(|ceiling| path_is_within(root, ceiling))
        }) {
            return Err(sandbox_rejection(format!(
                "sandbox violation: process sandbox workspace root '{}' is outside workspace_roots [{}]",
                rejected.display(),
                ceiling_roots
                    .iter()
                    .map(|root| root.display().to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            )));
        }
    }

    let mut merged_roots = if policy.workspace_roots.is_empty() {
        Vec::new()
    } else {
        normalized_workspace_roots(&policy)
    };
    for requested in requested_roots {
        if !merged_roots
            .iter()
            .any(|existing| path_is_within(&requested, existing))
        {
            merged_roots.push(requested);
        }
    }
    policy.workspace_roots = merged_roots
        .into_iter()
        .map(|root| root.display().to_string())
        .collect();
    crate::orchestration::push_execution_policy(policy);
    Ok(ProcessSandboxScopeGuard { pushed: true })
}

/// Close a freshly built command's environment under an active session policy:
/// the choke point that makes the environment contract structural, since every
/// spawn seam in the VM and `harn-hostlib` reaches a child through the three
/// funnel fns below. Callers still layer `env`/`env_remove` on top afterward;
/// sandbox confinement sets no env vars, so clearing cannot weaken it.
macro_rules! close_env_for_session {
    ($command:expr, $program:expr) => {
        if let Some(env) =
            crate::stdlib::process::session_closed_env_for_command($program, std::iter::empty())?
        {
            $command.env_clear();
            for (key, value) in env {
                $command.env(key, value);
            }
        }
    };
}

pub fn std_command_for(program: &str, args: &[String]) -> Result<Command, VmError> {
    let resolved_program = crate::stdlib::process::resolve_program_path_for_spawn(program);
    let active = active_sandbox_policy();
    let mut command = match active.as_ref() {
        Some((policy, profile)) => {
            build_std_command::<ActiveBackend>(&resolved_program, args, policy, *profile)?
        }
        None => {
            let mut command = Command::new(&resolved_program);
            command.args(args);
            command
        }
    };
    close_env_for_session!(command, program);
    if let Some(proxy) = active.and_then(|(policy, _)| policy.process_network_proxy) {
        process_output::apply_managed_proxy_env(&mut command, proxy);
    }
    Ok(command)
}

pub fn tokio_command_for(
    program: &str,
    args: &[String],
) -> Result<tokio::process::Command, VmError> {
    let resolved_program = crate::stdlib::process::resolve_program_path_for_spawn(program);
    let active = active_sandbox_policy();
    let mut command = match active.as_ref() {
        Some((policy, profile)) => {
            build_tokio_command::<ActiveBackend>(&resolved_program, args, policy, *profile)?
        }
        None => {
            let mut command = tokio::process::Command::new(&resolved_program);
            command.args(args);
            command
        }
    };
    close_env_for_session!(command, program);
    if let Some(proxy) = active.and_then(|(policy, _)| policy.process_network_proxy) {
        process_output::apply_managed_proxy_env_tokio(&mut command, proxy);
    }
    Ok(command)
}

pub fn command_output(
    program: &str,
    args: &[String],
    config: &ProcessCommandConfig,
) -> Result<Output, VmError> {
    // Testbench replay mode short-circuits the spawn entirely.
    // Recording mode falls through; the duration is captured by the
    // recording handle below using the injected mock clock when one
    // is active.
    if let Some(intercepted) =
        crate::testbench::process_tape::intercept_spawn(program, args, config.cwd.as_deref())
    {
        return intercepted.map_err(|message| {
            VmError::Thrown(crate::value::VmValue::String(arcstr::ArcStr::from(message)))
        });
    }

    let recording =
        crate::testbench::process_tape::start_recording(program, args, config.cwd.as_deref());

    // Always rebuild through the command-aware resolver when a session env is
    // active so an earlier ambient `closed_env` cannot omit `for_command`
    // grants (harn#5549). `config.env` remains the overlay and still wins.
    let closed_config;
    let config = if let Some(env) =
        crate::stdlib::process::session_closed_env_for_command(program, config.env.iter().cloned())?
    {
        closed_config = ProcessCommandConfig {
            env,
            closed_env: true,
            ..config.clone()
        };
        &closed_config
    } else {
        config
    };

    let output = match active_sandbox_policy() {
        Some((policy, profile)) => {
            ensure_managed_process_egress_supported::<ActiveBackend>(&policy)?;
            let config = sandboxed_process_config(config, &policy)?;
            ActiveBackend::run_to_output(program, args, &config, &policy, profile)?
        }
        None => {
            let mut command = Command::new(program);
            command.args(args);
            apply_process_config(&mut command, config, None);
            // Interrupt-aware `Command::output()`: puts the child in its own
            // kill group and gracefully terminates the whole group when the
            // invoking scope is cancelled, a deadline fires, or the VM is
            // dropped. See `crate::op_interrupt`.
            crate::op_interrupt::capture_output_interruptible(&mut command).map_err(|error| {
                process_spawn_error(&error).unwrap_or_else(|| spawn_error(error))
            })?
        }
    };
    let refusal_command: Vec<String> = std::iter::once(program.to_string())
        .chain(args.iter().cloned())
        .collect();
    let refusal_cwd = config
        .cwd
        .as_deref()
        .map(|path| path.display().to_string())
        .unwrap_or_default();
    if let Some(error) = process_violation_error(&output, &refusal_command, &refusal_cwd) {
        return Err(error);
    }
    if let Some(span) = recording {
        span.finish(&output);
    }
    Ok(output)
}

fn sandboxed_process_config(
    config: &ProcessCommandConfig,
    policy: &CapabilityPolicy,
) -> Result<ProcessCommandConfig, VmError> {
    let mut resolved = config.clone();
    if let Some(cwd) = resolved.cwd.as_ref() {
        enforce_process_cwd_for_policy(cwd, policy)?;
    } else {
        resolved.cwd = Some(policy_process_cwd(policy, None)?);
    }
    neutralize_rustc_wrapper(&mut resolved.env, &mut resolved.env_remove);
    inject_workspace_process_env(&mut resolved.env, policy);
    resolved.env.retain(|(key, _)| {
        !resolved
            .env_remove
            .iter()
            .any(|removed| key.eq_ignore_ascii_case(removed))
    });
    Ok(resolved)
}

fn build_std_command<B: SandboxBackend + ?Sized>(
    program: &str,
    args: &[String],
    policy: &CapabilityPolicy,
    profile: SandboxProfile,
) -> Result<Command, VmError> {
    ensure_managed_process_egress_supported::<B>(policy)?;
    let mut command = Command::new(program);
    command.args(args);
    match B::prepare_std_command(program, args, &mut command, policy, profile)? {
        PrepareOutcome::Direct => Ok(command),
        PrepareOutcome::WrappedExec { wrapper, args } => {
            let mut wrapped = Command::new(wrapper);
            wrapped.args(args);
            Ok(wrapped)
        }
    }
}

fn build_tokio_command<B: SandboxBackend + ?Sized>(
    program: &str,
    args: &[String],
    policy: &CapabilityPolicy,
    profile: SandboxProfile,
) -> Result<tokio::process::Command, VmError> {
    ensure_managed_process_egress_supported::<B>(policy)?;
    let mut command = tokio::process::Command::new(program);
    command.args(args);
    match B::prepare_tokio_command(program, args, &mut command, policy, profile)? {
        PrepareOutcome::Direct => Ok(command),
        PrepareOutcome::WrappedExec { wrapper, args } => {
            let mut wrapped = tokio::process::Command::new(wrapper);
            wrapped.args(args);
            Ok(wrapped)
        }
    }
}

fn ensure_managed_process_egress_supported<B: SandboxBackend + ?Sized>(
    policy: &CapabilityPolicy,
) -> Result<(), VmError> {
    #[cfg(target_os = "macos")]
    {
        let _ = (std::marker::PhantomData::<B>, policy);
        Ok(())
    }
    #[cfg(not(target_os = "macos"))]
    {
        if policy.process_network_proxy.is_some() {
            return Err(sandbox_rejection(format!(
                "managed child-process egress is not enforceable by the {} process sandbox",
                B::name()
            )));
        }
        Ok(())
    }
}

pub fn process_spawn_error(error: &std::io::Error) -> Option<VmError> {
    let policy = crate::orchestration::current_execution_policy()?;
    if !policy.sandbox_profile.confines_processes() {
        return None;
    }
    if effective_fallback(policy.sandbox_profile) == SandboxFallback::Off
        || !ActiveBackend::available()
    {
        return None;
    }
    let message = error.to_string().to_ascii_lowercase();
    if error.kind() == std::io::ErrorKind::PermissionDenied
        || message.contains("operation not permitted")
        || message.contains("permission denied")
        || message.contains("access is denied")
    {
        return Some(sandbox_denial_error(
            format!("sandbox violation: process was denied by the OS sandbox before exec: {error}"),
            &message,
            &policy,
        ));
    }
    None
}

#[cfg(unix)]
fn sandbox_signal_status(output: &std::process::Output) -> bool {
    use std::os::unix::process::ExitStatusExt;

    matches!(
        output.status.signal(),
        Some(libc::SIGSYS) | Some(libc::SIGABRT) | Some(libc::SIGKILL)
    )
}

#[cfg(not(unix))]
fn sandbox_signal_status(_output: &std::process::Output) -> bool {
    false
}

/// Returns the active capability policy and the resolved sandbox
/// profile, or `None` if process confinement should be skipped entirely.
///
/// Profiles that do not confine processes produce `None`, as does the
/// `HARN_HANDLER_SANDBOX=off` escape hatch.
pub(crate) fn active_sandbox_policy() -> Option<(CapabilityPolicy, SandboxProfile)> {
    let policy = crate::orchestration::current_execution_policy()?;
    let profile = policy.sandbox_profile;
    if !profile.confines_processes() || effective_fallback(profile) == SandboxFallback::Off {
        return None;
    }
    Some((policy, profile))
}

fn spawn_error(error: std::io::Error) -> VmError {
    environment_io_error_thrown(&error, format!("process spawn failed: {error}"))
}

pub(crate) fn warn_once(key: &str, message: &str) {
    let inserted = WARNED_KEYS.with(|keys| keys.borrow_mut().insert(key.to_string()));
    if inserted {
        crate::events::log_warn("handler_sandbox", message);
    }
}

pub(crate) fn sandbox_rejection(message: String) -> VmError {
    VmError::CategorizedError {
        message,
        category: ErrorCategory::ToolRejected,
    }
}

/// Build the error for a process the OS sandbox blocked or killed. `detail` is
/// the denial evidence (child stderr/stdout, or the spawn `io::Error` text) the
/// OS produced — the only thing that names *which* path was refused.
///
/// The denial is reclassified from the default [`ErrorCategory::ToolRejected`]
/// to [`ErrorCategory::Environment`] only when it is provably an environment
/// gap: a developer-toolchain cache env var (`GOCACHE`, `CARGO_HOME`, …)
/// resolves OUTSIDE the sandbox jail AND `detail` actually names that path.
/// Requiring the path to appear in the denial text keeps a plain policy refusal
/// (e.g. a write outside the workspace) classified as `ToolRejected` even when
/// unrelated toolchain caches happen to sit outside this jail — the sandbox
/// correctly refused an action, which is a policy decision, not a provisioning
/// gap. When it IS an environment gap, the message names the offending root so
/// an embedder never reports it as the agent's code defect. Either way the
/// message points at the knobs that widen coverage.
fn sandbox_denial_error(summary: String, detail: &str, policy: &CapabilityPolicy) -> VmError {
    if let Some((var, path)) = toolchain_cache_gap_named_in_denial(policy, detail) {
        return VmError::CategorizedError {
            message: format!(
                "{summary}; the {var} toolchain cache resolves to '{}', which is outside the \
                 sandbox profile — a host environment/config gap, not the agent's code defect. \
                 For `harn run`, pass --sandbox-write-root '{}'; embedders can add it to \
                 process_sandbox.write_roots or extend the DeveloperToolchains preset",
                path.display(),
                path.display()
            ),
            category: ErrorCategory::Environment,
        };
    }
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    if let Some(path) = toolchain_cache_default_named_in_denial(policy, detail) {
        return VmError::CategorizedError {
            message: format!(
                "{summary}; the sandbox denied writing '{}', a well-known developer-toolchain \
                 cache outside the active profile — a host environment/config gap, not the \
                 agent's code defect. For `harn run`, pass --sandbox-write-root '{}'; embedders \
                 can enable the DeveloperToolchains preset or add process_sandbox.write_roots",
                path.display(),
                path.display()
            ),
            category: ErrorCategory::Environment,
        };
    }
    sandbox_rejection(sandbox_process_violation_message(summary))
}

fn sandbox_process_violation_message(summary: String) -> String {
    format!(
        "{summary}; if the command depends on a developer toolchain or cache outside the \
         workspace, pass --sandbox-read-root / --sandbox-write-root to `harn run`, or add the \
         root to process_sandbox.read_roots / process_sandbox.write_roots in an embedder policy"
    )
}

/// The read-granted root set the coverage check treats as "inside the jail":
/// the workspace write roots plus every read root the profile layers on
/// (Harn read-only mounts, process-only roots, developer-toolchain read/cache
/// roots, package-manager config roots). Built from the same single-owner
/// helpers the OS backends render from, so coverage cannot drift from what the
/// profile actually grants.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn coverage_jail_roots(policy: &CapabilityPolicy) -> Vec<PathBuf> {
    let mut roots = normalized_workspace_roots(policy);
    roots.extend(process_sandbox_roots(policy));
    roots.extend(process_sandbox_readonly_roots(policy));
    roots.extend(process_sandbox_policy_read_roots(policy));
    roots.extend(process_sandbox_policy_write_roots(policy));
    roots.extend(process_sandbox_developer_toolchain_read_roots(policy));
    roots.extend(process_sandbox_package_manager_config_read_roots(policy));
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    roots.extend(process_sandbox_developer_toolchain_cache_roots(policy));
    // The Windows backend grants an ACE on every `PATH` directory, so a path
    // under one of them is inside the jail and must not be refused here.
    #[cfg(target_os = "windows")]
    roots.extend(process_sandbox_path_read_roots(policy));
    roots
}

/// If a developer-toolchain *cache* env var is set to a path outside the
/// sandbox jail AND the denial evidence `detail` names that path, return
/// `(VAR, resolved_path)`. Both conditions are required: the out-of-jail cache
/// makes the gap possible, and the path appearing in the denial text is what
/// attributes *this* denial to it (so an unrelated refusal is not misread as an
/// environment gap just because some cache lives outside this jail). Read-only
/// install roots (`GOROOT`, `JAVA_HOME`, …) are intentionally excluded — they
/// usually sit under a system-preset prefix the jail set does not re-enumerate,
/// so flagging them would misclassify.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn toolchain_cache_gap_named_in_denial(
    policy: &CapabilityPolicy,
    detail: &str,
) -> Option<(String, PathBuf)> {
    let detail = detail.to_ascii_lowercase();
    let jail = coverage_jail_roots(policy);
    for name in crate::security::environment_policy::TOOLCHAIN_CACHE_ENV_VARS {
        let Some(value) = std::env::var(name)
            .ok()
            .filter(|value| !value.trim().is_empty())
        else {
            continue;
        };
        let path = normalize_for_policy(Path::new(&value));
        let named = detail.contains(&path.to_string_lossy().to_ascii_lowercase());
        if named && !jail.iter().any(|root| path_is_within(&path, root)) {
            return Some(((*name).to_string(), path));
        }
    }
    None
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
fn toolchain_cache_gap_named_in_denial(
    _policy: &CapabilityPolicy,
    _detail: &str,
) -> Option<(String, PathBuf)> {
    None
}

/// Fallback for toolchain caches that use their DEFAULT location (no env var
/// set), which [`toolchain_cache_gap_named_in_denial`] cannot see. If the denial
/// evidence names a well-known cache-write default (`~/Library/Caches/go-build`,
/// `~/.cargo/registry`, …) that is NOT inside the active jail — i.e. the
/// `DeveloperToolchains` preset is off or does not reach this policy — return the
/// path so the caller reclassifies to [`ErrorCategory::Environment`] instead of a
/// bare `ToolRejected`. When the preset IS active the cache is a jail root, so
/// the guard suppresses this and a genuine policy refusal stays `ToolRejected`.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn toolchain_cache_default_named_in_denial(
    policy: &CapabilityPolicy,
    detail: &str,
) -> Option<PathBuf> {
    let home = sandbox_user_home_dir()?;
    let detail = detail.to_ascii_lowercase();
    let jail = coverage_jail_roots(policy);
    developer_toolchain_cache_write_roots_for_home(&home)
        .into_iter()
        .find(|root| {
            detail.contains(&root.to_string_lossy().to_ascii_lowercase())
                && !jail.iter().any(|jail_root| path_is_within(root, jail_root))
        })
}

/// Writable workspace roots derived from the active agent session's
/// workspace anchor: the anchor `primary` plus any `Extend` (writable)
/// mounts. Read-only mounts are intentionally excluded — they are not
/// writable jail roots (a read of one is permitted via the read-only-roots
/// path, but a write must not be). Returns `None` when there is no current
/// session or the session has no anchor, so the caller falls back to the
/// process execution root.
fn current_session_anchor_workspace_roots() -> Option<Vec<PathBuf>> {
    let session_id = crate::agent_sessions::current_session_id()?;
    let anchor = crate::agent_sessions::workspace_anchor(&session_id)?;
    let mut roots = vec![anchor.primary.clone()];
    for mounted in &anchor.additional_roots {
        if matches!(
            mounted.mount_mode,
            crate::workspace_anchor::MountMode::Extend
        ) {
            roots.push(mounted.path.clone());
        }
    }
    Some(roots)
}

/// The project root a run is bound to even when the OS process cwd differs.
/// Prefer the typed execution context and keep `HARN_PROJECT_ROOT` as the
/// legacy standalone fallback. This mirrors the `workspace.project_root` host
/// fallback so the write jail and reported project root agree.
fn project_root_workspace_root() -> Option<PathBuf> {
    crate::stdlib::process::project_root_path().or_else(|| {
        std::env::var("HARN_PROJECT_ROOT")
            .ok()
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
            .map(PathBuf::from)
    })
}

fn normalized_workspace_roots(policy: &CapabilityPolicy) -> Vec<PathBuf> {
    let mut roots = base_workspace_roots(policy);
    // A linked worktree's git dirs and Harn's own relocated runtime
    // directories sit outside the working tree and must stay writable.
    let mut outside = git_scope_extension_for_roots(&roots).read_write;
    outside.extend(relocated_runtime_roots(&roots));
    for dir in outside {
        if !roots.iter().any(|existing| existing == &dir) {
            roots.push(dir);
        }
    }
    roots
}

/// The workspace roots as configured by the policy (or the anchored/project/
/// execution-root fallback), before any git-topology extension. Kept separate
/// from [`normalized_workspace_roots`] so the git-topology detection runs
/// against the real project roots and never re-inspects the git dirs it adds.
fn base_workspace_roots(policy: &CapabilityPolicy) -> Vec<PathBuf> {
    if policy.workspace_roots.is_empty() {
        // An empty `policy.workspace_roots` means no explicit write-jail was
        // configured for this call. Historically this fell straight back to the
        // process execution root, but under the eval pattern (process cwd !=
        // `--project`) and dispatch fan-out children, the process cwd is the
        // repo, not the project the run is bound to — so a write that correctly
        // resolved INTO the project was rejected as outside the jail
        // (HARN-CAP-201), the dispatched child wrote nothing, and the parent
        // silently compensated. Prefer, in order: (1) the active agent
        // session's workspace anchor (primary + writable `Extend` mounts) when
        // the session is anchored; (2) the typed execution project root, with
        // legacy `HARN_PROJECT_ROOT` as a fallback, robust across session
        // nesting that an unanchored dispatch child sees; (3) the process
        // execution root, the historical
        // default. Explicit `policy.workspace_roots` still take precedence
        // (handled in the non-empty branch below).
        if let Some(anchor_roots) = current_session_anchor_workspace_roots() {
            return anchor_roots
                .iter()
                .map(|root| normalize_for_policy(root))
                .collect();
        }
        if let Some(project_root) = project_root_workspace_root() {
            return vec![normalize_for_policy(&project_root)];
        }
        return vec![normalize_for_policy(
            &crate::stdlib::process::execution_root_path(),
        )];
    }
    policy
        .workspace_roots
        .iter()
        .map(|root| render_policy_root(root))
        .collect()
}

pub(crate) fn process_sandbox_roots(policy: &CapabilityPolicy) -> Vec<PathBuf> {
    normalized_workspace_roots(policy)
}

/// Normalize the policy's read-only roots. Unlike
/// [`normalized_workspace_roots`], an empty list stays empty — read-only
/// scope is purely additive, so there is no execution-root fallback to
/// synthesize.
fn normalized_read_only_roots(policy: &CapabilityPolicy) -> Vec<PathBuf> {
    let mut roots: Vec<PathBuf> = policy
        .read_only_roots
        .iter()
        .map(|root| normalize_for_policy(&resolve_policy_path(root)))
        .collect();
    // Object stores borrowed through `objects/info/alternates` (e.g. a
    // `git clone --shared`) live outside the workspace and are only ever read
    // by git; grant them read-only scope. See [`crate::stdlib::git_topology`].
    for dir in git_scope_extension_for_roots(&base_workspace_roots(policy)).read_only {
        if !roots.iter().any(|existing| existing == &dir) {
            roots.push(dir);
        }
    }
    roots
}

/// Merge the git-topology scope extension across every workspace `base_root`,
/// normalizing each discovered directory the same way as a configured root so
/// scope checks and dedup compare canonical paths. Both the OS sandbox backends
/// and the pure `check_fs_path_scope` enforcement consume the extended roots.
fn git_scope_extension_for_roots(
    base_roots: &[PathBuf],
) -> crate::stdlib::git_topology::GitScopeExtension {
    let mut merged = crate::stdlib::git_topology::GitScopeExtension::default();
    for root in base_roots {
        let ext = crate::stdlib::git_topology::git_scope_extension(root);
        for dir in ext.read_write {
            let dir = normalize_for_policy(&dir);
            if !merged.read_write.iter().any(|existing| existing == &dir) {
                merged.read_write.push(dir);
            }
        }
        for dir in ext.read_only {
            let dir = normalize_for_policy(&dir);
            if !merged.read_only.iter().any(|existing| existing == &dir) {
                merged.read_only.push(dir);
            }
        }
    }
    merged
}

#[cfg(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "openbsd",
    target_os = "windows"
))]
pub(crate) fn process_sandbox_readonly_roots(policy: &CapabilityPolicy) -> Vec<PathBuf> {
    normalized_read_only_roots(policy)
}

#[cfg(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "openbsd",
    target_os = "windows"
))]
pub(crate) fn process_sandbox_policy_read_roots(policy: &CapabilityPolicy) -> Vec<PathBuf> {
    normalized_process_roots(&policy.process_sandbox.read_roots)
}

#[cfg(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "openbsd",
    target_os = "windows"
))]
pub(crate) fn process_sandbox_policy_write_roots(policy: &CapabilityPolicy) -> Vec<PathBuf> {
    normalized_process_roots(&policy.process_sandbox.write_roots)
}

#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
pub(crate) fn process_sandbox_presets(policy: &CapabilityPolicy) -> Vec<ProcessSandboxPreset> {
    policy.process_sandbox.effective_presets()
}

#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
pub(crate) fn process_sandbox_developer_toolchain_read_roots(
    policy: &CapabilityPolicy,
) -> Vec<PathBuf> {
    if !process_sandbox_presets(policy).contains(&ProcessSandboxPreset::DeveloperToolchains) {
        return Vec::new();
    }
    let Some(home) = sandbox_user_home_dir() else {
        return Vec::new();
    };
    developer_toolchain_read_roots_for_home(&home)
}

#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
pub(crate) fn process_sandbox_package_manager_config_read_roots(
    policy: &CapabilityPolicy,
) -> Vec<PathBuf> {
    if !process_sandbox_presets(policy).contains(&ProcessSandboxPreset::PackageManagerConfig) {
        return Vec::new();
    }
    let Some(home) = sandbox_user_home_dir() else {
        return Vec::new();
    };
    package_manager_config_read_roots_for_home(&home)
}

/// Windows-only: every directory on this process's own `PATH`, gated on the
/// same `DeveloperToolchains` preset as the home-relative roots above.
///
/// This backend's AppContainer is read-closed by construction, so nothing
/// outside an explicit `icacls` grant is visible to the child, and
/// [`developer_toolchain_read_roots_for_home`] covers only *home-relative*
/// installs (`~/.cargo`, `~/.nvm`, …). A global install on `PATH` — the
/// official Node.js installer's `C:\Program Files\nodejs` is the case that
/// exposed this — stays invisible, and `cmd.exe` reports the unreadable
/// executable as "not recognized" rather than as a permission error. A `PATH`
/// entry is, definitionally, a toolchain location.
///
/// This lives here rather than in the backend because two consumers need the
/// same answer. The backend renders an `icacls` ACE per root, and
/// [`coverage_jail_roots`] answers whether a path is inside the jail when a
/// denial is being classified. While only the backend knew about these roots,
/// the two views disagreed: a path under a `PATH` directory was granted by the
/// backend and simultaneously reported as outside the jail, which is exactly
/// the drift the read-root helpers say cannot happen because "backends render
/// from it". Note what this does *not* reach: `check_fs_path_scope`, the check
/// that actually refuses a builtin's path access, consults only the workspace
/// and read-only roots and has never consulted any preset read root on any
/// platform. Widening that is a cross-platform decision, not a Windows one.
///
/// Existence filtering stays with the backend's grant loop, which already
/// skips a root that is not on disk, so a stray `PATH` entry costs nothing
/// here either.
#[cfg(target_os = "windows")]
pub(crate) fn process_sandbox_path_read_roots(policy: &CapabilityPolicy) -> Vec<PathBuf> {
    if !process_sandbox_presets(policy).contains(&ProcessSandboxPreset::DeveloperToolchains) {
        return Vec::new();
    }
    std::env::var_os("PATH")
        .iter()
        .flat_map(std::env::split_paths)
        .map(|dir| normalize_for_policy(&dir))
        .collect()
}

fn normalized_process_roots(roots: &[String]) -> Vec<PathBuf> {
    roots
        .iter()
        .map(|root| normalize_for_policy(&resolve_policy_path(root)))
        .collect()
}

fn resolve_policy_path(path: &str) -> PathBuf {
    let candidate = PathBuf::from(path);
    if candidate.is_absolute() {
        candidate
    } else {
        crate::stdlib::process::execution_root_path().join(candidate)
    }
}

/// Render one configured policy-root string to the exact path the sandbox jails
/// to — the single transform [`base_workspace_roots`] applies, exposed via
/// `crate::process_sandbox` so host disclosure and provenance surfaces report
/// the enforced jail path, not a pre-canonical approximation. Canonicalization
/// is best-effort for nonexistent paths (lexical fallback) and never panics.
pub fn render_policy_root(path: &str) -> PathBuf {
    normalize_for_policy(&resolve_policy_path(path))
}

#[cfg(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "openbsd",
    target_os = "windows"
))]
pub(crate) fn policy_allows_workspace_write(policy: &CapabilityPolicy) -> bool {
    !policy.capabilities_are_restricted()
        || policy_allows_capability(policy, "workspace", &["write_text", "delete"])
}

#[cfg(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "openbsd",
    target_os = "windows"
))]
pub(crate) fn policy_allows_capability(
    policy: &CapabilityPolicy,
    capability: &str,
    ops: &[&str],
) -> bool {
    policy
        .capabilities
        .get(capability)
        .map(|allowed| {
            ops.iter()
                .any(|op| allowed.iter().any(|candidate| candidate == op))
        })
        .unwrap_or(false)
}

impl FsAccess {
    fn verb(self) -> &'static str {
        match self {
            FsAccess::Read => "read",
            FsAccess::Write => "write",
            FsAccess::Delete => "delete",
        }
    }
}

#[cfg(test)]
mod tests;