fluers-runtime 0.6.0

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

use std::ffi::OsStr;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;

use async_trait::async_trait;
use rustix::fs::{fstat, ftruncate, mkdirat, open, openat, Dir, FileType, Mode, OFlags};
use rustix::io::Errno;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::process::Command;
use tokio_util::sync::CancellationToken;

// `fcntl(F_GETPATH)` is apple-only; it backs `fd_real_path` on macOS.
#[cfg(target_os = "macos")]
use rustix::fs::getpath;
// `/proc/self/fd/N` readlink needs the raw fd int on Linux.
#[cfg(target_os = "linux")]
use std::os::fd::AsRawFd;

use crate::env::{Limits, SessionEnv, ShellResult};
use crate::error::{RuntimeError, RuntimeResult};

/// POSIX `st_mode` masks (stable, platform-independent) for the regular-file
/// check — avoids pulling `libc` just for `S_ISREG`.
const ST_MODE_TYPE_MASK: u32 = 0o170_000; // S_IFMT
const ST_MODE_REGULAR: u32 = 0o100_000; // S_IFREG

/// A `SessionEnv` backed by a real local directory.
pub struct LocalSessionEnv {
    /// Held fd over the canonical root: the anchor for every fd-anchored walk.
    /// Opened once at construction with `O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC`,
    /// so root-path re-resolution never re-enters any data hot path. Because
    /// the root is pinned by fd (not path), renaming/symlinking the root *path*
    /// after construction cannot redirect a subsequent operation. `OwnedFd` is
    /// `Send + Sync` on Unix.
    root_fd: OwnedFd,
    #[allow(dead_code)]
    limits: Limits,
    /// Optional process-sandbox backend (WP-2 slot). `None` ⇒ spawn behaviour
    /// is byte-identical to pre-WP-2. When `Some`, every exec/grep argv is
    /// passed through `ProcessSandbox::wrap` and the returned env additions
    /// survive `env_clear()`.
    exec_sandbox: Option<Arc<dyn crate::process_sandbox::ProcessSandbox>>,
    /// Policy matching `exec_sandbox` (profile + egress). `Some` iff the
    /// backend is `Some`.
    sandbox_policy: Option<crate::process_sandbox::SandboxPolicy>,
}

impl LocalSessionEnv {
    /// Create an env rooted at `root`. The directory is canonicalized; if it
    /// does not exist it is created. An fd is held over the canonical root for
    /// the lifetime of the env.
    pub async fn new(root: impl Into<PathBuf>, limits: Limits) -> RuntimeResult<Self> {
        Self::build(root, limits, None, None).await
    }

    /// Crate-private constructor that attaches a (already `prepare`d) process-
    /// sandbox backend. Called by `LocalSandbox::env_for` on the path where a
    /// backend is ACTIVELY attached (FullyEnforced, or Partial+Degrade). When
    /// `env_for` degrades to no backend (Unavailable+Degrade), it calls
    /// [`LocalSessionEnv::new`] instead — there is no "backend None + policy
    /// Some" state, so this constructor takes a non-optional backend.
    pub(crate) async fn new_with_sandbox(
        root: impl Into<PathBuf>,
        limits: Limits,
        backend: Arc<dyn crate::process_sandbox::ProcessSandbox>,
        policy: crate::process_sandbox::SandboxPolicy,
    ) -> RuntimeResult<Self> {
        Self::build(root, limits, Some(backend), Some(policy)).await
    }

    /// Shared construction for both entry points.
    async fn build(
        root: impl Into<PathBuf>,
        limits: Limits,
        exec_sandbox: Option<Arc<dyn crate::process_sandbox::ProcessSandbox>>,
        sandbox_policy: Option<crate::process_sandbox::SandboxPolicy>,
    ) -> RuntimeResult<Self> {
        let root = root.into();
        tokio::fs::create_dir_all(&root)
            .await
            .map_err(RuntimeError::Io)?;
        let canon = tokio::fs::canonicalize(&root)
            .await
            .map_err(RuntimeError::Io)?;
        // Hold an fd over the canonical root. Opened with O_NOFOLLOW (reject a
        // root swapped to a symlink since construction) + O_DIRECTORY +
        // O_CLOEXEC. From here on, no operation re-resolves the root *path* —
        // they all anchor off this fd.
        let root_flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
        let root_fd = open(&canon, root_flags, Mode::empty())
            .map_err(|e| RuntimeError::Io(std::io::Error::from(e)))?;
        Ok(Self {
            root_fd,
            limits,
            exec_sandbox,
            sandbox_policy,
        })
    }

    /// Wrap a `sh -c <command>` argv through the attached process-sandbox
    /// backend (if any), returning the (possibly rewritten) argv plus any env
    /// additions the backend requires.
    ///
    /// With no backend, returns the original argv and an empty env — the spawn
    /// sites then behave byte-identically to pre-WP-2. With a backend, the
    /// shell runs *inside* the boundary (the wrap target is `sh`, not the raw
    /// command). An empty wrapped argv is rejected loud (a backend that drops
    /// the command is a misconfiguration).
    fn wrap_shell_argv(
        &self,
        argv: Vec<String>,
        cwd: Option<PathBuf>,
    ) -> RuntimeResult<crate::process_sandbox::WrappedCommand> {
        let Some(backend) = &self.exec_sandbox else {
            return Ok(crate::process_sandbox::WrappedCommand {
                argv,
                env: std::collections::BTreeMap::new(),
            });
        };
        let policy = self
            .sandbox_policy
            .as_ref()
            .ok_or_else(|| RuntimeError::Sandbox("backend set without policy".into()))?;
        let ctx = crate::process_sandbox::ExecSandboxContext {
            workspace_path: Self::fd_real_path(self.root_fd.as_fd())?,
            cwd,
            profile: policy.profile,
            egress: policy.egress.clone(),
        };
        let wrapped = backend.wrap(&argv, &ctx)?;
        if wrapped.argv.is_empty() {
            return Err(RuntimeError::Sandbox(
                "process-sandbox backend returned an empty argv".into(),
            ));
        }
        Ok(wrapped)
    }

