clawft-core 0.8.3

Core engine for clawft (agent loop, message bus, context management)
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
//! Tool registry and [`Tool`] trait definition.
//!
//! Defines the interface that all tool implementations must satisfy
//! ([`Tool`]) and provides a [`ToolRegistry`] that stores registered
//! tools and dispatches execution requests by name.
//!
//! Tool implementations live in the `clawft-tools` crate; this module
//! only defines the contract and registry infrastructure.

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tracing::debug;

use clawft_types::routing::UserPermissions;

use super::permit::{present_proof_at, PermitIssuer, PermitProofError, ToolPermitToken};

#[cfg(feature = "native")]
use std::path::PathBuf;
#[cfg(feature = "native")]
use std::sync::Mutex as StdMutex;
#[cfg(feature = "native")]
use std::sync::OnceLock;

// ── WEFT-37: per-path advisory locks ────────────────────────────────
//
// D1 of the pipeline-reliability sprint shipped parallel tool execution
// (see `agent/loop_core.rs` — `futures::join_all` over per-tool-call
// futures) but explicitly punted on per-path serialization. The hazard:
// two tools writing the same canonical path concurrently, producing
// torn reads or interleaved writes. This module provides a process-
// global `path → tokio::Mutex` map. When a tool whose argument JSON
// references a path is executed, the registry acquires the
// corresponding mutex for the duration of the call, serialising
// same-path executions while letting non-overlapping paths run fully
// in parallel.
//
// The lock map is native-only because:
//  - browser/wasm has a single-threaded executor — concurrent FS
//    operations on the same path can't interleave there.
//  - tokio::sync::Mutex is the natural fit for "hold across await
//    points"; pulling in a wasm-friendly equivalent for a hazard that
//    only exists on native is gold-plating.

#[cfg(feature = "native")]
type PathLockMap = HashMap<PathBuf, Arc<tokio::sync::Mutex<()>>>;

#[cfg(feature = "native")]
static PATH_LOCKS: OnceLock<StdMutex<PathLockMap>> = OnceLock::new();

#[cfg(feature = "native")]
fn path_locks() -> &'static StdMutex<PathLockMap> {
    PATH_LOCKS.get_or_init(|| StdMutex::new(HashMap::new()))
}

/// Names of common JSON keys that carry filesystem paths in the
/// built-in tool argument schema. Used to extract the path(s) to lock
/// before executing a tool.
#[cfg(feature = "native")]
const PATH_ARG_KEYS: &[&str] = &["path", "file", "file_path", "filepath", "target"];

/// Extract candidate path strings from a tool argument JSON value.
///
/// Returns one [`PathBuf`] per recognised key in [`PATH_ARG_KEYS`].
/// Multi-path tools (e.g. a hypothetical `copy {from, to}`) can lock
/// both keys via the canonical separator semantics — we just collect
/// every key found.
#[cfg(feature = "native")]
fn extract_paths(args: &serde_json::Value) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let Some(obj) = args.as_object() else {
        return out;
    };
    for key in PATH_ARG_KEYS {
        if let Some(s) = obj.get(*key).and_then(|v| v.as_str())
            && !s.is_empty()
        {
            out.push(canonicalize_for_lock(s));
        }
    }
    out
}

