leviath-tools 0.3.10

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

use leviath_core::resolves_within;
use leviath_providers::Tool;
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet};
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use tokio::process::Command;
use tokio::time::{Duration, timeout};

// The tool families, one module per concern; lib.rs keeps the struct and
// its constructors.
mod context;
mod defs;
mod exec;
pub use exec::is_null_device;
mod platform;
pub mod validate;
pub use context::*;
pub use defs::{SUBAGENT_TOOLS, is_subagent_tool, submit_output_description};
pub use platform::*;
pub use validate::*;

/// The tool an agent calls to hand back the run's final output.
///
/// Re-exported from `leviath-core`, which owns the name because the blueprint
/// validator and the manifest parser both need it and neither may depend on
/// this crate.
pub use leviath_core::blueprint::SUBMIT_OUTPUT_TOOL;

/// Built-in tools: read_file, write_file, edit_file, list_dir, shell.
///
/// Carries the [`PlatformCapabilities`] of the current platform; tools whose
/// [`tool_required_capabilities`] aren't satisfied are dropped from
/// [`tool_defs`](Self::tool_defs), [`names`](Self::names), and rejected by
/// [`execute`](Self::execute).
pub struct BuiltinTools {
    ctx: ToolContext,
    platform: PlatformCapabilities,
    /// When set, shell commands run through this sandbox instead of the host.
    shell_executor: Option<Arc<dyn ShellExecutor>>,
}

impl BuiltinTools {
    /// Create a new BuiltinTools instance with the given sandbox context,
    /// filtering tools against the current platform's capabilities.
    pub fn new(ctx: ToolContext) -> Self {
        Self {
            ctx,
            platform: PlatformCapabilities::current(),
            shell_executor: None,
        }
    }

    /// The directory every path these tools resolve is confined to, already
    /// canonicalized.
    ///
    /// Exposed so the authorization layer can hold a *shell redirect* to the
    /// same fence `resolve` already holds `write_file` to. Without it the two
    /// disagree, and `> path` becomes the spelling of `write_file` that works.
    ///
    /// Canonical rather than as-supplied, because that is what the fence
    /// compares against: on macOS a `/var/...` workdir resolves to
    /// `/private/var/...`, and handing out the former would refuse every write
    /// in the workspace.
    pub fn workdir(&self) -> &Path {
        &self.ctx.workdir
    }

    /// Route this agent's shell execution through `executor` (a container /
    /// namespace sandbox) instead of the host.
    pub fn with_shell_executor(mut self, executor: Arc<dyn ShellExecutor>) -> Self {
        self.shell_executor = Some(executor);
        self
    }

    /// Create a BuiltinTools instance with an explicit platform capability set,
    /// for tests or hosts that need to override the compile-time default.
    pub fn with_capabilities(ctx: ToolContext, platform: PlatformCapabilities) -> Self {
        Self {
            ctx,
            platform,
            shell_executor: None,
        }
    }