    /// Validate a model-supplied relative path and return its `Normal`
    /// components (skipping `.`). Rejects absolute paths and any `..`
    /// component up front — the fd walk itself then enforces containment, so
    /// there is no canonicalize-then-contain step anywhere in the data path.
    fn normal_components<'a>(&self, rel: &'a Path) -> RuntimeResult<Vec<&'a OsStr>> {
        if rel.is_absolute() {
            return Err(RuntimeError::Sandbox(format!(
                "absolute paths are not allowed: `{}`",
                rel.display()
            )));
        }
        if rel.components().any(|c| matches!(c, Component::ParentDir)) {
            return Err(RuntimeError::Sandbox(format!(
                "`..` is not allowed in paths: `{}`",
                rel.display()
            )));
        }
        Ok(rel
            .components()
            .filter_map(|c| match c {
                Component::Normal(name) => Some(name),
                // `CurDir` (".") is skipped; `ParentDir`/absolute are
                // pre-rejected above.
                _ => None,
            })
            .collect())
    }

    /// Open `rel` for reading via an fd-anchored walk from the held root fd
    /// (B-Swift Phase C1a / #4). Closes the path-based TOCTOU at the daemon
    /// read: every component is opened with `O_NOFOLLOW` (symlink → `ELOOP`),
    /// and the leaf is `fstat`'d on the SAME fd we hand back for reading — so a
    /// symlink/hardlink swap between confinement and the read cannot exfiltrate.
    /// Mirrors the Swift `readFdAnchored`.
    ///
    /// Returns the opened regular-file `File` and its size in bytes (the size is
    /// authoritative — taken off the open fd, not the path).
    fn open_anchored_read(&self, rel: &Path) -> RuntimeResult<(std::fs::File, u64)> {
        let names = self.normal_components(rel)?;
        if names.is_empty() {
            return Err(RuntimeError::Sandbox(format!(
                "read path has no components: `{}`",
                rel.display()
            )));
        }

        let oflag = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
        // Walk: hold every opened fd in `chain` so intermediates stay alive
        // until the next level is opened; the last element is the leaf.
        let mut chain: Vec<OwnedFd> = Vec::new();
        for name in names {
            let dir = match chain.last() {
                Some(f) => f.as_fd(),
                None => self.root_fd.as_fd(),
            };
            let fd = match openat(dir, name, oflag, Mode::empty()) {
                Ok(fd) => fd,
                Err(Errno::LOOP) => {
                    return Err(RuntimeError::Sandbox(format!(
                        "symlinks are not allowed in read paths: `{}`",
                        rel.display()
                    )));
                }
                Err(e) => return Err(RuntimeError::Io(std::io::Error::from(e))),
            };
            chain.push(fd);
        }
        let leaf_owned = chain
            .pop()
            .ok_or_else(|| RuntimeError::Sandbox("read path has no components".to_string()))?;
        // Remaining `chain` (intermediates) drops here → their fds close.

        // Authoritative leaf check: fstat the OPENED fd (not the path).
        let stat =
            fstat(leaf_owned.as_fd()).map_err(|e| RuntimeError::Io(std::io::Error::from(e)))?;
        if (stat.st_mode as u32 & ST_MODE_TYPE_MASK) != ST_MODE_REGULAR {
            return Err(RuntimeError::Sandbox(format!(
                "not a regular file: `{}`",
                rel.display()
            )));
        }
        if stat.st_nlink > 1 {
            // Hardlink exfil (`ln secret in_root; read in_root/link`) — mirrors
            // the Swift-side C2/#3 reject. Authoritative here: fstat off the
            // open fd, not the path.
            return Err(RuntimeError::Sandbox(format!(
                "multiple hard links — can't safely confine: `{}`",
                rel.display()
            )));
        }
        let size = stat.st_size.max(0) as u64;
        Ok((std::fs::File::from(leaf_owned), size))
    }

    /// Open an existing directory `rel` via an fd-anchored walk from the held
    /// root fd (B-Swift Phase C1b). Used to pin an exec `cwd` by fd (passed to
    /// the child as `/dev/fd/N`). Every component is opened with
    /// `O_DIRECTORY | O_NOFOLLOW`, so a symlinked intermediate dir → `ELOOP`
    /// → reject (never followed).
    fn open_anchored_dir(&self, rel: &Path) -> RuntimeResult<OwnedFd> {
        let names = self.normal_components(rel)?;
        let oflag = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
        // Open "." relative to the held root → an independent owned starting fd,
        // so we never borrow `root_fd` across the walk.
        let mut cur = openat(self.root_fd.as_fd(), ".", oflag, Mode::empty())
            .map_err(|e| RuntimeError::Io(std::io::Error::from(e)))?;
        for name in names {
            let next = match openat(cur.as_fd(), name, oflag, Mode::empty()) {
                Ok(fd) => fd,
                Err(Errno::LOOP) => {
                    return Err(RuntimeError::Sandbox(format!(
                        "symlinked directories are not allowed: `{}`",
                        rel.display()
                    )));
                }
                Err(e) => return Err(RuntimeError::Io(std::io::Error::from(e))),
            };
            cur = next;
        }
        Ok(cur)
    }

    /// Derive the real on-disk path of an already-open directory fd — macOS
    /// `fcntl(F_GETPATH)`, Linux `/proc/self/fd/N`. The path comes from the
    /// *inode* the fd names, NOT from any model-supplied input string, so a
    /// symlink swap on the input path between the fd-anchored open and the
    /// spawn/search can't redirect the operation. (`/dev/fd/N` as a `cwd` is
    /// Linux-only — macOS fdescfs rejects `chdir` to it with `ENOTDIR`, so the
    /// inode path is the portable fd-anchored handle.) A post-open *move* of the
    /// directory is a residual race outside the threat model: this is not an OS
    /// sandbox, and moving the dir requires write access under the confined root.
    fn fd_real_path(fd: BorrowedFd<'_>) -> RuntimeResult<PathBuf> {
        #[cfg(target_os = "macos")]
        {
            use std::os::unix::ffi::OsStrExt;
            let c = getpath(fd).map_err(|e| RuntimeError::Io(std::io::Error::from(e)))?;
            Ok(PathBuf::from(OsStr::from_bytes(c.to_bytes())))
        }
        #[cfg(target_os = "linux")]
        {
            let raw = fd.as_raw_fd();
            std::fs::read_link(format!("/proc/self/fd/{raw}")).map_err(RuntimeError::Io)
        }
        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
        {
            let _ = fd;
            Err(RuntimeError::Sandbox(
                "fd-derived directory path is unsupported on this platform".into(),
            ))
        }
    }

    /// Resolve a grep search path to its real INODE path, fd-anchored from the
    /// held root fd. Every component is opened `O_NOFOLLOW`; a symlink anywhere
    /// in the path (including a symlinked dir passed explicitly) is rejected
    /// outright — `rg --no-follow` would otherwise follow an explicit
    /// symlinked-dir argument and leak its contents. The returned path is the
    /// inode's path (from `fd_real_path`), so a swap on the input can't redirect
    /// the search. Handles directory and file leaf targets; `.`/empty → root.
    fn search_path_inode(&self, p: &str) -> RuntimeResult<PathBuf> {
        let names = self.normal_components(Path::new(p))?;
        if names.is_empty() {
            // `.` or empty path → the root.
            return Self::fd_real_path(self.root_fd.as_fd());
        }
        let dir_oflag = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
        let file_oflag = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
        let (parents, last) = names.split_at(names.len() - 1);
        let mut parent = openat(self.root_fd.as_fd(), ".", dir_oflag, Mode::empty())
            .map_err(|e| RuntimeError::Io(std::io::Error::from(e)))?;
        for name in parents.iter().copied() {
            parent = match openat(parent.as_fd(), name, dir_oflag, Mode::empty()) {
                Ok(fd) => fd,
                Err(Errno::LOOP) => {
                    return Err(RuntimeError::Sandbox(format!(
                        "symlinked search path is not allowed: `{p}`"
                    )))
                }
                Err(e) => return Err(RuntimeError::Io(std::io::Error::from(e))),
            };
        }
        let last_name = last[0];
        // Leaf: try dir, fall back to file (a file grep target). `O_NOFOLLOW`
        // in both means a symlink leaf → `ELOOP` → reject.
        let leaf_fd = match openat(parent.as_fd(), last_name, dir_oflag, Mode::empty()) {
            Ok(fd) => fd,
            Err(Errno::NOTDIR) => {
                match openat(parent.as_fd(), last_name, file_oflag, Mode::empty()) {
                    Ok(fd) => fd,
                    Err(Errno::LOOP) => {
                        return Err(RuntimeError::Sandbox(format!(
                            "symlinked search path is not allowed: `{p}`"
                        )))
                    }
                    Err(e) => return Err(RuntimeError::Io(std::io::Error::from(e))),
                }
            }
            Err(Errno::LOOP) => {
                return Err(RuntimeError::Sandbox(format!(
                    "symlinked search path is not allowed: `{p}`"
                )))
            }
            Err(e) => return Err(RuntimeError::Io(std::io::Error::from(e))),
        };
        Self::fd_real_path(leaf_fd.as_fd())
    }

    /// Open `rel` for writing via an fd-anchored walk from the held root fd
    /// (B-Swift Phase C1b — the critical counterpart of `open_anchored_read`).
    ///
    /// Invariants:
    /// - Parent dirs are created with a `mkdirat` walk from the root fd (each
    ///   level opened `O_NOFOLLOW`); `mkdirat` does not follow a symlink at the
    ///   target name, and the follow-up `openat(O_DIRECTORY|O_NOFOLLOW)` rejects
    ///   a symlinked intermediate outright.
    /// - The leaf is opened `WRONLY | CREATE | NOFOLLOW` — `O_NOFOLLOW` rejects
    ///   a symlink leaf outright (`ELOOP`). Critically, `O_TRUNC` is **not**
    ///   passed: truncation is deferred to `ftruncate` *after* the hardlink
    ///   check, so a write through a hardlink can never mutate before the
    ///   confinement decision.
    /// - The opened leaf fd is `fstat`'d (authoritative): non-regular files are
    ///   rejected, and `st_nlink > 1` is rejected — a write through a hardlink
    ///   mutates every name in the set (silent cross-target data loss).
    /// - The caller truncates + writes off the SAME fd.
    fn open_anchored_write(&self, rel: &Path) -> RuntimeResult<OwnedFd> {
        let names = self.normal_components(rel)?;
        let (parents, leaf) = names.split_at(names.len().saturating_sub(1));
        let leaf_name = leaf.first().copied().ok_or_else(|| {
            RuntimeError::Sandbox(format!("write path has no file name: `{}`", rel.display()))
        })?;

        let dir_oflag = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
        // mkdirat default mode mirrors std's `create_dir` (0o777 & !umask);
        // files below use 0o666 & !umask (std's `fs::write` default).
        let dir_mode = Mode::RWXU | Mode::RWXG | Mode::RWXO;
        let file_mode = Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::WGRP | Mode::ROTH | Mode::WOTH;

        let mut parent = openat(self.root_fd.as_fd(), ".", dir_oflag, Mode::empty())
            .map_err(|e| RuntimeError::Io(std::io::Error::from(e)))?;
        for name in parents.iter().copied() {
            let next = match openat(parent.as_fd(), name, dir_oflag, Mode::empty()) {
                Ok(fd) => fd,
                Err(Errno::NOENT) => {
                    // Create the missing intermediate dir. `mkdirat` does NOT
                    // follow a symlink at `name` (it would fail EEXIST); the
                    // reopen below re-establishes the fd-anchored position.
                    // EEXIST from mkdirat means another writer created it
                    // concurrently — that's safe; just reopen it.
                    if let Err(e) = mkdirat(parent.as_fd(), name, dir_mode) {
                        if e != Errno::EXIST {
                            return Err(RuntimeError::Io(std::io::Error::from(e)));
                        }
                    }
                    match openat(parent.as_fd(), name, dir_oflag, Mode::empty()) {
                        Ok(fd) => fd,
                        Err(Errno::LOOP) => {
                            return Err(RuntimeError::Sandbox(format!(
                                "symlinked directories are not allowed: `{}`",
                                rel.display()
                            )));
                        }
                        Err(e) => return Err(RuntimeError::Io(std::io::Error::from(e))),
                    }
                }
                Err(Errno::LOOP) => {
                    return Err(RuntimeError::Sandbox(format!(
                        "symlinked directories are not allowed: `{}`",
                        rel.display()
                    )));
                }
                Err(e) => return Err(RuntimeError::Io(std::io::Error::from(e))),
            };
            parent = next;
        }

        // Leaf: CREATE + NOFOLLOW, but deliberately NO TRUNC — truncate after
        // the nlink check so a hardlink can't be mutated pre-decision.
        let leaf_oflag = OFlags::WRONLY | OFlags::CREATE | OFlags::NOFOLLOW | OFlags::CLOEXEC;
        let leaf_fd = match openat(parent.as_fd(), leaf_name, leaf_oflag, file_mode) {
            Ok(fd) => fd,
            Err(Errno::LOOP) => {
                return Err(RuntimeError::Sandbox(format!(
                    "symlink leaf is not allowed: `{}`",
                    rel.display()
                )));
            }
            Err(e) => return Err(RuntimeError::Io(std::io::Error::from(e))),
        };

        // Authoritative confinement checks off the OPEN fd (not the path).
        let stat = fstat(leaf_fd.as_fd()).map_err(|e| RuntimeError::Io(std::io::Error::from(e)))?;
        if (stat.st_mode as u32 & ST_MODE_TYPE_MASK) != ST_MODE_REGULAR {
            return Err(RuntimeError::Sandbox(format!(
                "not a regular file: `{}`",
                rel.display()
            )));
        }
        if stat.st_nlink > 1 {
            // A write through a hardlink mutates every name in the set — reject,
            // mirroring the read-side decision.
            return Err(RuntimeError::Sandbox(format!(
                "multiple hard links — can't safely confine: `{}`",
                rel.display()
            )));
        }
        Ok(leaf_fd)
    }
}