/// Canonicalise a path string for use as a lock key. Two callers
/// referring to the same file via different relative spellings must
/// land on the same lock entry, so we resolve to an absolute path
/// where possible and fall back to a normalised representation.
///
/// We deliberately do NOT call `std::fs::canonicalize` (which requires
/// the file to exist and would fail for new files); instead we
/// normalise components with `Path::components` to collapse `.` and
/// `..` segments without touching the filesystem.
#[cfg(feature = "native")]
fn canonicalize_for_lock(raw: &str) -> PathBuf {
    use std::path::{Component, Path};
    let p = Path::new(raw);
    let absolute = if p.is_absolute() {
        p.to_path_buf()
    } else {
        std::env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("/"))
            .join(p)
    };
    let mut out = PathBuf::new();
    for c in absolute.components() {
        match c {
            Component::CurDir => {}
            Component::ParentDir => {
                out.pop();
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// Acquire (and lazily-create) the advisory lock for the given path.
///
/// The returned `OwnedMutexGuard` keeps the lock map entry alive and
/// is dropped at the end of the tool execution scope. The lock entries
/// are kept in the map indefinitely — the working set of paths a
/// long-lived agent touches is bounded enough in practice that we
/// don't bother garbage-collecting unused entries.
#[cfg(feature = "native")]
async fn acquire_path_lock(path: PathBuf) -> tokio::sync::OwnedMutexGuard<()> {
    let lock = {
        let mut map = path_locks().lock().expect("path lock map poisoned");
        map.entry(path)
            .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
            .clone()
    };
    lock.lock_owned().await
}

/// Test helper: clear the global advisory lock map between tests so
/// each test starts with a clean state. Inside the `cfg(test)`
/// boundary; the production code path never calls this.
#[cfg(all(test, feature = "native"))]
pub(crate) fn _clear_path_locks_for_test() {
    if let Some(map) = PATH_LOCKS.get() {
        map.lock().expect("path lock map poisoned").clear();
    }
}

/// Error type for tool execution.
///
/// Covers the common failure modes: unknown tool, bad arguments,
/// runtime failures, permission issues, and timeouts.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ToolError {
    /// The requested tool was not found in the registry.
    #[error("tool not found: {0}")]
    NotFound(String),

    /// The arguments provided to the tool are invalid.
    #[error("invalid arguments: {0}")]
    InvalidArgs(String),

    /// The tool execution failed at runtime.
    #[error("execution failed: {0}")]
    ExecutionFailed(String),

    /// The caller lacks permission to invoke this tool.
    ///
    /// `tool` is the name of the tool that was denied.
    /// `reason` explains why (not in allowlist, explicitly denied,
    /// insufficient level, missing custom permission).
    #[error("permission denied for tool '{tool}': {reason}")]
    PermissionDenied { tool: String, reason: String },

    /// A file or resource the tool needs was not found.
    #[error("not found: {0}")]
    FileNotFound(String),

    /// A filesystem path is invalid or traverses outside allowed boundaries.
    #[error("invalid path: {0}")]
    InvalidPath(String),

    /// The tool execution exceeded the allowed time limit.
    #[error("timeout after {0}s")]
    Timeout(u64),
}

// ---------------------------------------------------------------------------
// ToolMetadata
// ---------------------------------------------------------------------------

/// Permission metadata that a tool can declare.
///
/// Built-in tools define this via the `Tool::metadata()` trait method.
/// MCP tools derive this from their server's tool declaration JSON.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ToolMetadata {
    /// Minimum permission level required to invoke this tool.
    /// `None` means no level requirement beyond the allowlist check.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub required_permission_level: Option<u8>,

    /// Custom permission keys and values that must match.
    /// Example: `{"exec_enabled": true}` requires the user to have
    /// `custom_permissions["exec_enabled"] == true`.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub required_custom_permissions: HashMap<String, serde_json::Value>,
}

// ---------------------------------------------------------------------------
// Glob matching
// ---------------------------------------------------------------------------

/// Match a tool name against a glob pattern.
///
/// Supports `*` (matches zero or more characters) and `?` (matches exactly
/// one character). This is a minimal implementation sufficient for tool
/// access patterns without pulling in a full glob crate.
///
/// Examples:
///   `glob_matches("file_*", "file_read")` -> true
///   `glob_matches("file_*", "web_search")` -> false
///   `glob_matches("*", "anything")` -> true
///   `glob_matches("read_?", "read_a")` -> true
///   `glob_matches("read_?", "read_file")` -> false
fn glob_matches(pattern: &str, text: &str) -> bool {
    let pattern: Vec<char> = pattern.chars().collect();
    let text: Vec<char> = text.chars().collect();
    let (plen, tlen) = (pattern.len(), text.len());

    let mut pi = 0;
    let mut ti = 0;
    let mut star_pi = None;
    let mut star_ti = 0;

    while ti < tlen {
        if pi < plen && (pattern[pi] == '?' || pattern[pi] == text[ti]) {
            pi += 1;
            ti += 1;
        } else if pi < plen && pattern[pi] == '*' {
            star_pi = Some(pi);
            star_ti = ti;
            pi += 1;
        } else if let Some(spi) = star_pi {
            pi = spi + 1;
            star_ti += 1;
            ti = star_ti;
        } else {
            return false;
        }
    }

    // Consume trailing stars in pattern.
    while pi < plen && pattern[pi] == '*' {
        pi += 1;
    }

    pi == plen
}

/// Check whether a tool name matches any pattern in the given list.
/// Each entry in `patterns` is either an exact name or a glob pattern.
fn matches_any_pattern(tool_name: &str, patterns: &[String]) -> bool {
    patterns.iter().any(|pattern| {
        if pattern.contains('*') || pattern.contains('?') {
            glob_matches(pattern, tool_name)
        } else {
            pattern == tool_name
        }
    })
}

// ---------------------------------------------------------------------------
// Permission checking
// ---------------------------------------------------------------------------

/// Check whether the given permissions allow invoking the named tool.
///
/// This is a pure function with no side effects -- suitable for
/// unit testing without async or I/O.
///
/// Evaluation order:
///   1. Denylist (checked first, deny overrides everything)
///   2. Allowlist (empty = deny all, `["*"]` = allow all, else pattern match)
///   3. Tool metadata `required_permission_level`
///   4. Tool metadata `required_custom_permissions`
///
/// Returns `Ok(())` if allowed, `Err(ToolError::PermissionDenied)` if not.
pub fn check_tool_permission(
    tool_name: &str,
    permissions: &UserPermissions,
    tool_metadata: Option<&ToolMetadata>,
) -> Result<(), ToolError> {
    // Step 1: Denylist check (deny overrides everything, even ["*"] allowlist).
    if matches_any_pattern(tool_name, &permissions.tool_denylist) {
        return Err(ToolError::PermissionDenied {
            tool: tool_name.to_string(),
            reason: "tool is explicitly denied for this user".to_string(),
        });
    }

    // Step 2: Allowlist check.
    let allowed = if permissions.tool_access.is_empty() {
        // Empty allowlist = no tools allowed (zero_trust default).
        false
    } else if permissions.tool_access.iter().any(|s| s == "*") {
        // Wildcard entry = all tools allowed (admin default).
        true
    } else {
        // Check each pattern in tool_access for a match.
        matches_any_pattern(tool_name, &permissions.tool_access)
    };

    if !allowed {
        return Err(ToolError::PermissionDenied {
            tool: tool_name.to_string(),
            reason: format!(
                "tool is not in the allowed tools for permission level {}",
                permissions.level,
            ),
        });
    }

    // Step 2b (WEFT-32): MCP wildcard namespace guard.
    //
    // A bare `["*"]` allowlist must NOT cover sensitive MCP namespaces
    // (`exec_*`, `shell_*`, `system_*`, ...). The operator has to opt
    // in to each sensitive namespace explicitly. This stops the
    // attack vector where a benign-looking `tool_access: ["*"]`
    // exposes a maliciously-registered `exec__shell` tool.
    if let Err(err) = crate::security::validate_mcp_namespace_against_wildcard(
        tool_name,
        &permissions.tool_access,
    ) {
        return Err(ToolError::PermissionDenied {
            tool: tool_name.to_string(),
            reason: format!("MCP namespace guard: {err}"),
        });
    }

    // Step 3: Tool metadata -- required permission level.
    if let Some(meta) = tool_metadata {
        if let Some(required_level) = meta.required_permission_level
            && permissions.level < required_level
        {
            return Err(ToolError::PermissionDenied {
                tool: tool_name.to_string(),
                reason: format!(
                    "tool requires permission level {} but user has level {}",
                    required_level, permissions.level,
                ),
            });
        }

        // Step 4: Tool metadata -- required custom permissions.
        for (key, required_value) in &meta.required_custom_permissions {
            match permissions.custom_permissions.get(key) {
                None => {
                    return Err(ToolError::PermissionDenied {
                        tool: tool_name.to_string(),
                        reason: format!(
                            "tool requires custom permission '{}' which is not set",
                            key,
                        ),
                    });
                }
                Some(actual) if actual != required_value => {
                    return Err(ToolError::PermissionDenied {
                        tool: tool_name.to_string(),
                        reason: format!(
                            "tool requires {}={} but user has {}={}",
                            key, required_value, key, actual,
                        ),
                    });
                }
                Some(_) => {} // Value matches, continue.
            }
        }
    }

    Ok(())
}

/// Map a [`PermitProofError`] into [`ToolError::PermissionDenied`].
fn permit_to_tool_error(tool: &str, err: PermitProofError) -> ToolError {
    ToolError::PermissionDenied {
        tool: tool.to_string(),
        reason: format!("permit proof failed: {err}"),
    }
}

/// Extract permission metadata from an MCP tool declaration JSON.
///
/// MCP tool declarations may include:
///   `"required_permission_level": 2`
///   `"required_custom_permissions": {"exec_enabled": true}`
pub fn extract_mcp_metadata(tool_decl: &serde_json::Value) -> ToolMetadata {
    let required_level = tool_decl
        .get("required_permission_level")
        .and_then(|v| v.as_u64())
        .map(|v| v as u8);

    let required_custom = tool_decl
        .get("required_custom_permissions")
        .and_then(|v| v.as_object())
        .map(|obj| obj.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
        .unwrap_or_default();

    ToolMetadata {
        required_permission_level: required_level,
        required_custom_permissions: required_custom,
    }
}

// ---------------------------------------------------------------------------
// Tool trait
// ---------------------------------------------------------------------------

/// A tool that can be invoked by the agent pipeline.
///
/// Implementations provide a name, description, JSON Schema for parameters,
/// and an async `execute` method. Tools are registered in a [`ToolRegistry`]
/// and dispatched by the agent loop when the LLM emits a tool-use request.
///
/// # Implementing a tool
///
/// ```rust,ignore
/// use async_trait::async_trait;
/// use clawft_core::tools::registry::{Tool, ToolError};
///
/// struct EchoTool;
///
/// #[async_trait]
/// impl Tool for EchoTool {
///     fn name(&self) -> &str { "echo" }
///     fn description(&self) -> &str { "Echo back the input" }
///     fn parameters(&self) -> serde_json::Value {
///         serde_json::json!({
///             "type": "object",
///             "properties": {
///                 "text": { "type": "string", "description": "Text to echo" }
///             },
///             "required": ["text"]
///         })
///     }
///     async fn execute(&self, args: serde_json::Value) -> Result<serde_json::Value, ToolError> {
///         let text = args.get("text")
///             .and_then(|v| v.as_str())
///             .ok_or_else(|| ToolError::InvalidArgs("missing 'text'".into()))?;
///         Ok(serde_json::json!({ "output": text }))
///     }
/// }
/// ```
#[cfg_attr(not(feature = "browser"), async_trait)]
#[cfg_attr(feature = "browser", async_trait(?Send))]
pub trait Tool: Send + Sync {
    /// The unique name of this tool (used in LLM function calling).
    fn name(&self) -> &str;

    /// A human-readable description of what this tool does.
    fn description(&self) -> &str;

    /// JSON Schema describing the tool's parameters.
    ///
    /// Should return a valid JSON Schema object (type: "object" with
    /// properties, required, etc.) suitable for OpenAI function calling.
    fn parameters(&self) -> serde_json::Value;

    /// Execute the tool with the given arguments.
    ///
    /// Arguments are a JSON object matching the schema from [`parameters`].
    /// Returns a JSON value representing the tool's output, or a
    /// [`ToolError`] on failure.
    async fn execute(&self, args: serde_json::Value) -> Result<serde_json::Value, ToolError>;

    /// Optional permission metadata for this tool.
    ///
    /// Override to declare minimum permission levels or required
    /// custom permissions. Default: no requirements (returns `None`).
    fn metadata(&self) -> Option<ToolMetadata> {
        None
    }
}

/// Registry of available tools, indexed by name.
///
/// Provides lookup, listing, schema generation in OpenAI function calling
/// format, and dispatch-by-name execution.
///
/// # Proof-of-permission (WEFT-341)
///
/// After a gate check permits a tool, the agent loop issues a
/// [`ToolPermitToken`] via [`Self::permit_issuer`] and passes it to
/// [`Self::execute_with_permit`]. Verification is optional by default
/// (`require_permit = false`): callers that pass `None` keep the
/// pre-WEFT-341 behaviour. When a token *is* presented it is always
/// checked (MAC, tool binding, agent binding, TTL).
pub struct ToolRegistry {
    tools: HashMap<String, Arc<dyn Tool>>,
    metadata: HashMap<String, ToolMetadata>,
    /// Shared issuer for minting / verifying per-tool permits.
    permit_issuer: Arc<PermitIssuer>,
    /// When `true`, [`Self::execute_with_permit`] rejects a missing
    /// token. Default `false` for back-compat.
    require_permit: bool,
}

impl ToolRegistry {
    /// Create an empty tool registry with an ephemeral permit issuer.
    pub fn new() -> Self {
        Self {
            tools: HashMap::new(),
            metadata: HashMap::new(),
            permit_issuer: Arc::new(PermitIssuer::ephemeral()),
            require_permit: false,
        }
    }

    /// Replace the permit issuer (share one with the agent loop so
    /// issued tokens verify against the same key).
    pub fn with_permit_issuer(mut self, issuer: Arc<PermitIssuer>) -> Self {
        self.permit_issuer = issuer;
        self
    }

    /// Install a permit issuer after construction.
    pub fn set_permit_issuer(&mut self, issuer: Arc<PermitIssuer>) {
        self.permit_issuer = issuer;
    }

    /// Shared [`PermitIssuer`] for minting tokens that this registry
    /// will accept.
    pub fn permit_issuer(&self) -> Arc<PermitIssuer> {
        Arc::clone(&self.permit_issuer)
    }

    /// Require a valid permit token on every
    /// [`Self::execute_with_permit`] call (strict mode).
    pub fn with_require_permit(mut self, require: bool) -> Self {
        self.require_permit = require;
        self
    }

    /// Whether a permit token is required on execute.
    pub fn require_permit(&self) -> bool {
        self.require_permit
    }

    /// Register a tool in the registry.
    ///
    /// If a tool with the same name already exists, it is replaced.
    /// If the tool provides metadata via [`Tool::metadata()`], it is stored
    /// in the metadata map automatically.
    pub fn register(&mut self, tool: Arc<dyn Tool>) {
        let name = tool.name().to_string();
        debug!(tool = %name, "registering tool");
        // Extract metadata from the tool if provided.
        if let Some(meta) = tool.metadata() {
            self.metadata.insert(name.clone(), meta);
        }
        self.tools.insert(name.clone(), tool);

        // Chain event marker for tool registration.
        crate::chain_event!(
            "tools",
            crate::chain_event::EVENT_KIND_TOOL_REGISTER,
            { "tool_name": name }
        );
    }

    /// Register a tool with explicit metadata (used for MCP tools whose
    /// metadata comes from JSON declarations rather than the Rust trait).
    ///
    /// Emits [`EVENT_KIND_TOOL_REGISTER_METADATA`](crate::chain_event::EVENT_KIND_TOOL_REGISTER_METADATA)
    /// so the daemon chain bridge records the registration (WEFT-153).
    pub fn register_with_metadata(&mut self, tool: Arc<dyn Tool>, metadata: ToolMetadata) {
        let name = tool.name().to_string();
        debug!(tool = %name, "registering tool with metadata");
        let permission_level = metadata
            .required_permission_level
            .map(|l| l.to_string())
            .unwrap_or_else(|| "none".into());
        self.metadata.insert(name.clone(), metadata);
        self.tools.insert(name.clone(), tool);

        // Chain event marker — distinct from plain `tool.register` so auditors
        // can tell metadata-bearing MCP registrations apart (WEFT-153).
        // Use bare identifiers as keys so stringify!($key) yields clean names
        // (quoted string keys become `"\"tool_name\""` under the macro).
        crate::chain_event!(
            "tools",
            crate::chain_event::EVENT_KIND_TOOL_REGISTER_METADATA,
            {
                tool_name: name,
                has_metadata: true,
                permission_level: permission_level
            }
        );
    }

    /// Check if a tool with the given name is registered.
    pub fn has(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    /// Look up a tool by name.
    pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
        self.tools.get(name).cloned()
    }

    /// Look up metadata for a tool by name.
    pub fn get_metadata(&self, name: &str) -> Option<&ToolMetadata> {
        self.metadata.get(name)
    }

    /// List all registered tool names (sorted alphabetically).
    pub fn list(&self) -> Vec<String> {
        let mut names: Vec<String> = self.tools.keys().cloned().collect();
        names.sort();
        names
    }

    /// Generate tool schemas in OpenAI function calling format.
    ///
    /// Returns one schema object per registered tool:
    /// ```json
    /// {
    ///   "type": "function",
    ///   "function": {
    ///     "name": "tool_name",
    ///     "description": "tool description",
    ///     "parameters": { ... json schema ... }
    ///   }
    /// }
    /// ```
    ///
    /// The returned vector is sorted by tool name for deterministic output.
    pub fn schemas(&self) -> Vec<serde_json::Value> {
        let mut schemas: Vec<(String, serde_json::Value)> = self
            .tools
            .iter()
            .map(|(name, tool)| {
                let schema = serde_json::json!({
                    "type": "function",
                    "function": {
                        "name": name,
                        "description": tool.description(),
                        "parameters": tool.parameters(),
                    }
                });
                (name.clone(), schema)
            })
            .collect();

        schemas.sort_by(|a, b| a.0.cmp(&b.0));
        schemas.into_iter().map(|(_, v)| v).collect()
    }

    /// Generate tool schemas for a specified subset of tools.
    ///
    /// Only includes tools whose names match at least one pattern in
    /// `allowed`. Patterns support glob syntax (`*` and `?`).
    ///
    /// This enables per-turn tool filtering: skills declare which tools
    /// they need, and only those schemas are sent to the LLM.
    pub fn schemas_for_tools(&self, allowed: &[String]) -> Vec<serde_json::Value> {
        let mut schemas: Vec<(String, serde_json::Value)> = self
            .tools
            .iter()
            .filter(|(name, _)| matches_any_pattern(name, allowed))
            .map(|(name, tool)| {
                let schema = serde_json::json!({
                    "type": "function",
                    "function": {
                        "name": name,
                        "description": tool.description(),
                        "parameters": tool.parameters(),
                    }
                });
                (name.clone(), schema)
            })
            .collect();

        schemas.sort_by(|a, b| a.0.cmp(&b.0));
        schemas.into_iter().map(|(_, v)| v).collect()
    }

    /// Execute a tool by name with optional permission enforcement.
    ///
    /// Equivalent to [`Self::execute_with_permit`] with `permit = None`
    /// (back-compat for callers that do not yet present a gate token).
    ///
    /// When `permissions` is `None`, all tools are allowed (backward
    /// compatibility for StaticRouter mode and unit tests).
    /// When `Some`, permissions are checked before the tool runs.
    ///
    /// Returns [`ToolError::NotFound`] if no tool with that name is registered.
    /// Returns [`ToolError::PermissionDenied`] if the caller lacks permission.
    ///
    /// WEFT-37: when a tool's argument JSON references a filesystem
    /// path (via `path`, `file`, `file_path`, etc.), this method
    /// acquires the corresponding per-path advisory lock for the
    /// duration of execution. Concurrent invocations against the same
    /// canonical path serialise; non-overlapping paths still run in
    /// full parallel. Native-only — browser/wasm has a single-threaded
    /// executor.
    pub async fn execute(
        &self,
        name: &str,
        args: serde_json::Value,
        permissions: Option<&UserPermissions>,
    ) -> Result<serde_json::Value, ToolError> {
        self.execute_with_permit(name, args, permissions, None).await
    }

    /// Execute a tool by name with optional permission enforcement and
    /// an optional per-tool [`ToolPermitToken`] (WEFT-341).
    ///
    /// # Proof-of-permission
    ///
    /// - `permit = None` and `require_permit = false` → skip (back-compat)
    /// - `permit = None` and `require_permit = true`  →
    ///   [`ToolError::PermissionDenied`] (missing)
    /// - `permit = Some(_)` → verify MAC / tool / agent / TTL; any
    ///   failure becomes [`ToolError::PermissionDenied`]
    ///
    /// Tools themselves may also call
    /// [`super::permit::present_proof`] with the same token if they
    /// re-check mid-execution; the registry check is the choke-point
    /// so most tools can ignore the token.
    pub async fn execute_with_permit(
        &self,
        name: &str,
        args: serde_json::Value,
        permissions: Option<&UserPermissions>,
        permit: Option<&ToolPermitToken>,
    ) -> Result<serde_json::Value, ToolError> {
        // Look up the tool first (NotFound fires before PermissionDenied).
        let tool = self
            .tools
            .get(name)
            .ok_or_else(|| ToolError::NotFound(name.to_string()))?;

        // WEFT-341: proof-of-permission (optional unless require_permit).
        // Agent id for the check comes from the token when present so a
        // forged agent cannot swap identities after issue; when no token
        // is presented the agent_id argument is unused by present_proof.
        let agent_for_proof = permit.map(|t| t.agent_id.as_str()).unwrap_or("");
        if let Err(err) = present_proof_at(
            &self.permit_issuer,
            permit,
            agent_for_proof,
            name,
            self.require_permit,
            // Use live clock; tests drive time via issue_at + short TTLs
            // or by constructing tokens directly against the issuer.
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos() as u64)
                .unwrap_or(0),
        ) {
            return Err(permit_to_tool_error(name, err));
        }

        // Permission check (only when permissions are provided).
        if let Some(perms) = permissions {
            let meta = self.metadata.get(name);
            check_tool_permission(name, perms, meta)?;
        }

        debug!(tool = %name, "executing tool");

        // WEFT-37: per-path advisory locks (native only).
        #[cfg(feature = "native")]
        {
            let paths = extract_paths(&args);
            // Sort paths so two callers locking the same set of paths
            // acquire them in the same order — prevents A-then-B vs
            // B-then-A deadlocks when a tool args object references
            // multiple paths at once.
            let mut sorted = paths;
            sorted.sort();
            sorted.dedup();
            // Hold guards for the duration of the call.
            let mut _guards: Vec<tokio::sync::OwnedMutexGuard<()>> =
                Vec::with_capacity(sorted.len());
            for p in sorted {
                _guards.push(acquire_path_lock(p).await);
            }
            return tool.execute(args).await;
        }
        #[cfg(not(feature = "native"))]
        {
            tool.execute(args).await
        }
    }

    /// Return the number of registered tools.
    pub fn len(&self) -> usize {
        self.tools.len()
    }

    /// Return true if no tools are registered.
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }

    /// Create a filtered snapshot of this registry containing only tools
    /// whose names are in the given allow list.
    ///
    /// If `allow` is empty, all tools are included (no filtering).
    /// If `deny` is non-empty, matching tools are excluded even if
    /// they appear in the allow list (deny overrides allow).
    ///
    /// This is used by the kernel supervisor to create per-agent
    /// tool registries that respect capability restrictions.
    pub fn filtered_tools(&self, allow: &[String], deny: &[String]) -> Self {
        let mut filtered = Self {
            tools: HashMap::new(),
            metadata: HashMap::new(),
            permit_issuer: Arc::clone(&self.permit_issuer),
            require_permit: self.require_permit,
        };
        for (name, tool) in &self.tools {
            // Check deny list first
            if deny.iter().any(|d| d == name) {
                continue;
            }
            // Check allow list (empty = all allowed)
            if !allow.is_empty() && !allow.iter().any(|a| a == name) {
                continue;
            }
            filtered.tools.insert(name.clone(), tool.clone());
            if let Some(meta) = self.metadata.get(name) {
                filtered.metadata.insert(name.clone(), meta.clone());
            }
        }
        filtered
    }

    /// Create a snapshot of this registry as a new `ToolRegistry`.
    ///
    /// The returned registry contains clones of all `Arc<dyn Tool>`
    /// handles currently registered. This is useful for passing a
    /// frozen copy of the tool set to components that need shared
    /// access (e.g., wrapped in `Arc<ToolRegistry>`) without requiring
    /// the original registry to be `Arc`-wrapped itself.
    pub fn snapshot(&self) -> Self {
        Self {
            tools: self.tools.clone(),
            metadata: self.metadata.clone(),
            permit_issuer: Arc::clone(&self.permit_issuer),
            require_permit: self.require_permit,
        }
    }
}

