lean-ctx-server 3.12.8

The LeanCTX MCP server and its tools on top of LeanCTX | OSS.
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
// SPDX-License-Identifier: Apache-2.0

use std::sync::Arc;
use std::time::Duration;

use rmcp::ErrorData;
use serde_json::Value;

use crate::server::helpers::get_str;
use crate::server::tool_trait::{McpTool, ShellOutcome, ToolContext, ToolOutput};
use crate::tools::LeanCtxServer;
use rmcp::model::ContentBlock;

impl LeanCtxServer {
    /// Returns (output_text, saved_tokens, shell_outcome, content_blocks).
    /// saved_tokens > 0 indicates the tool already applied internal compression
    /// (shell engine, cache deltas, etc.). shell_outcome is `Some` for
    /// shell-executing tools so the caller can populate MCP error metadata
    /// (#389). content_blocks carries image/binary MCP blocks when present.
    pub(super) async fn dispatch_tool(
        &self,
        name: &str,
        args: Option<&serde_json::Map<String, Value>>,
        minimal: bool,
    ) -> Result<
        (
            String,
            usize,
            Option<ShellOutcome>,
            Option<Vec<ContentBlock>>,
        ),
        ErrorData,
    > {
        fn format_rate_limited(
            tool: &str,
            agent_id: &str,
            retry_after_ms: u64,
            args: Option<&serde_json::Map<String, Value>>,
        ) -> String {
            let as_json = get_str(args, "format").as_deref() == Some("json");
            if as_json {
                serde_json::json!({
                    "error": "rate_limited",
                    "tool": tool,
                    "agent_id": agent_id,
                    "retry_after_ms": retry_after_ms,
                })
                .to_string()
            } else {
                format!("[RATE LIMITED] tool={tool} retry_after_ms={retry_after_ms}")
            }
        }

        // A host replaces a native tool's output with a host hook's success
        // body, so a gate refusal on such a call must be an error: then the host
        // keeps the original output instead of a block message (#2089).
        let host_hook = crate::server::dynamic_tools::targets_internal_host_tool(name, args);
        let refuse = |text: String| {
            if host_hook {
                Err(ErrorData::invalid_request(text, None))
            } else {
                Ok((text, 0, None, None))
            }
        };

        // Cloud tools follow the Cloud release switch: off, every path (direct, ctx_call, ctx)
        // answers one line before any rate or capability gate.
        if let Some(line) = crate::server::dynamic_tools::withheld_cloud_tool_refusal(name, args) {
            return Ok((line.to_owned(), 0, None, None));
        }

        let agent_id = self
            .agent_id
            .read()
            .await
            .clone()
            .unwrap_or_else(|| "unknown".to_string());
        {
            if let lean_ctx::core::a2a::rate_limiter::RateLimitResult::Limited { retry_after_ms } =
                lean_ctx::core::a2a::rate_limiter::check_rate_limit(&agent_id, name)
            {
                return refuse(format_rate_limited(name, &agent_id, retry_after_ms, args));
            }
        }

        if name.starts_with("ctx_") {
            crate::server::tool_visibility::mark_auto_ctx_tool_used();
        }
        // K13: a tool call of a host family no enforcing hook regulates.
        if lean_ctx_cloud::metrics_v2::signals::recording() {
            let client = self.client_name.read().await.clone();
            lean_ctx_cloud::metrics_v2::signals::host_call(&client);
        }
        // Background semantic passes yield to tool calls in flight.
        let _activity = lean_ctx::core::graph_enricher::ToolActivity::begin();

        match name {
            "ctx_call" => {
                let (inner, arg_map) = crate::tools::registered::ctx_call::resolve_inner(args)?;

                if let lean_ctx::core::a2a::rate_limiter::RateLimitResult::Limited {
                    retry_after_ms,
                } = lean_ctx::core::a2a::rate_limiter::check_rate_limit(&agent_id, &inner)
                {
                    return refuse(format_rate_limited(
                        &inner,
                        &agent_id,
                        retry_after_ms,
                        arg_map.as_ref(),
                    ));
                }

                let inner_role_check = crate::server::role_guard::check_tool_access(&inner);
                if let Some(denied) =
                    crate::server::role_guard::into_call_tool_result(&inner_role_check)
                {
                    let msg = denied
                        .content
                        .first()
                        .and_then(|c| c.as_text())
                        .map_or_else(|| "Blocked by role policy".to_string(), |t| t.text.clone());
                    return refuse(msg);
                }

                // The decision is `core::workflow::tool_gate`, shared with the
                // direct gate (`call_tool/policy.rs::guard_workflow`).
                let active = self.workflow.read().await.clone();
                if let Some(run) = active {
                    use lean_ctx::core::workflow::ToolGate;
                    match lean_ctx::core::workflow::tool_gate(
                        &run,
                        &inner,
                        super::WORKFLOW_PASSTHROUGH_TOOLS,
                    ) {
                        ToolGate::Pass => {}
                        ToolGate::Expired => {
                            let mut wf = self.workflow.write().await;
                            *wf = None;
                            let _ = lean_ctx::core::workflow::clear_active();
                        }
                        ToolGate::Refuse(reason) => return refuse(reason),
                    }
                }

                let result = self
                    .dispatch_inner(&inner, arg_map.as_ref(), minimal)
                    .await?;
                // Inner tool is already recorded by dispatch_inner with correct tokens.
                Ok(result)
            }
            _ => self.dispatch_inner(name, args, minimal).await,
        }
    }