#[async_trait]
impl SessionEnv for LocalSessionEnv {
    async fn read_file(
        &self,
        path: &Path,
        max_lines: usize,
        max_bytes: usize,
    ) -> RuntimeResult<String> {
        // B-Swift Phase C1a / #4: fd-anchored open + read from the SAME fd
        // (closes the check-then-use TOCTOU the path-based read had).
        //
        // Bounded read (0.5.2): the output is capped at `max_bytes` anyway
        // (apply_read_limits truncates beyond it), so reading the whole file
        // first would OOM on a multi-GB file. Read at most `max_bytes` and
        // trim any partial UTF-8 char at the cut. Memory is thus bounded by
        // `max_bytes`, independent of the on-disk size.
        let (file, _size) = self.open_anchored_read(path)?;
        let (raw, truncated_at_cap) = read_bounded_string(file, max_bytes).await?;
        let mut out = apply_read_limits(raw, max_lines, max_bytes);
        // If the bounded read cut the file short (file > max_bytes) and
        // apply_read_limits didn't itself add a truncation marker, surface that
        // the content was capped — preserves the original oversized-file
        // indicator that the unbounded read had.
        if truncated_at_cap && !out.contains("[... truncated") {
            out.push_str(&format!("\n[... truncated at {max_bytes} bytes ...]"));
        }
        Ok(out)
    }

    async fn read_file_full(&self, path: &Path, max_bytes: usize) -> RuntimeResult<String> {
        // B-Swift Phase C1a / #4: size + read off the SAME open fd. The old
        // path-based metadata check raced the read; now the size gate is
        // authoritative (fstat off the open fd) and the read uses that fd.
        let (file, size) = self.open_anchored_read(path)?;
        let size = size as usize;
        if size > max_bytes {
            return Err(RuntimeError::FileTooLarge {
                path: path.display().to_string(),
                size,
                max: max_bytes,
            });
        }
        let mut file = tokio::fs::File::from_std(file);
        let mut raw = String::new();
        file.read_to_string(&mut raw)
            .await
            .map_err(RuntimeError::Io)?;
        Ok(raw)
    }

    async fn write_file(&self, path: &Path, content: &str) -> RuntimeResult<()> {
        // B-Swift Phase C1b: fd-anchored write. Open the leaf off the held root
        // fd (mkdirat-walking parents), fstat for hardlink confinement, THEN
        // truncate + write off the SAME fd. No path re-resolution in any step.
        let leaf_fd = self.open_anchored_write(path)?;
        // Truncate AFTER the nlink check (the open deliberately omitted O_TRUNC).
        ftruncate(&leaf_fd, 0).map_err(|e| RuntimeError::Io(std::io::Error::from(e)))?;
        let mut file = tokio::fs::File::from_std(std::fs::File::from(leaf_fd));
        file.write_all(content.as_bytes())
            .await
            .map_err(RuntimeError::Io)?;
        // Flush before returning: a subsequent `fstat` (e.g. a size-gated
        // `read_file_full`) must observe the full new size. `write_all`'s await
        // dispatches the pwrite on the blocking pool, but tokio `File`'s close is
        // deferred on drop — without this barrier the size was intermittently
        // not yet visible to a following `fstat` under parallel load (a rare
        // flake that returned a stale/short size). `flush` completes the pending
        // async write without an `fsync` (no durability/perf cost vs `sync_all`).
        file.flush().await.map_err(RuntimeError::Io)?;
        Ok(())
    }

    async fn exec(
        &self,
        command: &str,
        cwd: &Path,
        timeout_ms: Option<u64>,
        cancel: &CancellationToken,
    ) -> RuntimeResult<ShellResult> {
        // The cwd is opened fd-anchored (`openat(O_DIRECTORY|O_NOFOLLOW)` per
        // component from the held root fd), so a symlinked cwd dir is rejected
        // outright. The child then chdirs to the *inode's* real path — derived
        // from the open fd via `fd_real_path`, not from the input string — so a
        // symlink swap on the cwd path between open and spawn can't redirect it.
        // (`/dev/fd/N` would be the pure-inode handle, but macOS fdescfs rejects
        // `chdir` to it; the inode path is the portable form.) `cwd_fd` is held
        // in scope through `spawn()` so the inode it names stays valid.
        let cwd_fd = self.open_anchored_dir(cwd)?;
        let cwd_path = Self::fd_real_path(cwd_fd.as_fd())?;

        // `kill_on_drop(true)`: on timeout/cancel the in-flight `wait_with_output`
        // future (which owns the child) is dropped, and its `Drop` sends SIGKILL —
        // so a still-running child is never orphaned.
        //
        // `env_clear()` + allowlist: model-run shells must NOT inherit the
        // parent's full environment — that includes provider API keys
        // (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `FLUERS_SERVER_TOKEN`, …),
        // which a prompt-injected model could exfiltrate via `env | grep KEY`.
        // Only a safe, minimal allowlist (needed for commands to function) is
        // re-set.
        // Wrap the `sh -c <command>` argv through the process-sandbox backend
        // (if attached). With no backend this is a no-op (byte-identical to
        // pre-WP-2). With a backend the shell runs *inside* the boundary.
        let wrapped = self.wrap_shell_argv(
            vec!["sh".into(), "-c".into(), command.into()],
            Some(cwd_path.clone()),
        )?;
        let mut cmd = Command::new(&wrapped.argv[0]);
        cmd.args(&wrapped.argv[1..])
            .current_dir(&cwd_path)
            .env_clear()
            .envs(safe_exec_env())
            // Backend-required env additions survive env_clear (C1).
            .envs(wrapped.env)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .kill_on_drop(true);
        let child = cmd.spawn().map_err(RuntimeError::Io)?;
        // `cwd_fd` stays live until end of scope (spawn has run by now).

        let timeout_fut = match timeout_ms {
            Some(ms) => Box::pin(tokio::time::sleep(std::time::Duration::from_millis(ms)))
                as std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>,
            None => Box::pin(std::future::pending()),
        };
        let cancel_fut = cancel.cancelled();

        // `wait_with_output` drains stdout AND stderr concurrently while it waits.
        // The old `child.wait()` did not read the pipes, so a child emitting more
        // than the OS pipe buffer (~64 KB) blocked on a full pipe while `wait()`
        // blocked on the child — a deadlock that only broke on timeout (output
        // lost, misreported as a 124), or hung forever with no timeout set.
        tokio::select! {
            _ = timeout_fut => {
                // `child` (moved into the dropped `wait_with_output` future) is
                // SIGKILLed via `kill_on_drop`. Return the 124-shaped result.
                Ok(ShellResult {
                    exit_code: 124,
                    stdout: String::new(),
                    stderr: format!("command timed out after {}ms", timeout_ms.unwrap_or(0)),
                })
            }
            _ = cancel_fut => {
                Err(RuntimeError::Sandbox("command cancelled".into()))
            }
            output = child.wait_with_output() => {
                let output = output.map_err(RuntimeError::Io)?;
                Ok(ShellResult {
                    exit_code: output.status.code().unwrap_or(-1),
                    stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
                    stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
                })
            }
        }
    }

    async fn glob(&self, pattern: &str, limit: usize) -> RuntimeResult<Vec<String>> {
        // Containment: reject absolute patterns and `..` so the model can't
        // list files outside the root (e.g. `../../*` or `/etc/*`).
        validate_search_pattern(pattern)?;
        // Split into a base dir (must exist) + a single-segment filename pattern.
        // As in the original matcher, the filename pattern is applied at every
        // depth under the base (the descent is what changed: it is now
        // fd-anchored and never enters a symlinked directory).
        let pat_path = Path::new(pattern);
        let base_rel = pat_path.parent().unwrap_or_else(|| Path::new(""));
        let fname = pat_path.file_name().and_then(|s| s.to_str()).unwrap_or("*");
        // Results are reported relative to the ROOT, but the walk starts at the
        // base dir — so seed the descent with the base's own path relative to
        // root (e.g. `sub/*.txt` → base prefix `sub`, so `sub/nested.txt` is
        // reported, not `nested.txt`).
        let base_prefix = self
            .normal_components(base_rel)?
            .iter()
            .map(|s| s.to_string_lossy().into_owned())
            .collect::<Vec<_>>()
            .join("/");
        // A missing/symlinked base yields no matches (preserves the original
        // "no results" behavior for non-existent bases after validation).
        let base_fd = match self.open_anchored_dir(base_rel) {
            Ok(fd) => fd,
            Err(_) => return Ok(Vec::new()),
        };
        let dir = match Dir::new(base_fd) {
            Ok(d) => d,
            Err(_) => return Ok(Vec::new()),
        };
        let mut results: Vec<String> = Vec::new();
        walk_glob_fd(dir, fname, &base_prefix, &mut results, limit)?;
        results.sort();
        // De-dup (a `**`/depth-recursion can surface the same relative path).
        results.dedup();
        Ok(results)
    }