    /// Whether a built-in named `canonical_name` is available on this platform.
    fn available(&self, canonical_name: &str) -> bool {
        self.platform
            .satisfies(tool_required_capabilities(canonical_name))
    }
}

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

    fn make_tools(dir: &std::path::Path) -> BuiltinTools {
        BuiltinTools::new(ToolContext::new(dir.to_path_buf()))
    }

    /// The accessor the authorization layer holds shell redirects against, so
    /// `> path` answers to the same fence `resolve` holds `write_file` to.
    ///
    /// It reports the *canonicalized* directory, which is the point rather than
    /// an accident: `resolves_within` canonicalizes what it is given, so a
    /// workdir that came back uncanonicalized would compare `/var/...` against
    /// `/private/var/...` on macOS and refuse every write in the workspace.
    #[test]
    fn workdir_reports_the_canonical_directory_the_tools_were_built_over() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let canonical = std::fs::canonicalize(dir.path()).unwrap();
        assert_eq!(tools.workdir(), canonical);
        // And it really is inside itself by the predicate the fence uses, which
        // is the property the accessor exists to serve.
        assert!(leviath_core::resolves_within(
            &tools.workdir().join("out.txt"),
            tools.workdir()
        ));
    }

    /// Built-ins over a mobile capability set (no `ProcessSpawn`), so the
    /// `shell` tool and its `bash` alias are filtered out.
    fn make_mobile_tools(dir: &std::path::Path) -> BuiltinTools {
        BuiltinTools::with_capabilities(
            ToolContext::new(dir.to_path_buf()),
            PlatformCapabilities::mobile(),
        )
    }

    #[test]
    fn the_shell_tool_advertises_the_shell_this_host_resolved() {
        // Whichever shell the host has, the description has to name *it*: a
        // model that reads "cmd" and gets zsh (or the reverse) writes the wrong
        // commands, which is exactly the failure this replaced.
        let dir = tempfile::tempdir().unwrap();
        let defs = make_tools(dir.path()).tool_defs();
        let shell = defs
            .iter()
            .find(|t| t.name == "shell")
            .expect("shell is advertised on a desktop capability set");
        let (resolved, _) = BuiltinTools::detect_shell();
        assert!(
            shell.description.contains(resolved),
            "description {:?} does not name the resolved shell {resolved:?}",
            shell.description
        );

        // Both platforms' wordings, without needing to run on both.
        assert!(crate::defs::shell_tool_description("cmd.exe").contains("`cmd.exe`"));
        assert!(crate::defs::shell_tool_description("/bin/zsh").contains("`/bin/zsh`"));
    }

    #[test]
    fn subagent_predicate_covers_the_five_names_and_nothing_else() {
        for name in SUBAGENT_TOOLS {
            assert!(is_subagent_tool(name));
        }
        assert!(!is_subagent_tool("read_file"));
    }

    // ── Tool definitions ──────────────────────────────────────────────────

    #[test]
    fn tool_defs_returns_twenty_tools() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let defs = tools.tool_defs();
        assert_eq!(defs.len(), 20);
    }

    #[test]
    fn tool_defs_names_are_correct() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let names: Vec<String> = tools.tool_defs().iter().map(|t| t.name.clone()).collect();
        assert!(names.contains(&"read_file".to_string()));
        assert!(names.contains(&"read_files".to_string()));
        assert!(names.contains(&"write_file".to_string()));
        assert!(names.contains(&"edit_file".to_string()));
        assert!(names.contains(&"list_dir".to_string()));
        assert!(names.contains(&"shell".to_string()));
        assert!(names.contains(&"present_for_review".to_string()));
        assert!(names.contains(&"ask_user_text".to_string()));
        assert!(names.contains(&"ask_user_choice".to_string()));
        assert!(names.contains(&"ask_user_confirm".to_string()));
        assert!(names.contains(&"edit_document".to_string()));
        assert!(names.contains(&"context_write".to_string()));
        assert!(names.contains(&"context_append".to_string()));
        assert!(names.contains(&"context_read".to_string()));
        assert!(names.contains(&"context_delete".to_string()));
        assert!(names.contains(&"context_list".to_string()));
    }

    #[test]
    fn tool_defs_edit_document_requires_content() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let def = tools
            .tool_defs()
            .into_iter()
            .find(|t| t.name == "edit_document")
            .expect("edit_document tool def must exist");
        let required = def.parameters["required"].as_array().unwrap();
        assert!(required.iter().any(|v| v == "content"));
        assert_eq!(def.parameters["properties"]["content"]["type"], "string");
        // Also present in the builtin name list.
        assert!(tools.names().contains(&"edit_document".to_string()));
    }

    #[test]
    fn tool_defs_ask_user_choice_has_options_array() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let def = tools
            .tool_defs()
            .into_iter()
            .find(|t| t.name == "ask_user_choice")
            .unwrap();
        let required = def.parameters["required"].as_array().unwrap();
        assert!(required.iter().any(|v| v == "prompt"));
        assert!(required.iter().any(|v| v == "options"));
        assert_eq!(def.parameters["properties"]["options"]["type"], "array");
    }

    #[tokio::test]
    async fn context_tools_return_runtime_error() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        for name in [
            "context_write",
            "context_append",
            "context_read",
            "context_delete",
            "context_list",
        ] {
            let result = tools.execute(name, serde_json::json!({})).await;
            assert!(result.contains("context tools must be handled by the runtime"));
        }
    }

    /// `submit_output` writes an ECS component and a context region, neither of
    /// which the built-in executor can reach. Refused here so the runtime stays
    /// the only path that can record an answer: a second path would let a
    /// submission land somewhere no consumer reads.
    #[tokio::test]
    async fn submit_output_is_not_handled_by_builtin_execute() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let result = tools
            .execute(
                crate::SUBMIT_OUTPUT_TOOL,
                serde_json::json!({"content": "the answer"}),
            )
            .await;
        assert!(
            result.contains("submit_output must be handled by the runtime"),
            "{result}"
        );
    }

    /// The description is the whole mechanism for arbitrary formats, so a stage
    /// that declares nothing gets the generic wording rather than an invented
    /// sentence about a format nobody asked for.
    #[test]
    fn the_submit_description_carries_a_declared_shape_and_nothing_otherwise() {
        let generic = submit_output_description("");
        assert!(generic.contains("artifacts"), "{generic}");
        assert!(!generic.contains("a2ui"));

        let shaped = submit_output_description("Return it in this format: a2ui.");
        assert!(shaped.starts_with(&generic), "the generic part is kept");
        assert!(shaped.ends_with("Return it in this format: a2ui."));
    }

    #[tokio::test]
    async fn ask_user_tools_not_handled_by_builtin_execute() {
        // ask_user_* tools are intercepted upstream (worker.rs/foreground.rs),
        // exactly like present_for_review - execute() must never run them.
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        for name in [
            "ask_user_text",
            "ask_user_choice",
            "ask_user_confirm",
            "edit_document",
        ] {
            let result = tools.execute(name, serde_json::json!({})).await;
            assert!(result.contains("Unknown built-in tool"));
        }
    }

    #[test]
    fn context_tool_descriptions_mention_key_concepts() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let defs = tools.tool_defs();

        let write_def = defs.iter().find(|t| t.name == "context_write").unwrap();
        assert!(
            write_def.description.contains("system prompt"),
            "context_write should mention system prompt: {}",
            write_def.description
        );
        assert!(
            write_def.description.contains("replaced"),
            "context_write should mention replacement: {}",
            write_def.description
        );

        let read_def = defs.iter().find(|t| t.name == "context_read").unwrap();
        assert!(
            read_def.description.contains("summary"),
            "context_read should mention summary: {}",
            read_def.description
        );

        let list_def = defs.iter().find(|t| t.name == "context_list").unwrap();
        assert!(
            list_def.description.contains("token"),
            "context_list should mention tokens: {}",
            list_def.description
        );

        let append_def = defs.iter().find(|t| t.name == "context_append").unwrap();
        assert!(
            append_def.description.contains("without replacing"),
            "context_append should mention 'without replacing': {}",
            append_def.description
        );
    }

    fn assert_has_description(name: &str, description: &str) {
        assert!(
            !description.is_empty(),
            "tool {} has empty description",
            name
        );
    }

    fn assert_has_object_params(name: &str, params: &serde_json::Value) {
        assert!(params.is_object(), "tool {} has non-object params", name);
    }

    #[test]
    fn tool_defs_have_descriptions() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        for def in tools.tool_defs() {
            assert_has_description(&def.name, &def.description);
        }
    }

    #[test]
    #[should_panic(expected = "tool bogus has empty description")]
    fn tool_defs_have_descriptions_panics_on_empty_description() {
        assert_has_description("bogus", "");
    }

    #[test]
    fn tool_defs_have_parameters() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        for def in tools.tool_defs() {
            assert_has_object_params(&def.name, &def.parameters);
        }
    }

    #[test]
    #[should_panic(expected = "tool bogus has non-object params")]
    fn tool_defs_have_parameters_panics_on_non_object_params() {
        assert_has_object_params("bogus", &serde_json::Value::Null);
    }

    // ── names() ───────────────────────────────────────────────────────────

    #[test]
    fn names_includes_bash_alias() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let names = tools.names();
        assert!(names.contains(&"bash".to_string()));
        assert!(names.contains(&"shell".to_string()));
    }

    /// Policy is matched against the name the model calls, which is always
    /// canonical, while the writer of a config may have picked either spelling.
    /// Both have to find each other, or a `bash` entry is dead.
    #[test]
    fn tool_name_spellings_covers_both_directions_without_repeating() {
        fn of(n: &str) -> Vec<&str> {
            tool_name_spellings(n).collect()
        }
        assert_eq!(of("shell"), ["shell", "bash"]);
        assert_eq!(of("bash"), ["bash", "shell"]);
        // A name with no alias yields itself once, not twice.
        assert_eq!(of("read_file"), ["read_file"]);
        assert_eq!(of("linear__search"), ["linear__search"]);
    }

    #[test]
    fn canonical_tool_name_resolves_aliases_and_passes_others_through() {
        // An alias resolves to its canonical name.
        assert_eq!(canonical_tool_name("bash"), "shell");
        // A canonical built-in is unchanged.
        assert_eq!(canonical_tool_name("shell"), "shell");
        assert_eq!(canonical_tool_name("read_file"), "read_file");
        // An unknown name (e.g. an MCP tool whose server may not be installed)
        // passes through untouched, so it is matched/omitted as-is.
        assert_eq!(canonical_tool_name("acme__do_thing"), "acme__do_thing");
        // Every alias in the table round-trips to a real canonical name.
        for (alias, canonical) in TOOL_ALIASES {
            assert_eq!(canonical_tool_name(alias), *canonical);
        }
    }

    #[test]
    fn names_returns_twenty_one_entries() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        assert_eq!(tools.names().len(), 21);
    }

    // ── Sub-agent tool definitions ────────────────────────────────────────

    #[test]
    fn subagent_tool_defs_returns_five_tools() {
        let defs = BuiltinTools::subagent_tool_defs();
        assert_eq!(defs.len(), 5);
    }

    #[test]
    fn subagent_tool_names_returns_five_names() {
        let names = BuiltinTools::subagent_tool_names();
        assert_eq!(names.len(), 5);
        assert!(names.contains(&"spawn_agent".to_string()));
        assert!(names.contains(&"check_agent".to_string()));
        assert!(names.contains(&"wait_for_agent".to_string()));
        assert!(names.contains(&"send_to_agent".to_string()));
        assert!(names.contains(&"kill_agent".to_string()));
    }

    #[test]
    fn subagent_tool_defs_names_match_subagent_tool_names() {
        let defs = BuiltinTools::subagent_tool_defs();
        let names = BuiltinTools::subagent_tool_names();
        let def_names: Vec<String> = defs.iter().map(|d| d.name.clone()).collect();
        assert_eq!(def_names, names);
    }

    // ── resolve() ─────────────────────────────────────────────────────────

    #[test]
    fn resolve_relative_path() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let result = tools.resolve("hello.txt").unwrap();
        assert!(result.starts_with(&tools.ctx.workdir));
        assert!(result.ends_with("hello.txt"));
    }

    #[test]
    fn resolve_rejects_path_escape() {
        let dir = std::env::temp_dir().join("leviath_test_sandbox");
        fs::create_dir_all(&dir).ok();
        let tools = make_tools(&dir);
        let result = tools.resolve("../../etc/passwd");
        assert!(result.is_err());
    }

    /// The escape a lexical check cannot see. `<workdir>/link -> /` makes
    /// `link/etc/passwd` textually contained the whole way, and the old
    /// `starts_with` containment let `fs::read_to_string` follow it straight out.
    ///
    /// This matters most where the containment is load-bearing: Leviath's file
    /// tools run on the *host* over the bind-mounted workdir even when the
    /// The containment refusal itself, driven through the injected predicate so
    /// it is exercised on every platform. The `#[cfg(unix)]` tests below prove
    /// the same refusal against a real symlink; this one proves the arm exists
    /// and fires on Windows too, where a test cannot create one.
    #[test]
    fn resolve_refuses_a_path_that_does_not_resolve_within_the_workdir() {
        fn escapes(_: &Path, _: &Path) -> bool {
            false
        }
        let dir = tempfile::tempdir().unwrap();
        let err = BuiltinTools::resolve_within("notes.txt", dir.path(), escapes)
            .expect_err("a path that resolves outside must be refused");
        assert!(err.to_string().contains("symlink"), "{err}");
    }

    /// The converse, so the test above is not passing merely because everything
    /// is refused: with the real predicate an ordinary path resolves.
    #[test]
    fn resolve_admits_an_ordinary_path_within_the_workdir() {
        let dir = tempfile::tempdir().unwrap();
        let resolved =
            BuiltinTools::resolve_within("notes.txt", dir.path(), leviath_core::resolves_within)
                .expect("an ordinary path resolves");
        assert!(resolved.ends_with("notes.txt"));
    }

    /// stage's `shell` is confined to a container, so a symlink the agent made
    /// inside the container escaped the container through these tools. It is also
    /// reachable from a checked-in symlink in a freshly cloned repository, which
    /// is exactly what a coding agent is pointed at.
    #[cfg(unix)]
    #[tokio::test]
    async fn resolve_rejects_symlink_escape() {
        let dir = tempfile::tempdir().unwrap();
        let workdir = dir.path().join("workspace");
        fs::create_dir(&workdir).unwrap();
        std::os::unix::fs::symlink("/", workdir.join("link")).unwrap();
        let tools = make_tools(&workdir);

        // Precondition: this is textually inside the workdir, so a lexical
        // `starts_with` containment check alone would pass it.
        // Built from `ctx.workdir` rather than `workdir` because the context
        // canonicalizes (on macOS `/var` becomes `/private/var`).
        let normalized = tools.ctx.workdir.join("link/etc/hosts");
        assert!(normalized.starts_with(&tools.ctx.workdir));

        let err = tools.resolve("link/etc/hosts").unwrap_err().to_string();
        assert!(err.contains("symlink"), "got: {err}");

        // And the tool itself refuses rather than returning the file.
        let out = tools.read_file(&json!({ "path": "link/etc/hosts" })).await;
        assert!(out.contains("[error]"), "got: {out}");
    }

    /// A write through an escaping symlink is refused too - this was the path
    /// that could overwrite `~/.ssh/authorized_keys`.
    #[cfg(unix)]
    #[tokio::test]
    async fn write_file_rejects_symlink_escape() {
        let dir = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let workdir = dir.path().join("workspace");
        fs::create_dir(&workdir).unwrap();
        std::os::unix::fs::symlink(outside.path(), workdir.join("link")).unwrap();
        let tools = make_tools(&workdir);

        let out = tools
            .write_file(&json!({ "path": "link/pwned.txt", "content": "x" }))
            .await;
        assert!(out.contains("[error]"), "got: {out}");
        assert!(
            !outside.path().join("pwned.txt").exists(),
            "nothing may be written outside the workdir"
        );
    }

    // ── [read_paths]: reads may be granted outside the workdir ────────────

    /// Tools whose context carries a `[read_paths]` policy compiled for
    /// `workdir` (no home, unix path semantics - the platform seams have
    /// their own tests in `leviath_core::read_paths`).
    fn make_tools_with_read_paths(
        workdir: &std::path::Path,
        blueprint: &[&str],
        grants: &[&str],
        allow_blueprint: bool,
    ) -> BuiltinTools {
        let compile = |entries: &[&str]| {
            let raw: Vec<String> = entries.iter().map(|s| s.to_string()).collect();
            leviath_core::ReadPathSet::compile(&raw, workdir, None, false)
                .expect("test entries compile")
        };
        let policy = leviath_core::ReadPathPolicy {
            agent: "tester".into(),
            blueprint: compile(blueprint),
            grants: compile(grants),
            allow_blueprint,
        };
        BuiltinTools::new(ToolContext::new(workdir.to_path_buf()).with_read_paths(policy))
    }

    /// The whole point of the feature: a declared-and-granted directory is
    /// readable, through every read-only tool.
    #[tokio::test]
    async fn read_tools_reach_a_declared_and_granted_outside_path() {
        let dir = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("doc.md"), "outside contents").unwrap();
        let entry = outside.path().to_str().unwrap();
        let tools = make_tools_with_read_paths(dir.path(), &[entry], &[entry], false);

        let target = outside.path().join("doc.md");
        let target = target.to_str().unwrap();
        let out = tools.read_file(&json!({ "path": target })).await;
        assert_eq!(out, "outside contents");

        let listed = tools
            .list_dir(&json!({ "path": outside.path().to_str().unwrap() }))
            .await;
        assert!(listed.contains("doc.md"), "got: {listed}");

        // `read_files` mixes inside and outside paths per element.
        fs::write(dir.path().join("inside.txt"), "inside contents").unwrap();
        let out = tools
            .read_files(&json!({ "paths": ["inside.txt", target] }))
            .await;
        assert!(out.contains("inside contents"), "got: {out}");
        assert!(out.contains("outside contents"), "got: {out}");
    }

    /// `[read_paths]` grants reads and nothing else: the same fully granted
    /// path is still refused for `write_file` and `edit_file`, which never
    /// consult the policy.
    #[tokio::test]
    async fn write_and_edit_stay_confined_despite_read_grants() {
        let dir = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("doc.md"), "original").unwrap();
        let entry = outside.path().to_str().unwrap();
        let tools = make_tools_with_read_paths(dir.path(), &[entry], &[entry], false);

        let target = outside.path().join("doc.md");
        let target = target.to_str().unwrap();
        let out = tools
            .write_file(&json!({ "path": target, "content": "clobbered" }))
            .await;
        assert!(out.contains("[error]"), "got: {out}");
        let out = tools
            .edit_file(&json!({ "path": target, "old_str": "original", "new_str": "x" }))
            .await;
        assert!(out.contains("[error]"), "got: {out}");
        assert_eq!(
            fs::read_to_string(outside.path().join("doc.md")).unwrap(),
            "original",
            "a read grant must never permit a write"
        );
    }

    /// Declared by the blueprint but granted by nothing: refused, and the
    /// error says exactly which config stanza would grant it.
    #[tokio::test]
    async fn an_ungranted_declaration_is_refused_with_guidance() {
        let dir = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("doc.md"), "secret").unwrap();
        let entry = outside.path().to_str().unwrap();
        let tools = make_tools_with_read_paths(dir.path(), &[entry], &[], false);

        let target = outside.path().join("doc.md");
        let out = tools
            .read_file(&json!({ "path": target.to_str().unwrap() }))
            .await;
        assert!(out.contains("[error]"), "got: {out}");
        assert!(out.contains("does not grant"), "got: {out}");
        assert!(out.contains("[agent_read_paths.tester]"), "got: {out}");
        assert!(!out.contains("secret"), "content must not leak");
    }

    /// The `allow_blueprint_read_paths` override honors declarations without
    /// itemized grants - and still nothing beyond what is declared.
    #[tokio::test]
    async fn the_blanket_override_honors_declarations() {
        let dir = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("doc.md"), "outside contents").unwrap();
        let entry = outside.path().to_str().unwrap();
        let tools = make_tools_with_read_paths(dir.path(), &[entry], &[], true);

        let target = outside.path().join("doc.md");
        let out = tools
            .read_file(&json!({ "path": target.to_str().unwrap() }))
            .await;
        assert_eq!(out, "outside contents");

        // Undeclared stays undeclared: the override widens nothing.
        let undeclared = tempfile::tempdir().unwrap();
        fs::write(undeclared.path().join("x.txt"), "x").unwrap();
        let out = tools
            .read_file(&json!({ "path": undeclared.path().join("x.txt").to_str().unwrap() }))
            .await;
        assert!(
            out.contains("not in this agent's [read_paths]"),
            "got: {out}"
        );
    }

    /// With no `[read_paths]` at all, an outside read gets the original
    /// workdir refusal, word for word - the policy is never consulted.
    #[tokio::test]
    async fn an_inactive_policy_keeps_the_workdir_error() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let out = tools.read_file(&json!({ "path": "/etc/hosts" })).await;
        assert!(
            out.contains("would escape the working directory"),
            "got: {out}"
        );
    }

    /// A relative request resolves against the workdir in the fallback too,
    /// so a workdir-relative entry like `../shared` is reachable by the
    /// matching relative request.
    #[tokio::test]
    async fn a_relative_request_reaches_a_relative_grant() {
        let parent = tempfile::tempdir().unwrap();
        let workdir = parent.path().join("work");
        let shared = parent.path().join("shared");
        fs::create_dir_all(&workdir).unwrap();
        fs::create_dir_all(&shared).unwrap();
        fs::write(shared.join("doc.md"), "shared contents").unwrap();
        let tools = make_tools_with_read_paths(&workdir, &["../shared"], &["../shared"], false);

        let out = tools
            .read_file(&json!({ "path": "../shared/doc.md" }))
            .await;
        assert_eq!(out, "shared contents");
    }

    /// An interior `.` in a fallback request is folded away (`Path::components`
    /// drops it), so `<granted>/./doc.md` resolves the same as
    /// `<granted>/doc.md`.
    #[tokio::test]
    async fn a_dot_component_is_folded_in_the_fallback() {
        let dir = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("doc.md"), "outside contents").unwrap();
        let entry = outside.path().to_str().unwrap();
        let tools = make_tools_with_read_paths(dir.path(), &[entry], &[entry], false);

        let target = format!("{}/./doc.md", outside.path().to_str().unwrap());
        let out = tools.read_file(&json!({ "path": target })).await;
        assert_eq!(out, "outside contents");
    }

    /// Folding `..` past the top is unresolvable no matter what any allowlist
    /// says. Mirrors `resolve_rejects_excessive_parent_dir_traversal`: a
    /// *relative* base (`wd`) gives the accumulator exactly one leading
    /// `Normal` component and no platform-specific root/drive/prefix, so the
    /// first `..` pops `wd` and the second calls `pop()` on an empty
    /// accumulator - firing the bail on every OS. `/..` or an empty base does
    /// not: neither is absolute on Windows, and the join reshapes them so the
    /// `pop()` never fails there.
    #[test]
    fn folding_past_the_root_is_unresolvable() {
        let policy = leviath_core::ReadPathPolicy {
            agent: "tester".into(),
            allow_blueprint: true,
            ..Default::default()
        };
        let err = BuiltinTools::resolve_outside(
            "../../x",
            Path::new("wd"),
            &policy,
            leviath_core::canonicalize_for_match,
        )
        .expect_err("popping past the top must be refused");
        assert!(err.to_string().contains("cannot be resolved"), "{err}");
    }

    /// The fail-closed arm, driven through the injected canonicalizer so it
    /// runs on every platform: a path nothing can verify is refused, never
    /// matched.
    #[test]
    fn an_unverifiable_path_is_refused() {
        fn unverifiable(_: &Path) -> Option<PathBuf> {
            None
        }
        let policy = leviath_core::ReadPathPolicy {
            agent: "tester".into(),
            allow_blueprint: true,
            ..Default::default()
        };
        let err =
            BuiltinTools::resolve_outside("/outside/x", Path::new("/w"), &policy, unverifiable)
                .expect_err("an unverifiable path must be refused");
        assert!(err.to_string().contains("cannot be verified"), "{err}");
    }

    /// The attack the policy exists to stop: a symlink planted *inside* a
    /// granted directory, pointing outside it. The policy sees the real
    /// target, which no entry declares.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_symlink_inside_a_granted_directory_cannot_escape_it() {
        let dir = tempfile::tempdir().unwrap();
        let granted = tempfile::tempdir().unwrap();
        let secret_home = tempfile::tempdir().unwrap();
        fs::write(secret_home.path().join("id_rsa"), "PRIVATE KEY").unwrap();
        std::os::unix::fs::symlink(
            secret_home.path().join("id_rsa"),
            granted.path().join("innocent.md"),
        )
        .unwrap();
        let entry = granted.path().to_str().unwrap();
        let tools = make_tools_with_read_paths(dir.path(), &[entry], &[entry], false);

        let out = tools
            .read_file(&json!({ "path": granted.path().join("innocent.md").to_str().unwrap() }))
            .await;
        assert!(out.contains("[error]"), "got: {out}");
        assert!(!out.contains("PRIVATE KEY"), "content must not leak");
    }

    /// The same attack against a glob entry - the variant the original PR
    /// missed entirely. The pattern is matched against the symlink-resolved
    /// real path, and the real target does not match it.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_glob_grant_is_symlink_safe() {
        let dir = tempfile::tempdir().unwrap();
        let granted = tempfile::tempdir().unwrap();
        let secret_home = tempfile::tempdir().unwrap();
        fs::write(secret_home.path().join("id_rsa"), "PRIVATE KEY").unwrap();
        std::os::unix::fs::symlink(
            secret_home.path().join("id_rsa"),
            granted.path().join("innocent.md"),
        )
        .unwrap();
        // Patterns match the canonical real path, so build the entry from it.
        let canonical = fs::canonicalize(granted.path()).unwrap();
        let entry = format!("glob:{}/**", canonical.display());
        let tools = make_tools_with_read_paths(dir.path(), &[&entry], &[&entry], false);

        let out = tools
            .read_file(&json!({ "path": granted.path().join("innocent.md").to_str().unwrap() }))
            .await;
        assert!(out.contains("[error]"), "got: {out}");
        assert!(!out.contains("PRIVATE KEY"), "content must not leak");

        // The positive pair: a real file under the same glob is readable, so
        // the refusal above is the symlink and not the pattern.
        fs::write(granted.path().join("real.md"), "real contents").unwrap();
        let out = tools
            .read_file(&json!({ "path": granted.path().join("real.md").to_str().unwrap() }))
            .await;
        assert_eq!(out, "real contents");
    }

    /// A symlink whose target stays inside the granted subtree is fine - the
    /// rule is about where the path lands, exactly as in the workdir.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_symlink_within_a_granted_directory_is_readable() {
        let dir = tempfile::tempdir().unwrap();
        let granted = tempfile::tempdir().unwrap();
        fs::create_dir(granted.path().join("real")).unwrap();
        fs::write(granted.path().join("real/doc.md"), "granted contents").unwrap();
        std::os::unix::fs::symlink(granted.path().join("real"), granted.path().join("link"))
            .unwrap();
        let entry = granted.path().to_str().unwrap();
        let tools = make_tools_with_read_paths(dir.path(), &[entry], &[entry], false);

        let out = tools
            .read_file(&json!({ "path": granted.path().join("link/doc.md").to_str().unwrap() }))
            .await;
        assert_eq!(out, "granted contents");
    }

    /// A symlink that stays *inside* the workdir keeps working - the rule is
    /// about where the path lands, not whether a symlink was involved. Agents
    /// operate on real repositories, which contain plenty of internal symlinks.
    #[cfg(unix)]
    #[tokio::test]
    async fn resolve_allows_symlink_within_workdir() {
        let dir = tempfile::tempdir().unwrap();
        let workdir = dir.path().join("workspace");
        fs::create_dir(&workdir).unwrap();
        fs::create_dir(workdir.join("real")).unwrap();
        fs::write(workdir.join("real/file.txt"), "contents").unwrap();
        std::os::unix::fs::symlink(workdir.join("real"), workdir.join("link")).unwrap();
        let tools = make_tools(&workdir);

        assert!(tools.resolve("link/file.txt").is_ok());
        let out = tools.read_file(&json!({ "path": "link/file.txt" })).await;
        assert_eq!(out, "contents");
    }

    #[test]
    fn resolve_dot_stays_in_workdir() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let result = tools.resolve("./foo/./bar.txt").unwrap();
        assert!(result.starts_with(&tools.ctx.workdir));
        assert!(result.ends_with("foo/bar.txt"));
    }

    // ── execute() with file I/O (async) ───────────────────────────────────

    #[tokio::test]
    async fn execute_unknown_tool_returns_error() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let result = tools.execute("nonexistent", json!({})).await;
        assert!(result.contains("[error]"));
        assert!(result.contains("Unknown built-in tool"));
    }

    #[tokio::test]
    async fn read_file_missing_path_arg() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let result = tools.execute("read_file", json!({})).await;
        assert!(result.contains("[error]"));
        assert!(result.contains("missing 'path'"));
    }

    #[tokio::test]
    async fn write_and_read_file_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());

        let write_result = tools
            .execute(
                "write_file",
                json!({"path": "test.txt", "content": "hello world"}),
            )
            .await;
        assert!(write_result.contains("Successfully wrote"));
        assert!(write_result.contains("11 bytes"));

        let read_result = tools
            .execute("read_file", json!({"path": "test.txt"}))
            .await;
        assert_eq!(read_result, "hello world");
    }

    #[tokio::test]
    async fn write_file_creates_parent_dirs() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());

        let result = tools
            .execute(
                "write_file",
                json!({"path": "sub/dir/file.txt", "content": "nested"}),
            )
            .await;
        assert!(result.contains("Successfully wrote"));
        assert!(dir.path().join("sub/dir/file.txt").exists());
    }

    #[tokio::test]
    async fn write_tools_refuse_to_resurrect_a_deleted_workspace() {
        // Issue #107: an external harness deletes the workspace mid-run.
        // `create_dir_all` would happily recreate it and let the agent write
        // into an empty tree that no longer resembles the checkout it reasoned
        // about - and the runtime's health check, which just stats the workdir,
        // would never see it was gone.
        let dir = tempfile::tempdir().unwrap();
        let workdir = dir.path().join("workspace");
        fs::create_dir(&workdir).unwrap();
        fs::write(workdir.join("a.txt"), "before").unwrap();
        let tools = make_tools(&workdir);
        fs::remove_dir_all(&workdir).unwrap();

        for (tool, args) in [
            ("write_file", json!({"path": "a.txt", "content": "after"})),
            (
                "edit_file",
                json!({"path": "a.txt", "old_str": "before", "new_str": "after"}),
            ),
        ] {
            let result = tools.execute(tool, args).await;
            assert!(
                result.contains("workspace") && result.contains("no longer accessible"),
                "{tool} got: {result}"
            );
        }
        assert!(!workdir.exists(), "the workspace must stay gone");
    }

    #[tokio::test]
    async fn write_file_missing_content_arg() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools.execute("write_file", json!({"path": "f.txt"})).await;
        assert!(result.contains("missing 'content'"));
    }

    #[tokio::test]
    async fn write_file_missing_path_arg() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools.execute("write_file", json!({"content": "x"})).await;
        assert!(result.contains("missing 'path'"));
    }

    #[test]
    fn resolve_rejects_excessive_parent_dir_traversal() {
        // A *relative, nonexistent* workdir keeps `resolve`'s accumulator free
        // of any platform-specific leading root/drive/prefix components:
        // `canonicalize` fails for a path that doesn't exist (on every OS), so
        // `ToolContext::new` keeps the raw relative `PathBuf` verbatim. The
        // request then decomposes into exactly `[Normal(workdir), ParentDir,
        // ParentDir, ...]`; the first `..` pops the single workdir component and
        // the second `..` calls `normalized.pop()` on an *empty* accumulator,
        // which returns `false` - firing the "escapes the working directory"
        // bail deterministically on every OS.
        //
        // (An empty "" workdir is not portable here: on Windows `canonicalize("")`
        // can succeed and yield an absolute cwd whose Prefix/RootDir components
        // absorb the `..`, so `pop()` never fails and this bail is never hit --
        // which is exactly why this branch was Windows-uncovered before.)
        let tools = BuiltinTools::new(ToolContext::new(PathBuf::from(
            "leviath-nonexistent-relative-workdir",
        )));
        let result = tools.resolve("../../etc/passwd");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("escapes the working directory")
        );
    }

    #[tokio::test]
    async fn edit_file_successful_replacement() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());

        tools
            .execute(
                "write_file",
                json!({"path": "e.txt", "content": "foo bar baz"}),
            )
            .await;

        let result = tools
            .execute(
                "edit_file",
                json!({"path": "e.txt", "old_str": "bar", "new_str": "qux"}),
            )
            .await;
        assert!(result.contains("Successfully edited"));

        let content = tools.execute("read_file", json!({"path": "e.txt"})).await;
        assert_eq!(content, "foo qux baz");
    }

    #[tokio::test]
    async fn edit_file_string_not_found() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());

        tools
            .execute("write_file", json!({"path": "e.txt", "content": "abc"}))
            .await;

        let result = tools
            .execute(
                "edit_file",
                json!({"path": "e.txt", "old_str": "xyz", "new_str": "123"}),
            )
            .await;
        assert!(result.contains("String not found"));
    }

    #[tokio::test]
    async fn edit_file_missing_file_returns_read_error() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());

        let result = tools
            .execute(
                "edit_file",
                json!({"path": "does-not-exist.txt", "old_str": "a", "new_str": "b"}),
            )
            .await;
        assert!(result.contains("[error]"));
        assert!(result.contains("Failed to read"));
    }

    #[tokio::test]
    async fn edit_file_multiple_occurrences() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());

        tools
            .execute("write_file", json!({"path": "e.txt", "content": "aaa aaa"}))
            .await;

        let result = tools
            .execute(
                "edit_file",
                json!({"path": "e.txt", "old_str": "aaa", "new_str": "bbb"}),
            )
            .await;
        assert!(result.contains("2 occurrences"));
        assert!(result.contains("must be unique"));
    }

    #[tokio::test]
    async fn edit_file_missing_args() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());

        let r1 = tools.execute("edit_file", json!({})).await;
        assert!(r1.contains("missing 'path'"));

        let r2 = tools.execute("edit_file", json!({"path": "f.txt"})).await;
        assert!(r2.contains("missing 'old_str'"));

        let r3 = tools
            .execute("edit_file", json!({"path": "f.txt", "old_str": "x"}))
            .await;
        assert!(r3.contains("missing 'new_str'"));
    }

    #[tokio::test]
    async fn list_dir_contents() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());

        fs::write(dir.path().join("a.txt"), "hello").unwrap();
        fs::create_dir(dir.path().join("subdir")).unwrap();

        let result = tools.execute("list_dir", json!({})).await;
        assert!(result.contains("a.txt"));
        assert!(result.contains("subdir/"));
    }

    #[tokio::test]
    async fn list_dir_empty() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools.execute("list_dir", json!({})).await;
        assert!(result.contains("empty directory"));
    }

    #[tokio::test]
    async fn list_dir_with_path() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());

        fs::create_dir(dir.path().join("sub")).unwrap();
        fs::write(dir.path().join("sub/inner.txt"), "data").unwrap();

        let result = tools.execute("list_dir", json!({"path": "sub"})).await;
        assert!(result.contains("inner.txt"));
    }

    #[tokio::test]
    async fn read_file_nonexistent() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .execute("read_file", json!({"path": "nope.txt"}))
            .await;
        assert!(result.contains("[error]"));
        assert!(result.contains("Failed to read"));
    }

    // ── read_files (batch reads) ────────────────────────────────────────────

    #[tokio::test]
    async fn read_files_multiple_valid_files() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        fs::write(dir.path().join("a.txt"), "alpha").unwrap();
        fs::write(dir.path().join("b.txt"), "beta").unwrap();

        let result = tools
            .execute("read_files", json!({"paths": ["a.txt", "b.txt"]}))
            .await;
        assert!(result.contains("### [a.txt]"));
        assert!(result.contains("alpha"));
        assert!(result.contains("### [b.txt]"));
        assert!(result.contains("beta"));
        // Results are joined with a blank line between entries.
        assert!(result.contains("\n\n"));
    }

    #[tokio::test]
    async fn read_files_missing_paths_arg() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools.execute("read_files", json!({})).await;
        assert!(result.contains("[error]"));
        assert!(result.contains("missing 'paths'"));
    }

    #[tokio::test]
    async fn read_files_non_array_paths_arg() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        // A string (not an array) → as_array() returns None → same error path.
        let result = tools.execute("read_files", json!({"paths": "a.txt"})).await;
        assert!(result.contains("[error]"));
        assert!(result.contains("missing 'paths'"));
    }

    #[tokio::test]
    async fn read_files_empty_paths_array() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools.execute("read_files", json!({"paths": []})).await;
        assert!(result.contains("[error]"));
        assert!(result.contains("empty"));
    }

    #[tokio::test]
    async fn read_files_missing_file_reports_per_file_error() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        fs::write(dir.path().join("present.txt"), "here").unwrap();

        let result = tools
            .execute(
                "read_files",
                json!({"paths": ["present.txt", "absent.txt"]}),
            )
            .await;
        // Valid file still returned…
        assert!(result.contains("### [present.txt]"));
        assert!(result.contains("here"));
        // …while the missing one produces a per-file error under its header.
        assert!(result.contains("### [absent.txt]"));
        assert!(result.contains("Failed to read"));
    }

    #[tokio::test]
    async fn read_files_non_string_element_reports_error() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        fs::write(dir.path().join("ok.txt"), "content").unwrap();

        let result = tools
            .execute("read_files", json!({"paths": ["ok.txt", 42]}))
            .await;
        assert!(result.contains("content"));
        assert!(result.contains("non-string path in array"));
    }

    #[tokio::test]
    async fn read_files_path_escape_reported_per_file() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .execute("read_files", json!({"paths": ["../../etc/passwd"]}))
            .await;
        assert!(result.contains("### [../../etc/passwd]"));
        assert!(result.contains("escape"));
    }

    // ── resolve() absolute paths ────────────────────────────────────────────

    #[test]
    fn resolve_absolute_path_inside_workdir() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        // Build the absolute path from the tool's own (canonicalized) workdir
        // rather than `dir.path()` directly - on macOS `/tmp`/`/var` are
        // symlinks, so the two can differ even though they're the same place.
        let abs = tools.ctx.workdir.join("inside.txt");
        let result = tools.resolve(abs.to_str().unwrap()).unwrap();
        assert_eq!(result, abs);
    }

    #[test]
    fn resolve_rejects_absolute_path_outside_workdir() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools.resolve("/etc/passwd");
        assert!(result.is_err());
    }

    // ── path-escape rejection propagates through each tool ─────────────────

    #[tokio::test]
    async fn read_file_path_escape_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .execute("read_file", json!({"path": "../../etc/passwd"}))
            .await;
        assert!(result.contains("[error]"));
        assert!(result.contains("escape"));
    }

    #[tokio::test]
    async fn write_file_path_escape_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .execute(
                "write_file",
                json!({"path": "../../evil.txt", "content": "x"}),
            )
            .await;
        assert!(result.contains("[error]"));
        assert!(result.contains("escape"));
    }

    #[tokio::test]
    async fn edit_file_path_escape_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .execute(
                "edit_file",
                json!({"path": "../../evil.txt", "old_str": "a", "new_str": "b"}),
            )
            .await;
        assert!(result.contains("[error]"));
        assert!(result.contains("escape"));
    }

    #[tokio::test]
    async fn list_dir_path_escape_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools.execute("list_dir", json!({"path": "../../"})).await;
        assert!(result.contains("[error]"));
        assert!(result.contains("escape"));
    }

    // ── filesystem failure branches ─────────────────────────────────────────

    #[tokio::test]
    async fn write_file_fails_when_path_is_a_directory() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        fs::create_dir(dir.path().join("adir")).unwrap();

        let result = tools
            .execute("write_file", json!({"path": "adir", "content": "x"}))
            .await;
        assert!(result.contains("[error]"));
        assert!(result.contains("Failed to write"));
    }

    #[tokio::test]
    async fn write_file_parent_dir_creation_fails_when_blocked_by_file() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        // "blocker" exists as a plain file, so create_dir_all("blocker") must fail.
        fs::write(dir.path().join("blocker"), "im a file").unwrap();

        let result = tools
            .execute(
                "write_file",
                json!({"path": "blocker/nested.txt", "content": "x"}),
            )
            .await;
        assert!(result.contains("[error]"));
        assert!(result.contains("Failed to create directories"));
    }

    #[tokio::test]
    async fn read_file_fails_when_path_is_a_directory() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        fs::create_dir(dir.path().join("adir")).unwrap();

        let result = tools.execute("read_file", json!({"path": "adir"})).await;
        assert!(result.contains("[error]"));
        assert!(result.contains("Failed to read"));
    }

    #[tokio::test]
    async fn list_dir_fails_when_path_is_a_file() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        fs::write(dir.path().join("afile.txt"), "content").unwrap();

        let result = tools
            .execute("list_dir", json!({"path": "afile.txt"}))
            .await;
        assert!(result.contains("[error]"));
        assert!(result.contains("Failed to read directory"));
    }

    #[tokio::test]
    async fn edit_file_write_failure_after_successful_match() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let file_path = dir.path().join("ro.txt");
        fs::write(&file_path, "hello world").unwrap();

        // Make the file read-only so the read succeeds but the write-back
        // fails. `set_readonly(true)` is cross-platform (clears the write bits
        // on Unix; sets the read-only attribute on Windows), so the write
        // error arm is exercised on every OS. The original permissions are kept
        // so they can be put back exactly, rather than reconstructed.
        let original = fs::metadata(&file_path).unwrap().permissions();
        let mut perms = original.clone();
        perms.set_readonly(true);
        fs::set_permissions(&file_path, perms).unwrap();

        let result = tools
            .execute(
                "edit_file",
                json!({"path": "ro.txt", "old_str": "hello", "new_str": "goodbye"}),
            )
            .await;

        // Put the original permissions back so tempdir cleanup can remove the
        // file on Windows, where a read-only file cannot be deleted. Restoring
        // what was there beats `set_readonly(false)`, which on Unix sets *every*
        // write bit and would hand back 0o666 for a file that was 0o644.
        fs::set_permissions(&file_path, original).unwrap();

        assert!(result.contains("[error]"));
        assert!(result.contains("Failed to write"));
    }

    #[tokio::test]
    async fn shell_echo_command() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .execute("shell", json!({"command": "echo hello"}))
            .await;
        assert!(result.trim().contains("hello"));
    }

    #[tokio::test]
    async fn bash_alias_works() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .execute("bash", json!({"command": "echo alias_test"}))
            .await;
        assert!(result.contains("alias_test"));
    }

    #[tokio::test]
    async fn shell_missing_command_arg() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools.execute("shell", json!({})).await;
        assert!(result.contains("missing 'command'"));
    }

    /// A `ShellExecutor` that ignores the requested command and instead runs a
    /// fixed marker command - proof that shell execution is routed through it.
    struct RedirectExecutor;
    impl ShellExecutor for RedirectExecutor {
        fn build_command(
            &self,
            shell: &str,
            flag: &str,
            _command: &str,
            workdir: &Path,
        ) -> Command {
            let mut c = Command::new(shell);
            c.arg(flag).arg("echo SANDBOXED").current_dir(workdir);
            c
        }
    }

    #[tokio::test]
    async fn shell_routes_through_executor_when_present() {
        let dir = tempfile::tempdir().unwrap();
        let tools = BuiltinTools::new(ToolContext::new(dir.path().to_path_buf()))
            .with_shell_executor(Arc::new(RedirectExecutor));
        // The agent asked for `echo host`, but the executor redirects it.
        let result = tools
            .execute("shell", json!({"command": "echo host"}))
            .await;
        assert!(result.contains("SANDBOXED"), "got: {result}");
        assert!(!result.contains("host"));
    }

    #[tokio::test]
    async fn shell_failing_command() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools.execute("shell", json!({"command": "false"})).await;
        assert!(result.contains("[exit code"));
    }

    #[tokio::test]
    async fn shell_successful_command_with_no_output() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools.execute("shell", json!({"command": "true"})).await;
        assert_eq!(result, "(command succeeded with no output)");
    }

    // The stdout+stderr non-zero-exit formatting is asserted directly against
    // `format_command_output` (below) rather than via a real shell command:
    // producing stdout, stderr, and a non-zero exit in a single command needs
    // shell-specific syntax (`;`/`1>&2` on `sh`, `&`/redirection on `cmd.exe`)
    // that isn't portable, and this session already hit real Windows CI
    // failures from insufficiently-verified platform-specific test commands.
    #[test]
    fn format_command_output_non_zero_exit_reports_stdout_and_stderr() {
        let result = BuiltinTools::format_command_output(b"out-line\n", b"err-line\n", false, 1);
        assert!(result.contains("[exit code 1]"));
        assert!(result.contains("stdout:"));
        assert!(result.contains("out-line"));
        assert!(result.contains("stderr:"));
        assert!(result.contains("err-line"));
    }

    #[test]
    fn format_command_output_non_zero_exit_omits_empty_streams() {
        // Whitespace-only streams are treated as empty and neither the
        // stdout: nor stderr: block is emitted.
        let result = BuiltinTools::format_command_output(b"   \n", b"", false, 2);
        assert_eq!(result, "[exit code 2]\n");
    }

    #[test]
    fn format_command_output_success_with_output_returns_stdout() {
        let result = BuiltinTools::format_command_output(b"hello\n", b"", true, 0);
        assert_eq!(result, "hello\n");
    }

    #[test]
    fn format_command_output_success_no_output() {
        let result = BuiltinTools::format_command_output(b"   ", b"noise", true, 0);
        assert_eq!(result, "(command succeeded with no output)");
    }

    // ─── Bounded shell capture (issue #252) ──────────────────────────────────

    use crate::exec::{
        Captured, MAX_CAPTURE_BYTES, MAX_READ_FILE_BYTES, cap_file_content, capture_capped,
        capture_note,
    };

    /// A reader that hands back `chunk` `count` times and records how many
    /// reads it was asked for, standing in for a child's pipe.
    struct CountingReader {
        remaining: usize,
        chunk: usize,
        reads: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    }

    impl tokio::io::AsyncRead for CountingReader {
        fn poll_read(
            mut self: std::pin::Pin<&mut Self>,
            _cx: &mut std::task::Context<'_>,
            buf: &mut tokio::io::ReadBuf<'_>,
        ) -> std::task::Poll<std::io::Result<()>> {
            self.reads
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            if self.remaining == 0 {
                return std::task::Poll::Ready(Ok(()));
            }
            let n = self.chunk.min(self.remaining).min(buf.remaining());
            buf.put_slice(&vec![b'x'; n]);
            self.remaining -= n;
            std::task::Poll::Ready(Ok(()))
        }
    }

    #[tokio::test]
    async fn capture_capped_keeps_the_cap_and_counts_what_it_dropped() {
        let payload = vec![b'a'; 5000];
        let mut source = &payload[..];
        let got = capture_capped(&mut source, 100).await;
        assert_eq!(got.kept.len(), 100);
        assert_eq!(got.total, 5000);
    }

    #[tokio::test]
    async fn capture_capped_keeps_everything_under_the_cap() {
        let payload = [b'a'; 40];
        let mut source = &payload[..];
        let got = capture_capped(&mut source, 100).await;
        assert_eq!(got.kept.len(), 40);
        assert_eq!(got.total, 40);
    }

    /// The property the whole design rests on. A reader that stopped at the cap
    /// would leave the child blocked on a full pipe, so a command producing
    /// more than the cap would stop making progress and die at the timeout
    /// instead of returning a truncated answer.
    #[tokio::test]
    async fn capture_capped_drains_past_the_cap_so_the_child_never_blocks() {
        let reads = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let mut source = CountingReader {
            remaining: 10_000,
            chunk: 1_000,
            reads: reads.clone(),
        };
        let got = capture_capped(&mut source, 100).await;
        assert_eq!(got.total, 10_000, "the tail was not read");
        assert_eq!(got.kept.len(), 100);
        // Ten chunks plus the final empty read that signals EOF.
        assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 11);
    }

    /// A broken pipe ends the capture and keeps what arrived before it, rather
    /// than discarding a completed command's output and reporting a spawn
    /// failure for a command that actually ran.
    #[tokio::test]
    async fn capture_capped_treats_a_read_error_as_the_end_of_the_output() {
        struct FailsAfterOne(bool);
        impl tokio::io::AsyncRead for FailsAfterOne {
            fn poll_read(
                mut self: std::pin::Pin<&mut Self>,
                _cx: &mut std::task::Context<'_>,
                buf: &mut tokio::io::ReadBuf<'_>,
            ) -> std::task::Poll<std::io::Result<()>> {
                if self.0 {
                    return std::task::Poll::Ready(Err(std::io::Error::other("pipe broke")));
                }
                self.0 = true;
                buf.put_slice(b"partial");
                std::task::Poll::Ready(Ok(()))
            }
        }
        let mut source = FailsAfterOne(false);
        let got = capture_capped(&mut source, 100).await;
        assert_eq!(got.kept, b"partial");
        assert_eq!(got.total, 7);
    }

    fn captured(kept: usize, total: u64) -> Captured {
        Captured {
            kept: vec![b'x'; kept],
            total,
        }
    }

    #[test]
    fn capture_note_is_silent_when_nothing_was_dropped() {
        assert!(capture_note(&captured(10, 10), &captured(0, 0), 10).is_none());
    }

    // ─── read_file has a bound ──────────────────────────────────────────────

    #[test]
    fn a_file_under_the_cap_comes_back_whole() {
        let content = "hello".repeat(10);
        assert_eq!(cap_file_content(&content, 1024), content);
    }

    #[test]
    fn a_file_over_the_cap_is_truncated_and_says_so() {
        // The old behaviour was an all-or-nothing cliff: the whole file went
        // into the routed region, and the ladder in `tool_results` either
        // truncated it or dropped it as `[result omitted]` depending on how
        // full the region already was.
        let content = "x".repeat(5000);
        let capped = cap_file_content(&content, 1000);
        assert!(capped.starts_with(&"x".repeat(1000)));
        assert!(capped.contains("[truncated]"), "{capped}");
        assert!(
            capped.contains("5000"),
            "the real size is the useful part: {capped}"
        );
    }

    #[test]
    fn truncation_lands_on_a_char_boundary() {
        // The cap is a byte count and file content is arbitrary text, so a
        // naive slice would panic on the way back to a `String`.
        let content = "é".repeat(100);
        let capped = cap_file_content(&content, 51);
        assert!(capped.starts_with("é"));
        assert!(capped.contains("[truncated]"));
    }

    #[tokio::test]
    async fn read_file_applies_the_cap() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("big.txt"),
            "y".repeat(MAX_READ_FILE_BYTES + 4096),
        )
        .unwrap();
        let tools = make_tools(dir.path());
        let out = tools.read_file(&json!({ "path": "big.txt" })).await;
        assert!(out.contains("[truncated]"), "an unbounded read is the bug");
        assert!(out.len() < MAX_READ_FILE_BYTES + 4096);
    }

    #[test]
    fn capture_note_names_whichever_stream_overran() {
        let over = captured(10, 5_000);
        let fine = captured(10, 10);
        let stdout_only = capture_note(&over, &fine, 10).expect("stdout overran");
        assert!(stdout_only.contains("stdout exceeded"), "{stdout_only}");
        let stderr_only = capture_note(&fine, &over, 10).expect("stderr overran");
        assert!(stderr_only.contains("stderr exceeded"), "{stderr_only}");
        let both = capture_note(&over, &over, 10).expect("both overran");
        assert!(both.contains("stdout and stderr exceeded"), "{both}");
        // The count is everything the command wrote, not what survived.
        assert!(both.contains("10000 bytes"), "{both}");
    }

    /// The truncation wiring, driven through a real process on every platform.
    ///
    /// `echo hello` is the one flooding-free way to exceed a cap that both
    /// `cmd.exe` and `sh` understand, so the cap is injected rather than the
    /// output being made enormous. The `#[cfg(unix)]` test below is the
    /// real-megabyte twin.
    #[tokio::test]
    async fn a_command_that_outruns_the_cap_is_truncated_and_says_so() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .shell_with_limits(
                &json!({"command": "echo hello"}),
                Duration::from_secs(30),
                4,
            )
            .await;
        assert!(result.contains("[truncated]"), "{result}");
        assert!(result.contains("hell"), "{result}");
        assert!(!result.contains("[timed out]"), "{result}");
    }

    /// The control: under a cap it comfortably fits, nothing is said about
    /// truncation. Without this the test above passes against a version that
    /// always appends the note.
    #[tokio::test]
    async fn a_command_within_the_cap_gets_no_truncation_note() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .shell_with_limits(
                &json!({"command": "echo hello"}),
                Duration::from_secs(30),
                MAX_CAPTURE_BYTES,
            )
            .await;
        assert!(result.contains("hello"), "{result}");
        assert!(!result.contains("[truncated]"), "{result}");
    }

    /// The end-to-end twin: a real command that outproduces the cap comes back
    /// truncated and *successful*, not timed out.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_command_that_floods_stdout_is_truncated_rather_than_timing_out() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .shell_with_timeout(
                &json!({"command": "head -c 3000000 /dev/zero | tr '\\0' 'x'"}),
                Duration::from_secs(30),
            )
            .await;
        assert!(result.contains("[truncated]"));
        assert!(!result.contains("[timed out]"));
        // Kept the cap, plus the note. Nothing near the 3 MB the command wrote.
        let ceiling = MAX_CAPTURE_BYTES + 1000;
        assert!(result.len() < ceiling);
    }

    #[tokio::test]
    async fn shell_with_timeout_fires_on_slow_command() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .shell_with_timeout(&json!({"command": "sleep 5"}), Duration::from_millis(100))
            .await;
        assert!(result.contains("[timed out]"));
    }

    /// A timed-out (or cancelled) command takes its *grandchildren* with it.
    ///
    /// `kill_on_drop` only reaps the shell. Anything the shell started is
    /// reparented to init and keeps running - a cancelled agent's `sleep`
    /// outliving the run that spawned it. Verified by writing a marker file
    /// after a delay: if the grandchild survived, the marker appears.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_timed_out_command_kills_its_grandchildren() {
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join("survived");
        let tools = make_tools(dir.path());

        // A *backgrounded subshell* is the grandchild, and it is what writes the
        // marker. Chaining (`sleep 2 && touch`) would not test anything: the
        // `touch` is run by the shell itself, so killing the shell suppresses it
        // whether or not the group was signalled.
        let cmd = format!("( sleep 2; touch {} ) & sleep 30", marker.display());
        let result = tools
            .shell_with_timeout(&json!({ "command": cmd }), Duration::from_millis(100))
            .await;
        assert!(result.contains("[timed out]"), "got: {result}");

        // Well past when the grandchild would have written it.
        tokio::time::sleep(Duration::from_secs(3)).await;
        assert!(
            !marker.exists(),
            "the grandchild outlived the command that started it"
        );
    }

    #[tokio::test]
    async fn shell_spawn_failure_when_workdir_missing() {
        // A workdir that doesn't exist on disk makes Command::output() fail
        // before the shell ever runs (current_dir() can't chdir into it).
        // canonicalize() fails for a nonexistent path, so ToolContext::new()
        // falls back to keeping the raw (nonexistent) path as-is.
        let tools = make_tools(std::path::Path::new(
            "/definitely/does/not/exist/leviath-test",
        ));
        let result = tools.execute("shell", json!({"command": "echo hi"})).await;
        assert!(result.contains("[error]"));
        assert!(result.contains("Failed to spawn shell"));
    }

    // ── ToolContext ────────────────────────────────────────────────────────

    #[test]
    fn tool_context_new_canonicalizes() {
        let dir = std::env::temp_dir();
        let ctx = ToolContext::new(dir.clone());
        // Canonicalized path should be absolute
        assert!(ctx.workdir.is_absolute());
    }

    #[test]
    fn tool_context_new_with_nonexistent_dir() {
        let ctx = ToolContext::new(PathBuf::from("/nonexistent/path/unlikely"));
        // Falls back to the original path when canonicalization fails
        assert_eq!(ctx.workdir, PathBuf::from("/nonexistent/path/unlikely"));
    }

    // ── detect_shell ──────────────────────────────────────────────────────

    /// The Windows answer, asserted from every platform now that the OS is a
    /// parameter rather than a `#[cfg]`. `$SHELL` is ignored there even when it
    /// is set (Git for Windows sets it to an MSYS path `CreateProcess` cannot
    /// run), which is what the second call pins.
    #[test]
    fn detect_shell_returns_cmd_exe_on_windows() {
        let (shell, flag) = BuiltinTools::detect_shell_for("windows", None, &|_| true);
        assert_eq!(shell, "cmd.exe");
        assert_eq!(flag, "/C");

        let (shell, _) =
            BuiltinTools::detect_shell_for("windows", Some("/usr/bin/bash".to_string()), &|_| true);
        assert_eq!(shell, "cmd.exe", "$SHELL is not consulted on Windows");
    }

    #[test]
    fn detect_shell_returns_valid_shell() {
        // Pure reader: `detect_shell()` always returns a non-empty shell (and the
        // "-c" flag on non-Windows) regardless of $SHELL, so it is robust to a
        // concurrent temp-env writer and needs no serialization of its own.
        let (shell, flag) = BuiltinTools::detect_shell();
        assert!(!shell.is_empty());
        assert!(!flag.is_empty());
        #[cfg(not(windows))]
        assert_eq!(flag, "-c");
    }

    /// Drives the real filesystem probe (`shell_path_exists`) through the seam,
    /// with an unrecognized `$SHELL` so the candidate loop is reached. Passing
    /// `"linux"` rather than the host OS is what lets this run on the Windows
    /// leg too - production's probe would otherwise be a function no Windows
    /// test ever calls.
    ///
    /// The result is host-dependent: a Unix host finds one of the candidates,
    /// a Windows host finds none and falls to the last resort. Both are correct,
    /// so only the shape is asserted.
    #[test]
    fn detect_shell_queries_the_real_filesystem_for_an_unrecognized_shell() {
        let (shell, flag) = BuiltinTools::detect_shell_for(
            "linux",
            Some("/opt/not-a-recognized-shell".to_string()),
            &BuiltinTools::shell_path_exists,
        );
        assert_eq!(flag, "-c");
        assert!(
            [
                "/bin/bash",
                "/usr/bin/bash",
                "/bin/zsh",
                "/usr/bin/zsh",
                "/bin/sh",
                "sh",
            ]
            .contains(&shell),
            "unexpected shell: {shell}"
        );
    }

    // ── detect_shell_for() - inject OS, env and filesystem for full branch coverage ──

    #[test]
    fn detect_shell_for_returns_zsh_from_env() {
        // `$SHELL` is trusted only when it exists on disk.
        let (shell, flag) =
            BuiltinTools::detect_shell_for("linux", Some("/usr/local/bin/zsh".to_string()), &|s| {
                s == "/usr/local/bin/zsh"
            });
        assert_eq!(shell, "/usr/local/bin/zsh");
        assert_eq!(flag, "-c");
    }

    #[test]
    fn detect_shell_for_returns_bash_from_env() {
        let (shell, flag) = BuiltinTools::detect_shell_for(
            "macos",
            Some("/usr/local/bin/bash".to_string()),
            &|s| s == "/usr/local/bin/bash",
        );
        assert_eq!(shell, "/usr/local/bin/bash");
        assert_eq!(flag, "-c");
    }

    #[test]
    fn detect_shell_for_returns_sh_from_env() {
        // An OS nobody special-cases still gets the POSIX treatment rather than
        // falling into the Windows arm.
        let (shell, flag) =
            BuiltinTools::detect_shell_for("freebsd", Some("/usr/bin/sh".to_string()), &|s| {
                s == "/usr/bin/sh"
            });
        assert_eq!(shell, "/usr/bin/sh");
        assert_eq!(flag, "-c");
    }

    #[test]
    fn detect_shell_for_falls_back_when_env_shell_is_missing() {
        // Regression for #79: `$SHELL` is a recognized shell name but does not
        // exist on disk (a stale or sandbox-missing `/bin/zsh`). It must NOT be
        // returned - fall through to an available fallback instead of failing
        // every shell call with "No such file or directory".
        let (shell, flag) =
            BuiltinTools::detect_shell_for("linux", Some("/bin/zsh".to_string()), &|s| {
                s == "/bin/sh"
            });
        assert_eq!(shell, "/bin/sh");
        assert_eq!(flag, "-c");
    }

    #[test]
    fn detect_shell_for_falls_through_when_env_unrecognized() {
        // /opt/fish doesn't end with /zsh, /bash, or /sh → falls to candidate loop
        let (shell, flag) =
            BuiltinTools::detect_shell_for("linux", Some("/opt/fish".to_string()), &|s| {
                s == "/bin/bash"
            });
        assert_eq!(shell, "/bin/bash");
        assert_eq!(flag, "-c");
    }

    #[test]
    fn detect_shell_for_skips_missing_candidates_and_finds_zsh() {
        // bash paths return false; /bin/zsh exists - covers shell_exists false branch
        let (shell, flag) = BuiltinTools::detect_shell_for("linux", None, &|s| s == "/bin/zsh");
        assert_eq!(shell, "/bin/zsh");
        assert_eq!(flag, "-c");
    }

    #[test]
    fn detect_shell_for_returns_last_resort_when_nothing_exists() {
        let (shell, flag) = BuiltinTools::detect_shell_for("linux", None, &|_| false);
        assert_eq!(shell, "sh");
        assert_eq!(flag, "-c");
    }

    #[tokio::test]
    async fn concurrent_edits_same_file_serialize_no_lost_update() {
        // Two workers edit different unique strings in the SAME file at once.
        // The per-path lock serializes the read-modify-write, so both edits
        // land; without it, the second write would clobber the first.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("f.txt"), "A\nB\n").unwrap();
        let tools = std::sync::Arc::new(make_tools(dir.path()));

        let t1 = {
            let t = tools.clone();
            tokio::spawn(async move {
                t.execute(
                    "edit_file",
                    json!({"path": "f.txt", "old_str": "A", "new_str": "A1"}),
                )
                .await
            })
        };
        let t2 = {
            let t = tools.clone();
            tokio::spawn(async move {
                t.execute(
                    "edit_file",
                    json!({"path": "f.txt", "old_str": "B", "new_str": "B2"}),
                )
                .await
            })
        };
        let (r1, r2) = tokio::join!(t1, t2);
        assert!(!r1.unwrap().starts_with("[error]"));
        assert!(!r2.unwrap().starts_with("[error]"));

        let final_content = std::fs::read_to_string(dir.path().join("f.txt")).unwrap();
        assert_eq!(
            final_content, "A1\nB2\n",
            "both concurrent edits must apply (no lost update)"
        );
    }

    #[tokio::test]
    async fn concurrent_writes_different_files_both_succeed() {
        // Different files never contend on the per-path lock.
        let dir = tempfile::tempdir().unwrap();
        let tools = std::sync::Arc::new(make_tools(dir.path()));

        let a = {
            let t = tools.clone();
            tokio::spawn(async move {
                t.execute("write_file", json!({"path": "a.txt", "content": "AAA"}))
                    .await
            })
        };
        let b = {
            let t = tools.clone();
            tokio::spawn(async move {
                t.execute("write_file", json!({"path": "b.txt", "content": "BBB"}))
                    .await
            })
        };
        let (ra, rb) = tokio::join!(a, b);
        assert!(!ra.unwrap().starts_with("[error]"));
        assert!(!rb.unwrap().starts_with("[error]"));
        assert_eq!(
            std::fs::read_to_string(dir.path().join("a.txt")).unwrap(),
            "AAA"
        );
        assert_eq!(
            std::fs::read_to_string(dir.path().join("b.txt")).unwrap(),
            "BBB"
        );
    }

    // ── Platform capabilities ─────────────────────────────────────────────

    #[test]
    fn desktop_supports_all_capabilities() {
        let caps = PlatformCapabilities::desktop();
        assert!(caps.supports(ToolCapability::ProcessSpawn));
        assert!(caps.supports(ToolCapability::FileSystem));
        assert!(caps.supports(ToolCapability::Network));
    }

    #[test]
    fn mobile_lacks_process_spawn() {
        let caps = PlatformCapabilities::mobile();
        assert!(!caps.supports(ToolCapability::ProcessSpawn));
        assert!(caps.supports(ToolCapability::FileSystem));
        assert!(caps.supports(ToolCapability::Network));
    }

    #[test]
    fn current_matches_desktop_and_is_the_default() {
        // Only desktop targets are built today.
        assert_eq!(
            PlatformCapabilities::current(),
            PlatformCapabilities::desktop()
        );
        assert_eq!(
            PlatformCapabilities::default(),
            PlatformCapabilities::desktop()
        );
    }

    #[test]
    fn satisfies_requires_all_and_empty_is_always_met() {
        let caps = PlatformCapabilities::mobile();
        assert!(caps.satisfies(&[]));
        assert!(caps.satisfies(&[ToolCapability::FileSystem]));
        assert!(!caps.satisfies(&[ToolCapability::ProcessSpawn]));
        // All-or-nothing: one unmet requirement fails the whole set.
        assert!(!caps.satisfies(&[ToolCapability::FileSystem, ToolCapability::ProcessSpawn]));
    }

    #[test]
    fn from_capabilities_builds_explicit_set() {
        let caps = PlatformCapabilities::from_capabilities([ToolCapability::Network]);
        assert!(caps.supports(ToolCapability::Network));
        assert!(!caps.supports(ToolCapability::FileSystem));
    }

    #[test]
    fn tool_required_capabilities_by_name() {
        assert_eq!(
            tool_required_capabilities("shell"),
            &[ToolCapability::ProcessSpawn]
        );
        assert_eq!(
            tool_required_capabilities("read_file"),
            &[ToolCapability::FileSystem]
        );
        // Runtime-handled / platform-agnostic tools require nothing.
        assert!(tool_required_capabilities("context_write").is_empty());
        assert!(tool_required_capabilities("present_for_review").is_empty());
        assert!(tool_required_capabilities("unknown_tool").is_empty());
    }

    #[test]
    fn mobile_tool_defs_omit_shell_but_keep_the_rest() {
        let dir = std::env::temp_dir();
        let tools = make_mobile_tools(&dir);
        let names: Vec<String> = tools.tool_defs().iter().map(|t| t.name.clone()).collect();
        assert!(!names.contains(&"shell".to_string()));
        // The other 16 built-ins remain.
        assert_eq!(tools.tool_defs().len(), 19);
        assert!(names.contains(&"read_file".to_string()));
        assert!(names.contains(&"context_write".to_string()));
        assert!(names.contains(&"present_for_review".to_string()));
    }

    #[test]
    fn desktop_tool_defs_include_shell() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let names: Vec<String> = tools.tool_defs().iter().map(|t| t.name.clone()).collect();
        assert!(names.contains(&"shell".to_string()));
    }

    #[test]
    fn mobile_names_omit_shell_and_bash_alias() {
        let dir = std::env::temp_dir();
        let tools = make_mobile_tools(&dir);
        let names = tools.names();
        assert!(!names.contains(&"shell".to_string()));
        assert!(!names.contains(&"bash".to_string()));
        // File + context tools still recognized.
        assert!(names.contains(&"read_file".to_string()));
        assert!(names.contains(&"context_write".to_string()));
    }

    #[test]
    fn desktop_names_include_shell_and_bash_alias() {
        let dir = std::env::temp_dir();
        let tools = make_tools(&dir);
        let names = tools.names();
        assert!(names.contains(&"shell".to_string()));
        assert!(names.contains(&"bash".to_string()));
    }

    #[tokio::test]
    async fn mobile_execute_shell_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_mobile_tools(dir.path());
        let out = tools.execute("shell", json!({"command": "echo hi"})).await;
        assert!(out.contains("not available on this platform"), "got: {out}");
        // The `bash` alias resolves to `shell` and is rejected the same way.
        let out = tools.execute("bash", json!({"command": "echo hi"})).await;
        assert!(out.contains("not available on this platform"), "got: {out}");
    }

    #[tokio::test]
    async fn mobile_execute_file_tool_still_works() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_mobile_tools(dir.path());
        let out = tools
            .execute("write_file", json!({"path": "x.txt", "content": "hi"}))
            .await;
        assert!(!out.starts_with("[error]"), "got: {out}");
        assert_eq!(
            std::fs::read_to_string(dir.path().join("x.txt")).unwrap(),
            "hi"
        );
    }

    // ─── The null device is not an escape (#373) ─────────────────────────────────

    /// Writing to the null device writes nowhere, so containment has nothing to
    /// refuse. It used to answer `path '/dev/null' would escape the working
    /// directory`, which is both wrong and unfixable from the agent's side: there
    /// is no path inside the workspace that means "discard this".
    #[tokio::test]
    async fn write_file_to_the_null_device_is_allowed() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .execute(
                "write_file",
                json!({"path": "/dev/null", "content": "thrown away"}),
            )
            .await;
        assert!(
            !result.contains("escape"),
            "the null device is not an escape: {result}"
        );
    }

    #[tokio::test]
    async fn read_file_from_the_null_device_is_allowed() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .execute("read_file", json!({"path": "/dev/null"}))
            .await;
        assert!(
            !result.contains("escape"),
            "the null device is not an escape: {result}"
        );
    }

    /// The control, so the allowance above cannot be mistaken for containment
    /// having been switched off: a real path outside the workspace is still
    /// refused.
    #[tokio::test]
    async fn a_real_outside_path_is_still_refused() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .execute("write_file", json!({"path": "../out.txt", "content": "x"}))
            .await;
        assert!(result.contains("escape"), "got: {result}");
    }

    /// `/dev/stdout` and `/dev/stderr` are not sinks, on purpose. Opened by
    /// name from inside the daemon they are its own streams, so a tool writing
    /// there lands in the middle of whatever the CLI is drawing. A shell
    /// redirect to them is a different thing spelled the same way and stays
    /// allowed.
    ///
    /// Asserted against the predicate rather than through a tool call: on
    /// Windows a `/dev/...` path is relative, so a call would be judged against
    /// the workdir and the test would be measuring the platform's path rules
    /// rather than this one.
    #[test]
    fn the_daemons_own_streams_are_not_null_devices() {
        assert!(is_null_device("/dev/null"), "the sink is a sink");
        assert!(is_null_device("NUL"), "and so is the Windows spelling");
        assert!(is_null_device("nul"), "case does not decide it");
        assert!(!is_null_device("/dev/stdout"));
        assert!(!is_null_device("/dev/stderr"));
        assert!(
            !is_null_device("notes.md"),
            "an ordinary path is not a sink"
        );
    }

    /// A refusal names the workspace and what to do about it. An agent told only
    /// "denied" tries a different escape; one told where to write complies, and the
    /// turns it would have spent guessing are charged to the stage's budget.
    #[tokio::test]
    async fn an_escape_refusal_says_where_to_write_instead() {
        let dir = tempfile::tempdir().unwrap();
        let tools = make_tools(dir.path());
        let result = tools
            .execute("write_file", json!({"path": "../out.txt", "content": "x"}))
            .await;
        // The tempdir's own directory name rather than its full path: Windows
        // canonicalizes a temp path (verbatim prefix, short names), so the
        // workdir in the message is not textually the string `display()`
        // returns here. The unique final component survives that.
        let leaf = dir
            .path()
            .file_name()
            .expect("a temp dir has a name")
            .to_string_lossy()
            .to_string();
        assert!(result.contains(&leaf), "names the workspace root: {result}");
        assert!(
            result.contains("inside the workspace"),
            "says what to do instead: {result}"
        );
    }
}