    /// Dispatches a single tool via the trait-based registry.
    /// Returns (output_text, saved_tokens, shell_outcome).
    async fn dispatch_inner(
        &self,
        name: &str,
        args: Option<&serde_json::Map<String, Value>>,
        minimal: bool,
    ) -> Result<
        (
            String,
            usize,
            Option<ShellOutcome>,
            Option<Vec<ContentBlock>>,
        ),
        ErrorData,
    > {
        // #454: when the user prefers their host's native editor, lean-ctx edit
        // operations are fully disabled — refused here so neither a direct call
        // nor `ctx_call` can reach them (list_tools already hides them).
        if lean_ctx::core::config::Config::load().edit_tool_blocked(name) {
            return Ok((
                format!(
                    "[disabled] '{name}' is turned off (prefer_native_editor): use your editor's \
                     built-in edit tool. Re-enable with `lean-ctx config set prefer_native_editor false`."
                ),
                0,
                None,
                None,
            ));
        }

        // Cloud tools follow the Cloud release switch: off, they never run.
        if crate::server::dynamic_tools::is_withheld_cloud_tool(name) {
            return Ok((lean_ctx_cloud::TOOL_NOT_AVAILABLE.to_owned(), 0, None, None));
        }

        // Cloud claims belong to the calling agent's session (C8): a shared
        // server serves several clients under one process and agent
        // identity, so it cannot bind a claim to its caller.
        if name == "ctx_tasks" && self.session_mode == crate::tools::SessionMode::Shared {
            return Ok((
                "[unavailable] ctx_tasks works only in a personal MCP session: a shared \
                 server cannot bind a task claim to the client that calls it."
                    .to_owned(),
                0,
                None,
                None,
            ));
        }

        if let Some(tool) = self.registry.as_ref().and_then(|r| r.get_arc(name)) {
            let empty = serde_json::Map::new();
            let args_map = args.unwrap_or(&empty);
            let aliased = canonicalize_arg_aliases(tool.as_ref(), args_map);
            let args_map = aliased.as_ref().unwrap_or(args_map);
            let project_root = {
                let session = self.session.read().await;
                session.project_root.clone().unwrap_or_default()
            };

            // Lazy, demand-driven index warming (#152): only tools that actually
            // need a prebuilt index trigger a (background, once-per-root) scan.
            // The first heavy pre-warm also warms any configured extra roots once.
            let authority = lean_ctx::core::workspace_authority::current();
            // Under a Workspace only its own roots are indexed (#2120); an
            // unusable one grants no root, so nothing is.
            let may_index = lean_ctx::core::workspace_authority::root_authorized(
                std::path::Path::new(&project_root),
            );
            if may_index
                && !project_root.is_empty()
                && lean_ctx::core::index_orchestrator::ensure_warm_for_tool(&project_root, name)
            {
                let extra_roots = match authority.snapshot() {
                    Some(snapshot) => snapshot.additional_root_strings(),
                    None => self.session.read().await.extra_roots.clone(),
                };
                if !extra_roots.is_empty() {
                    let primary = project_root.clone();
                    std::thread::spawn(move || {
                        lean_ctx::core::index_orchestrator::ensure_extra_roots_background(
                            &primary,
                            &extra_roots,
                        );
                    });
                }
            }

            let mut resolved_paths = std::collections::HashMap::new();
            let mut path_errors: std::collections::HashMap<String, String> =
                std::collections::HashMap::new();
            for key in PATH_LIKE_KEYS {
                if let Some(val) = args_map.get(*key) {
                    if let Some(raw) = val.as_str() {
                        match self.resolve_path_for_tool(raw, name).await {
                            Ok(resolved) => {
                                if !["path", "project_root", "root"].contains(key) {
                                    tracing::trace!(
                                        "[pathjail] resolved non-standard path key '{key}': {raw} -> {resolved}"
                                    );
                                }
                                resolved_paths.insert(key.to_string(), resolved);
                            }
                            Err(refusal) => {
                                tracing::debug!(
                                    "[dispatch] path resolution failed for '{key}' = '{raw}': {}",
                                    refusal.message
                                );
                                // Recorded once, here, with the calling tool.
                                self.record_path_refusal(name, &refusal).await;
                                path_errors.insert(key.to_string(), refusal.message);
                            }
                        }
                    } else {
                        let type_name = match val {
                            serde_json::Value::Number(_) => "number",
                            serde_json::Value::Bool(_) => "boolean",
                            serde_json::Value::Array(_) => "array",
                            serde_json::Value::Object(_) => "object",
                            serde_json::Value::Null => "null",
                            serde_json::Value::String(_) => unreachable!(),
                        };
                        path_errors.insert(
                            key.to_string(),
                            format!("{key} must be a string, got {type_name}"),
                        );
                    }
                }
            }

            let crp_mode = crate::tools::CrpMode::effective();
            // One snapshot after path resolution, which may have corrected a
            // stale root: the handler's root and its writable roots agree
            // (AP04-G6). The home jail scope opens other projects for reading
            // only; these roots stay writable for this call (pathjail_scope).
            let (project_root, extra_roots) = {
                let session = self.session.read().await;
                (
                    session.project_root.clone().unwrap_or_default(),
                    session.extra_roots.clone(),
                )
            };
            // Under a Workspace the call's roots are the snapshot's (#2120),
            // whatever the session carries; everything that derives roots from
            // the context (admitted sources, write roots, shell capture)
            // follows.
            let (project_root, extra_roots) = match authority.snapshot() {
                Some(snapshot) => {
                    let root = snapshot.project_root_for(&project_root);
                    let extra = snapshot
                        .granting_roots()
                        .map(|(path, _)| path.to_string_lossy().into_owned())
                        .filter(|path| *path != root)
                        .collect();
                    (root, extra)
                }
                // An unusable Workspace leaves the call without any root.
                None if authority.is_active() => (String::new(), Vec::new()),
                None => (project_root, extra_roots),
            };
            let ctx = crate::server::tool_trait::ToolContext {
                project_root,
                extra_roots,
                minimal,
                resolved_paths,
                crp_mode,
                cache: Some(self.cache.clone()),
                session: Some(self.session.instance()),
                tool_calls: Some(self.tool_calls.clone()),
                agent_id: Some(self.agent_id.clone()),
                workflow: Some(self.workflow.clone()),
                ledger: Some(self.ledger.clone()),
                client_name: Some(self.client_name.clone()),
                client_role: None,
                shell_access: None,
                pipeline_stats: Some(self.pipeline_stats.clone()),
                call_count: Some(self.call_count.clone()),
                autonomy: Some(self.autonomy.clone()),
                path_errors,
                bm25_cache: Some(self.bm25_cache.clone()),
                // This request's own sender, `None` without a progress token or
                // outside a `call_tool` scope.
                progress_sender: crate::server::tool_trait::REQUEST_PROGRESS
                    .try_with(Clone::clone)
                    .ok()
                    .flatten()
                    .map(|sender| std::sync::Arc::new(std::sync::Mutex::new(Some(sender)))),
                // #1781: the request's cancellation token, scoped per request by
                // `call_tool`. `try_with` yields `None` outside such a scope —
                // unit tests and internal dispatch paths — which leaves their
                // behaviour exactly as it was.
                cancel: crate::server::tool_trait::REQUEST_CT
                    .try_with(tokio_util::sync::CancellationToken::clone)
                    .ok(),
            };
            // Run the (synchronous) handler on the dedicated blocking pool under
            // a watchdog deadline (#271). `block_in_place` would pin one of the
            // few core workers and — being synchronous — cannot be interrupted
            // by `tokio::time::timeout` from the same task, so a hung handler
            // would silently swallow the JSON-RPC response and the MCP client
            // would crash with "Cannot read properties of undefined (reading
            // 'invoke')". `spawn_blocking` keeps the core workers free and lets
            // the watchdog always return a response.
            let provider_snapshot =
                name == "ctx_provider" && crate::tools::ctx_provider::is_snapshot_request(args_map);
            let handler_started = std::time::Instant::now();
            // Pair each handler's origin with its own output, including nested calls.
            let (output, observed_origin) = lean_ctx::core::archive::authority::capture(
                self.run_tool_handler(name, tool, args_map, ctx),
            )
            .await;
            let output = output?;
            // The tool's tokenizer measurement of its sources, for the receipt.
            if let Some(admissions) = lean_ctx::core::context_admission::capture::current() {
                admissions.set_original_tokens(output.original_tokens as u64);
            }
            let file_output = name == "ctx_execute"
                && args_map.get("action").and_then(Value::as_str) == Some("file")
                && matches!(output.shell_outcome, Some(ShellOutcome::Exit(0)));
            // Hand every observed source — and an incomplete observation as
            // such — to the outer pipeline capture: it decides, from the
            // tool's own declaration, whether the set may authorize reuse
            // (replay, response cache, source-bound archive). Nested handlers
            // join the same outer set.
            if let Some(origin) = &observed_origin {
                origin.clone().publish();
            }
            // The reference store below keeps its narrower rule: only the
            // admitted file handler's output is bound there.
            let output_origin = observed_origin.filter(|_| file_output);
            let handler_ms = handler_started.elapsed().as_millis() as u64;

            // Image/binary content blocks bypass all text processing.
            if output.content_blocks.is_some() {
                if let Some(ref path) = output.path {
                    self.record_call_with_path(
                        name,
                        0,
                        0,
                        Some("image".to_string()),
                        Some(path),
                        handler_ms,
                    )
                    .await;
                } else {
                    self.record_call_with_timing(name, 0, 0, Some("image".to_string()), handler_ms)
                        .await;
                }
                return Ok((
                    String::new(),
                    0,
                    output.shell_outcome,
                    output.content_blocks,
                ));
            }

            let config_changed =
                super::tools_config_watch::has_changed(&self.last_tools_config_hash);
            if (output.changed || config_changed)
                && let Some(peer) = self.peer.read().await.as_ref()
            {
                if config_changed {
                    tracing::info!(
                        "Tool-config changed (profile/enabled/disabled) — sending tools/list_changed"
                    );
                }
                super::notifications::send_tools_list_changed(peer).await;
            }

            let headers_only =
                lean_ctx::core::config::ResponseVerbosity::effective().is_headers_only();
            let header_line = if headers_only && !provider_snapshot {
                Some(output.to_header_line(name))
            } else {
                None
            };

            let output_token_estimate = lean_ctx::core::tokens::count_tokens(&output.text) as u32;

            if let Some(ref path) = output.path {
                {
                    // Skip ledger record for ctx_read — it's recorded in post_dispatch
                    // with correct final token counts after terse compression.
                    if name != "ctx_read" {
                        let sent_tokens = if output.original_tokens > 0 {
                            output.original_tokens.saturating_sub(output.saved_tokens)
                        } else {
                            lean_ctx::core::tokens::count_tokens(&output.text)
                        };
                        let orig = if output.original_tokens > 0 {
                            output.original_tokens
                        } else {
                            sent_tokens
                        };
                        let mode_str = output.mode.as_deref().unwrap_or("full");
                        let mut ledger = self.ledger.write().await;
                        ledger.record(path, mode_str, orig, sent_tokens);
                        ledger.save_debounced();
                    }
                }
                self.record_call_with_path(
                    name,
                    output.original_tokens,
                    output.saved_tokens,
                    output.mode,
                    Some(path),
                    handler_ms,
                )
                .await;
            } else {
                self.record_call_with_timing(
                    name,
                    output.original_tokens,
                    output.saved_tokens,
                    output.mode,
                    handler_ms,
                )
                .await;
            }

            let agent_id = self
                .agent_id
                .read()
                .await
                .clone()
                .unwrap_or_else(|| "unknown".into());
            let role = lean_ctx::core::roles::active_role_name();
            {
                use lean_ctx::core::audit_trail as audit;
                // Keyed digests (audit entry v2): a digest that leaves the
                // machine cannot be tested against a guessed input. Without
                // the local key the input falls back to the v1 plain hash.
                let input_hash = audit::keyed_input_digest(args_map)
                    .unwrap_or_else(|| audit::hash_input(args_map));
                let data = audit::AuditEntryData {
                    agent_id: agent_id.clone(),
                    tool: name.to_string(),
                    action: None,
                    input_hash,
                    output_tokens: output_token_estimate,
                    role: role.clone(),
                    event_type: audit::AuditEventType::ToolCall,
                };
                let session_id = self.session.read().await.id.clone();
                if session_id.is_empty() {
                    audit::record(data);
                } else {
                    audit::record_v2(
                        data,
                        audit::SessionFacts {
                            session_id,
                            // The instance id (Cloud) and policy digest (ent2)
                            // are bound once those land.
                            instance_id: None,
                            policy_digest: None,
                            decision: audit::AuditDecision::Allow,
                            output_digest: audit::keyed_digest("output", output.text.as_bytes()),
                        },
                    );
                }
            }

            let saved = output.saved_tokens;
            let raw_text = header_line.unwrap_or(output.text);
            let final_text = if provider_snapshot {
                raw_text
            } else {
                sanitized_tool_text(name, raw_text)
            };

            // Context immune system: scan for prompt-injection patterns in tool output,
            // read as the kind of content its source file is (code, logs, prose).
            let output_kind = lean_ctx::core::output_sanitizer::ContentKind::of(
                &final_text,
                output.path.as_deref().map(std::path::Path::new),
            );
            let injection_signals =
                lean_ctx::core::output_sanitizer::detect_injection_as(&final_text, output_kind);
            // Sources the gateway already flagged are counted by their receipt.
            let gateway_flagged = lean_ctx::core::context_admission::capture::current()
                .is_some_and(|admissions| admissions.flagged_injection());
            if !injection_signals.is_empty() && !gateway_flagged {
                tracing::warn!(
                    tool = name,
                    lines = injection_signals.len(),
                    "prompt-injection patterns detected in tool output"
                );
                // Flagged, not neutralized: the output still reaches the agent.
                // One flag per output object, recorded once per process.
                let flag = lean_ctx::core::security_events::InjectionFlag {
                    object_sha256: {
                        use sha2::Digest as _;
                        lean_ctx::core::agent_identity::hex_encode(&sha2::Sha256::digest(
                            final_text.as_bytes(),
                        ))
                    },
                    patterns: lean_ctx::core::output_sanitizer::InjectionCategory::mask(
                        &injection_signals,
                    ),
                };
                if lean_ctx::core::security_events::record_injections(name, &agent_id, &[flag]) > 0
                {
                    self.publish_value_snapshot().await;
                }
            }

            let reference_enabled = std::env::var("LEAN_CTX_REFERENCE_RESULTS").map_or_else(
                |_| lean_ctx::core::config::Config::load().reference_results,
                |v| v == "1" || v == "true",
            );

            // An explicit file read must always return its content — never a
            // stored-reference stub — so the agent can edit against the lines. The
            // firewall already exempts reads; the reference-results path honours the
            // same rule via `is_protected_read` (otherwise enabling reference_results
            // silently turns `ctx_read` into an un-editable "Output stored …" preview).
            if reference_enabled
                && !provider_snapshot
                && !lean_ctx::core::firewall::is_protected_read(name)
                && !output.shell_outcome.as_ref().is_some_and(
                    crate::server::tool_trait::ShellOutcome::is_terminal_background_status,
                )
                && final_text.len() > REFERENCE_THRESHOLD
                && let Some(ref_id) = super::reference_store::store_with_authority(
                    &final_text,
                    output_origin.as_ref(),
                )
            {
                let mut preview_end = final_text.len().min(200);
                while preview_end > 0 && !final_text.is_char_boundary(preview_end) {
                    preview_end -= 1;
                }
                let resolve = if output_origin.is_some() {
                    format!("ctx_expand(id=\"{ref_id}\")")
                } else {
                    format!("/v1/references/{ref_id}")
                };
                let summary = format!(
                    "[Reference: {ref_id}] Output stored ({} chars, ~{} tokens). Resolve: {resolve}\nPreview: {}...",
                    final_text.len(),
                    final_text.len() / 4,
                    &final_text[..preview_end]
                );
                // The outcome must survive the reference-store substitution —
                // a failed shell command stays a failure even when its output
                // is delivered out-of-band (#389).
                return Ok((summary, saved, output.shell_outcome, None));
            }

            return Ok((final_text, saved, output.shell_outcome, None));
        }

        // A removed tool names its successor; an unknown one (#712) gets the
        // closest registered name so a typo (`ctx_raed`) costs a hint, not a
        // blind retry.
        if let Some(message) = crate::server::dynamic_tools::removed_tool_message(name) {
            return Err(ErrorData::new(
                rmcp::model::ErrorCode::METHOD_NOT_FOUND,
                message,
                None,
            ));
        }
        let suggestion = self
            .registry
            .as_ref()
            .and_then(|r| {
                let names = r
                    .names()
                    .into_iter()
                    .filter(|n| !crate::server::dynamic_tools::is_withheld_cloud_tool(n));
                lean_ctx::core::levenshtein::closest(name, names)
            })
            .map(|s| format!(" — did you mean '{s}'?"))
            .unwrap_or_default();
        Err(ErrorData::new(
            rmcp::model::ErrorCode::METHOD_NOT_FOUND,
            format!("Unknown tool: {name}{suggestion}"),
            None,
        ))
    }