impl Default for ToolRegistry {
    fn default() -> Self {
        Self::new()
    }
}

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

    /// A simple test tool that echoes its input.
    struct EchoTool;

    #[async_trait]
    impl Tool for EchoTool {
        fn name(&self) -> &str {
            "echo"
        }

        fn description(&self) -> &str {
            "Echo back the input text"
        }

        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {
                    "text": {
                        "type": "string",
                        "description": "Text to echo"
                    }
                },
                "required": ["text"]
            })
        }

        async fn execute(&self, args: serde_json::Value) -> Result<serde_json::Value, ToolError> {
            let text = args
                .get("text")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ToolError::InvalidArgs("missing 'text' field".into()))?;
            Ok(serde_json::json!({ "output": text }))
        }
    }

    /// A tool that always fails for testing error paths.
    struct FailTool;

    #[async_trait]
    impl Tool for FailTool {
        fn name(&self) -> &str {
            "fail"
        }

        fn description(&self) -> &str {
            "A tool that always fails"
        }

        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {}
            })
        }

        async fn execute(&self, _args: serde_json::Value) -> Result<serde_json::Value, ToolError> {
            Err(ToolError::ExecutionFailed("intentional failure".into()))
        }
    }

    /// A math tool for testing multiple registrations.
    struct AddTool;

    #[async_trait]
    impl Tool for AddTool {
        fn name(&self) -> &str {
            "add"
        }

        fn description(&self) -> &str {
            "Add two numbers"
        }

        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {
                    "a": { "type": "number" },
                    "b": { "type": "number" }
                },
                "required": ["a", "b"]
            })
        }

        async fn execute(&self, args: serde_json::Value) -> Result<serde_json::Value, ToolError> {
            let a = args
                .get("a")
                .and_then(|v| v.as_f64())
                .ok_or_else(|| ToolError::InvalidArgs("missing 'a'".into()))?;
            let b = args
                .get("b")
                .and_then(|v| v.as_f64())
                .ok_or_else(|| ToolError::InvalidArgs("missing 'b'".into()))?;
            Ok(serde_json::json!({ "result": a + b }))
        }
    }

    /// Helper: build admin permissions (level 2, wildcard tool_access).
    fn admin_permissions() -> UserPermissions {
        UserPermissions {
            level: 2,
            tool_access: vec!["*".into()],
            ..UserPermissions::default()
        }
    }

    /// Helper: build user-level permissions with specific tools.
    fn user_permissions(tools: Vec<&str>) -> UserPermissions {
        UserPermissions {
            level: 1,
            tool_access: tools.into_iter().map(String::from).collect(),
            ..UserPermissions::default()
        }
    }

    /// Helper: build zero-trust permissions (empty tool_access).
    fn zero_trust_permissions() -> UserPermissions {
        UserPermissions::default()
    }

    #[test]
    fn new_registry_is_empty() {
        let registry = ToolRegistry::new();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);
        assert!(registry.list().is_empty());
    }

    #[test]
    fn default_registry_is_empty() {
        let registry = ToolRegistry::default();
        assert!(registry.is_empty());
    }

    #[test]
    fn register_and_get() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));

        let tool = registry.get("echo").unwrap();
        assert_eq!(tool.name(), "echo");
        assert_eq!(tool.description(), "Echo back the input text");
    }

    #[test]
    fn get_nonexistent_returns_none() {
        let registry = ToolRegistry::new();
        assert!(registry.get("nonexistent").is_none());
    }

    #[test]
    fn list_returns_sorted_names() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        registry.register(Arc::new(AddTool));
        registry.register(Arc::new(FailTool));

        let names = registry.list();
        assert_eq!(names, vec!["add", "echo", "fail"]);
    }

    #[test]
    fn len_reflects_registered_count() {
        let mut registry = ToolRegistry::new();
        assert_eq!(registry.len(), 0);

        registry.register(Arc::new(EchoTool));
        assert_eq!(registry.len(), 1);

        registry.register(Arc::new(AddTool));
        assert_eq!(registry.len(), 2);
    }

    #[test]
    fn register_replaces_existing() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        registry.register(Arc::new(EchoTool)); // Same name, should replace.
        assert_eq!(registry.len(), 1);
    }

    #[tokio::test]
    async fn execute_echo_tool() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));

        let result = registry
            .execute("echo", serde_json::json!({ "text": "hello" }), None)
            .await
            .unwrap();

        assert_eq!(result["output"], "hello");
    }

    #[tokio::test]
    async fn execute_add_tool() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(AddTool));

        let result = registry
            .execute("add", serde_json::json!({ "a": 3, "b": 4 }), None)
            .await
            .unwrap();

        assert_eq!(result["result"], 7.0);
    }

    #[tokio::test]
    async fn execute_not_found() {
        let registry = ToolRegistry::new();
        let result = registry
            .execute("missing", serde_json::json!({}), None)
            .await;

        assert!(result.is_err());
        match result.unwrap_err() {
            ToolError::NotFound(name) => assert_eq!(name, "missing"),
            other => panic!("expected NotFound, got: {other}"),
        }
    }

    #[tokio::test]
    async fn execute_tool_that_fails() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(FailTool));

        let result = registry.execute("fail", serde_json::json!({}), None).await;
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolError::ExecutionFailed(msg) => {
                assert_eq!(msg, "intentional failure");
            }
            other => panic!("expected ExecutionFailed, got: {other}"),
        }
    }

    #[tokio::test]
    async fn execute_with_invalid_args() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));

        let result = registry
            .execute("echo", serde_json::json!({}), None) // missing "text"
            .await;

        assert!(result.is_err());
        match result.unwrap_err() {
            ToolError::InvalidArgs(msg) => {
                assert!(msg.contains("text"));
            }
            other => panic!("expected InvalidArgs, got: {other}"),
        }
    }

    #[test]
    fn schemas_openai_format() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        registry.register(Arc::new(AddTool));

        let schemas = registry.schemas();
        assert_eq!(schemas.len(), 2);

        // Schemas should be sorted by name: "add" before "echo".
        let first = &schemas[0];
        assert_eq!(first["type"], "function");
        assert_eq!(first["function"]["name"], "add");
        assert_eq!(first["function"]["description"], "Add two numbers");
        assert!(
            first["function"]["parameters"]["properties"]
                .get("a")
                .is_some()
        );

        let second = &schemas[1];
        assert_eq!(second["type"], "function");
        assert_eq!(second["function"]["name"], "echo");
        assert_eq!(
            second["function"]["description"],
            "Echo back the input text"
        );
        assert!(
            second["function"]["parameters"]["properties"]
                .get("text")
                .is_some()
        );
    }

    #[test]
    fn schemas_empty_registry() {
        let registry = ToolRegistry::new();
        assert!(registry.schemas().is_empty());
    }

    #[test]
    fn schemas_for_tools_filters_by_pattern() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        registry.register(Arc::new(AddTool));
        registry.register(Arc::new(FailTool));

        // Exact name filter
        let schemas = registry.schemas_for_tools(&["echo".into()]);
        assert_eq!(schemas.len(), 1);
        assert_eq!(schemas[0]["function"]["name"], "echo");

        // Glob filter
        let schemas = registry.schemas_for_tools(&["*".into()]);
        assert_eq!(schemas.len(), 3);

        // No match
        let schemas = registry.schemas_for_tools(&["nonexistent".into()]);
        assert!(schemas.is_empty());

        // Multiple patterns
        let schemas = registry.schemas_for_tools(&["echo".into(), "add".into()]);
        assert_eq!(schemas.len(), 2);
    }

    #[test]
    fn tool_error_display() {
        let err = ToolError::NotFound("web_search".into());
        assert_eq!(err.to_string(), "tool not found: web_search");

        let err = ToolError::InvalidArgs("missing required field".into());
        assert_eq!(err.to_string(), "invalid arguments: missing required field");

        let err = ToolError::ExecutionFailed("command failed".into());
        assert_eq!(err.to_string(), "execution failed: command failed");

        let err = ToolError::PermissionDenied {
            tool: "test".into(),
            reason: "no exec access".into(),
        };
        assert_eq!(
            err.to_string(),
            "permission denied for tool 'test': no exec access"
        );

        let err = ToolError::FileNotFound("/tmp/missing.txt".into());
        assert_eq!(err.to_string(), "not found: /tmp/missing.txt");

        let err = ToolError::InvalidPath("../../../etc/passwd".into());
        assert_eq!(err.to_string(), "invalid path: ../../../etc/passwd");

        let err = ToolError::Timeout(30);
        assert_eq!(err.to_string(), "timeout after 30s");
    }

    #[test]
    fn tool_trait_is_object_safe() {
        // Verify Tool can be used as a trait object.
        fn accepts_tool(_t: &dyn Tool) {}
        let tool = EchoTool;
        accepts_tool(&tool);
    }

    #[test]
    fn tool_parameters_returns_valid_json_schema() {
        let tool = EchoTool;
        let params = tool.parameters();
        assert_eq!(params["type"], "object");
        assert!(params["properties"].is_object());
        assert!(params["required"].is_array());
    }

    // ── Glob matching unit tests ──────────────────────────────────────

    #[test]
    fn test_glob_star_matches() {
        assert!(glob_matches("file_*", "file_read"));
        assert!(glob_matches("file_*", "file_write"));
        assert!(!glob_matches("file_*", "web_search"));
        assert!(glob_matches("*", "anything"));
        assert!(glob_matches("*", ""));
        assert!(glob_matches("myserver__*", "myserver__search"));
        assert!(!glob_matches("myserver__*", "otherserver__search"));
    }

    #[test]
    fn test_glob_question_mark() {
        assert!(glob_matches("read_?", "read_a"));
        assert!(!glob_matches("read_?", "read_file"));
        assert!(glob_matches("?", "a"));
        assert!(!glob_matches("?", ""));
    }

    #[test]
    fn test_glob_exact_match_fast_path() {
        // matches_any_pattern uses exact match when no wildcards.
        assert!(matches_any_pattern("read_file", &["read_file".into()]));
        assert!(!matches_any_pattern("write_file", &["read_file".into()]));
    }

    // ── Permission check unit tests ───────────────────────────────────

    #[test]
    fn test_wildcard_allows_all_tools() {
        let perms = admin_permissions();
        assert!(check_tool_permission("exec_shell", &perms, None).is_ok());
        assert!(check_tool_permission("read_file", &perms, None).is_ok());
        assert!(check_tool_permission("myserver__tool", &perms, None).is_ok());
    }

    #[test]
    fn test_empty_allowlist_denies_all_tools() {
        let perms = zero_trust_permissions();
        let result = check_tool_permission("read_file", &perms, None);
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolError::PermissionDenied { tool, reason } => {
                assert_eq!(tool, "read_file");
                assert!(reason.contains("not in the allowed tools"));
            }
            other => panic!("expected PermissionDenied, got: {other}"),
        }
    }

    #[test]
    fn test_explicit_allowlist_permits_listed_tool() {
        let perms = user_permissions(vec!["read_file", "write_file"]);
        assert!(check_tool_permission("read_file", &perms, None).is_ok());
        assert!(check_tool_permission("write_file", &perms, None).is_ok());
    }

    #[test]
    fn test_explicit_allowlist_denies_unlisted_tool() {
        let perms = user_permissions(vec!["read_file", "write_file"]);
        assert!(check_tool_permission("exec_shell", &perms, None).is_err());
    }

    #[test]
    fn test_denylist_overrides_wildcard() {
        let perms = UserPermissions {
            level: 2,
            tool_access: vec!["*".into()],
            tool_denylist: vec!["exec_shell".into()],
            ..UserPermissions::default()
        };
        assert!(check_tool_permission("exec_shell", &perms, None).is_err());
        assert!(check_tool_permission("read_file", &perms, None).is_ok());
    }

    #[test]
    fn test_denylist_overrides_explicit_allow() {
        let perms = UserPermissions {
            level: 1,
            tool_access: vec!["exec_shell".into()],
            tool_denylist: vec!["exec_shell".into()],
            ..UserPermissions::default()
        };
        assert!(check_tool_permission("exec_shell", &perms, None).is_err());
    }

    #[test]
    fn test_glob_allowlist_pattern() {
        let perms = UserPermissions {
            level: 1,
            tool_access: vec!["file_*".into()],
            ..UserPermissions::default()
        };
        assert!(check_tool_permission("file_read", &perms, None).is_ok());
        assert!(check_tool_permission("file_write", &perms, None).is_ok());
        assert!(check_tool_permission("web_search", &perms, None).is_err());
    }

    #[test]
    fn test_glob_denylist_pattern() {
        let perms = UserPermissions {
            level: 2,
            tool_access: vec!["*".into()],
            tool_denylist: vec!["exec_*".into()],
            ..UserPermissions::default()
        };
        assert!(check_tool_permission("exec_shell", &perms, None).is_err());
        assert!(check_tool_permission("exec_spawn", &perms, None).is_err());
        assert!(check_tool_permission("read_file", &perms, None).is_ok());
    }

    #[test]
    fn test_metadata_required_level_blocks_low_user() {
        let perms = UserPermissions {
            level: 1,
            tool_access: vec!["*".into()],
            ..UserPermissions::default()
        };
        let meta = ToolMetadata {
            required_permission_level: Some(2),
            ..ToolMetadata::default()
        };
        let result = check_tool_permission("admin_tool", &perms, Some(&meta));
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolError::PermissionDenied { reason, .. } => {
                assert!(reason.contains("requires permission level 2"));
                assert!(reason.contains("user has level 1"));
            }
            other => panic!("expected PermissionDenied, got: {other}"),
        }
    }

    #[test]
    fn test_metadata_required_level_allows_sufficient_user() {
        let perms = UserPermissions {
            level: 2,
            tool_access: vec!["*".into()],
            ..UserPermissions::default()
        };
        let meta = ToolMetadata {
            required_permission_level: Some(2),
            ..ToolMetadata::default()
        };
        assert!(check_tool_permission("admin_tool", &perms, Some(&meta)).is_ok());
    }

    #[test]
    fn test_metadata_custom_permission_missing() {
        let perms = admin_permissions();
        let meta = ToolMetadata {
            required_custom_permissions: HashMap::from([(
                "exec_enabled".into(),
                serde_json::json!(true),
            )]),
            ..ToolMetadata::default()
        };
        let result = check_tool_permission("custom_tool", &perms, Some(&meta));
        assert!(result.is_err());
        match result.unwrap_err() {
            ToolError::PermissionDenied { reason, .. } => {
                assert!(reason.contains("exec_enabled"));
                assert!(reason.contains("not set"));
            }
            other => panic!("expected PermissionDenied, got: {other}"),
        }
    }

    #[test]
    fn test_metadata_custom_permission_wrong_value() {
        let perms = UserPermissions {
            level: 2,
            tool_access: vec!["*".into()],
            custom_permissions: HashMap::from([("exec_enabled".into(), serde_json::json!(false))]),
            ..UserPermissions::default()
        };
        let meta = ToolMetadata {
            required_custom_permissions: HashMap::from([(
                "exec_enabled".into(),
                serde_json::json!(true),
            )]),
            ..ToolMetadata::default()
        };
        let result = check_tool_permission("custom_tool", &perms, Some(&meta));
        assert!(result.is_err());
    }

    #[test]
    fn test_mcp_namespaced_tool_exact_match() {
        let perms = UserPermissions {
            level: 1,
            tool_access: vec!["myserver__search".into()],
            ..UserPermissions::default()
        };
        assert!(check_tool_permission("myserver__search", &perms, None).is_ok());
        assert!(check_tool_permission("myserver__exec", &perms, None).is_err());
    }

    #[test]
    fn test_mcp_namespaced_tool_glob_match() {
        let perms = UserPermissions {
            level: 1,
            tool_access: vec!["myserver__*".into()],
            ..UserPermissions::default()
        };
        assert!(check_tool_permission("myserver__search", &perms, None).is_ok());
        assert!(check_tool_permission("otherserver__search", &perms, None).is_err());
    }

    // ── Registry integration tests ────────────────────────────────────

    #[tokio::test]
    async fn test_registry_execute_with_none_permissions() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));

        // None permissions = backward compat, all tools allowed.
        let result = registry
            .execute("echo", serde_json::json!({ "text": "hello" }), None)
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_registry_execute_with_denied_permissions() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));

        let perms = zero_trust_permissions();
        let result = registry
            .execute("echo", serde_json::json!({ "text": "hello" }), Some(&perms))
            .await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ToolError::PermissionDenied { .. }
        ));
    }

    #[tokio::test]
    async fn test_registry_execute_not_found_before_permission_check() {
        let registry = ToolRegistry::new();
        let perms = zero_trust_permissions();

        // NotFound should fire before PermissionDenied.
        let result = registry
            .execute("nonexistent", serde_json::json!({}), Some(&perms))
            .await;
        assert!(matches!(result.unwrap_err(), ToolError::NotFound(_)));
    }

    // ── Security-critical tests ───────────────────────────────────────

    #[test]
    fn test_zero_trust_blocked_from_exec_and_spawn() {
        let perms = zero_trust_permissions();
        assert!(check_tool_permission("exec_shell", &perms, None).is_err());
        assert!(check_tool_permission("spawn", &perms, None).is_err());
    }

    #[test]
    fn test_user_level_blocked_from_exec_and_spawn() {
        let perms = user_permissions(vec![
            "read_file",
            "write_file",
            "edit_file",
            "list_dir",
            "web_search",
            "web_fetch",
            "message",
        ]);
        assert!(check_tool_permission("exec_shell", &perms, None).is_err());
        assert!(check_tool_permission("spawn", &perms, None).is_err());
    }

    #[test]
    fn test_admin_can_call_all_tools() {
        let perms = admin_permissions();
        assert!(check_tool_permission("exec_shell", &perms, None).is_ok());
        assert!(check_tool_permission("spawn", &perms, None).is_ok());
        assert!(check_tool_permission("read_file", &perms, None).is_ok());
        assert!(check_tool_permission("myserver__tool", &perms, None).is_ok());
    }

    #[test]
    fn test_permission_denied_error_includes_tool_name() {
        let perms = zero_trust_permissions();
        let result = check_tool_permission("exec_shell", &perms, None);
        match result.unwrap_err() {
            ToolError::PermissionDenied { tool, reason } => {
                assert_eq!(tool, "exec_shell");
                assert!(!reason.is_empty());
            }
            other => panic!("expected PermissionDenied, got: {other}"),
        }
    }

    #[test]
    fn test_permission_denied_error_display_format() {
        let err = ToolError::PermissionDenied {
            tool: "exec_shell".into(),
            reason: "tool is explicitly denied for this user".into(),
        };
        assert_eq!(
            err.to_string(),
            "permission denied for tool 'exec_shell': tool is explicitly denied for this user"
        );
    }

    // ── MCP metadata extraction ───────────────────────────────────────

    #[test]
    fn test_extract_mcp_metadata() {
        let decl = serde_json::json!({
            "required_permission_level": 2,
            "required_custom_permissions": {
                "exec_enabled": true
            }
        });
        let meta = extract_mcp_metadata(&decl);
        assert_eq!(meta.required_permission_level, Some(2));
        assert_eq!(
            meta.required_custom_permissions.get("exec_enabled"),
            Some(&serde_json::json!(true))
        );
    }

    #[test]
    fn test_extract_mcp_metadata_empty() {
        let decl = serde_json::json!({});
        let meta = extract_mcp_metadata(&decl);
        assert!(meta.required_permission_level.is_none());
        assert!(meta.required_custom_permissions.is_empty());
    }

    // ── Register with metadata ────────────────────────────────────────

    #[test]
    fn test_register_with_metadata_stores_metadata() {
        let mut registry = ToolRegistry::new();
        let meta = ToolMetadata {
            required_permission_level: Some(2),
            ..ToolMetadata::default()
        };
        registry.register_with_metadata(Arc::new(EchoTool), meta);

        let stored = registry.get_metadata("echo").unwrap();
        assert_eq!(stored.required_permission_level, Some(2));
    }

    /// WEFT-153: register_with_metadata emits tool.register.metadata chain event.
    #[test]
    fn test_register_with_metadata_emits_chain_event() {
        crate::chain_event::drain_pending_chain_events();

        let mut registry = ToolRegistry::new();
        let meta = ToolMetadata {
            required_permission_level: Some(2),
            ..ToolMetadata::default()
        };
        registry.register_with_metadata(Arc::new(EchoTool), meta);

        let events = crate::chain_event::drain_pending_chain_events();
        let meta_events: Vec<_> = events
            .iter()
            .filter(|e| e.kind == crate::chain_event::EVENT_KIND_TOOL_REGISTER_METADATA)
            .collect();
        assert_eq!(
            meta_events.len(),
            1,
            "expected one tool.register.metadata event, got {events:?}"
        );
        assert_eq!(meta_events[0].source, "tools");
        let payload = meta_events[0].payload.as_ref().unwrap();
        // chain_event! formats values via format!("{}"), so they are strings.
        assert_eq!(payload.get("tool_name").and_then(|v| v.as_str()), Some("echo"));
        assert_eq!(
            payload.get("has_metadata").and_then(|v| v.as_str()),
            Some("true")
        );
        assert_eq!(
            payload.get("permission_level").and_then(|v| v.as_str()),
            Some("2")
        );
    }

    #[tokio::test]
    async fn test_registry_execute_with_admin_and_metadata() {
        let mut registry = ToolRegistry::new();
        let meta = ToolMetadata {
            required_permission_level: Some(2),
            ..ToolMetadata::default()
        };
        registry.register_with_metadata(Arc::new(EchoTool), meta);

        let perms = admin_permissions();
        let result = registry
            .execute("echo", serde_json::json!({ "text": "hello" }), Some(&perms))
            .await;
        assert!(result.is_ok());
    }

    // ── filtered_tools tests ───────────────────────────────────────

    #[test]
    fn filtered_tools_allow_empty_returns_all() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        registry.register(Arc::new(AddTool));
        registry.register(Arc::new(FailTool));

        let filtered = registry.filtered_tools(&[], &[]);
        assert_eq!(filtered.len(), 3);
    }

    #[test]
    fn filtered_tools_allow_restricts() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        registry.register(Arc::new(AddTool));
        registry.register(Arc::new(FailTool));

        let filtered = registry.filtered_tools(&["echo".into(), "add".into()], &[]);
        assert_eq!(filtered.len(), 2);
        assert!(filtered.has("echo"));
        assert!(filtered.has("add"));
        assert!(!filtered.has("fail"));
    }

    #[test]
    fn filtered_tools_deny_overrides_allow() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        registry.register(Arc::new(AddTool));

        let filtered = registry.filtered_tools(&["echo".into(), "add".into()], &["echo".into()]);
        assert_eq!(filtered.len(), 1);
        assert!(filtered.has("add"));
        assert!(!filtered.has("echo"));
    }

    #[test]
    fn filtered_tools_deny_only() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        registry.register(Arc::new(AddTool));
        registry.register(Arc::new(FailTool));

        let filtered = registry.filtered_tools(&[], &["fail".into()]);
        assert_eq!(filtered.len(), 2);
        assert!(!filtered.has("fail"));
    }

    #[test]
    fn filtered_tools_preserves_metadata() {
        let mut registry = ToolRegistry::new();
        let meta = ToolMetadata {
            required_permission_level: Some(2),
            ..ToolMetadata::default()
        };
        registry.register_with_metadata(Arc::new(EchoTool), meta);
        registry.register(Arc::new(AddTool));

        let filtered = registry.filtered_tools(&["echo".into()], &[]);
        assert!(filtered.get_metadata("echo").is_some());
        assert_eq!(
            filtered
                .get_metadata("echo")
                .unwrap()
                .required_permission_level,
            Some(2)
        );
    }

    #[tokio::test]
    async fn test_registry_execute_with_low_level_and_metadata() {
        let mut registry = ToolRegistry::new();
        let meta = ToolMetadata {
            required_permission_level: Some(2),
            ..ToolMetadata::default()
        };
        registry.register_with_metadata(Arc::new(EchoTool), meta);

        let perms = UserPermissions {
            level: 1,
            tool_access: vec!["*".into()],
            ..UserPermissions::default()
        };
        let result = registry
            .execute("echo", serde_json::json!({ "text": "hello" }), Some(&perms))
            .await;
        assert!(matches!(
            result.unwrap_err(),
            ToolError::PermissionDenied { .. }
        ));
    }

    // ── WEFT-341: per-tool Permit token on execute ─────────────────

    #[tokio::test]
    async fn execute_with_permit_allow_shape() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        let issuer = registry.permit_issuer();
        let token = issuer.issue("agent-1", "echo", "noop");

        let result = registry
            .execute_with_permit(
                "echo",
                serde_json::json!({ "text": "hi" }),
                None,
                Some(&token),
            )
            .await
            .unwrap();
        assert_eq!(result["output"], "hi");
    }

    #[tokio::test]
    async fn execute_with_permit_none_is_back_compat() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        let result = registry
            .execute_with_permit("echo", serde_json::json!({ "text": "x" }), None, None)
            .await
            .unwrap();
        assert_eq!(result["output"], "x");
    }

    #[tokio::test]
    async fn execute_with_permit_deny_tool_mismatch() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        let issuer = registry.permit_issuer();
        // Token bound to a different tool name.
        let token = issuer.issue("agent-1", "write_file", "noop");

        let err = registry
            .execute_with_permit(
                "echo",
                serde_json::json!({ "text": "x" }),
                None,
                Some(&token),
            )
            .await
            .unwrap_err();
        match err {
            ToolError::PermissionDenied { tool, reason } => {
                assert_eq!(tool, "echo");
                assert!(
                    reason.contains("tool mismatch") || reason.contains("permit proof failed"),
                    "reason={reason}"
                );
            }
            other => panic!("expected PermissionDenied, got {other}"),
        }
    }

    #[tokio::test]
    async fn execute_with_permit_deny_invalid_mac() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool));
        let issuer = registry.permit_issuer();
        let mut token = issuer.issue("agent-1", "echo", "noop");
        token.mac = "ff".repeat(32);

        let err = registry
            .execute_with_permit(
                "echo",
                serde_json::json!({ "text": "x" }),
                None,
                Some(&token),
            )
            .await
            .unwrap_err();
        assert!(matches!(err, ToolError::PermissionDenied { .. }));
        assert!(err.to_string().contains("MAC") || err.to_string().contains("permit"));
    }

    #[tokio::test]
    async fn execute_with_permit_expired_shape() {
        let mut registry = ToolRegistry::new().with_permit_issuer(Arc::new(
            PermitIssuer::from_key(b"reg-test").with_ttl_ns(1),
        ));
        registry.register(Arc::new(EchoTool));
        let issuer = registry.permit_issuer();
        // Issue with ttl_ns=1 at t=0; by wall clock (>> 1 ns later) it's expired.
        let token = issuer.issue_at("agent-1", "echo", "noop", 0, 1);

        let err = registry
            .execute_with_permit(
                "echo",
                serde_json::json!({ "text": "x" }),
                None,
                Some(&token),
            )
            .await
            .unwrap_err();
        match err {
            ToolError::PermissionDenied { reason, .. } => {
                assert!(
                    reason.contains("expired"),
                    "expected expired shape in reason, got: {reason}"
                );
            }
            other => panic!("expected PermissionDenied, got {other}"),
        }
    }

    #[tokio::test]
    async fn execute_require_permit_missing_denies() {
        let mut registry = ToolRegistry::new().with_require_permit(true);
        registry.register(Arc::new(EchoTool));
        let err = registry
            .execute_with_permit("echo", serde_json::json!({ "text": "x" }), None, None)
            .await
            .unwrap_err();
        match err {
            ToolError::PermissionDenied { reason, .. } => {
                assert!(reason.contains("missing"), "reason={reason}");
            }
            other => panic!("expected PermissionDenied, got {other}"),
        }
    }

    // ── WEFT-37: per-path advisory locks ───────────────────────────

    /// A tool that records each invocation's "scope" — defined as
    /// "entered before previous one exited" — into a shared vector.
    /// If two invocations against the same path are properly
    /// serialised, every call records `{started: T, finished: T+ε}`
    /// with no overlap.
    #[cfg(feature = "native")]
    struct InterleaveTool {
        log: Arc<StdMutex<Vec<(u64, &'static str)>>>,
        delay_ms: u64,
    }

    #[cfg(feature = "native")]
    #[async_trait]
    impl Tool for InterleaveTool {
        fn name(&self) -> &str {
            "interleave"
        }
        fn description(&self) -> &str {
            "test tool that logs entry/exit events"
        }
        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": { "path": { "type": "string" } },
                "required": ["path"]
            })
        }
        async fn execute(&self, args: serde_json::Value) -> Result<serde_json::Value, ToolError> {
            let path = args
                .get("path")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let id = args.get("id").and_then(|v| v.as_u64()).unwrap_or(0);
            let _ = path; // unused in event log; lock is keyed off it
            {
                let mut log = self.log.lock().expect("log poisoned");
                log.push((id, "enter"));
            }
            tokio::time::sleep(std::time::Duration::from_millis(self.delay_ms)).await;
            {
                let mut log = self.log.lock().expect("log poisoned");
                log.push((id, "exit"));
            }
            Ok(serde_json::json!({ "ok": true }))
        }
    }

    #[cfg(feature = "native")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn weft37_same_path_executions_serialize() {
        _clear_path_locks_for_test();

        let log = Arc::new(StdMutex::new(Vec::<(u64, &'static str)>::new()));
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(InterleaveTool {
            log: log.clone(),
            delay_ms: 20,
        }));
        let registry = Arc::new(registry);

        // Spawn 10 parallel calls all hitting the same path.
        let mut handles = Vec::new();
        for id in 0..10u64 {
            let r = registry.clone();
            handles.push(tokio::spawn(async move {
                r.execute(
                    "interleave",
                    serde_json::json!({ "path": "/tmp/weft37-shared", "id": id }),
                    None,
                )
                .await
            }));
        }
        for h in handles {
            h.await.expect("task panicked").expect("tool failed");
        }

        // Verify the log is strictly enter/exit per call — no two
        // enters in a row.
        let log = log.lock().expect("log poisoned");
        let mut depth: i32 = 0;
        for (_id, kind) in log.iter() {
            match *kind {
                "enter" => {
                    depth += 1;
                    assert!(
                        depth <= 1,
                        "two parallel calls overlapped on the same path; \
                         events: {:?}",
                        log
                    );
                }
                "exit" => depth -= 1,
                _ => panic!("unexpected kind {kind}"),
            }
        }
        assert_eq!(depth, 0, "every enter must be matched by an exit");
        assert_eq!(log.len(), 20, "expected 10 enter + 10 exit events");
    }

    #[cfg(feature = "native")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn weft37_distinct_paths_run_in_parallel() {
        _clear_path_locks_for_test();

        let log = Arc::new(StdMutex::new(Vec::<(u64, &'static str)>::new()));
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(InterleaveTool {
            log: log.clone(),
            delay_ms: 50,
        }));
        let registry = Arc::new(registry);

        let start = std::time::Instant::now();
        let mut handles = Vec::new();
        for id in 0..4u64 {
            let r = registry.clone();
            handles.push(tokio::spawn(async move {
                r.execute(
                    "interleave",
                    serde_json::json!({
                        "path": format!("/tmp/weft37-distinct-{id}"),
                        "id": id,
                    }),
                    None,
                )
                .await
            }));
        }
        for h in handles {
            h.await.expect("task panicked").expect("tool failed");
        }
        let elapsed = start.elapsed();

        // 4 parallel 50ms tasks should finish in well under serial
        // 4 × 50ms = 200ms. Allow generous slack for CI noise.
        assert!(
            elapsed.as_millis() < 180,
            "distinct-path executions did not run in parallel; took {}ms",
            elapsed.as_millis()
        );
    }

    #[cfg(feature = "native")]
    #[test]
    fn weft37_canonicalize_collapses_dot_segments() {
        let a = canonicalize_for_lock("/tmp/foo/./bar");
        let b = canonicalize_for_lock("/tmp/foo/bar");
        let c = canonicalize_for_lock("/tmp/foo/baz/../bar");
        assert_eq!(a, b);
        assert_eq!(a, c);
    }

    #[cfg(feature = "native")]
    #[test]
    fn weft37_extract_paths_supports_common_keys() {
        for key in &["path", "file", "file_path", "filepath", "target"] {
            let args = serde_json::json!({ *key: "/tmp/x" });
            let paths = extract_paths(&args);
            assert_eq!(paths.len(), 1, "key {key} did not extract");
        }
        // Args without a recognised key produce no paths.
        let none = extract_paths(&serde_json::json!({ "text": "hello" }));
        assert!(none.is_empty());
    }
}