    async fn grep(
        &self,
        pattern: &str,
        paths: &[&str],
        max_matches: usize,
    ) -> RuntimeResult<Vec<String>> {
        // Containment: validate each search path's SHAPE (reject absolute/`..`
        // so the model can't reach outside the root), then resolve it fd-anchored
        // to its real INODE path. This is essential: `rg --no-follow` still
        // follows a symlinked dir passed EXPLICITLY as a search path, so passing
        // the input string would leak through `linkdir -> outside`. Resolving to
        // the inode path (and rejecting symlinks outright at `openat(NO_FOLLOW)`)
        // closes that — the search runs against the real confined dir/file.
        let root_path = Self::fd_real_path(self.root_fd.as_fd())?;
        let mut validated: Vec<String> = Vec::new();
        if paths.is_empty() {
            validated.push(shell_quote(&root_path.to_string_lossy()));
        } else {
            for p in paths {
                validate_search_pattern(p)?;
                let inode = self.search_path_inode(p)?;
                validated.push(shell_quote(&inode.to_string_lossy()));
            }
        }
        let search = validated.join(" ");
        // The process cwd is the root's inode path too (belt-and-suspenders);
        // `rg --no-follow` / the `find -P` fallback never follow symlinks.
        // `kill_on_drop(true)` + a bounded timeout ensure a grep against a hung
        // filesystem (stuck NFS, adversarial tree) can neither block this future
        // forever nor orphan the child. The trait gives no cancel token/timeout,
        // so a fixed ceiling is applied here.
        const GREP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
        // Build the grep shell argv, then wrap it through the backend (if any).
        // With no backend this is a no-op and the spawn is byte-identical to
        // pre-WP-2 (grep intentionally does NOT env_clear — it inherits the
        // parent env). With a backend the shell runs inside the boundary and
        // backend env additions are applied.
        let grep_command = format!(
            "rg -n --no-follow -- {pat} {search} 2>/dev/null \
             || find -P {search} -type f -exec grep -Hn -- {pat} {{}} + 2>/dev/null",
            pat = shell_quote(pattern),
        );
        let wrapped = self.wrap_shell_argv(vec!["sh".into(), "-c".into(), grep_command], None)?;
        let mut cmd = Command::new(&wrapped.argv[0]);
        cmd.args(&wrapped.argv[1..])
            .current_dir(&root_path)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .kill_on_drop(true);
        // Only apply env additions when a backend is present; with no backend
        // wrapped.env is empty and `.envs` of an empty map is a no-op, keeping
        // the no-backend spawn byte-identical to pre-WP-2.
        cmd.envs(wrapped.env);
        let child = cmd.spawn().map_err(RuntimeError::Io)?;
        let rg = match tokio::time::timeout(GREP_TIMEOUT, child.wait_with_output()).await {
            Ok(res) => res.map_err(RuntimeError::Io)?,
            // On timeout the `wait_with_output` future is dropped; `kill_on_drop`
            // SIGKILLs the child. Surface an empty result rather than hanging.
            Err(_) => return Ok(Vec::new()),
        };
        let out = String::from_utf8_lossy(&rg.stdout);
        // Search paths are absolute inode paths (see above), so `rg`/`grep` emit
        // absolute paths — strip the root's inode prefix so results stay
        // root-relative (as they did pre-fd-anchoring) and don't leak the host
        // temp/root path to the model.
        let root_prefix = format!("{}/", root_path.to_string_lossy());
        Ok(out
            .lines()
            .map(|l| {
                l.strip_prefix(root_prefix.as_str())
                    .unwrap_or(l)
                    .to_string()
            })
            .take(max_matches)
            .collect())
    }
}

/// Truncate `raw` to `max_lines` and `max_bytes`, whichever binds first.
fn apply_read_limits(raw: String, max_lines: usize, max_bytes: usize) -> String {
    let mut bytes_left = max_bytes;
    let mut out = String::new();
    let mut truncated = false;
    for (i, line) in raw.split_inclusive('\n').enumerate() {
        if i >= max_lines {
            out.push_str(&format!("\n[... truncated at {max_lines} lines ...]"));
            truncated = true;
            break;
        }
        if bytes_left < line.len() {
            // Take as many whole bytes as fit on a UTF-8 boundary.
            let take = line
                .char_indices()
                .map(|(i, _)| i)
                .find(|&pos| pos > bytes_left)
                .unwrap_or(line.len());
            out.push_str(line.get(..take).unwrap_or(line));
            out.push_str(&format!("\n[... truncated at {max_bytes} bytes ...]"));
            truncated = true;
            break;
        }
        out.push_str(line);
        bytes_left -= line.len();
    }
    if truncated {
        out
    } else {
        raw
    }
}

/// Read at most `max_bytes` bytes from `file` into a `String`, trimming any
/// partial UTF-8 char at the read boundary.
///
/// Bounds memory at `max_bytes` so a multi-GB file cannot OOM the truncating
/// `read_file` path — the output is already capped at `max_bytes` by
/// [`apply_read_limits`], so reading more than that is pure waste. If the
/// `max_bytes` boundary splits a multibyte char, the partial trailing bytes are
/// trimmed to the last valid char boundary. A genuinely invalid-UTF-8 file that
/// fits within `max_bytes` still errors (mirrors the prior `read_to_string`).
///
/// Returns the decoded prefix and a flag set when the file was larger than
/// `max_bytes` (i.e. the read hit the cap) so the caller can surface a
/// truncation marker.
async fn read_bounded_string(
    file: std::fs::File,
    max_bytes: usize,
) -> RuntimeResult<(String, bool)> {
    let file = tokio::fs::File::from_std(file);
    let mut buf: Vec<u8> = Vec::with_capacity(max_bytes.min(8 * 1024));
    file.take(max_bytes as u64)
        .read_to_end(&mut buf)
        .await
        .map_err(RuntimeError::Io)?;
    // `read_full`: we read the whole file (didn't hit the cap) → any UTF-8
    // error is genuine and should surface, not be silently trimmed.
    let read_full = buf.len() < max_bytes;
    let truncated_at_cap = !read_full;
    match std::str::from_utf8(&buf) {
        Ok(s) => Ok((s.to_string(), truncated_at_cap)),
        Err(e) => {
            let vu = e.valid_up_to();
            if read_full {
                Err(RuntimeError::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "stream did not contain valid UTF-8",
                )))
            } else {
                // Hit the cap: trim the truncated multibyte suffix. `vu` is, by
                // definition, a valid char boundary, so `&buf[..vu]` is valid.
                Ok((
                    std::str::from_utf8(&buf[..vu])
                        .map(str::to_string)
                        .unwrap_or_default(),
                    truncated_at_cap,
                ))
            }
        }
    }
}

/// fd-anchored recursive glob descent. `dir` is an already-opened directory
/// (opened `O_NOFOLLOW` by the caller). The single-segment filename pattern
/// `fname_pat` (supporting `*`/`?`) is matched against every entry at every
/// depth under `dir`. Recursion into a subdirectory happens ONLY via
/// `openat(O_DIRECTORY | O_NOFOLLOW)` — that gate authoritatively refuses a
/// symlinked directory, so a symlink can never lead the walk out of the root.
/// `rel_prefix` is the path of `dir` relative to the session root ("" at the
/// base); results are accumulated as root-relative strings.
fn walk_glob_fd(
    mut dir: Dir,
    fname_pat: &str,
    rel_prefix: &str,
    out: &mut Vec<String>,
    limit: usize,
) -> RuntimeResult<()> {
    // Phase 1: drain entries into an owned vec. This ends the mutable borrow of
    // `dir` so phase 2 can take an immutable borrow for `dir.fd()` (needed to
    // openat children). `.`/`..` are skipped.
    let mut entries: Vec<(String, FileType)> = Vec::new();
    for res in &mut dir {
        match res {
            Ok(e) => {
                let name = e.file_name().to_string_lossy().into_owned();
                if name == "." || name == ".." {
                    continue;
                }
                entries.push((name, e.file_type()));
            }
            Err(e) => return Err(RuntimeError::Io(std::io::Error::from(e))),
        }
    }
    if out.len() >= limit {
        return Ok(());
    }
    // The parent fd for recursion (immutable borrow — no conflict with the
    // finished iterator).
    let parent_fd = dir
        .fd()
        .map_err(|e| RuntimeError::Io(std::io::Error::from(e)))?;
    for (name, ftype) in entries {
        if out.len() >= limit {
            return Ok(());
        }
        let rel = if rel_prefix.is_empty() {
            name.clone()
        } else {
            format!("{rel_prefix}/{name}")
        };
        if matches_glob(&name, fname_pat) {
            out.push(rel.clone());
        }
        // `is_dir()` is only a *hint* to attempt recursion; the authoritative
        // gate is the `openat(O_DIRECTORY | O_NOFOLLOW)` below — even if d_type
        // lies, a symlinked dir cannot be entered.
        if ftype.is_dir() {
            if let Ok(child_fd) = openat(
                parent_fd,
                name.as_str(),
                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
                Mode::empty(),
            ) {
                if let Ok(child_dir) = Dir::new(child_fd) {
                    walk_glob_fd(child_dir, fname_pat, &rel, out, limit)?;
                }
            }
            // openat/Dir failure (symlink, ENOTDIR, race, …) → skip, don't error.
        }
    }
    Ok(())
}

/// Single-segment glob (`*`/`?`) matcher. `**` is treated as `*` here.
fn matches_glob(name: &str, pat: &str) -> bool {
    let name_b = name.as_bytes();
    let pat_b = pat.as_bytes();
    matches_at(name_b, pat_b, 0, 0)
}

fn matches_at(n: &[u8], p: &[u8], mut ni: usize, mut pi: usize) -> bool {
    let mut star: Option<(usize, usize)> = None;
    while ni < n.len() {
        if pi < p.len() && (p[pi] == b'?' || p[pi] == b'*') {
            if p[pi] == b'*' {
                star = Some((pi, ni));
                pi += 1;
                continue;
            }
            pi += 1;
            ni += 1;
        } else if pi < p.len() && p[pi] == n[ni] {
            pi += 1;
            ni += 1;
        } else if let Some((sp, sn)) = star {
            pi = sp + 1;
            ni = sn + 1;
            star = Some((sp, sn + 1));
        } else {
            return false;
        }
    }
    while pi < p.len() && p[pi] == b'*' {
        pi += 1;
    }
    pi == p.len()
}