    /// Execute a (synchronous) tool handler on the blocking pool under a
    /// watchdog deadline (#271).
    ///
    /// The handler is `Send + 'static` (it owns an `Arc<dyn McpTool>`, a cloned
    /// arg map and the `ToolContext`), so it runs via `spawn_blocking` on the
    /// dedicated blocking-thread pool. That keeps the few core async workers free
    /// to keep driving the stdio JSON-RPC loop, and — crucially — lets the
    /// watchdog `timeout` actually fire (a synchronous `block_in_place` on the
    /// same task can never be timed out, because the task's own timer cannot be
    /// polled while it blocks).
    async fn run_tool_handler(
        &self,
        name: &str,
        tool: Arc<dyn McpTool>,
        args_map: &serde_json::Map<String, Value>,
        ctx: ToolContext,
    ) -> Result<ToolOutput, ErrorData> {
        let watchdog = Self::handler_watchdog_for(name, args_map);
        let args_owned = args_map.clone();
        let tool_name = name.to_string();
        let agent_id = self
            .agent_id
            .read()
            .await
            .clone()
            .unwrap_or_else(|| "unknown".to_string());
        // Tokio task locals do not propagate into spawn_blocking. Capture the
        // immutable handoff, then scope only the synchronous handler invocation.
        let handoff = lean_ctx::core::context_kernel::bridge::runtime::current_handoff();
        let task = lean_ctx::core::task_spine::TaskSpine::current();
        let receipt_capture = crate::server::native_receipts::current_capture();
        let archive_capture = lean_ctx::core::archive::authority::current_capture();
        let admissions = lean_ctx::core::context_admission::capture::current();
        // The presenter capability the host showed for this call: without it
        // the handler would act as the process's own presenter.
        let presenter = lean_ctx::core::archive::presented::request_presenter();
        // The caller's own session for session-continuity reads and writes in
        // the handler (I07): never the project's latest saved session.
        let caller = ctx.session.clone();
        let workspace = lean_ctx::core::workspace_authority::current();
        let session_rights = lean_ctx::core::session_rights::current();
        // The user's approval of this ctx_shell call (server::shell_approval).
        let shell_grant = crate::server::shell_approval::current_grant();
        let write_roots: Vec<String> = std::iter::once(ctx.project_root.clone())
            .chain(ctx.extra_roots.iter().cloned())
            .collect();
        let policy_project = lean_ctx::core::policy::runtime::REQUEST_PROJECT
            .try_with(|slot| slot.borrow().clone())
            .ok()
            .flatten()
            .or_else(|| {
                (!ctx.project_root.is_empty()).then(|| std::path::PathBuf::from(&ctx.project_root))
            });
        let join = tokio::task::spawn_blocking(move || {
            let handle = || {
                lean_ctx::core::archive::authority::CAPTURE.sync_scope(archive_capture, || {
                    lean_ctx::core::task_spine::TaskSpine::sync_scope(task, || {
                        crate::server::native_receipts::NATIVE_RECEIPT_CAPTURE.sync_scope(
                            receipt_capture,
                            || {
                                lean_ctx::core::policy::runtime::REQUEST_PROJECT.sync_scope(
                                    std::cell::RefCell::new(policy_project),
                                    || {
                                        lean_ctx::core::context_kernel::bridge::runtime::KERNEL_PLANNING_HANDOFF
                                            .sync_scope(handoff, || {
                                                lean_ctx::core::context_admission::capture::ADMISSIONS
                                                    .sync_scope(admissions, || {
                                                        lean_ctx::core::archive::presented::with_presenter(
                                                            presenter,
                                                            || {
                                                                lean_ctx::core::pathjail_scope::with_request_write_roots(
                                                                    &write_roots,
                                                                    || {
                                                                        lean_ctx::core::session::caller::scope(
                                                                            caller.clone(),
                                                                            || {
                                                                                lean_ctx::core::workspace_authority::sync_scope(
                                                                                    workspace.clone(),
                                                                                    || {
                                                                                        crate::server::shell_approval::SHELL_GRANT
                                                                                            .sync_scope(shell_grant.clone(), || {
                                                                                                tool.handle(&args_owned, &ctx)
                                                                                            })
                                                                                    },
                                                                                )
                                                                            },
                                                                        )
                                                                    },
                                                                )
                                                            },
                                                        )
                                                    })
                                            })
                                    },
                                )
                            },
                        )
                    })
                })
            };
            // Security events are counted once per tool result: the collector
            // sees exactly this handler, and the tally is recorded (audit trail +
            // session counters) before `record_call` publishes the value snapshot.
            let (result, tally) = lean_ctx::core::security_events::collect_call(|| {
                lean_ctx::core::session_rights::sync_scope(session_rights, handle)
            });
            lean_ctx::core::security_events::record_call(&tool_name, &agent_id, &tally);
            result
        });
        Self::watchdog_join(name, join, watchdog).await
    }

    /// [`Self::handler_watchdog`], except that `ctx_agent action=wait` may
    /// block for its own `timeout_secs` (it bounds itself) plus a margin.
    fn handler_watchdog_for(name: &str, args: &serde_json::Map<String, Value>) -> Option<Duration> {
        let base = Self::handler_watchdog(name)?;
        if name == "ctx_agent" && args.get("action").and_then(Value::as_str) == Some("wait") {
            let secs = args
                .get("timeout_secs")
                .and_then(Value::as_u64)
                .unwrap_or(crate::tools::ctx_agent::WAIT_DEFAULT_SECS)
                .min(crate::tools::ctx_agent::WAIT_MAX_SECS);
            return Some(base.max(Duration::from_secs(secs + 30)));
        }
        Some(base)
    }

    /// Await a blocking handler's join handle, enforcing an optional watchdog.
    ///
    /// On timeout the join handle is **aborted** — the blocking-pool thread
    /// receives a cancellation signal so it does not permanently leak a pool
    /// slot (#1018). A clean error is always returned so the MCP client gets a
    /// JSON-RPC reply. A handler panic is isolated and surfaced as an error too.
    async fn watchdog_join(
        name: &str,
        join: tokio::task::JoinHandle<Result<ToolOutput, ErrorData>>,
        watchdog: Option<Duration>,
    ) -> Result<ToolOutput, ErrorData> {
        let Some(limit) = watchdog else {
            return Self::unwrap_join(name, join.await);
        };
        tokio::select! {
            joined = join => Self::unwrap_join(name, joined),
            () = tokio::time::sleep(limit) => {
                // The JoinHandle was moved into `select!` — when this branch
                // wins, Tokio drops the handle which sets the task's cancelled
                // flag. For `spawn_blocking` this means the thread will be
                // reclaimed once it returns (#1018).
                lean_ctx::core::io_health::record_freeze();
                tracing::error!(
                    tool = name,
                    timeout_secs = limit.as_secs(),
                    "tool watchdog fired — handler cancelled to reclaim pool slot (#1018)"
                );
                Err(ErrorData::internal_error(
                    format!(
                        "tool '{name}' exceeded its {}s watchdog and was abandoned. \
                         The MCP server is still running — retry or narrow the request.",
                        limit.as_secs()
                    ),
                    None,
                ))
            }
        }
    }

    /// Collapse a `spawn_blocking` join result into the handler result.
    /// A `JoinError` (handler panic) becomes a clean error instead of crashing
    /// the request task.
    fn unwrap_join(
        name: &str,
        joined: Result<Result<ToolOutput, ErrorData>, tokio::task::JoinError>,
    ) -> Result<ToolOutput, ErrorData> {
        match joined {
            Ok(inner) => inner,
            Err(join_err) => {
                tracing::error!(
                    tool = name,
                    is_panic = join_err.is_panic(),
                    "tool handler did not complete (panic isolated on the blocking pool)"
                );
                Err(ErrorData::internal_error(
                    format!(
                        "tool '{name}' failed unexpectedly. The MCP server is still running \
                         — retry or use a different approach."
                    ),
                    None,
                ))
            }
        }
    }

    /// Watchdog deadline for a single tool handler, or `None` to disable it.
    ///
    /// `ctx_shell` / `ctx_execute` run arbitrary user commands (builds, long
    /// test suites) and already enforce their own command timeouts, so a generic
    /// watchdog would wrongly abort a legitimate long-running command. Every
    /// other tool is bounded so a hang can never swallow the JSON-RPC response.
    /// Tunable via `LEAN_CTX_TOOL_TIMEOUT_SECS` (`0` disables the watchdog).
    fn handler_watchdog(name: &str) -> Option<Duration> {
        if super::is_shell_tool_name(name) {
            return None;
        }
        watchdog_from_secs(read_watchdog_secs())
    }
}

/// Last-pass degenerate-output filter — EXCEPT for protected read tools (#709):
/// their contract is byte-fidelity. File content is never a model artifact, so
/// a file that legitimately contains flood-like lines (`!!!!!!!!!!` in test
/// fixtures, ASCII art) must survive a `mode=raw`/`full` read byte-for-byte.
/// Every other tool keeps the #257 degenerate-CJK/flood cleanup, whose target
/// is compressed/summarized output.
fn sanitized_tool_text(name: &str, raw_text: String) -> String {
    if lean_ctx::core::firewall::is_protected_read(name) {
        return raw_text;
    }
    lean_ctx::core::output_sanitizer::sanitize(&raw_text)
}