/// Validate a glob/grep search pattern/path is contained: reject absolute
/// paths and `..` components so the model can't reach outside the root.
///
/// Patterns may legitimately contain `*`/`?` (glob) — only path-structure
/// escapes are rejected.
fn validate_search_pattern(input: &str) -> RuntimeResult<()> {
    // Reject absolute paths.
    if input.starts_with('/') || input.starts_with('\\') {
        return Err(RuntimeError::Sandbox(format!(
            "absolute paths are not allowed: `{input}`"
        )));
    }
    // Reject any `..` path component. Walk segments, ignoring glob wildcards.
    for seg in input.split('/') {
        if seg == ".." {
            return Err(RuntimeError::Sandbox(format!(
                "`..` is not allowed in search paths: `{input}`"
            )));
        }
    }
    Ok(())
}

/// Quote a string for safe inclusion in a `sh -c` command.
fn shell_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

/// The minimal, safe environment re-applied to a model-run shell after
/// [`std::process::Command::env_clear`]. Carries only what commands need to
/// function — NOT provider API keys, tokens, or other secrets the parent holds.
/// Locale/timezone are passed through (set by the user's login shell) so command
/// output formatting matches the user's session. Keys are owned to avoid
/// per-call leaking.
fn safe_exec_env() -> Vec<(String, std::ffi::OsString)> {
    let mut out: Vec<(String, std::ffi::OsString)> = Vec::new();
    // Essentials for commands to run and find binaries.
    for name in ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "TMPDIR"] {
        if let Some(v) = std::env::var_os(name) {
            out.push((name.to_string(), v));
        }
    }
    // Locale/timezone (formatting only — no secrets). Use exact names plus the
    // `LC_` category prefix; a broad `LANG` prefix match would also pass secrets
    // like `LANGCHAIN_API_KEY`/`LANGFUSE_SECRET_KEY`, defeating `env_clear()`.
    for (k, v) in std::env::vars_os() {
        let key = k.to_string_lossy().into_owned();
        if matches!(key.as_str(), "TZ" | "LANG" | "LANGUAGE") || key.starts_with("LC_") {
            out.push((key, v));
        }
    }
    out
}

#[cfg(test)]
mod tests {
    //! Local sandbox path-containment and tool tests against a temp dir.

    use super::*;