/// Read the configured watchdog budget in seconds (defaults to
/// [`DEFAULT_TOOL_TIMEOUT_SECS`]). Kept separate from the policy so the pure
/// `secs -> Option<Duration>` mapping stays trivially testable.
fn read_watchdog_secs() -> u64 {
    std::env::var("LEAN_CTX_TOOL_TIMEOUT_SECS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(DEFAULT_TOOL_TIMEOUT_SECS)
}

/// Map a watchdog budget in seconds to a duration; `0` disables the watchdog.
fn watchdog_from_secs(secs: u64) -> Option<Duration> {
    (secs > 0).then(|| Duration::from_secs(secs))
}

const REFERENCE_THRESHOLD: usize = 4000;

/// Default per-tool watchdog budget (#271). Long enough that no legitimate
/// read/search/graph call ever hits it, short enough that a hang degrades to a
/// clean error instead of a dropped request.
const DEFAULT_TOOL_TIMEOUT_SECS: u64 = 120;

use super::tool_trait::PATH_LIKE_KEYS;

/// Spellings agents carry over from other tool sets (Claude Code's
/// `file_path`, shell tools' `cmd`) for a parameter a tool calls differently.
const ARG_ALIASES: &[(&str, &[&str])] = &[
    ("path", &["file_path", "filePath", "file", "filename"]),
    ("command", &["cmd"]),
];

/// Renames an alias to the canonical parameter when the tool declares the
/// canonical name but not the alias, and the caller sent only the alias. A
/// tool that declares the alias itself keeps its own meaning for it, and an
/// explicit canonical value always wins. `None` when nothing changed, so the
/// common call borrows the original map.
pub fn canonicalize_arg_aliases(
    tool: &dyn McpTool,
    args: &serde_json::Map<String, Value>,
) -> Option<serde_json::Map<String, Value>> {
    let pending: Vec<(&str, &str)> = ARG_ALIASES
        .iter()
        .filter(|(canonical, _)| !args.contains_key(*canonical))
        .filter_map(|(canonical, aliases)| {
            aliases
                .iter()
                .find(|alias| args.get(**alias).is_some_and(Value::is_string))
                .map(|alias| (*canonical, *alias))
        })
        .collect();
    if pending.is_empty() {
        return None;
    }
    let def = tool.tool_def();
    let declared = def
        .input_schema
        .get("properties")
        .and_then(Value::as_object)?;
    let mut out = args.clone();
    let mut changed = false;
    for (canonical, alias) in pending {
        if declared.contains_key(canonical)
            && !declared.contains_key(alias)
            && let Some(value) = out.remove(alias)
        {
            out.insert(canonical.to_string(), value);
            changed = true;
        }
    }
    changed.then_some(out)
}

#[cfg(test)]
mod session_stats_tests;

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

    fn tool(name: &str) -> Arc<dyn McpTool> {
        crate::server::registry::build_registry()
            .get_arc(name)
            .unwrap_or_else(|| panic!("{name} registered"))
    }

    fn map(v: Value) -> serde_json::Map<String, Value> {
        match v {
            Value::Object(m) => m,
            other => panic!("expected an object, got {other}"),
        }
    }

    #[test]
    fn file_path_becomes_path_for_ctx_read() {
        let out = canonicalize_arg_aliases(
            tool("ctx_read").as_ref(),
            &map(serde_json::json!({"file_path": "src/main.rs", "mode": "map"})),
        )
        .expect("alias renamed");
        assert_eq!(out.get("path").and_then(Value::as_str), Some("src/main.rs"));
        assert!(!out.contains_key("file_path"));
    }

    #[test]
    fn cmd_becomes_command_for_ctx_shell() {
        let out = canonicalize_arg_aliases(
            tool("ctx_shell").as_ref(),
            &map(serde_json::json!({"cmd": "git status"})),
        )
        .expect("alias renamed");
        assert_eq!(
            out.get("command").and_then(Value::as_str),
            Some("git status")
        );
    }

    #[test]
    fn declared_alias_and_explicit_canonical_are_untouched() {
        // ctx_search declares `file_path` itself (#846).
        assert!(
            canonicalize_arg_aliases(
                tool("ctx_search").as_ref(),
                &map(serde_json::json!({"pattern": "x", "file_path": "a.rs"})),
            )
            .is_none()
        );
        assert!(
            canonicalize_arg_aliases(
                tool("ctx_read").as_ref(),
                &map(serde_json::json!({"path": "a.rs", "file_path": "b.rs"})),
            )
            .is_none()
        );
    }
}

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

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn provider_snapshot_uses_normal_pipeline_and_token_accounting() {
        let server = crate::tools::create_server();
        let args = serde_json::json!({
            "action": "query", "mode": "snapshot", "provider": "gitlab",
            "resource": "merge_requests", "limit": 0
        });
        let (text, saved, _, blocks) = server
            .dispatch_inner("ctx_provider", args.as_object(), false)
            .await
            .expect("bounded input error is a snapshot envelope");
        assert!(
            blocks.is_none(),
            "snapshot must not bypass policy/budget/IR processing"
        );
        assert_eq!(saved, 0);
        let parsed: Value = serde_json::from_str(&text).expect("unmodified JSON");
        assert_eq!(parsed["schema_version"], 1);
        assert!(parsed.get("error").is_some());
        let calls = server.tool_calls.read().await;
        let record = calls.last().expect("snapshot call recorded");
        assert_eq!(record.mode.as_deref(), Some("snapshot"));
        assert_eq!(
            record.original_tokens,
            lean_ctx::core::tokens::count_tokens(&text)
        );
        assert!(record.original_tokens > 0);
        assert_eq!(record.saved_tokens, 0);
    }

    #[test]
    fn protected_reads_bypass_the_degenerate_output_sanitizer() {
        // #709 follow-up: an explicit read is byte-exact even for content that
        // *looks* like degenerate model output (fixtures full of `!!!!!!!!!!`).
        let fixture = "ok line\n!!!!!!!!!!!!\ntail\n".to_string();
        assert_eq!(
            sanitized_tool_text("ctx_read", fixture.clone()),
            fixture,
            "ctx_read must never lose file bytes to the flood filter"
        );

        // Non-read tools keep the #257 degenerate-output cleanup.
        let cleaned = sanitized_tool_text("ctx_shell", fixture);
        assert!(
            !cleaned.contains("!!!!!!!!!!"),
            "flood line must be removed"
        );
        assert!(cleaned.contains("ok line") && cleaned.contains("tail"));
    }

    #[test]
    fn path_like_keys_has_no_duplicates() {
        let mut seen = std::collections::HashSet::new();
        for key in PATH_LIKE_KEYS {
            assert!(seen.insert(*key), "duplicate PATH_LIKE_KEYS entry: {key}");
        }
    }

    #[test]
    fn path_like_keys_includes_primary_keys() {
        for primary in &["path", "project_root", "root"] {
            assert!(
                PATH_LIKE_KEYS.contains(primary),
                "primary key '{primary}' missing from PATH_LIKE_KEYS"
            );
        }
    }

    #[test]
    fn path_like_keys_all_non_empty() {
        for key in PATH_LIKE_KEYS {
            assert!(!key.is_empty(), "PATH_LIKE_KEYS contains empty string");
        }
        assert!(
            PATH_LIKE_KEYS.len() >= 3,
            "PATH_LIKE_KEYS must have at least the 3 primary keys"
        );
    }

    #[test]
    fn watchdog_disabled_for_long_running_shell_tools() {
        assert!(
            LeanCtxServer::handler_watchdog("ctx_shell").is_none(),
            "ctx_shell runs arbitrary user commands and must not be watchdog-bounded"
        );
        assert!(
            LeanCtxServer::handler_watchdog("ctx_execute").is_none(),
            "ctx_execute must not be watchdog-bounded"
        );
    }

    #[test]
    fn ctx_agent_wait_outlives_the_default_watchdog_by_its_own_timeout() {
        let args = |v: Value| v.as_object().cloned().unwrap();
        if std::env::var_os("LEAN_CTX_TOOL_TIMEOUT_SECS").is_some() {
            return;
        }
        let wait = LeanCtxServer::handler_watchdog_for(
            "ctx_agent",
            &args(serde_json::json!({"action": "wait", "timeout_secs": 900})),
        );
        assert_eq!(wait, Some(Duration::from_secs(930)));
        let default_wait = LeanCtxServer::handler_watchdog_for(
            "ctx_agent",
            &args(serde_json::json!({"action": "wait"})),
        );
        assert_eq!(default_wait, Some(Duration::from_secs(630)));
        let read = LeanCtxServer::handler_watchdog_for(
            "ctx_agent",
            &args(serde_json::json!({"action": "read"})),
        );
        assert_eq!(read, Some(Duration::from_secs(DEFAULT_TOOL_TIMEOUT_SECS)));
    }

    #[test]
    fn watchdog_from_secs_zero_disables() {
        assert!(watchdog_from_secs(0).is_none());
    }

    #[test]
    fn watchdog_from_secs_positive_maps_to_duration() {
        assert_eq!(watchdog_from_secs(5).unwrap().as_secs(), 5);
        assert_eq!(
            watchdog_from_secs(DEFAULT_TOOL_TIMEOUT_SECS)
                .unwrap()
                .as_secs(),
            120
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn watchdog_returns_error_on_hung_handler() {
        use std::sync::atomic::{AtomicBool, Ordering};
        // A hung handler must surface as a clean error (not a dropped request),
        // which is the core #271 guarantee. The stop flag lets the simulated
        // hang exit promptly after the assertion so the runtime shuts down fast.
        let stop = std::sync::Arc::new(AtomicBool::new(false));
        let stop_in = stop.clone();
        let join = tokio::task::spawn_blocking(move || {
            for _ in 0..400 {
                if stop_in.load(Ordering::Relaxed) {
                    break;
                }
                std::thread::sleep(Duration::from_millis(50));
            }
            Ok(ToolOutput::simple("late".to_string()))
        });
        let start = std::time::Instant::now();
        let result =
            LeanCtxServer::watchdog_join("mock", join, Some(Duration::from_millis(200))).await;
        let elapsed = start.elapsed();
        stop.store(true, Ordering::Relaxed);
        assert!(result.is_err(), "hung handler must surface as an error");
        assert!(
            elapsed < Duration::from_secs(2),
            "watchdog must fire promptly, took {elapsed:?}"
        );
    }

    #[cfg(not(feature = "no-jail"))]
    /// A server whose session starts in `root` (a GUI host's `~`, an agent
    /// config directory).
    async fn server_rooted_in(root: &std::path::Path) -> LeanCtxServer {
        let server = LeanCtxServer::new_with_startup(
            None,
            None,
            crate::tools::SessionMode::Personal,
            "default",
            "default",
        );
        let root = root.to_string_lossy().to_string();
        let mut session = server.session.write().await;
        session.project_root = Some(root.clone());
        session.shell_cwd = Some(root);
        drop(session);
        server
    }

    #[cfg(not(feature = "no-jail"))]
    fn git_project(dir: &std::path::Path) -> std::path::PathBuf {
        std::fs::create_dir_all(dir.join(".git")).unwrap();
        std::fs::write(dir.join("a.txt"), "before\n").unwrap();
        dir.canonicalize().unwrap()
    }

    #[cfg(not(feature = "no-jail"))]
    async fn edit(server: &LeanCtxServer, file: &str) -> String {
        let edit = serde_json::json!({
            "path": file, "old_string": "before", "new_string": "after"
        });
        server
            .dispatch_tool("ctx_edit", edit.as_object(), false)
            .await
            .map_or_else(|e| e.message.to_string(), |(text, ..)| text)
    }

    /// Activation #3 (pins #580/#649): a session started in `~` adopts the
    /// project of its first absolute path as a normal, WRITABLE session
    /// project — once. A second project never moves the session.
    #[cfg(not(feature = "no-jail"))]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[allow(clippy::await_holding_lock)]
    async fn a_session_in_home_adopts_its_first_project_writable_and_once() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
        let home = tmp.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let home = home.canonicalize().unwrap();
        let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
        let repo = git_project(&home.join("code/app"));
        let other = git_project(&home.join("code/other"));
        let server = server_rooted_in(&home).await;

        let file = repo.join("a.txt").to_string_lossy().to_string();
        let read = serde_json::json!({ "path": file, "mode": "full" });
        let (text, ..) = server
            .dispatch_tool("ctx_read", read.as_object(), false)
            .await
            .unwrap();
        assert!(text.contains("before"), "{text}");
        let root = repo.to_string_lossy().to_string();
        assert_eq!(
            server.session.read().await.project_root.as_deref(),
            Some(root.as_str())
        );

        let text = edit(&server, &file).await;
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "after\n", "{text}");

        let other_file = other.join("a.txt").to_string_lossy().to_string();
        let read = serde_json::json!({ "path": other_file, "mode": "full" });
        let _ = server
            .dispatch_tool("ctx_read", read.as_object(), false)
            .await;
        assert_eq!(
            server.session.read().await.project_root.as_deref(),
            Some(root.as_str()),
            "only the first adoption binds"
        );
    }

    /// A write tool as the very first call of a session started in an agent
    /// config directory adopts the project and writes in the same call.
    #[cfg(not(feature = "no-jail"))]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[allow(clippy::await_holding_lock)]
    async fn a_first_write_from_an_agent_dir_adopts_the_project_and_writes() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
        let home = tmp.path().join("home");
        let agent = home.join(".copilot");
        std::fs::create_dir_all(&agent).unwrap();
        let home = home.canonicalize().unwrap();
        let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
        let repo = git_project(&home.join("code/app"));
        let server = server_rooted_in(&agent.canonicalize().unwrap()).await;

        let file = repo.join("a.txt").to_string_lossy().to_string();
        let text = edit(&server, &file).await;
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "after\n", "{text}");
        assert_eq!(
            server.session.read().await.project_root.as_deref(),
            Some(repo.to_string_lossy().as_ref())
        );
        // B1: the adoption is audited exactly once, under the dispatching
        // tool, naming the adopted root.
        let adoptions: Vec<_> = lean_ctx::core::audit_trail::load_recent(1_000)
            .into_iter()
            .filter(|e| {
                e.action
                    .as_deref()
                    .is_some_and(|a| a.starts_with("jail_autobind:adopted"))
            })
            .collect();
        assert_eq!(adoptions.len(), 1, "{adoptions:?}");
        assert_eq!(adoptions[0].tool, "ctx_edit");
        let action = adoptions[0].action.as_deref().unwrap();
        assert!(
            action.ends_with(&format!("|root={}", repo.to_string_lossy())),
            "{action}"
        );
    }

    /// Review r2 R2-2 (two steps): a read adopts the project, but its VCS
    /// metadata and execution hooks stay closed to writes until the user
    /// declares the root; its ordinary files are writable.
    #[cfg(not(feature = "no-jail"))]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[allow(clippy::await_holding_lock)]
    async fn an_adopted_project_keeps_its_hooks_closed_to_writes() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
        let home = tmp.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let home = home.canonicalize().unwrap();
        let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
        let repo = git_project(&home.join("code/b"));
        let server = server_rooted_in(&home).await;

        let readme = repo.join("a.txt").to_string_lossy().to_string();
        let read = serde_json::json!({ "path": readme, "mode": "full" });
        server
            .dispatch_tool("ctx_read", read.as_object(), false)
            .await
            .unwrap();
        assert_eq!(
            server.session.read().await.project_root.as_deref(),
            Some(repo.to_string_lossy().as_ref())
        );

        for hook in [".git/hooks/pre-commit", ".husky/pre-commit", ".envrc"] {
            let file = repo.join(hook);
            std::fs::create_dir_all(file.parent().unwrap()).unwrap();
            std::fs::write(&file, "before\n").unwrap();
            let text = edit(&server, &file.to_string_lossy()).await;
            assert_eq!(
                std::fs::read_to_string(&file).unwrap(),
                "before\n",
                "{hook}: {text}"
            );
            assert!(text.contains("lean-ctx allow-path"), "{hook}: {text}");
        }
        let text = edit(&server, &readme).await;
        assert_eq!(
            std::fs::read_to_string(&readme).unwrap(),
            "after\n",
            "{text}"
        );
    }

    /// Review bd (4): a refused first write, into an execution hook or a
    /// personal container, adopts nothing: the session stays on `~` and a
    /// later write into a real project still adopts it.
    #[cfg(not(feature = "no-jail"))]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[allow(clippy::await_holding_lock)]
    async fn a_refused_first_write_leaves_the_session_on_home() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
        let home = tmp.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let home = home.canonicalize().unwrap();
        let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
        let repo = git_project(&home.join("code/b"));
        let documents = home.join("Documents");
        std::fs::create_dir_all(&documents).unwrap();
        std::fs::write(documents.join("package.json"), "{}").unwrap();
        let server = server_rooted_in(&home).await;
        let home_root = home.to_string_lossy().to_string();

        let hook = repo.join(".git/hooks/pre-commit");
        let notes = documents.join("notes.md");
        for file in [&hook, &notes] {
            std::fs::create_dir_all(file.parent().unwrap()).unwrap();
            std::fs::write(file, "before\n").unwrap();
            let text = edit(&server, &file.to_string_lossy()).await;
            assert_eq!(std::fs::read_to_string(file).unwrap(), "before\n", "{text}");
            assert_eq!(
                server.session.read().await.project_root.as_deref(),
                Some(home_root.as_str()),
                "{}: {text}",
                file.display()
            );
        }

        let readme = repo.join("a.txt").to_string_lossy().to_string();
        let text = edit(&server, &readme).await;
        assert_eq!(
            std::fs::read_to_string(&readme).unwrap(),
            "after\n",
            "{text}"
        );
        assert_eq!(
            server.session.read().await.project_root.as_deref(),
            Some(repo.to_string_lossy().as_ref())
        );
    }

    /// Lead follow-up 7: two first writes racing into different projects
    /// give one adoption. The loser is judged by the winner's root and
    /// refused, since its project lies outside, never by the stale `~` it was
    /// first jailed to. (Reads would pass: `~` projects stay readable.)
    /// A barrier holds both calls past the unbound check until both arrive,
    /// so the adoption lock alone decides the race.
    #[cfg(not(feature = "no-jail"))]
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    #[allow(clippy::await_holding_lock)]
    async fn racing_first_calls_adopt_one_project_and_refuse_the_other() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
        let home = tmp.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let home = home.canonicalize().unwrap();
        let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
        let projects = ["alpha", "beta"].map(|name| git_project(&home.join("code").join(name)));
        let server = server_rooted_in(&home).await;

        let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));
        let calls = projects.clone().map(|repo| {
            let server = server.clone();
            let barrier = std::cell::RefCell::new(Some(barrier.clone()));
            tokio::spawn(crate::tools::ADOPTION_BARRIER.scope(barrier, async move {
                let file = repo.join("a.txt").to_string_lossy().to_string();
                edit(&server, &file).await
            }))
        });
        let mut outputs = Vec::new();
        for call in calls {
            let output = tokio::time::timeout(Duration::from_secs(60), call)
                .await
                .expect("both racing calls reach the adoption barrier");
            outputs.push(output.unwrap());
        }

        let bound = server.session.read().await.project_root.clone().unwrap();
        let winner = projects
            .iter()
            .position(|repo| repo.to_string_lossy() == bound)
            .expect("one of the two projects is adopted");
        for (i, repo) in projects.iter().enumerate() {
            let written = std::fs::read_to_string(repo.join("a.txt")).unwrap() == "after\n";
            assert_eq!(written, i == winner, "{}: {}", repo.display(), outputs[i]);
        }
    }

    /// Review 33452: once a session adopted a project, a host resetting it
    /// to `~` never re-opens the adoption; a later path cannot move it.
    #[cfg(not(feature = "no-jail"))]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[allow(clippy::await_holding_lock)]
    async fn a_session_reset_to_home_after_adopting_never_adopts_again() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
        let home = tmp.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let home = home.canonicalize().unwrap();
        let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
        let first = git_project(&home.join("code/first"));
        let second = git_project(&home.join("code/second"));
        let server = server_rooted_in(&home).await;

        let path = |repo: &std::path::Path| repo.join("a.txt").to_string_lossy().to_string();
        server.resolve_path(&path(&first)).await.unwrap();
        let bound = server.session.read().await.project_root.clone();
        assert_eq!(bound.as_deref(), Some(first.to_string_lossy().as_ref()));

        let home_root = home.to_string_lossy().to_string();
        server.session.write().await.project_root = Some(home_root.clone());
        let _ = server.resolve_path(&path(&second)).await;
        let bound = server.session.read().await.project_root.clone();
        assert_eq!(
            bound.as_deref(),
            Some(home_root.as_str()),
            "a reset session keeps its root; the adoption happened once"
        );
    }

    /// Review 33452: shared sessions and a configured Workspace rooted in `~`
    /// are never adopted away from, and neither is a session jailed to a root
    /// pinned with `LEAN_CTX_PROJECT_ROOT`. `pinned_root()` ignores broad
    /// pins (`~`, agent dirs), so the pin reaches the adoption only as the
    /// `shell_cwd` jail of a session without a project root.
    #[cfg(not(feature = "no-jail"))]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[allow(clippy::await_holding_lock)]
    async fn shared_workspace_and_pinned_sessions_never_adopt() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
        let home = tmp.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let home = home.canonicalize().unwrap();
        let home_root = home.to_string_lossy().to_string();
        let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
        let repo = git_project(&home.join("code/app"));
        let file = repo.join("a.txt").to_string_lossy().to_string();

        // `new_with_startup` falls back to a personal session without a
        // usable startup root (and `~` is a broad one), so set the mode the
        // way a shared server carries it.
        let mut shared = server_rooted_in(&home).await;
        shared.session_mode = crate::tools::SessionMode::Shared;
        let mut cases = vec![("shared", shared, Some(home_root.clone()))];
        {
            let _workspace = lean_ctx::test_env::VarGuard::set(
                lean_ctx::core::workspace_authority::ENV_FILE,
                tmp.path().join("workspace.json"),
            );
            let server = server_rooted_in(&home).await;
            let _ = server.resolve_path(&file).await;
            cases.push(("workspace", server, Some(home_root.clone())));
        }
        {
            let pinned = home.join("pinned");
            std::fs::create_dir_all(&pinned).unwrap();
            let _pinned = lean_ctx::test_env::VarGuard::set("LEAN_CTX_PROJECT_ROOT", &pinned);
            let server = server_rooted_in(&pinned).await;
            server.session.write().await.project_root = None;
            let _ = server.resolve_path(&file).await;
            cases.push(("pinned", server, None));
        }
        let _ = cases[0].1.resolve_path(&file).await;
        for (mode, server, root) in cases {
            assert_eq!(
                server.session.read().await.project_root.as_deref(),
                root.as_deref(),
                "{mode}: the session root stays"
            );
        }
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn watchdog_passes_through_fast_handler() {
        let join = tokio::task::spawn_blocking(|| Ok(ToolOutput::simple("ok".to_string())));
        let result = LeanCtxServer::watchdog_join("mock", join, Some(Duration::from_secs(5))).await;
        assert_eq!(result.unwrap().text, "ok");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn watchdog_none_awaits_handler_to_completion() {
        let join = tokio::task::spawn_blocking(|| Ok(ToolOutput::simple("ok".to_string())));
        let result = LeanCtxServer::watchdog_join("ctx_shell", join, None).await;
        assert_eq!(result.unwrap().text, "ok");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn handler_panic_becomes_error_not_crash() {
        let join: tokio::task::JoinHandle<Result<ToolOutput, ErrorData>> =
            tokio::task::spawn_blocking(|| panic!("simulated handler panic"));
        let result = LeanCtxServer::watchdog_join("mock", join, Some(Duration::from_secs(5))).await;
        assert!(
            result.is_err(),
            "a handler panic must surface as an error; the server process survives"
        );
    }

    /// #712: a typo'd tool name must return a "did you mean" hint from the
    /// live registry instead of a bare unknown-tool error; a name nowhere
    /// near any registered tool must stay suggestion-free.
    /// C8: a shared server never runs ctx_tasks for its clients.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_shared_server_refuses_cloud_tasks() {
        if lean_ctx::test_env::run_in_own_process(
            "server::dispatch::tests::a_shared_server_refuses_cloud_tasks",
            &[(lean_ctx_cloud::PREVIEW_ENV, "1")],
        ) {
            return;
        }
        let mut server = crate::tools::create_server();
        server.session_mode = crate::tools::SessionMode::Shared;
        let mut args = serde_json::Map::new();
        args.insert("action".into(), Value::String("list".into()));
        let (text, ..) = server
            .dispatch_tool("ctx_tasks", Some(&args), false)
            .await
            .unwrap();
        assert!(text.contains("only in a personal MCP session"), "{text}");
    }

    /// Owner 28.10.: while the Cloud switch is off, ctx_tasks is in no tool
    /// list and every call path answers one fixed line.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cloud_tools_are_withheld_while_the_switch_is_off() {
        if lean_ctx_cloud::available_locally() {
            return;
        }
        // The guarded calls persist receipts: alone, in a store of its own, so
        // the suite's shared store under load cannot withhold the answer.
        let store = tempfile::tempdir().unwrap();
        let store = store.path().to_str().unwrap();
        if lean_ctx::test_env::run_in_own_process(
            "server::dispatch::tests::cloud_tools_are_withheld_while_the_switch_is_off",
            &[
                ("LEAN_CTX_DATA_DIR", store),
                ("LEAN_CTX_CONFIG_DIR", store),
                ("LEAN_CTX_STATE_DIR", store),
                ("LEAN_CTX_CACHE_DIR", store),
            ],
        ) {
            return;
        }
        use crate::server::dynamic_tools::CLOUD_TOOLS;
        use lean_ctx::core::tool_profiles::ToolProfile;
        let registry = crate::server::registry::build_registry();
        let mut surfaces = vec![registry.tool_defs(), registry.active_tool_defs()];
        for profile in [
            ToolProfile::Minimal,
            ToolProfile::Standard,
            ToolProfile::Power,
        ] {
            surfaces.push(registry.profile_tool_defs(&profile));
        }
        for defs in &surfaces {
            for def in defs {
                assert!(!CLOUD_TOOLS.contains(&def.name.as_ref()), "{}", def.name);
            }
        }
        for name in CLOUD_TOOLS {
            assert!(
                !crate::server::tool_visibility::is_tool_visible(
                    name,
                    &ToolProfile::Power,
                    &[],
                    crate::server::tool_visibility::ClientQuirks::default(),
                    true,
                ),
                "{name}"
            );
            // The answer may echo the query ("No tools found matching '…'"); no listed entry
            // may be the withheld tool.
            let found = lean_ctx::tool_defs::discover_tools(name);
            assert!(
                !found
                    .lines()
                    .any(|l| l.trim_start().starts_with(&format!("{name} —"))),
                "{found}"
            );
        }

        let server = crate::tools::create_server();
        let line = lean_ctx_cloud::TOOL_NOT_AVAILABLE;
        for name in CLOUD_TOOLS {
            let mut args = serde_json::Map::new();
            args.insert("action".into(), Value::String("list".into()));
            let (direct, ..) = server
                .dispatch_tool(name, Some(&args), false)
                .await
                .unwrap();
            assert_eq!(direct, line);

            let mut wrapped = serde_json::Map::new();
            wrapped.insert("name".into(), Value::String((*name).into()));
            wrapped.insert("arguments".into(), Value::Object(args.clone()));
            let (via_call, ..) = server
                .dispatch_tool("ctx_call", Some(&wrapped), false)
                .await
                .unwrap();
            assert_eq!(via_call, line);

            for (outer, outer_args) in [
                (*name, args.clone()),
                ("ctx_call", wrapped.clone()),
                ("ctx", {
                    let mut meta = args.clone();
                    meta.insert("tool".into(), Value::String((*name).into()));
                    meta
                }),
            ] {
                let request =
                    rmcp::model::CallToolRequestParams::new(outer).with_arguments(outer_args);
                let result = server.call_tool_guarded(request).await.unwrap();
                assert_eq!(result.is_error, Some(true), "{outer}");
                let text: Vec<_> = result
                    .content
                    .iter()
                    .filter_map(|block| block.as_text())
                    .map(|block| block.text.as_str())
                    .collect();
                assert_eq!(text, [line], "{outer}");
            }
        }
    }

    /// With the test preview the Cloud tools are advertised as before.
    #[test]
    fn cloud_tools_return_with_the_preview() {
        if lean_ctx::test_env::run_in_own_process(
            "server::dispatch::tests::cloud_tools_return_with_the_preview",
            &[(lean_ctx_cloud::PREVIEW_ENV, "1")],
        ) {
            return;
        }
        let defs = crate::server::registry::build_registry().tool_defs();
        for name in crate::server::dynamic_tools::CLOUD_TOOLS {
            assert!(defs.iter().any(|def| def.name.as_ref() == *name), "{name}");
        }
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn unknown_tool_suggests_closest_registered_name() {
        let server = crate::tools::create_server();

        let err = server
            .dispatch_tool("ctx_raed", None, false)
            .await
            .expect_err("typo'd tool must error");
        assert!(
            err.message.contains("Unknown tool: ctx_raed"),
            "unexpected message: {}",
            err.message
        );
        assert!(
            err.message.contains("did you mean 'ctx_read'"),
            "missing suggestion: {}",
            err.message
        );

        // A removed tool names its successor instead of a near-miss guess.
        let err = server
            .dispatch_tool("ctx_overview", None, false)
            .await
            .expect_err("removed tool must error");
        assert!(
            err.message
                .starts_with("ctx_overview was removed; use ctx_compose instead"),
            "unexpected message: {}",
            err.message
        );

        let err = server
            .dispatch_tool("zzz_qqq_www", None, false)
            .await
            .expect_err("unrelated name must error");
        assert!(
            !err.message.contains("did you mean"),
            "no confident suggestion for garbage: {}",
            err.message
        );
    }

    /// #1604: `ctx_call(name="ctx_edit", path=…, old_string=…)` — the inner
    /// tool's arguments flattened onto the ctx_call envelope instead of nested
    /// under `arguments` — used to reach the inner tool with NO arguments, so
    /// it answered "path is required" about a parameter the caller had just
    /// supplied. `name` is the only key ctx_call reserves, so the rest is
    /// forwarded. The nested form and the #658 misspelling guard are unchanged.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn ctx_call_forwards_flattened_inner_arguments() {
        let server = crate::tools::create_server();
        fn msg(
            r: Result<
                (
                    String,
                    usize,
                    Option<ShellOutcome>,
                    Option<Vec<ContentBlock>>,
                ),
                ErrorData,
            >,
        ) -> String {
            match r {
                Ok((text, ..)) => text,
                Err(e) => e.message.to_string(),
            }
        }

        // `ctx_read` on purpose: it is on every built-in role's allowlist, so a
        // sibling test that leaves a non-default role in the global slot cannot
        // turn these assertions into `[ROLE DENIED]`. Its missing-argument error
        // is also the exact one from the report.
        //
        // Control: genuinely no arguments — the inner tool's own error stands.
        let mut bare = serde_json::Map::new();
        bare.insert("name".into(), Value::String("ctx_read".into()));
        let bare = msg(server.dispatch_tool("ctx_call", Some(&bare), false).await);
        assert!(
            bare.contains("path is required"),
            "an argument-less inner call must still say what is missing: {bare}"
        );

        // Flattened: the same message would be a lie — the caller passed it.
        let mut flat = serde_json::Map::new();
        flat.insert("name".into(), Value::String("ctx_read".into()));
        flat.insert("path".into(), Value::String("Cargo.toml".into()));
        let flat = msg(server.dispatch_tool("ctx_call", Some(&flat), false).await);
        assert!(
            !flat.contains("path is required"),
            "flattened arguments must reach the inner tool: {flat}"
        );

        // Nested form: unchanged.
        let mut nested = serde_json::Map::new();
        nested.insert("name".into(), Value::String("ctx_read".into()));
        nested.insert(
            "arguments".into(),
            serde_json::json!({ "path": "Cargo.toml" }),
        );
        let nested = msg(server.dispatch_tool("ctx_call", Some(&nested), false).await);
        assert!(
            !nested.contains("path is required"),
            "nested arguments must keep working: {nested}"
        );

        // #658 guard: an `args`/`params` wrapper is a typo, not a flat call —
        // forwarding it would hand the inner tool a bogus `args` parameter.
        let mut typo = serde_json::Map::new();
        typo.insert("name".into(), Value::String("ctx_read".into()));
        typo.insert("args".into(), serde_json::json!({ "path": "Cargo.toml" }));
        let typo = msg(server.dispatch_tool("ctx_call", Some(&typo), false).await);
        assert!(
            typo.contains("unknown key 'args'"),
            "the #658 misspelling hint must survive: {typo}"
        );
    }
}