    #[tokio::test]
    async fn read_file_within_root_works() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("hello.txt"), "hi there\n")
            .await
            .unwrap();
        let got = env
            .read_file(Path::new("hello.txt"), 100, 1024)
            .await
            .unwrap();
        assert_eq!(got, "hi there\n");
    }

    #[tokio::test]
    async fn read_file_rejects_absolute_path() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let res = env.read_file(Path::new("/etc/passwd"), 100, 1024).await;
        assert!(res.is_err(), "absolute paths must be rejected");
    }

    #[tokio::test]
    async fn read_file_rejects_parent_dir() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let res = env.read_file(Path::new("../escape.txt"), 100, 1024).await;
        assert!(res.is_err(), "`..` must be rejected");
    }

    #[tokio::test]
    async fn read_file_full_returns_complete_content_without_truncation() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        // 10 lines of 60 bytes each = 600 bytes, well under the default cap,
        // but above the *truncating* read's line/byte interplay. Ensure the
        // full-read path returns the whole file verbatim, with no marker.
        let body = (0..10)
            .map(|i| format!("line number {i:02} with some padding text\n"))
            .collect::<String>();
        tokio::fs::write(dir.path().join("big.txt"), &body)
            .await
            .unwrap();
        let got = env
            .read_file_full(Path::new("big.txt"), 1024)
            .await
            .unwrap();
        assert_eq!(got, body);
        assert!(!got.contains("[... truncated"));
    }

    #[tokio::test]
    async fn read_file_full_rejects_absolute_path() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let res = env.read_file_full(Path::new("/etc/passwd"), 1024).await;
        assert!(res.is_err(), "absolute paths must be rejected");
    }

    #[tokio::test]
    async fn read_file_full_rejects_parent_dir() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let res = env.read_file_full(Path::new("../escape.txt"), 1024).await;
        assert!(res.is_err(), "`..` must be rejected");
    }

    #[tokio::test]
    async fn read_file_full_errors_when_too_large_not_truncated() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        // 100 bytes, cap at 50 -> must ERROR (FileTooLarge), never return a
        // truncated prefix (the whole point vs `read_file`).
        tokio::fs::write(dir.path().join("over.txt"), &"a".repeat(100))
            .await
            .unwrap();
        let res = env.read_file_full(Path::new("over.txt"), 50).await;
        assert!(res.is_err(), "oversized file must error, not truncate");
        match res {
            Err(RuntimeError::FileTooLarge { size, max, .. }) => {
                assert_eq!(size, 100);
                assert_eq!(max, 50);
            }
            other => panic!("expected FileTooLarge, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn write_then_read_roundtrips() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        env.write_file(Path::new("sub/nested/file.txt"), "deep content")
            .await
            .unwrap();
        let got = env
            .read_file(Path::new("sub/nested/file.txt"), 100, 1024)
            .await
            .unwrap();
        assert_eq!(got, "deep content");
    }

    #[tokio::test]
    async fn read_file_bounded_read_does_not_oom_on_large_file() {
        // Regression for 0.5.2 bounded read: a file far larger than `max_bytes`
        // must be read bounded (not fully buffered) and truncated, without
        // erroring or OOMing. The old `read_to_string` of the whole file would
        // allocate the entire multi-MB body.
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        // 100 KB of ASCII, capped at 64 bytes. Only the first ~64 bytes are
        // returned (plus a truncation marker); nothing else is held in memory.
        let body = "a".repeat(100 * 1024);
        tokio::fs::write(dir.path().join("big.txt"), &body)
            .await
            .unwrap();
        let got = env
            .read_file(Path::new("big.txt"), 10_000, 64)
            .await
            .unwrap();
        assert!(
            got.contains("[... truncated at 64 bytes"),
            "expected a byte-cap truncation marker: {got:?}"
        );
        assert!(got.len() < 128, "output must be bounded near max_bytes");
    }

    #[tokio::test]
    async fn read_file_bounded_read_trims_multibyte_boundary() {
        // A multibyte char straddling the `max_bytes` cut must be trimmed to a
        // valid char boundary — no panic, no invalid UTF-8 in the output.
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        // Each `é` is 2 bytes (U+00E9, UTF-8 C3 A9). 10 of them = 20 bytes.
        // Capping at 11 bytes splits the 6th char; the trim drops its trailing
        // byte so the result is 5 chars (10 bytes).
        let body = "é".repeat(10);
        tokio::fs::write(dir.path().join("accent.txt"), body.as_bytes())
            .await
            .unwrap();
        let got = env
            .read_file(Path::new("accent.txt"), 10_000, 11)
            .await
            .unwrap();
        // The bounded prefix must be valid UTF-8 and contain only whole chars.
        assert!(
            got.starts_with("ééééé"),
            "trimmed prefix should be whole chars"
        );
    }

    #[tokio::test]
    async fn exec_runs_shell_command() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let res = env
            .exec(
                "echo hello",
                Path::new("."),
                None,
                &CancellationToken::new(),
            )
            .await
            .unwrap();
        assert_eq!(res.exit_code, 0);
        assert_eq!(res.stdout.trim(), "hello");
    }

    #[tokio::test]
    async fn exec_does_not_leak_parent_env_secrets() {
        // The model-run shell must NOT inherit provider keys / tokens from the
        // parent. We set a distinctive secret in the parent env, run `env` in the
        // child, and assert the secret is absent (env_clear + allowlist).
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        std::env::set_var("FLUERS_TEST_SECRET", "leak-me-if-you-can");
        let res = env
            .exec("env", Path::new("."), None, &CancellationToken::new())
            .await
            .unwrap();
        assert_eq!(res.exit_code, 0, "env should run");
        assert!(
            !res.stdout.contains("FLUERS_TEST_SECRET"),
            "parent env secret must not leak into the model-run shell"
        );
        assert!(
            !res.stdout.contains("leak-me-if-you-can"),
            "the secret value must not appear in the child env"
        );
        std::env::remove_var("FLUERS_TEST_SECRET");
    }

    #[tokio::test]
    async fn exec_does_not_leak_lang_prefixed_secrets() {
        // Regression: the locale allowlist once used `starts_with("LANG")`, which
        // also passed secrets like `LANGCHAIN_API_KEY` into the child. The
        // allowlist must match locale names exactly, not by `LANG` prefix.
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        std::env::set_var("LANGCHAIN_API_KEY", "lang-prefixed-secret");
        let res = env
            .exec("env", Path::new("."), None, &CancellationToken::new())
            .await
            .unwrap();
        std::env::remove_var("LANGCHAIN_API_KEY");
        assert!(
            !res.stdout.contains("LANGCHAIN_API_KEY"),
            "a LANG-prefixed secret must not leak into the model-run shell"
        );
        assert!(
            !res.stdout.contains("lang-prefixed-secret"),
            "the LANG-prefixed secret value must not appear in the child env"
        );
    }

    #[tokio::test]
    async fn exec_timeout_returns_124() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let res = env
            .exec(
                "sleep 5",
                Path::new("."),
                Some(200),
                &CancellationToken::new(),
            )
            .await
            .unwrap();
        assert_eq!(res.exit_code, 124, "timeout must yield exit 124");
    }

    #[test]
    fn glob_matcher_basics() {
        assert!(matches_glob("foo.txt", "*.txt"));
        assert!(matches_glob("foo.txt", "foo.*"));
        assert!(!matches_glob("foo.txt", "*.md"));
        assert!(matches_glob("a", "?"));
    }

    #[test]
    fn read_limit_truncates() {
        let got = apply_read_limits("a\nb\nc\nd\n".into(), 2, 1024);
        assert!(got.contains("a"));
        assert!(got.contains("b"));
        assert!(got.contains("truncated"));
    }

    #[tokio::test]
    async fn glob_rejects_absolute_pattern() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let res = env.glob("/etc/*", 10).await;
        assert!(res.is_err(), "absolute glob patterns must be rejected");
    }

    #[tokio::test]
    async fn glob_rejects_parent_dir_pattern() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let res = env.glob("../**/*", 10).await;
        assert!(res.is_err(), "`..` in glob patterns must be rejected");
    }

    #[tokio::test]
    async fn grep_rejects_absolute_path() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let res = env.grep("foo", &["/etc/passwd"], 10).await;
        assert!(res.is_err(), "absolute grep paths must be rejected");
    }

    #[tokio::test]
    async fn grep_rejects_parent_dir_path() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let res = env.grep("foo", &["../.env"], 10).await;
        assert!(res.is_err(), "`..` grep paths must be rejected");
    }

    // ── B-Swift Phase C1a / #4: fd-anchored read TOCTOU / hardlink coverage ──
    // These prove the fix: the OLD path-based `read_to_string(resolved)` followed
    // symlinks (leaking the target) and ignored `st_nlink`, so each of these
    // would have SUCCEEDED (exfiltrated the secret) before the fix.

    /// Write a secret to a file OUTSIDE the env root (a sibling temp dir) and
    /// return both the held `TempDir` (keep alive for the test) and its path.
    #[cfg(unix)]
    fn outside_secret(body: &str) -> (tempfile::TempDir, PathBuf) {
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("secret.txt");
        let mut f = std::fs::File::create(&path).unwrap();
        f.write_all(body.as_bytes()).unwrap();
        (dir, path)
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn read_file_rejects_symlink_leaf_even_when_target_inside_root() {
        use std::os::unix::fs::symlink;
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("inside.txt"), "ok\n")
            .await
            .unwrap();
        symlink("inside.txt", dir.path().join("link.txt")).unwrap();
        let res = env.read_file(Path::new("link.txt"), 100, 1024).await;
        assert!(
            res.is_err(),
            "a symlink leaf must be rejected even if its target is inside the root"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn read_file_rejects_symlink_leaf_to_outside_root() {
        // Exfil via symlink: link.txt -> /outside/secret. The OLD read followed
        // it and leaked "TOPSECRET"; the anchored `openat(O_NOFOLLOW)` rejects
        // the symlink leaf outright.
        use std::os::unix::fs::symlink;
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let (_outside, secret) = outside_secret("TOPSECRET");
        symlink(&secret, dir.path().join("link.txt")).unwrap();
        let res = env.read_file(Path::new("link.txt"), 100, 1024).await;
        assert!(
            res.is_err(),
            "a symlink to outside the root must be rejected"
        );
        if let Ok(s) = res {
            assert!(!s.contains("TOPSECRET"), "the secret must not leak");
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn read_file_rejects_intermediate_symlink_dir() {
        // Exfil via a symlinked intermediate dir: linkdir -> realdir; reading
        // `linkdir/file.txt` must reject at the `linkdir` component (per-component
        // `openat(O_NOFOLLOW)`).
        use std::os::unix::fs::symlink;
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        tokio::fs::create_dir_all(dir.path().join("realdir"))
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("realdir/file.txt"), "ok\n")
            .await
            .unwrap();
        symlink("realdir", dir.path().join("linkdir")).unwrap();
        let res = env
            .read_file(Path::new("linkdir/file.txt"), 100, 1024)
            .await;
        assert!(
            res.is_err(),
            "a symlinked intermediate dir must be rejected"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn read_file_rejects_hardlink_to_outside_secret() {
        // Hardlink exfil: `ln /outside/secret root/link.txt`. The file is regular
        // and inside the root, but `st_nlink > 1` → reject (mirrors the Swift
        // C2/#3 decision; authoritative here via post-open `fstat`).
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let (_outside, secret) = outside_secret("TOPSECRET");
        std::fs::hard_link(&secret, dir.path().join("link.txt")).unwrap();
        let res = env.read_file(Path::new("link.txt"), 100, 1024).await;
        assert!(res.is_err(), "a hardlink (st_nlink > 1) must be rejected");
        if let Ok(s) = res {
            assert!(!s.contains("TOPSECRET"), "the secret must not leak");
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn read_file_full_rejects_symlink_leaf() {
        use std::os::unix::fs::symlink;
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let (_outside, secret) = outside_secret("TOPSECRET");
        symlink(&secret, dir.path().join("link.txt")).unwrap();
        let res = env.read_file_full(Path::new("link.txt"), 1024).await;
        assert!(res.is_err(), "read_file_full must reject a symlink leaf");
        if let Ok(s) = res {
            assert!(!s.contains("TOPSECRET"));
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn read_file_full_rejects_hardlink() {
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let (_outside, secret) = outside_secret("TOPSECRET");
        std::fs::hard_link(&secret, dir.path().join("link.txt")).unwrap();
        let res = env.read_file_full(Path::new("link.txt"), 1024).await;
        assert!(
            res.is_err(),
            "read_file_full must reject a hardlink (st_nlink > 1)"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn read_anchored_nested_relative_path_still_works() {
        // Regression guard: the anchored walk must still read a real nested
        // file (intermediate dirs are opened `O_NOFOLLOW` + read off the leaf fd).
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        tokio::fs::create_dir_all(dir.path().join("a/b"))
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("a/b/c.txt"), "deep\n")
            .await
            .unwrap();
        let got = env
            .read_file(Path::new("a/b/c.txt"), 100, 1024)
            .await
            .unwrap();
        assert_eq!(got, "deep\n");
    }

    // ── B-Swift Phase C1b: fd-anchored write / exec / glob / grep TOCTOU ──
    // Each of these FAILED (or leaked) on the old path-based `resolve()` and
    // passes on the fd-anchored walk. The inside-target symlink cases are the
    // real TOCTOU proof: the OLD `resolve()` canonicalized a symlink whose
    // target was inside the root → passed containment → the subsequent path-
    // based op followed it. The fd-anchored walk rejects at `openat(NO_FOLLOW)`.

    #[cfg(unix)]
    #[tokio::test]
    async fn write_file_rejects_symlink_leaf_pointing_inside() {
        // OLD: resolve() canonicalized `link.txt` → inside `target.txt`
        // (contained) → `tokio::fs::write` followed the symlink and overwrote
        // the target. NEW: `openat(O_NOFOLLOW)` rejects the symlink leaf; the
        // inside target is untouched.
        use std::os::unix::fs::symlink;
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("target.txt"), "ORIGINAL")
            .await
            .unwrap();
        symlink("target.txt", dir.path().join("link.txt")).unwrap();
        let res = env.write_file(Path::new("link.txt"), "OVERWRITE").await;
        assert!(
            res.is_err(),
            "writing through a symlink leaf must be rejected"
        );
        let got = tokio::fs::read_to_string(dir.path().join("target.txt"))
            .await
            .unwrap();
        assert_eq!(
            got, "ORIGINAL",
            "the symlink target must not be overwritten"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn write_file_rejects_symlinked_intermediate_dir() {
        // OLD: resolve() canonicalized `linkdir/file.txt` through the symlink
        // (contained) → wrote through it. NEW: the mkdirat/openat walk rejects
        // the symlinked `linkdir` component.
        use std::os::unix::fs::symlink;
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        tokio::fs::create_dir_all(dir.path().join("realdir"))
            .await
            .unwrap();
        symlink("realdir", dir.path().join("linkdir")).unwrap();
        let res = env.write_file(Path::new("linkdir/file.txt"), "data").await;
        assert!(
            res.is_err(),
            "writing through a symlinked intermediate dir must be rejected"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn write_file_rejects_hardlink_to_outside_secret() {
        // OLD: resolve() canonicalized the inside link (contained) →
        // `tokio::fs::write` wrote through the shared inode → corrupted
        // /outside/secret. NEW: fstat off the open fd sees `st_nlink > 1` →
        // reject; the outside file is unchanged.
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let (_outside, secret) = outside_secret("ORIGINAL-SECRET");
        std::fs::hard_link(&secret, dir.path().join("link.txt")).unwrap();
        let res = env.write_file(Path::new("link.txt"), "CORRUPTED").await;
        assert!(
            res.is_err(),
            "writing a hardlink (st_nlink > 1) must be rejected"
        );
        let got = std::fs::read_to_string(&secret).unwrap();
        assert_eq!(
            got, "ORIGINAL-SECRET",
            "the outside secret must not be corrupted"
        );
    }

    #[tokio::test]
    async fn write_file_creates_new_nested_path() {
        // Regression: the mkdirat walk + leaf open must still create brand-new
        // nested files (the happy path must not regress).
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        env.write_file(Path::new("a/b/c/new.txt"), "deep")
            .await
            .unwrap();
        let got = env
            .read_file(Path::new("a/b/c/new.txt"), 100, 1024)
            .await
            .unwrap();
        assert_eq!(got, "deep");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn exec_rejects_symlinked_cwd_pointing_inside() {
        // OLD: resolve() canonicalized the symlinked cwd → inside dir
        // (contained) → the child ran there. NEW: open_anchored_dir rejects the
        // symlink at the openat component.
        use std::os::unix::fs::symlink;
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        tokio::fs::create_dir_all(dir.path().join("realcwd"))
            .await
            .unwrap();
        symlink("realcwd", dir.path().join("linkcwd")).unwrap();
        let res = env
            .exec(
                "echo hi",
                Path::new("linkcwd"),
                None,
                &CancellationToken::new(),
            )
            .await;
        assert!(res.is_err(), "a symlinked cwd must be rejected");
    }

    #[tokio::test]
    async fn exec_large_stdout_does_not_deadlock() {
        // Regression: `exec` used to `child.wait()` WITHOUT draining the stdout
        // pipe, so a child emitting more than the OS pipe buffer (~64 KB) blocked
        // on a full pipe while `wait()` blocked on the child — a deadlock. With no
        // timeout set (as here) the old code hung forever; `wait_with_output` now
        // drains both pipes concurrently, so the full output returns intact.
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let res = env
            .exec(
                "yes a | head -c 200000",
                Path::new("."),
                None,
                &CancellationToken::new(),
            )
            .await
            .unwrap();
        assert_eq!(res.exit_code, 0);
        assert_eq!(
            res.stdout.len(),
            200_000,
            "full >64 KB stdout must survive without deadlock"
        );
    }

    #[tokio::test]
    async fn glob_returns_matching_files() {
        // Regression for the fd-anchored rewrite: it must still surface real
        // files at the base and nested under real subdirectories.
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("top.txt"), "x")
            .await
            .unwrap();
        tokio::fs::create_dir_all(dir.path().join("sub"))
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("sub/nested.txt"), "x")
            .await
            .unwrap();
        let matched = env.glob("*.txt", 100).await.unwrap();
        assert!(
            matched.iter().any(|m| m == "top.txt"),
            "base file should match: {matched:?}"
        );
        assert!(
            matched.iter().any(|m| m == "sub/nested.txt"),
            "nested file should match: {matched:?}"
        );
    }

    #[tokio::test]
    async fn glob_subdir_pattern_reports_root_relative_paths() {
        // Regression for the base-prefix bug: a pattern with a subdir base must
        // report paths relative to the ROOT, not relative to the base.
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        tokio::fs::create_dir_all(dir.path().join("sub"))
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("sub/nested.txt"), "x")
            .await
            .unwrap();
        let matched = env.glob("sub/*.txt", 100).await.unwrap();
        assert!(
            matched.iter().any(|m| m == "sub/nested.txt"),
            "must be root-relative (`sub/nested.txt`), not base-relative: {matched:?}"
        );
        assert!(
            !matched.iter().any(|m| m == "nested.txt"),
            "base-relative leak must not happen: {matched:?}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn glob_does_not_traverse_symlinked_dir_to_outside() {
        // OLD glob's `path.is_dir()` FOLLOWED the symlink → recursed into the
        // outside dir → leaked its `.txt`. NEW: descent is via
        // `openat(O_DIRECTORY|O_NOFOLLOW)` → the symlinked dir is never entered.
        use std::os::unix::fs::symlink;
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("inside.txt"), "ok")
            .await
            .unwrap();
        tokio::fs::create_dir_all(dir.path().join("realdir"))
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("realdir/nested.txt"), "ok")
            .await
            .unwrap();
        // A symlinked dir pointing at the outside temp dir (which holds
        // `secret.txt`).
        let (_outside, secret) = outside_secret("OUTSIDE-SECRET");
        let outside_dir = secret.parent().unwrap();
        symlink(outside_dir, dir.path().join("linkdir")).unwrap();
        let matched = env.glob("*.txt", 100).await.unwrap();
        assert!(
            matched.iter().any(|m| m == "inside.txt"),
            "inside file should match: {matched:?}"
        );
        assert!(
            matched.iter().any(|m| m == "realdir/nested.txt"),
            "real nested file should match: {matched:?}"
        );
        assert!(
            !matched.iter().any(|m| m.starts_with("linkdir")),
            "symlinked dir must not be traversed: {matched:?}"
        );
        for m in &matched {
            assert!(
                !m.contains("secret.txt") && !m.contains("OUTSIDE-SECRET"),
                "outside file must not leak: {m}"
            );
        }
    }

    #[tokio::test]
    async fn grep_returns_matches() {
        // Regression for the inode-anchored search: it must still surface real
        // matches inside the root, AND the output must be root-relative (not the
        // absolute host temp/root path, which the inode-path search would
        // otherwise leak).
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("note.md"), "findme here\n")
            .await
            .unwrap();
        let matched = env.grep("findme", &["."], 100).await.unwrap();
        assert!(
            matched.iter().any(|m| m.contains("findme")),
            "expected a match: {matched:?}"
        );
        // Output paths are root-relative...
        assert!(
            matched.iter().any(|m| m.starts_with("note.md:")),
            "expected a root-relative `note.md:` line: {matched:?}"
        );
        // ...and must NOT leak the host temp/root path.
        let root_str = dir.path().to_string_lossy().into_owned();
        for m in &matched {
            assert!(
                !m.contains(&root_str),
                "grep output must not leak the absolute root path: {m}"
            );
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn grep_rejects_symlinked_search_path() {
        // `rg --no-follow` still follows a symlinked dir passed EXPLICITLY as a
        // search path, so the path is resolved fd-anchored to its inode and a
        // symlink is rejected outright (no leak via `linkdir -> outside`).
        use std::os::unix::fs::symlink;
        let dir = tempfile::tempdir().unwrap();
        let env = LocalSessionEnv::new(dir.path(), Limits::default())
            .await
            .unwrap();
        let (_outside, secret) = outside_secret("GREP-LEAK");
        let outside_dir = secret.parent().unwrap();
        symlink(outside_dir, dir.path().join("linkdir")).unwrap();
        // Explicit symlinked path → rejected (Err), never searched.
        let res = env.grep("GREP-LEAK", &["linkdir"], 100).await;
        assert!(
            res.is_err(),
            "an explicit symlinked search path must be rejected"
        );
        // And a `.` search must not traverse the symlinked dir either.
        let matched = env.grep("GREP-LEAK", &["."], 100).await.unwrap();
        assert!(
            matched.is_empty(),
            "the symlinked dir must not be traversed: {matched:?}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn grep_anchors_to_root_fd_not_root_path() {
        // TOCTOU for grep: after the env is built, move the real root aside and
        // replace the root *path* with a symlink to an outside dir holding a
        // secret. OLD grep used `current_dir(self.root)` (the path) → would
        // chdir through the symlink and surface the secret. NEW grep anchors to
        // `/dev/fd/{root_fd}` → chdir to the real (moved) root → no leak.
        use std::os::unix::fs::symlink;
        // A parent dir we fully control (manual, not TempDir, so the swap + the
        // symlink-over-root don't confuse Drop cleanup).
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let parent = std::env::temp_dir().join(format!("fluers-grep-swap-{nonce}"));
        std::fs::create_dir_all(&parent).unwrap();
        let root_path = parent.join("root");
        std::fs::create_dir_all(&root_path).unwrap();
        let env = LocalSessionEnv::new(&root_path, Limits::default())
            .await
            .unwrap();

        let outside = parent.join("outside");
        std::fs::create_dir_all(&outside).unwrap();
        std::fs::write(outside.join("leak.txt"), "PATHSWAP-SECRET\n").unwrap();

        // Swap: move the real root aside (sibling), then symlink the root path
        // → outside.
        let moved = parent.join("moved-real-root");
        std::fs::rename(&root_path, &moved).unwrap();
        symlink(&outside, &root_path).unwrap();

        let matched = env.grep("PATHSWAP-SECRET", &["."], 100).await.unwrap();
        assert!(
            matched.is_empty(),
            "root-fd anchoring must not follow the swapped root path: {matched:?}"
        );

        // We own `parent` fully — clean up everything under it.
        let _ = std::fs::remove_dir_all(&parent);
    }

    // ── WP-2: ProcessSandbox backend slot ───────────────────────────────────
    //
    // These tests exercise the *shape* only: a mock `ProcessSandbox` proves
    // wrap is applied at BOTH spawn sites, fail-closed fires on Refuse+Partial,
    // and backend-injected env survives into the child. No real backend ships.

    use crate::process_sandbox::{
        Enforcement, ExecSandboxContext, OnUnavailable, ProcessSandbox, SandboxPolicy,
        SandboxProfile, WrappedCommand,
    };
    use crate::sandbox::Sandbox;
    use std::collections::BTreeMap;
    use std::sync::Mutex;

    /// A mock `ProcessSandbox` that records every wrapped argv, optionally
    /// injects an env var, and reports a configurable `Enforcement`.
    struct MockProcessSandbox {
        enforcement: Enforcement,
        /// Every argv handed to `wrap`, recorded in order.
        wraps: Arc<Mutex<Vec<Vec<String>>>>,
        /// Env additions to inject on every wrap (proves env survives env_clear).
        inject_env: BTreeMap<String, String>,
        prepare_calls: Arc<Mutex<u32>>,
        /// The canonical workspace_path `prepare` saw (proves the backend gets
        /// the same absolute root LocalSessionEnv anchors on).
        prepared_workspace: Arc<Mutex<Option<PathBuf>>>,
    }

    impl MockProcessSandbox {
        fn new(enforcement: Enforcement) -> Self {
            Self {
                enforcement,
                wraps: Arc::new(Mutex::new(Vec::new())),
                inject_env: BTreeMap::new(),
                prepare_calls: Arc::new(Mutex::new(0)),
                prepared_workspace: Arc::new(Mutex::new(None)),
            }
        }

        fn with_env(mut self, env: BTreeMap<String, String>) -> Self {
            self.inject_env = env;
            self
        }
    }

    #[async_trait::async_trait]
    impl ProcessSandbox for MockProcessSandbox {
        async fn prepare(&self, ctx: &ExecSandboxContext) -> RuntimeResult<()> {
            *self.prepare_calls.lock().unwrap() += 1;
            *self.prepared_workspace.lock().unwrap() = Some(ctx.workspace_path.clone());
            Ok(())
        }
        fn wrap(
            &self,
            argv: &[String],
            _ctx: &ExecSandboxContext,
        ) -> RuntimeResult<WrappedCommand> {
            self.wraps.lock().unwrap().push(argv.to_vec());
            Ok(WrappedCommand {
                argv: argv.to_vec(),
                env: self.inject_env.clone(),
            })
        }
        async fn probe(&self, _profile: &SandboxProfile) -> RuntimeResult<Enforcement> {
            Ok(self.enforcement)
        }
        async fn shutdown(&self) -> RuntimeResult<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn wrap_is_applied_at_both_spawn_sites() {
        // A backend that reports FullDev-FullyEnforced; record every wrap.
        let dir = tempfile::tempdir().unwrap();
        let mock = Arc::new(MockProcessSandbox::new(Enforcement::FullyEnforced));
        let wraps = Arc::clone(&mock.wraps);
        let sandbox = crate::LocalSandbox::new(dir.path().to_path_buf()).with_exec_sandbox(
            mock,
            SandboxPolicy {
                profile: SandboxProfile::FullDev,
                egress: Vec::new(),
                on_unavailable: OnUnavailable::Degrade,
            },
        );
        let env = sandbox.env_for(dir.path()).await.unwrap();

        // Trigger the exec spawn site.
        env.exec(
            "true",
            Path::new("."),
            None,
            &tokio_util::sync::CancellationToken::new(),
        )
        .await
        .unwrap();
        // Trigger the grep spawn site (needs a file to exist).
        tokio::fs::write(dir.path().join("needle.txt"), "secret\n")
            .await
            .unwrap();
        env.grep("secret", &["."], 10).await.unwrap();

        let recorded = wraps.lock().unwrap().clone();
        assert_eq!(
            recorded.len(),
            2,
            "wrap must be called at BOTH spawn sites; got {recorded:?}"
        );
        // Each wrap target is `sh -c <...>`.
        for argv in &recorded {
            assert_eq!(argv.first().map(String::as_str), Some("sh"));
            assert_eq!(argv.get(1).map(String::as_str), Some("-c"));
        }
    }

    #[tokio::test]
    async fn refuse_policy_with_partial_probe_errors_at_session_construction() {
        // Backend reports Partial; policy is Refuse ⇒ env_for must fail loud,
        // before any command runs.
        let dir = tempfile::tempdir().unwrap();
        let mock = Arc::new(MockProcessSandbox::new(Enforcement::Partial));
        let sandbox = crate::LocalSandbox::new(dir.path().to_path_buf()).with_exec_sandbox(
            mock,
            SandboxPolicy {
                profile: SandboxProfile::ReadOnly,
                egress: Vec::new(),
                on_unavailable: OnUnavailable::Refuse,
            },
        );
        let result = sandbox.env_for(dir.path()).await;
        let msg = match result {
            Ok(_) => panic!("Refuse + Partial must fail-closed at env_for; got Ok"),
            Err(e) => format!("{e:?}"),
        };
        assert!(
            msg.contains("Refuse"),
            "error must explain the refuse decision: {msg}"
        );
    }

    #[tokio::test]
    async fn wrap_injected_env_survives_into_child() {
        // The mock injects FLUERS_SANDBOX_MARKER=ok. After env_clear + the safe
        // allowlist, the child must still see it (proving C1: wrap env survives).
        let dir = tempfile::tempdir().unwrap();
        let mut env = BTreeMap::new();
        env.insert("FLUERS_SANDBOX_MARKER".into(), "ok".into());
        let mock = Arc::new(MockProcessSandbox::new(Enforcement::FullyEnforced).with_env(env));
        let sandbox = crate::LocalSandbox::new(dir.path().to_path_buf()).with_exec_sandbox(
            mock,
            SandboxPolicy {
                profile: SandboxProfile::FullDev,
                egress: Vec::new(),
                on_unavailable: OnUnavailable::Degrade,
            },
        );
        let env = sandbox.env_for(dir.path()).await.unwrap();
        let res = env
            .exec(
                "printf '%s' \"$FLUERS_SANDBOX_MARKER\"",
                Path::new("."),
                None,
                &tokio_util::sync::CancellationToken::new(),
            )
            .await
            .unwrap();
        assert_eq!(
            res.exit_code, 0,
            "marker print must succeed; stderr:\n{}",
            res.stderr
        );
        assert_eq!(
            res.stdout, "ok",
            "wrap-injected env must survive env_clear into the child; got stdout:\n{}",
            res.stdout
        );
    }

    #[tokio::test]
    async fn degrade_with_unavailable_drops_the_backend() {
        // HIGH-1 (red-team): Unavailable + Degrade must DROP the backend and
        // fall back to fd-anchored containment (no prepare, no wrap calls).
        // The mock records wraps; none must be recorded after env_for + an exec.
        let dir = tempfile::tempdir().unwrap();
        let mock = Arc::new(MockProcessSandbox::new(Enforcement::Unavailable));
        let wraps = Arc::clone(&mock.wraps);
        let prepare_calls = Arc::clone(&mock.prepare_calls);
        let sandbox = crate::LocalSandbox::new(dir.path().to_path_buf()).with_exec_sandbox(
            mock,
            SandboxPolicy {
                profile: SandboxProfile::ReadOnly,
                egress: Vec::new(),
                on_unavailable: OnUnavailable::Degrade,
            },
        );
        let env = sandbox.env_for(dir.path()).await.unwrap();
        // The session built (Degrade accepted the unavailable backend by
        // dropping it), so a subsequent exec must NOT go through wrap.
        env.exec(
            "true",
            Path::new("."),
            None,
            &tokio_util::sync::CancellationToken::new(),
        )
        .await
        .unwrap();
        assert_eq!(
            *prepare_calls.lock().unwrap(),
            0,
            "Unavailable+Degrade must not call prepare (backend dropped)"
        );
        assert!(
            wraps.lock().unwrap().is_empty(),
            "Unavailable+Degrade must not wrap any command (backend dropped)"
        );
    }

    #[tokio::test]
    async fn active_backend_creates_missing_root_and_passes_canonical_path() {
        // Regression (advisor): the active-backend path canonicalizes the root
        // before building the env. `LocalSessionEnv::new` creates a missing
        // root; the backend path MUST match that parity (create-then-canonicalize)
        // so a non-existent root doesn't fail env_for. And `prepare` must see the
        // SAME canonical absolute path the env anchors on.
        let dir = tempfile::tempdir().unwrap();
        let missing_root = dir.path().join("does-not-exist-yet");
        let mock = Arc::new(MockProcessSandbox::new(Enforcement::FullyEnforced));
        let prepared = Arc::clone(&mock.prepared_workspace);
        let sandbox = crate::LocalSandbox::new(missing_root.clone()).with_exec_sandbox(
            mock,
            SandboxPolicy {
                profile: SandboxProfile::FullDev,
                egress: Vec::new(),
                on_unavailable: OnUnavailable::Degrade,
            },
        );
        // Must succeed (root created), not error on a missing root.
        let env = sandbox.env_for(&missing_root).await.unwrap();
        let prepared_path = prepared.lock().unwrap().clone();
        assert!(
            prepared_path.is_some(),
            "prepare must have been called with a workspace_path"
        );
        let prepared_path = prepared_path.unwrap();
        assert!(
            prepared_path.is_absolute(),
            "prepare must see a canonical ABSOLUTE workspace path; got {prepared_path:?}"
        );
        // The root now exists on disk (created by env_for).
        assert!(
            missing_root.exists(),
            "active-backend path must create the missing root (parity with new)"
        );
        // A command runs (the env is usable).
        env.exec(
            "true",
            Path::new("."),
            None,
            &tokio_util::sync::CancellationToken::new(),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn wrap_injected_env_survives_into_grep_child() {
        // MEDIUM-2 (red-team): prove backend-injected env reaches the GREP
        // child specifically (grep has no env_clear, unlike exec). The previous
        // version of this test was a false positive (it materialized the marker
        // via exec then grepped a literal). Instead: a mock that REWRITES argv
        // to `test "$VAR" = VAL && exec "$@" <original argv...>` so the child
        // verifies its own env before running the real grep. If the env var is
        // absent, the `test` fails, the child exits before grep, and the result
        // is empty.
        let dir = tempfile::tempdir().unwrap();
        tokio::fs::write(dir.path().join("needle.txt"), "findme\n")
            .await
            .unwrap();
        let mock = Arc::new(CheckingEnvMock::new("FLUERS_GREP_MARKER", "GREP_OK"));
        let sandbox = crate::LocalSandbox::new(dir.path().to_path_buf()).with_exec_sandbox(
            mock,
            SandboxPolicy {
                profile: SandboxProfile::FullDev,
                egress: Vec::new(),
                on_unavailable: OnUnavailable::Degrade,
            },
        );
        let env = sandbox.env_for(dir.path()).await.unwrap();
        let matches = env.grep("findme", &["needle.txt"], 10).await.unwrap();
        assert!(
            !matches.is_empty(),
            "grep child must see the backend-injected marker env (the \
             `test` guard would have exited before grep otherwise); got {matches:?}"
        );
    }

    /// A `ProcessSandbox` that asserts a specific env var is present in every
    /// wrapped child before execing the original argv. Used by the grep
    /// env-propagation test: the wrap rewrites argv to
    /// `sh -c 'test "$VAR" = VAL && exec "$@"' -- <original argv...>`, so the
    /// child checks its OWN env; if the backend-injected var didn't survive to
    /// the spawn, `test` fails and the original command never runs.
    struct CheckingEnvMock {
        var: String,
        val: String,
        prepare_calls: Arc<Mutex<u32>>,
    }

    impl CheckingEnvMock {
        fn new(var: &str, val: &str) -> Self {
            Self {
                var: var.into(),
                val: val.into(),
                prepare_calls: Arc::new(Mutex::new(0)),
            }
        }
    }

    #[async_trait::async_trait]
    impl ProcessSandbox for CheckingEnvMock {
        async fn prepare(&self, _ctx: &ExecSandboxContext) -> RuntimeResult<()> {
            *self.prepare_calls.lock().unwrap() += 1;
            Ok(())
        }
        fn wrap(
            &self,
            argv: &[String],
            _ctx: &ExecSandboxContext,
        ) -> RuntimeResult<WrappedCommand> {
            // Rewrite to: sh -c 'test "$VAR" = VAL && exec "$@"' -- <argv...>
            let guard = format!("test \"${}\" = {} && exec \"$@\"", self.var, self.val);
            let mut wrapped = vec!["sh".to_string(), "-c".to_string(), guard, "--".to_string()];
            wrapped.extend(argv.iter().cloned());
            let mut env = BTreeMap::new();
            env.insert(self.var.clone(), self.val.clone());
            Ok(WrappedCommand { argv: wrapped, env })
        }
        async fn probe(&self, _profile: &SandboxProfile) -> RuntimeResult<Enforcement> {
            Ok(Enforcement::FullyEnforced)
        }
        async fn shutdown(&self) -> RuntimeResult<()> {
            Ok(())
        }
    }
}