#[cfg(test)]
mod workflow_gate_tests {
    use lean_ctx::core::context_admission::stored::lineage_support::{governed, project, scoped};
    use lean_ctx::core::policy::runtime::TestPolicyOverride;
    use lean_ctx::core::workflow::gate::test_support::{review, workflow_file};
    use lean_ctx::core::workflow::{is_withheld_sentinel, load_active, save_active};
    use serde_json::{Map, Value, json};

    fn call(inner: &str, arguments: &Value) -> Map<String, Value> {
        let mut args = Map::new();
        args.insert("name".into(), Value::String(inner.into()));
        args.insert("arguments".into(), arguments.clone());
        args
    }

    /// The `ctx_call` gate under the stand-in for a withheld workflow: the
    /// same closed decision as the direct gate — pass-through tools and write
    /// actions refused, the control tool working, no expiry, the stored
    /// workflow untouched — and the real workflow back once it may be read.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn the_ctx_call_gate_keeps_a_withheld_workflow_closed() {
        let _data = governed();
        let _community = TestPolicyOverride::set(None);
        let (_directory, root) = project();
        let (_other_directory, other) = project();
        scoped(&root, || save_active(&review())).expect("saved in its project");
        let stored = std::fs::read(workflow_file()).expect("stored workflow");

        let server = crate::tools::LeanCtxServer::new_with_project_root(Some(&other));
        let mut closed = scoped(&other, load_active)
            .expect("load")
            .expect("a withheld workflow is still a workflow");
        assert!(is_withheld_sentinel(&closed));
        closed.updated_at =
            lean_ctx_time::UtcDateTime::now() - lean_ctx_time::Duration::minutes(45);
        *server.workflow.write().await = Some(closed);

        for (inner, arguments) in [
            ("ctx_read", json!({ "path": "Cargo.toml" })),
            (
                "ctx_session",
                json!({ "action": "finding", "value": "noted" }),
            ),
            (
                "ctx_session",
                json!({ "action": "decision", "value": "decided" }),
            ),
        ] {
            let (reply, ..) = server
                .dispatch_tool("ctx_call", Some(&call(inner, &arguments)), false)
                .await
                .expect("a refusal is a reply");
            assert!(
                reply.contains("withheld by the context gateway"),
                "{inner}: {reply}"
            );
            assert!(!reply.contains("review"), "{reply}");
        }
        assert!(
            server
                .workflow
                .read()
                .await
                .as_ref()
                .is_some_and(is_withheld_sentinel),
            "not cleared by its age"
        );

        assert_eq!(
            std::fs::read(workflow_file()).expect("kept"),
            stored,
            "the withheld workflow is byte-identical on disk"
        );

        // The authority holds again: the real workflow loads, no stand-in.
        let real = scoped(&root, load_active).expect("load").expect("active");
        assert!(!is_withheld_sentinel(&real));
        *server.workflow.write().await = Some(real);
        let (reply, ..) = server
            .dispatch_tool(
                "ctx_call",
                Some(&call("ctx_shell", &json!({ "command": "true" }))),
                false,
            )
            .await
            .expect("a refusal is a reply");
        assert!(reply.contains("blocked by workflow 'review'"), "{reply}");
    }
}