patchloom 0.34.0

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

use rmcp::model::{CallToolResult, ContentBlock, ErrorData as McpError};

use crate::cli::global::GlobalFlags;
use crate::exit;

use super::params::*;
use super::{
    PatchloomService, exit_code_to_result, no_results, validate_content_size, validate_param_size,
};

/// Parse an optional lang hint. Unknown tokens are a tool envelope
/// (`invalid_input`), not JSON-RPC `invalid_params`.
fn parse_optional_lang(
    lang: Option<&str>,
) -> Result<Option<crate::ast::Language>, Box<Result<CallToolResult, McpError>>> {
    match lang {
        Some(s) => match crate::ast::parse_lang_hint(s) {
            Ok(parsed) => Ok(Some(parsed)),
            Err(e) => {
                let msg = crate::exit::agent_error_message(&e);
                let body = serde_json::json!({
                    "ok": false,
                    "applied": false,
                    "error_kind": "invalid_input",
                    "error": msg,
                });
                Err(Box::new(exit_code_to_result(
                    exit::FAILURE,
                    &body.to_string(),
                    &msg,
                )))
            }
        },
        None => Ok(None),
    }
}

pub(super) fn handle_ast_list(
    svc: &PatchloomService,
    p: AstListParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    let cwd = svc.cwd().to_path_buf();
    let target = cwd.join(&p.path);
    let lang_hint = match parse_optional_lang(p.lang.as_deref()) {
        Ok(lang) => lang,
        Err(r) => return *r,
    };
    let kind_filter = crate::cmd::ast::parse_kind_filter(&p.kind)
        .map_err(|e| McpError::invalid_params(crate::exit::agent_error_message(&e), None))?;

    let mut results = Vec::new();

    if target.is_file() {
        let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(&target));
        if !lang.has_grammar() {
            return Err(McpError::invalid_params(
                format!(
                    "Unsupported language: {} (detected from {}). \
                     Supported: Rust, Python, TypeScript, JavaScript, Go, Java, \
                     C#, Ruby, PHP, Swift, Kotlin, C, C++, HCL, XML, Protobuf, \
                     TOML, YAML, JSON, Shell.",
                    lang, p.path,
                ),
                None,
            ));
        }
        // Strict sole-path load (CLI list parity): binary/utf8 must not soft-empty.
        let source = crate::files::load_text_strict(&target, &p.path).map_err(|e| {
            if crate::exit::is_load_text_strict_fail(&e) || crate::exit::is_io_not_found(&e) {
                McpError::invalid_params(e.to_string(), None)
            } else {
                McpError::internal_error(e.to_string(), None)
            }
        })?;
        let symbols = match crate::ast::symbols::try_extract_symbols(&source, lang) {
            Ok(s) => s,
            Err(crate::ast::ParseFailure::DeadlineExceeded) => {
                let msg = format!("parse deadline exceeded for {}", p.path);
                let body = serde_json::json!({
                    "ok": false,
                    "applied": false,
                    "error_kind": "parse_timeout",
                    "error": msg,
                });
                return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
            }
            Err(crate::ast::ParseFailure::NoGrammar) => Vec::new(),
        };
        let filtered = crate::cmd::ast::filter_symbols(&symbols, &kind_filter);
        if !filtered.is_empty() {
            for sym in &filtered {
                results.push(crate::cmd::ast::symbol_to_json(sym, &p.path));
            }
        }
    } else if target.is_dir() {
        let global = GlobalFlags::with_cwd(&cwd);
        let paths = crate::cmd::ast::collect_source_files(&target, &global)
            .map_err(|e| McpError::internal_error(format!("{e}"), None))?;

        struct ListResult {
            entries: Vec<serde_json::Value>,
        }
        let timeout: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
        let par_results: Vec<ListResult> = crate::par_process_files(&paths, None, &[], |path| {
            let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(path));
            let symbols = match crate::ast::symbols::try_extract_symbols_from_file(path, Some(lang))
            {
                Ok(s) => s,
                Err(crate::ast::ParseFailure::DeadlineExceeded) => {
                    let mut slot = timeout.lock().unwrap_or_else(|e| e.into_inner());
                    if slot.is_none() {
                        *slot = Some(path.display().to_string());
                    }
                    return None;
                }
                Err(crate::ast::ParseFailure::NoGrammar) => Vec::new(),
            };
            let filtered = crate::cmd::ast::filter_symbols(&symbols, &kind_filter);
            if filtered.is_empty() {
                return None;
            }
            let display = crate::cmd::ast::display_path(path, &cwd);
            let entries = filtered
                .iter()
                .map(|sym| crate::cmd::ast::symbol_to_json(sym, &display))
                .collect();
            Some(ListResult { entries })
        });
        if let Some(file) = timeout.into_inner().unwrap_or_else(|e| e.into_inner()) {
            let msg = format!("parse deadline exceeded for {file}");
            let body = serde_json::json!({
                "ok": false,
                "applied": false,
                "error_kind": "parse_timeout",
                "error": msg,
            });
            return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
        }
        for r in par_results {
            results.extend(r.entries);
        }
        // All-unreadable dirs must not soft-empty as "No symbols found".
        if results.is_empty()
            && let Some(err) = crate::ops::file::empty_scan_masked_by_unreadable(&paths, &cwd)
        {
            return Err(McpError::invalid_params(err.msg, None));
        }
    } else {
        return Err(McpError::invalid_params(
            format!("path not found: {}", p.path),
            None,
        ));
    }

    if results.is_empty() {
        return no_results("No symbols found.");
    }
    let json = serde_json::to_string_pretty(&results)
        .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
    Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}

pub(super) fn handle_ast_read(
    svc: &PatchloomService,
    p: AstReadParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    validate_param_size("symbol", &p.symbol)?;
    let cwd = svc.cwd().to_path_buf();
    let target = cwd.join(&p.path);

    let lang_hint = match parse_optional_lang(p.lang.as_deref()) {
        Ok(lang) => lang,
        Err(r) => return *r,
    };
    let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(&target));
    // Strict sole-path text load (#1894): binary / invalid UTF-8 → invalid_params.
    let source = crate::files::load_text_strict(&target, &p.path).map_err(|e| {
        // load_text_strict already names path + OS detail (MPI 2026-07-23).
        if crate::exit::is_load_text_strict_fail(&e) || crate::exit::is_io_not_found(&e) {
            McpError::invalid_params(e.to_string(), None)
        } else {
            McpError::internal_error(e.to_string(), None)
        }
    })?;
    if !lang.has_grammar() {
        return Err(McpError::invalid_params(
            format!(
                "Unsupported language: {} (detected from {}). \
                 Supported: Rust, Python, TypeScript, JavaScript, Go, Java, \
                 C#, Ruby, PHP, Swift, Kotlin, C, C++, HCL, XML, Protobuf, \
                 TOML, YAML, JSON, Shell.",
                lang, p.path,
            ),
            None,
        ));
    }
    let all_symbols = match crate::ast::symbols::try_extract_symbols(&source, lang) {
        Ok(s) => s,
        Err(crate::ast::ParseFailure::DeadlineExceeded) => {
            let msg = format!("parse deadline exceeded for {}", p.path);
            let body = serde_json::json!({
                "ok": false,
                "applied": false,
                "error_kind": "parse_timeout",
                "error": msg,
            });
            return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
        }
        Err(crate::ast::ParseFailure::NoGrammar) => Vec::new(),
    };
    let Some(sym) = crate::ast::symbols::find_symbol(&all_symbols, &p.symbol) else {
        let msg = format!("symbol '{}' not found in {}", p.symbol, p.path);
        let body = serde_json::json!({
            "ok": false,
            "error_kind": "no_matches",
            "error": msg,
            "applied": false,
        });
        return exit_code_to_result(exit::NO_MATCHES, &body.to_string(), &msg);
    };

    let lines: Vec<&str> = crate::ops::file::text_lines(&source).collect();
    let start = sym
        .start_line
        .saturating_sub(1_usize.saturating_add(p.context));
    let end = sym.end_line.saturating_add(p.context).min(lines.len());
    let content: String = lines[start..end].iter().map(|l| format!("{l}\n")).collect();

    let obj = serde_json::json!({
        "file": p.path,
        "symbol": sym.name,
        "kind": sym.kind.to_string(),
        "start_line": sym.start_line,
        "end_line": sym.end_line,
        "signature": sym.signature,
        "content": content,
    });
    let json = serde_json::to_string_pretty(&obj)
        .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
    Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}

pub(super) fn handle_ast_rename(
    svc: &PatchloomService,
    p: AstRenameParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    validate_param_size("old", &p.old)?;
    validate_param_size("new", &p.new)?;
    if let Err(e) = crate::ast::rename::reject_empty_rename_names(&p.old, &p.new) {
        let msg = crate::exit::agent_error_message(&e);
        let body = serde_json::json!({
            "ok": false,
            "applied": false,
            "error_kind": "invalid_input",
            "error": msg,
        });
        return exit_code_to_result(exit::FAILURE, &body.to_string(), &msg);
    }
    if p.old == p.new {
        return exit_code_to_result(exit::NO_MATCHES, "", "old and new are identical.");
    }
    let cwd = svc.cwd().to_path_buf();
    let target = cwd.join(&p.path);
    let lang_hint = match parse_optional_lang(p.lang.as_deref()) {
        Ok(lang) => lang,
        Err(r) => return *r,
    };

    let global = GlobalFlags::with_cwd_and_json(&cwd);

    let paths = crate::cmd::ast::resolve_target_paths(&target, &p.path, &global)
        .map_err(|e| McpError::invalid_params(format!("{e}"), None))?;

    // Sole explicit non-text: fail closed (CLI rename parity), not soft empty.
    if crate::cmd::ast::is_sole_explicit_file(&paths, &p.path) {
        let sole = &paths[0];
        if let Err(e) = crate::files::load_text_strict(sole, &p.path)
            && (crate::exit::is_load_text_strict_fail(&e) || crate::exit::is_io_not_found(&e))
        {
            return Err(McpError::invalid_params(e.to_string(), None));
        }
    }

    // Pre-filter to files with matches (parallel, same as CLI ast rename),
    // build one AstRename op per file, then tx engine for backup/rollback (#1100).
    for path in &paths {
        let rel = path
            .strip_prefix(&cwd)
            .unwrap_or(path)
            .to_string_lossy()
            .into_owned();
        svc.check_path(&rel)?;
    }

    let old = p.old.as_str();
    let new = p.new.as_str();
    let lang_cli = p.lang.clone();
    let rename_op = |path: &std::path::Path| -> crate::plan::Operation {
        let rel = path
            .strip_prefix(&cwd)
            .unwrap_or(path)
            .to_string_lossy()
            .into_owned();
        crate::plan::Operation::AstRename {
            path: rel,
            old: old.to_string(),
            new: new.to_string(),
            lang: lang_cli.clone(),
        }
    };
    let unreadable = std::sync::Mutex::new(Vec::<String>::new());
    let operations: Vec<crate::plan::Operation> =
        if crate::cmd::ast::is_sole_explicit_file(&paths, &p.path) {
            let sole = &paths[0];
            match crate::files::try_read_text_file(sole) {
                Ok(source) => {
                    let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(sole));
                    match crate::ast::rename::source_has_rename_match(&source, old, new, lang) {
                        Err(e) if crate::exit::is_parse_timeout(&e) => {
                            let msg = crate::exit::agent_error_message(&e);
                            let body = serde_json::json!({
                                "ok": false,
                                "applied": false,
                                "error_kind": "parse_timeout",
                                "error": msg,
                            });
                            return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
                        }
                        Err(e) => {
                            return Err(McpError::invalid_params(
                                crate::exit::agent_error_message(&e),
                                None,
                            ));
                        }
                        Ok(true) => vec![rename_op(sole)],
                        Ok(false) => Vec::new(),
                    }
                }
                Err(
                    crate::files::SoftTextSkip::Binary
                    | crate::files::SoftTextSkip::InvalidUtf8
                    | crate::files::SoftTextSkip::NotRegularFile,
                ) => Vec::new(),
                Err(crate::files::SoftTextSkip::Unreadable) => {
                    if let Ok(mut g) = unreadable.lock()
                        && g.len() < 8
                    {
                        g.push(sole.display().to_string());
                    }
                    Vec::new()
                }
            }
        } else {
            crate::par_process_files(&paths, None, &[], |path| {
                // SoftSkip content; track Unreadable so empty ≠ no matches (#1894).
                let source = match crate::files::try_read_text_file(path) {
                    Ok(s) => s,
                    Err(
                        crate::files::SoftTextSkip::Binary
                        | crate::files::SoftTextSkip::InvalidUtf8
                        | crate::files::SoftTextSkip::NotRegularFile,
                    ) => {
                        return None;
                    }
                    Err(crate::files::SoftTextSkip::Unreadable) => {
                        if let Ok(mut g) = unreadable.lock()
                            && g.len() < 8
                        {
                            g.push(path.display().to_string());
                        }
                        return None;
                    }
                };
                let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(path));

                let has_match = if lang.has_grammar() {
                    crate::ast::rename::rename_in_source(&source, old, new, lang)
                        .is_some_and(|r| r.replacements > 0)
                } else {
                    false
                } || {
                    crate::ops::replace::compile_replace_regex(old, false, false, false, true)
                        .ok()
                        .flatten()
                        .is_some_and(|re| re.is_match(&source))
                };

                if !has_match {
                    return None;
                }
                Some(rename_op(path))
            })
        };

    if operations.is_empty() {
        let unread = unreadable.into_inner().unwrap_or_default();
        if !unread.is_empty() {
            let sample = unread.join(", ");
            return Err(McpError::invalid_params(
                format!(
                    "could not read {} path(s) while scanning {} (e.g. {}); \
                     not reporting as no matches",
                    unread.len(),
                    p.path,
                    sample
                ),
                None,
            ));
        }
        // Write tool: miss is not a successful soft query (contrast ast_list/refs).
        // Agents must see isError + no_matches, not a green tool result.
        let body = serde_json::json!({
            "ok": false,
            "error_kind": "no_matches",
            "error": "No matches found.",
            "applied": false,
        });
        return exit_code_to_result(exit::NO_MATCHES, &body.to_string(), "No matches found.");
    }

    svc.run_ops(operations, None)
}

pub(super) fn handle_ast_validate(
    svc: &PatchloomService,
    p: AstValidateParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    let cwd = svc.cwd().to_path_buf();
    let target = cwd.join(&p.path);
    let lang_hint = match parse_optional_lang(p.lang.as_deref()) {
        Ok(lang) => lang,
        Err(r) => return *r,
    };

    let global = GlobalFlags::with_cwd(&cwd);
    let paths = crate::cmd::ast::resolve_target_paths(&target, &p.path, &global)
        .map_err(|e| McpError::invalid_params(format!("{e}"), None))?;

    // Sole explicit path without grammar: invalid_input (CLI parity).
    if paths.len() == 1 {
        let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(&paths[0]));
        if !lang.has_grammar() {
            return Err(McpError::invalid_params(
                format!(
                    "Unsupported language: {} (detected from {}). \
                     Supported: Rust, Python, TypeScript, JavaScript, Go, Java, \
                     C#, Ruby, PHP, Swift, Kotlin, C, C++, HCL, XML, Protobuf, \
                     TOML, YAML, JSON, Shell.",
                    lang, p.path,
                ),
                None,
            ));
        }
    }

    // Preflight grammar paths: any binary/unreadable co-path fails closed
    // (CLI validate parity; soft-drop would claim partial trees validated OK).
    for path in &paths {
        let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(path));
        if !lang.has_grammar() {
            continue;
        }
        let display = crate::cmd::ast::display_path(path, &cwd);
        if let Err(e) = crate::files::load_text_strict(path, &display)
            && (crate::exit::is_load_text_strict_fail(&e) || crate::exit::is_io_not_found(&e))
        {
            return Err(McpError::invalid_params(e.to_string(), None));
        }
    }

    let results: Vec<serde_json::Value> = if paths.len() == 1 {
        let path = &paths[0];
        let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(path));
        match crate::ast::validate::validate_file(path, Some(lang)) {
            Ok(result) => {
                let display = crate::cmd::ast::display_path(path, &cwd);
                vec![serde_json::json!({
                    "file": display,
                    "valid": result.valid,
                    "language": result.language,
                    "errors": result.errors,
                })]
            }
            Err(e) if crate::exit::is_parse_timeout(&e) => {
                let msg = crate::exit::agent_error_message(&e);
                let body = serde_json::json!({
                    "ok": false,
                    "applied": false,
                    "error_kind": "parse_timeout",
                    "error": msg,
                });
                return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
            }
            Err(e) => return Err(McpError::invalid_params(e.to_string(), None)),
        }
    } else {
        crate::par_process_files(&paths, None, &[], |path| {
            let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(path));
            if !lang.has_grammar() {
                return None;
            }
            let result = crate::ast::validate::validate_file_for_walk(path, Some(lang))?;
            let display = crate::cmd::ast::display_path(path, &cwd);
            Some(serde_json::json!({
                "file": display,
                "valid": result.valid,
                "language": result.language,
                "errors": result.errors,
            }))
        })
    };

    // CLI parity: unreadable co-paths are not soft empty / no-grammar.
    if let Some(err) = crate::ops::file::empty_scan_masked_by_unreadable(&paths, &cwd) {
        return Err(McpError::invalid_params(err.msg, None));
    }

    if results.is_empty() {
        return Err(McpError::invalid_params(
            "No files with grammars found.",
            None,
        ));
    }
    let any_invalid = results
        .iter()
        .any(|r| r.get("valid") == Some(&serde_json::json!(false)));
    let json = serde_json::to_string_pretty(&results)
        .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
    // CLI exits 1 when invalid; hosts that only check isError must see failure.
    if any_invalid {
        Ok(CallToolResult::error(vec![ContentBlock::text(json)]))
    } else {
        Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
    }
}

pub(super) fn handle_ast_search(
    svc: &PatchloomService,
    p: AstSearchParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    validate_param_size("query", &p.query)?;
    let cwd = svc.cwd().to_path_buf();
    let target = cwd.join(&p.path);
    let lang_hint = match parse_optional_lang(p.lang.as_deref()) {
        Ok(lang) => lang,
        Err(r) => return *r,
    };

    let global = GlobalFlags::with_cwd(&cwd);
    let paths = crate::cmd::ast::resolve_target_paths(&target, &p.path, &global)
        .map_err(|e| McpError::invalid_params(format!("{e}"), None))?;

    // Sole explicit non-text: fail closed (CLI search parity).
    if crate::cmd::ast::is_sole_explicit_file(&paths, &p.path) {
        let sole = &paths[0];
        if let Err(e) = crate::files::load_text_strict(sole, &p.path)
            && (crate::exit::is_load_text_strict_fail(&e) || crate::exit::is_io_not_found(&e))
        {
            return Err(McpError::invalid_params(e.to_string(), None));
        }
    }

    struct SearchFileResult {
        entries: Vec<serde_json::Value>,
    }
    // Pre-validate pattern / S-expression before the walk soft-drops ParseError
    // into "No matches found".
    let precompiled_query = if p.pattern {
        let validation_lang = lang_hint.unwrap_or_else(|| {
            paths
                .iter()
                .find(|path| crate::ast::Language::from_path(path).has_grammar())
                .map(|path| crate::ast::Language::from_path(path))
                .unwrap_or(crate::ast::Language::Rust)
        });
        Some(
            match crate::ast::search::compile_pattern_query(&p.query, validation_lang) {
                Ok(q) => q,
                Err(e) if crate::exit::is_invalid_input(&e) => {
                    let msg = crate::exit::agent_error_message(&e);
                    let body = serde_json::json!({
                        "ok": false,
                        "applied": false,
                        "error_kind": "invalid_input",
                        "error": msg,
                    });
                    return exit_code_to_result(exit::FAILURE, &body.to_string(), &msg);
                }
                Err(e) => {
                    return Err(McpError::invalid_params(
                        format!("invalid pattern query: {e}"),
                        None,
                    ));
                }
            },
        )
    } else {
        None
    };

    let search_query_for = |path: &std::path::Path| -> String {
        if p.pattern {
            let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(path));
            crate::ast::search::compile_pattern_query(&p.query, lang)
                .unwrap_or_else(|_| precompiled_query.clone().unwrap_or_default())
        } else {
            p.query.clone()
        }
    };

    let search_timeout_result = |e: &anyhow::Error| -> Result<CallToolResult, McpError> {
        let msg = crate::exit::agent_error_message(e);
        let body = serde_json::json!({
            "ok": false,
            "applied": false,
            "error_kind": "parse_timeout",
            "error": msg,
        });
        exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg)
    };

    // Sole explicit file: surface parse_timeout instead of walk-soft no matches.
    if crate::cmd::ast::is_sole_explicit_file(&paths, &p.path) {
        let path = &paths[0];
        let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(path));
        let query_str = search_query_for(path);
        match crate::ast::search::search_file(path, &query_str, Some(lang), p.max_results) {
            Ok(results) => {
                if results.is_empty() {
                    if let Some(err) =
                        crate::ops::file::empty_scan_masked_by_unreadable(&paths, &cwd)
                    {
                        return Err(McpError::invalid_params(err.msg, None));
                    }
                    return no_results("No matches found.");
                }
                let display = crate::cmd::ast::display_path(path, &cwd);
                let all_matches: Vec<serde_json::Value> = results
                    .iter()
                    .map(|m| {
                        serde_json::json!({
                            "file": display,
                            "line": m.line,
                            "column": m.column,
                            "text": m.text,
                            "captures": m.captures,
                        })
                    })
                    .collect();
                let json = serde_json::to_string_pretty(&all_matches)
                    .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
                return Ok(CallToolResult::success(vec![ContentBlock::text(json)]));
            }
            Err(e) if crate::exit::is_parse_timeout(&e) => {
                return search_timeout_result(&e);
            }
            Err(e) if crate::exit::is_parse_error(&e) => {
                return Err(McpError::invalid_params(
                    crate::exit::agent_error_message(&e),
                    None,
                ));
            }
            Err(e) => return Err(McpError::invalid_params(e.to_string(), None)),
        }
    }

    if let Some(sample) = paths.iter().find(|path| {
        lang_hint
            .unwrap_or_else(|| crate::ast::Language::from_path(path))
            .has_grammar()
    }) {
        let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(sample));
        let query_str = search_query_for(sample);
        if let Err(e) = crate::ast::search::search_file(sample, &query_str, Some(lang), Some(1)) {
            if crate::exit::is_parse_timeout(&e) {
                return search_timeout_result(&e);
            }
            if crate::exit::is_parse_error(&e) {
                return Err(McpError::invalid_params(
                    crate::exit::agent_error_message(&e),
                    None,
                ));
            }
        }
    }

    let par_results: Vec<SearchFileResult> = crate::par_process_files(&paths, None, &[], |path| {
        let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(path));
        let query_str = search_query_for(path);
        let results =
            crate::ast::search::search_file(path, &query_str, Some(lang), p.max_results).ok()?;
        if results.is_empty() {
            return None;
        }
        let display = crate::cmd::ast::display_path(path, &cwd);
        let entries = results
            .iter()
            .map(|m| {
                serde_json::json!({
                    "file": display,
                    "line": m.line,
                    "column": m.column,
                    "text": m.text,
                    "captures": m.captures,
                })
            })
            .collect();
        Some(SearchFileResult { entries })
    });
    let all_matches: Vec<serde_json::Value> =
        par_results.into_iter().flat_map(|r| r.entries).collect();

    if all_matches.is_empty() {
        if let Some(err) = crate::ops::file::empty_scan_masked_by_unreadable(&paths, &cwd) {
            return Err(McpError::invalid_params(err.msg, None));
        }
        return no_results("No matches found.");
    }
    let json = serde_json::to_string_pretty(&all_matches)
        .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
    Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}

pub(super) fn handle_ast_refs(
    svc: &PatchloomService,
    p: AstRefsParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    validate_param_size("symbol", &p.symbol)?;
    let cwd = svc.cwd().to_path_buf();
    let target = cwd.join(&p.path);
    let lang_hint = match parse_optional_lang(p.lang.as_deref()) {
        Ok(lang) => lang,
        Err(r) => return *r,
    };

    let global = GlobalFlags::with_cwd(&cwd);
    let paths = crate::cmd::ast::resolve_target_paths(&target, &p.path, &global)
        .map_err(|e| McpError::invalid_params(format!("{e}"), None))?;

    let mut all_refs = if crate::cmd::ast::is_sole_explicit_file(&paths, &p.path) {
        let sole = &paths[0];
        let source = match crate::files::load_text_strict(sole, &p.path) {
            Ok(s) => s,
            Err(e)
                if crate::exit::is_load_text_strict_fail(&e)
                    || crate::exit::is_io_not_found(&e) =>
            {
                return Err(McpError::invalid_params(
                    crate::exit::agent_error_message(&e),
                    None,
                ));
            }
            Err(e) => {
                return Err(McpError::internal_error(
                    crate::exit::agent_error_message(&e),
                    None,
                ));
            }
        };
        let display = crate::cmd::ast::display_path(sole, &cwd);
        let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(sole));
        match crate::ast::refs::try_find_refs_in_source(&source, &p.symbol, lang, &display) {
            Ok(refs) => refs,
            Err(crate::ast::ParseFailure::DeadlineExceeded) => {
                let msg = format!("parse deadline exceeded for {}", p.path);
                let body = serde_json::json!({
                    "ok": false,
                    "applied": false,
                    "error_kind": "parse_timeout",
                    "error": msg,
                });
                return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
            }
            Err(crate::ast::ParseFailure::NoGrammar) => Vec::new(),
        }
    } else {
        let timeout: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
        let per_file: Vec<Vec<crate::ast::refs::SymbolRef>> =
            crate::par_process_files(&paths, None, &[], |path| {
                let display = crate::cmd::ast::display_path(path, &cwd);
                let refs = match crate::ast::refs::try_find_refs_in_file(
                    path, &p.symbol, lang_hint, &display,
                ) {
                    Ok(refs) => refs,
                    Err(crate::ast::ParseFailure::DeadlineExceeded) => {
                        let mut slot = timeout.lock().unwrap_or_else(|e| e.into_inner());
                        if slot.is_none() {
                            *slot = Some(path.display().to_string());
                        }
                        return None;
                    }
                    Err(crate::ast::ParseFailure::NoGrammar) => Vec::new(),
                };
                if refs.is_empty() { None } else { Some(refs) }
            });
        if let Some(file) = timeout.into_inner().unwrap_or_else(|e| e.into_inner()) {
            let msg = format!("parse deadline exceeded for {file}");
            let body = serde_json::json!({
                "ok": false,
                "applied": false,
                "error_kind": "parse_timeout",
                "error": msg,
            });
            return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
        }
        per_file.into_iter().flatten().collect()
    };

    if !p.include_def {
        all_refs.retain(|r| r.kind != crate::ast::refs::RefKind::Definition);
    }

    if all_refs.is_empty() {
        if let Some(err) = crate::ops::file::empty_scan_masked_by_unreadable(&paths, &cwd) {
            return Err(McpError::invalid_params(err.msg, None));
        }
        return no_results("No references found.");
    }

    let obj = serde_json::json!({
        "symbol": p.symbol,
        "references": all_refs,
        "count": all_refs.len(),
    });
    let json = serde_json::to_string_pretty(&obj)
        .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
    Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}

pub(super) fn handle_ast_deps(
    svc: &PatchloomService,
    p: AstDepsParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    let cwd = svc.cwd().to_path_buf();
    let target = cwd.join(&p.path);
    let lang_hint = match parse_optional_lang(p.lang.as_deref()) {
        Ok(lang) => lang,
        Err(r) => return *r,
    };

    let global = GlobalFlags::with_cwd(&cwd);
    let paths = crate::cmd::ast::resolve_target_paths(&target, &p.path, &global)
        .map_err(|e| McpError::invalid_params(format!("{e}"), None))?;

    // Sole explicit non-text: fail closed (CLI parity; not soft empty).
    if crate::cmd::ast::is_sole_explicit_file(&paths, &p.path) {
        let sole = &paths[0];
        if let Err(e) = crate::files::load_text_strict(sole, &p.path)
            && (crate::exit::is_load_text_strict_fail(&e) || crate::exit::is_io_not_found(&e))
        {
            return Err(McpError::invalid_params(
                crate::exit::agent_error_message(&e),
                None,
            ));
        }
    }

    if crate::cmd::ast::is_sole_explicit_file(&paths, &p.path) && !p.reverse {
        let sole = &paths[0];
        let source = crate::files::load_text_strict(sole, &p.path).map_err(|e| {
            if crate::exit::is_load_text_strict_fail(&e) || crate::exit::is_io_not_found(&e) {
                McpError::invalid_params(e.to_string(), None)
            } else {
                McpError::internal_error(e.to_string(), None)
            }
        })?;
        let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(sole));
        let imports = match crate::ast::deps::try_extract_imports(&source, lang) {
            Ok(i) => i,
            Err(crate::ast::ParseFailure::DeadlineExceeded) => {
                let msg = format!("parse deadline exceeded for {}", p.path);
                let body = serde_json::json!({
                    "ok": false,
                    "applied": false,
                    "error_kind": "parse_timeout",
                    "error": msg,
                });
                return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
            }
            Err(crate::ast::ParseFailure::NoGrammar) => Vec::new(),
        };
        if imports.is_empty() {
            return no_results("No imports found.");
        }
        let display = crate::cmd::ast::display_path(sole, &cwd);
        let results = vec![serde_json::json!({
            "file": display,
            "imports": imports,
        })];
        let json = serde_json::to_string_pretty(&results)
            .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
        return Ok(CallToolResult::success(vec![ContentBlock::text(json)]));
    }

    let mut results = Vec::new();

    if p.reverse {
        let target_name = target
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or_default()
            .to_string();
        let all_files = crate::cmd::ast::collect_source_files(&cwd, &global)
            .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
        // Reverse walk scans `all_files`; empty-mask must use that set, not `paths`.

        struct RevDepsResult {
            entries: Vec<serde_json::Value>,
        }
        let timeout: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
        let par_results: Vec<RevDepsResult> =
            crate::par_process_files(&all_files, None, &[], |path| {
                let imports = match crate::ast::deps::try_extract_imports_from_file(path, lang_hint)
                {
                    Ok(i) => i,
                    Err(crate::ast::ParseFailure::DeadlineExceeded) => {
                        let mut slot = timeout.lock().unwrap_or_else(|e| e.into_inner());
                        if slot.is_none() {
                            *slot = Some(path.display().to_string());
                        }
                        return None;
                    }
                    Err(crate::ast::ParseFailure::NoGrammar) => Vec::new(),
                };
                let matching: Vec<_> = imports
                    .iter()
                    .filter(|i| crate::ast::deps::import_path_refers_to_stem(&i.path, &target_name))
                    .collect();
                if matching.is_empty() {
                    return None;
                }
                let display = crate::cmd::ast::display_path(path, &cwd);
                let entries = matching
                    .iter()
                    .map(|imp| {
                        serde_json::json!({
                            "file": display,
                            "imports": imp.path,
                            "line": imp.line,
                            "raw": imp.raw,
                        })
                    })
                    .collect();
                Some(RevDepsResult { entries })
            });
        if let Some(file) = timeout.into_inner().unwrap_or_else(|e| e.into_inner()) {
            let msg = format!("parse deadline exceeded for {file}");
            let body = serde_json::json!({
                "ok": false,
                "applied": false,
                "error_kind": "parse_timeout",
                "error": msg,
            });
            return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
        }
        for r in par_results {
            results.extend(r.entries);
        }
        if results.is_empty()
            && let Some(err) = crate::ops::file::empty_scan_masked_by_unreadable(&all_files, &cwd)
        {
            let msg = err.msg;
            let body = serde_json::json!({
                "ok": false,
                "applied": false,
                "error_kind": "invalid_input",
                "error": msg,
            });
            return exit_code_to_result(exit::FAILURE, &body.to_string(), &msg);
        }
    } else {
        let timeout: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
        let par_results: Vec<serde_json::Value> =
            crate::par_process_files(&paths, None, &[], |path| {
                let imports = match crate::ast::deps::try_extract_imports_from_file(path, lang_hint)
                {
                    Ok(i) => i,
                    Err(crate::ast::ParseFailure::DeadlineExceeded) => {
                        let mut slot = timeout.lock().unwrap_or_else(|e| e.into_inner());
                        if slot.is_none() {
                            *slot = Some(path.display().to_string());
                        }
                        return None;
                    }
                    Err(crate::ast::ParseFailure::NoGrammar) => Vec::new(),
                };
                if imports.is_empty() {
                    return None;
                }
                let display = crate::cmd::ast::display_path(path, &cwd);
                Some(serde_json::json!({
                    "file": display,
                    "imports": imports,
                }))
            });
        if let Some(file) = timeout.into_inner().unwrap_or_else(|e| e.into_inner()) {
            let msg = format!("parse deadline exceeded for {file}");
            let body = serde_json::json!({
                "ok": false,
                "applied": false,
                "error_kind": "parse_timeout",
                "error": msg,
            });
            return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
        }
        results.extend(par_results);
    }

    if results.is_empty() {
        if let Some(err) = crate::ops::file::empty_scan_masked_by_unreadable(&paths, &cwd) {
            return Err(McpError::invalid_params(err.msg, None));
        }
        return no_results("No imports found.");
    }
    let json = serde_json::to_string_pretty(&results)
        .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
    Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}

pub(super) fn handle_ast_map(
    svc: &PatchloomService,
    p: AstMapParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    for s in &p.focus {
        validate_param_size("focus", s)?;
    }
    for s in &p.boost {
        validate_param_size("boost", s)?;
    }
    let cwd = svc.cwd().to_path_buf();
    let target = cwd.join(&p.path);

    if !target.is_dir() {
        return Err(McpError::invalid_params(
            format!("path must be a directory: {}", p.path),
            None,
        ));
    }

    let global = GlobalFlags::with_cwd(&cwd);
    let paths = crate::cmd::ast::collect_source_files(&target, &global)
        .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
    let file_pairs: Vec<(std::path::PathBuf, String)> = paths
        .iter()
        .map(|fp| {
            let display = crate::cmd::ast::display_path(fp, &cwd);
            (fp.clone(), display)
        })
        .collect();

    let opts = crate::ast::map::MapOptions {
        max_tokens: p.max_tokens,
        focus: &p.focus,
        boost: &p.boost,
    };

    let entries = match crate::ast::map::try_generate_map(&file_pairs, &opts) {
        Ok(e) => e,
        Err(e) if crate::exit::is_parse_timeout(&e) => {
            let msg = crate::exit::agent_error_message(&e);
            let body = serde_json::json!({
                "ok": false,
                "applied": false,
                "error_kind": "parse_timeout",
                "error": msg,
            });
            return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
        }
        Err(e) => return Err(McpError::internal_error(format!("{e}"), None)),
    };

    if entries.is_empty() {
        if let Some(err) = crate::ops::file::empty_scan_masked_by_unreadable(&paths, &cwd) {
            let msg = err.msg;
            let body = serde_json::json!({
                "ok": false,
                "applied": false,
                "error_kind": "invalid_input",
                "error": msg,
            });
            return exit_code_to_result(exit::FAILURE, &body.to_string(), &msg);
        }
        return no_results("No symbols found.");
    }

    let json = serde_json::to_string_pretty(&entries)
        .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
    Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}

pub(super) fn handle_ast_diff(
    svc: &PatchloomService,
    p: AstDiffParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    validate_param_size("from", &p.from)?;
    if let Some(ref to) = p.to {
        validate_param_size("to", to)?;
    }
    let cwd = svc.cwd().to_path_buf();
    let target = cwd.join(&p.path);
    let lang_hint = match parse_optional_lang(p.lang.as_deref()) {
        Ok(lang) => lang,
        Err(r) => return *r,
    };
    let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(&target));

    let old_source = crate::cmd::ast::get_git_file_content(&cwd, &p.path, &p.from)
        .map_err(|e| McpError::internal_error(format!("{e}"), None))?;

    let new_source = if let Some(ref to_ref) = p.to {
        crate::cmd::ast::get_git_file_content(&cwd, &p.path, to_ref)
            .map_err(|e| McpError::internal_error(format!("{e}"), None))?
    } else {
        // Strict sole-path (#1894): working-tree binary / invalid UTF-8.
        crate::files::load_text_strict(&target, &p.path).map_err(|e| {
            if crate::exit::is_load_text_strict_fail(&e) || crate::exit::is_io_not_found(&e) {
                McpError::invalid_params(e.to_string(), None)
            } else {
                McpError::internal_error(e.to_string(), None)
            }
        })?
    };

    let changes = match crate::ast::diff::try_structural_diff(&old_source, &new_source, lang) {
        Ok(c) => c,
        Err(crate::ast::ParseFailure::DeadlineExceeded) => {
            let msg = format!("parse deadline exceeded for {}", p.path);
            let body = serde_json::json!({
                "ok": false,
                "applied": false,
                "error_kind": "parse_timeout",
                "error": msg,
            });
            return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
        }
        Err(crate::ast::ParseFailure::NoGrammar) => Vec::new(),
    };

    if changes.is_empty() {
        return no_results("No structural changes.");
    }

    let obj = serde_json::json!({
        "file": p.path,
        "from": p.from,
        "to": p.to.as_deref().unwrap_or("working tree"),
        "changes": changes,
    });
    let json = serde_json::to_string_pretty(&obj)
        .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
    Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}

pub(super) fn handle_ast_impact(
    svc: &PatchloomService,
    p: AstImpactParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    validate_param_size("symbol", &p.symbol)?;
    let cwd = svc.cwd().to_path_buf();
    let target = cwd.join(&p.path);

    let global = GlobalFlags::with_cwd(&cwd);
    let paths = crate::cmd::ast::resolve_target_paths(&target, &p.path, &global)
        .map_err(|e| McpError::invalid_params(format!("{e}"), None))?;

    // Sole explicit non-text: fail closed (CLI parity; not soft empty).
    if crate::cmd::ast::is_sole_explicit_file(&paths, &p.path) {
        let sole = &paths[0];
        if let Err(e) = crate::files::load_text_strict(sole, &p.path)
            && (crate::exit::is_load_text_strict_fail(&e) || crate::exit::is_io_not_found(&e))
        {
            return Err(McpError::invalid_params(
                crate::exit::agent_error_message(&e),
                None,
            ));
        }
    }

    let file_pairs: Vec<(std::path::PathBuf, String)> = paths
        .iter()
        .map(|fp| {
            let display = crate::cmd::ast::display_path(fp, &cwd);
            (fp.clone(), display)
        })
        .collect();

    let nodes = match crate::ast::impact::try_compute_impact(&p.symbol, &file_pairs, p.depth) {
        Ok(n) => n,
        Err(crate::ast::ParseFailure::DeadlineExceeded) => {
            let msg = format!("parse deadline exceeded for {}", p.path);
            let body = serde_json::json!({
                "ok": false,
                "applied": false,
                "error_kind": "parse_timeout",
                "error": msg,
            });
            return exit_code_to_result(exit::PARSE_ERROR, &body.to_string(), &msg);
        }
        Err(crate::ast::ParseFailure::NoGrammar) => Vec::new(),
    };

    if nodes.is_empty() {
        if let Some(err) = crate::ops::file::empty_scan_masked_by_unreadable(&paths, &cwd) {
            return Err(McpError::invalid_params(err.msg, None));
        }
        return no_results(&format!("No references found for '{}'.", p.symbol));
    }

    let obj = serde_json::json!({
        "symbol": p.symbol,
        "depth": p.depth,
        "impact": nodes,
        "total_count": nodes.len(),
    });
    let json = serde_json::to_string_pretty(&obj)
        .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
    Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
}

pub(super) fn handle_ast_replace(
    svc: &PatchloomService,
    p: AstReplaceParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    validate_param_size("old", &p.old)?;
    validate_content_size("new", &p.new_text)?;
    validate_param_size("symbol", &p.symbol)?;
    // Route through the tx engine for backup/rollback safety (#1100).
    let op = crate::plan::Operation::AstReplace {
        path: p.path,
        symbol: p.symbol,
        old: p.old,
        new_text: p.new_text,
        regex: p.regex,
        lang: p.lang,
    };
    svc.run_one_op(op, None)
}

pub(super) fn handle_ast_rewrite_signature(
    svc: &PatchloomService,
    p: AstRewriteSignatureParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    validate_param_size("old", &p.old)?;
    if let Some(ref sig) = p.new_signature {
        validate_content_size("new_signature", sig)?;
    }
    let op = crate::plan::Operation::AstRewriteSignature {
        path: p.path,
        old: p.old,
        new_signature: p.new_signature,
        visibility: p.visibility,
        parameters: p.parameters,
        return_type: p.return_type,
        lang: p.lang,
    };
    svc.run_one_op(op, None)
}

pub(super) fn handle_ast_insert(
    svc: &PatchloomService,
    p: AstInsertParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    validate_content_size("content", &p.content)?;
    let op = crate::plan::Operation::AstInsert {
        path: p.path,
        content: p.content,
        inside: p.inside,
        after: p.after,
        before: p.before,
        position: p.position,
        lang: p.lang,
    };
    svc.run_one_op(op, None)
}

pub(super) fn handle_ast_wrap(
    svc: &PatchloomService,
    p: AstWrapParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    validate_param_size("wrapper", &p.wrapper)?;
    let op = crate::plan::Operation::AstWrap {
        path: p.path,
        symbols: p.symbols,
        lines: p.lines,
        wrapper: p.wrapper,
        preamble: p.preamble,
        lang: p.lang,
    };
    svc.run_one_op(op, None)
}

pub(super) fn handle_ast_imports(
    svc: &PatchloomService,
    p: AstImportsParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;

    // List-only mode (no mutation)
    if p.add.is_none() && p.remove.is_none() && !p.dedupe {
        let cwd = svc.cwd().to_path_buf();
        let target = cwd.join(&p.path);
        let lang_hint = match parse_optional_lang(p.lang.as_deref()) {
            Ok(lang) => lang,
            Err(r) => return *r,
        };
        let lang = lang_hint.unwrap_or_else(|| crate::ast::Language::from_path(&target));
        // Strict sole-path (#1894).
        let source = crate::files::load_text_strict(&target, &p.path).map_err(|e| {
            if crate::exit::is_load_text_strict_fail(&e) || crate::exit::is_io_not_found(&e) {
                McpError::invalid_params(e.to_string(), None)
            } else {
                McpError::internal_error(e.to_string(), None)
            }
        })?;
        let imports = crate::ast::imports::list_imports(&source, lang);
        let obj = serde_json::json!({
            "file": p.path,
            "imports": imports.iter().map(|i| serde_json::json!({
                "text": i.text,
                "line": i.line,
            })).collect::<Vec<_>>(),
            "count": imports.len(),
        });
        let json = serde_json::to_string_pretty(&obj)
            .map_err(|e| McpError::internal_error(format!("{e}"), None))?;
        return Ok(CallToolResult::success(vec![ContentBlock::text(json)]));
    }

    let op = crate::plan::Operation::AstImports {
        path: p.path,
        add: p.add,
        remove: p.remove,
        dedupe: p.dedupe,
        lang: p.lang,
    };
    svc.run_one_op(op, None)
}

pub(super) fn handle_ast_reorder(
    svc: &PatchloomService,
    p: AstReorderParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    let op = crate::plan::Operation::AstReorder {
        path: p.path,
        inside: p.inside,
        order: p.order,
        lang: p.lang,
    };
    svc.run_one_op(op, None)
}

pub(super) fn handle_ast_group(
    svc: &PatchloomService,
    p: AstGroupParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    let op = crate::plan::Operation::AstGroup {
        path: p.path,
        module: p.module,
        symbols: p.symbols,
        preamble: p.preamble,
        position: p.position,
        lang: p.lang,
    };
    svc.run_one_op(op, None)
}

pub(super) fn handle_ast_move(
    svc: &PatchloomService,
    p: AstMoveParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.path)?;
    svc.check_path(&p.target)?;
    let op = crate::plan::Operation::AstMove {
        path: p.path,
        target: p.target,
        symbols: p.symbols,
        position: p.position,
        target_prepend: p.target_prepend,
        lang: p.lang,
        update_imports: p.update_imports,
        old_module_path: p.old_module_path,
        new_module_path: p.new_module_path,
    };
    svc.run_one_op(op, None)
}

pub(super) fn handle_ast_extract_to_file(
    svc: &PatchloomService,
    p: AstExtractToFileParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.source)?;
    svc.check_path(&p.target)?;
    let op = crate::plan::Operation::AstExtractToFile {
        source: p.source,
        symbol: p.symbol,
        target: p.target,
        replacement: p.replacement,
        unwrap: p.unwrap,
        prepend: p.prepend,
        force: p.force,
        lang: p.lang,
        update_imports: p.update_imports,
        old_module_path: p.old_module_path,
        new_module_path: p.new_module_path,
    };
    svc.run_one_op(op, None)
}

pub(super) fn handle_ast_split(
    svc: &PatchloomService,
    p: AstSplitParams,
) -> Result<CallToolResult, McpError> {
    svc.check_path(&p.source)?;
    for t in &p.targets {
        svc.check_path(&t.path)?;
    }
    let targets: Vec<crate::plan::SplitTargetSpec> = p
        .targets
        .into_iter()
        .map(|t| crate::plan::SplitTargetSpec {
            path: t.path,
            symbols: t.symbols,
            prepend: t.prepend,
        })
        .collect();
    let op = crate::plan::Operation::AstSplit {
        source: p.source,
        targets,
        keep_in_source: p.keep_in_source,
        source_suffix: p.source_suffix,
        source_prefix: p.source_prefix,
        require_exhaustive: p.require_exhaustive,
        lang: p.lang,
    };
    svc.run_one_op(op, None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use rmcp::model::ContentBlock;
    use tempfile::TempDir;

    fn make_service(dir: &TempDir) -> PatchloomService {
        PatchloomService::new(dir.path().to_path_buf(), None).unwrap()
    }

    /// Extract text from the first ContentBlock item in a CallToolResult.
    fn extract_text(result: &CallToolResult) -> String {
        match &result.content[0] {
            ContentBlock::Text(t) => t.text.clone(),
            other => panic!("expected text content, got {other:?}"),
        }
    }

    const RUST_SAMPLE: &str = r#"
fn greet(name: &str) -> String {
    format!("Hello, {name}!")
}

struct Point {
    x: f64,
    y: f64,
}

impl Point {
    fn origin() -> Self {
        Point { x: 0.0, y: 0.0 }
    }
}
"#;

    #[test]
    fn ast_list_single_file() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("sample.rs"), RUST_SAMPLE).unwrap();

        let svc = make_service(&dir);
        let params = AstListParams {
            path: "sample.rs".into(),
            kind: None,
            lang: Some("rs".into()),
        };

        let result = handle_ast_list(&svc, params).unwrap();
        let text = extract_text(&result);
        assert!(text.contains("greet"));
        assert!(text.contains("Point"));
    }

    #[test]
    fn ast_list_kind_filter() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("sample.rs"), RUST_SAMPLE).unwrap();

        let svc = make_service(&dir);
        let params = AstListParams {
            path: "sample.rs".into(),
            kind: Some("struct".into()),
            lang: Some("rs".into()),
        };

        let result = handle_ast_list(&svc, params).unwrap();
        let text = extract_text(&result);
        assert!(text.contains("Point"));
        assert!(!text.contains("\"greet\""));
    }

    #[test]
    fn ast_list_unknown_lang() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("mod.py"), "def x():\n    pass\n").unwrap();

        let svc = make_service(&dir);
        let params = AstListParams {
            path: "mod.py".into(),
            kind: None,
            lang: Some("python3".into()),
        };

        let result = handle_ast_list(&svc, params).expect("unknown lang is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "unknown lang must set isError so hosts do not retry as invalid_params"
        );
        let text = extract_text(&result);
        assert!(
            text.contains("invalid_input"),
            "unknown lang must surface invalid_input, got: {text}"
        );
        assert!(text.contains("python3"), "must name the token: {text}");
        assert!(
            text.contains("\"error_kind\""),
            "must not be protocol-only invalid_params without error_kind: {text}"
        );
    }

    #[test]
    fn ast_list_path_not_found() {
        let dir = TempDir::new().unwrap();
        let svc = make_service(&dir);
        let params = AstListParams {
            path: "nonexistent.rs".into(),
            kind: None,
            lang: None,
        };

        let result = handle_ast_list(&svc, params);
        result.expect_err("expected error");
    }

    #[test]
    fn ast_read_symbol() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("sample.rs"), RUST_SAMPLE).unwrap();

        let svc = make_service(&dir);
        let params = AstReadParams {
            path: "sample.rs".into(),
            symbol: "greet".into(),
            context: 0,
            lang: Some("rs".into()),
        };

        let result = handle_ast_read(&svc, params).unwrap();
        let text = extract_text(&result);
        assert!(text.contains("greet"));
        assert!(text.contains("Hello"));
    }

    #[test]
    fn ast_read_symbol_not_found() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("sample.rs"), RUST_SAMPLE).unwrap();

        let svc = make_service(&dir);
        let params = AstReadParams {
            path: "sample.rs".into(),
            symbol: "nonexistent_fn".into(),
            context: 0,
            lang: Some("rs".into()),
        };

        let result = handle_ast_read(&svc, params).expect("miss is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "missing symbol must set isError so hosts do not retry as invalid_params"
        );
        let text = extract_text(&result);
        assert!(
            text.contains("no_matches"),
            "read miss must surface no_matches, got: {text}"
        );
        assert!(
            text.contains("symbol 'nonexistent_fn' not found in sample.rs"),
            "must keep the English miss, got: {text}"
        );
    }

    #[test]
    fn ast_validate_valid_file() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("valid.rs"), RUST_SAMPLE).unwrap();

        let svc = make_service(&dir);
        let params = AstValidateParams {
            path: "valid.rs".into(),
            lang: Some("rs".into()),
        };

        let result = handle_ast_validate(&svc, params).unwrap();
        let text = extract_text(&result);
        assert!(text.contains("\"valid\": true"));
    }

    #[test]
    fn ast_validate_syntax_error() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("bad.rs"), "fn broken( {").unwrap();

        let svc = make_service(&dir);
        let params = AstValidateParams {
            path: "bad.rs".into(),
            lang: Some("rs".into()),
        };

        let result = handle_ast_validate(&svc, params).unwrap();
        assert!(
            result.is_error.is_some_and(|v| v),
            "invalid syntax must set isError so agents do not treat as clean"
        );
        let text = extract_text(&result);
        assert!(text.contains("\"valid\": false"));
    }

    #[test]
    fn ast_search_finds_pattern() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("sample.rs"), RUST_SAMPLE).unwrap();

        let svc = make_service(&dir);
        let params = AstSearchParams {
            path: "sample.rs".into(),
            query: "(function_item name: (identifier) @name)".into(),
            pattern: false,
            lang: Some("rs".into()),
            max_results: None,
        };

        let result = handle_ast_search(&svc, params).unwrap();
        let text = extract_text(&result);
        assert!(text.contains("greet"));
    }

    #[test]
    fn ast_search_empty_pattern_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("sample.rs"), RUST_SAMPLE).unwrap();
        let svc = make_service(&dir);
        for query in ["", "   "] {
            let params = AstSearchParams {
                path: "sample.rs".into(),
                query: query.into(),
                pattern: true,
                lang: Some("rs".into()),
                max_results: None,
            };
            let result = handle_ast_search(&svc, params).expect("empty pattern is a tool result");
            assert!(
                result.is_error.unwrap_or(false),
                "empty pattern must set isError so hosts do not treat whole-file hit as success"
            );
            let text = extract_text(&result);
            let v: serde_json::Value = serde_json::from_str(&text)
                .unwrap_or_else(|e| panic!("tool text must be JSON: {e}\n{text}"));
            assert_eq!(
                v["error_kind"].as_str(),
                Some("invalid_input"),
                "empty pattern must peel invalid_input, got: {text}"
            );
            assert!(
                v["error"]
                    .as_str()
                    .is_some_and(|s| s.contains("must not be empty")),
                "must name empty pattern, got: {text}"
            );
        }
    }

    #[test]
    // Unique: MCP search envelope; timeout is parse_timeout, not "No matches found".
    fn ast_search_sole_file_timeout_is_parse_timeout() {
        let dir = TempDir::new().unwrap();
        std::fs::write(
            dir.path().join("deep.rs"),
            crate::ast::nested_rust_source_for_timeout(80_000),
        )
        .unwrap();
        let svc = make_service(&dir);
        let _guard = crate::ast::ParseTimeoutGuard::set(std::time::Duration::from_millis(1));
        let params = AstSearchParams {
            path: "deep.rs".into(),
            query: "(function_item) @fn".into(),
            pattern: false,
            lang: Some("rs".into()),
            max_results: None,
        };
        let result = handle_ast_search(&svc, params).expect("timeout is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "sole-path search timeout must not become no matches"
        );
        let text = extract_text(&result);
        assert!(
            text.contains("parse_timeout"),
            "timeout must surface parse_timeout, got: {text}"
        );
        assert!(
            text.contains("\"applied\":false") || text.contains("\"applied\": false"),
            "parse_timeout JSON must set applied:false: {text}"
        );
        assert!(
            !text.contains("No matches found"),
            "search_file timeout must not be .ok()?-swallowed: {text}"
        );
    }

    #[test]
    // Unique: MCP validate envelope; sole-file timeout is not a walk-soft valid:false row.
    fn ast_validate_sole_file_timeout_is_parse_timeout() {
        let dir = TempDir::new().unwrap();
        std::fs::write(
            dir.path().join("deep.rs"),
            crate::ast::nested_rust_source_for_timeout(80_000),
        )
        .unwrap();
        let svc = make_service(&dir);
        let _guard = crate::ast::ParseTimeoutGuard::set(std::time::Duration::from_millis(1));
        let params = AstValidateParams {
            path: "deep.rs".into(),
            lang: Some("rs".into()),
        };
        let result = handle_ast_validate(&svc, params).expect("timeout is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "sole-path validate timeout must not become a valid:false row"
        );
        let text = extract_text(&result);
        assert!(
            text.contains("parse_timeout"),
            "timeout must surface parse_timeout, not a walk-soft valid:false row only: {text}"
        );
        assert!(
            text.contains("\"applied\":false") || text.contains("\"applied\": false"),
            "parse_timeout JSON must set applied:false: {text}"
        );
        let walk_soft = (text.contains("\"valid\": false") || text.contains("\"valid\":false"))
            && !text.contains("parse_timeout");
        assert!(
            !walk_soft,
            "must not be a walk-soft valid:false row only: {text}"
        );
    }

    #[test]
    fn ast_map_unreadable_sibling_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("empty.rs"), "// no symbols\n").unwrap();
        let locked = dir.path().join("locked.rs");
        std::fs::write(&locked, "fn bar() {}\n").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
            if std::fs::read_to_string(&locked).is_ok() {
                std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644)).unwrap();
                return;
            }
            let svc = make_service(&dir);
            let params = AstMapParams {
                path: ".".into(),
                max_tokens: 1024,
                focus: Vec::new(),
                boost: Vec::new(),
            };
            let result = handle_ast_map(&svc, params).expect("unreadable sibling is a tool result");
            assert!(
                result.is_error.unwrap_or(false),
                "empty map must not mask an unreadable sibling as no symbols"
            );
            let text = extract_text(&result);
            assert!(
                text.contains("invalid_input"),
                "unreadable sibling must surface invalid_input, got: {text}"
            );
            assert!(
                text.contains("\"ok\":false") || text.contains("\"ok\": false"),
                "invalid_input JSON must set ok:false: {text}"
            );
            assert!(
                text.contains("\"applied\":false") || text.contains("\"applied\": false"),
                "invalid_input JSON must set applied:false: {text}"
            );
            assert!(
                !text.contains("No symbols found"),
                "must not claim no symbols when a scanned sibling is unreadable: {text}"
            );
            assert!(
                !text.contains("invalid_params"),
                "must be tool envelope, not JSON-RPC invalid_params: {text}"
            );
            std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644)).unwrap();
        }
        #[cfg(not(unix))]
        {
            let _ = locked;
        }
    }

    #[test]
    fn ast_deps_reverse_unreadable_sibling_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("target.rs"), "fn foo() {}\n").unwrap();
        let locked = dir.path().join("locked.rs");
        std::fs::write(&locked, "fn bar() {}\n").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
            if std::fs::read_to_string(&locked).is_ok() {
                std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644)).unwrap();
                return;
            }
            let svc = make_service(&dir);
            let params = AstDepsParams {
                path: "target.rs".into(),
                reverse: true,
                lang: Some("rs".into()),
            };
            let result =
                handle_ast_deps(&svc, params).expect("unreadable sibling is a tool result");
            assert!(
                result.is_error.unwrap_or(false),
                "reverse scan must not mask an unreadable sibling as no imports"
            );
            let text = extract_text(&result);
            assert!(
                text.contains("invalid_input"),
                "unreadable sibling must surface invalid_input, got: {text}"
            );
            assert!(
                text.contains("\"applied\":false") || text.contains("\"applied\": false"),
                "invalid_input JSON must set applied:false: {text}"
            );
            assert!(
                !text.contains("No imports found"),
                "must not claim no imports when a scanned sibling is unreadable: {text}"
            );
            std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644)).unwrap();
        }
        #[cfg(not(unix))]
        {
            let _ = locked;
        }
    }

    #[test]
    fn ast_deps_reverse_finds_importer_outside_target_parent() {
        let dir = TempDir::new().unwrap();
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        std::fs::create_dir_all(dir.path().join("tests")).unwrap();
        std::fs::write(dir.path().join("src/foo.rs"), "pub fn foo() {}\n").unwrap();
        std::fs::write(dir.path().join("src/lib.rs"), "use crate::foo;\n").unwrap();
        std::fs::write(dir.path().join("tests/import.rs"), "use crate::foo;\n").unwrap();
        let svc = make_service(&dir);
        let params = AstDepsParams {
            path: "src/foo.rs".into(),
            reverse: true,
            lang: Some("rs".into()),
        };
        let result = handle_ast_deps(&svc, params).expect("reverse deps is a tool result");
        let text = extract_text(&result);
        // Parse JSON so Windows `tests\import.rs` is one dest, not JSON `\\`.
        let rows: Vec<serde_json::Value> = serde_json::from_str(&text)
            .unwrap_or_else(|e| panic!("expected JSON rows, got {e}: {text}"));
        let files: Vec<String> = rows
            .iter()
            .filter_map(|r| r.get("file").and_then(|v| v.as_str()))
            .map(|s| s.replace('\\', "/"))
            .collect();
        assert!(
            files.iter().any(|f| f == "tests/import.rs"),
            "reverse deps must scan cwd and include importers outside dest parent, got: {text}"
        );
        assert!(
            files.iter().any(|f| f == "src/lib.rs"),
            "reverse deps must still report the in-parent importer, got: {text}"
        );
    }

    #[test]
    fn ast_deps_reverse_matches_dotted_import_stem() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("foo.py"), "def foo():\n    pass\n").unwrap();
        std::fs::write(dir.path().join("importer.py"), "from pkg.foo import x\n").unwrap();
        let svc = make_service(&dir);
        let params = AstDepsParams {
            path: "foo.py".into(),
            reverse: true,
            lang: Some("py".into()),
        };
        let result = handle_ast_deps(&svc, params).expect("reverse deps is a tool result");
        let text = extract_text(&result);
        assert!(
            text.contains("importer.py"),
            "dotted import pkg.foo must match stem foo, got: {text}"
        );
        assert!(
            text.contains("pkg.foo"),
            "result must include the dotted import path, got: {text}"
        );
    }

    #[test]
    // Unique: MCP rename preflight; timeout must not word-boundary-write.
    fn ast_rename_sole_file_timeout_is_parse_timeout() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("deep.rs");
        let original = crate::ast::nested_rust_source_for_timeout(80_000);
        std::fs::write(&path, &original).unwrap();
        let svc = make_service(&dir);
        let _guard = crate::ast::ParseTimeoutGuard::set(std::time::Duration::from_millis(1));
        let params = AstRenameParams {
            path: "deep.rs".into(),
            old: "x".into(),
            new: "y".into(),
            lang: Some("rs".into()),
        };
        let result = handle_ast_rename(&svc, params).expect("timeout is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "sole-path rename timeout must not apply a word-boundary write"
        );
        let text = extract_text(&result);
        assert!(
            text.contains("parse_timeout"),
            "timeout must surface parse_timeout, got: {text}"
        );
        assert!(
            text.contains("\"applied\":false") || text.contains("\"applied\": false"),
            "parse_timeout JSON must set applied:false: {text}"
        );
        let after = std::fs::read_to_string(&path).unwrap();
        assert_eq!(after, original, "timeout must not word-boundary-write");
    }

    #[test]
    fn ast_deps_one_file_dir_binary_is_no_imports() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("only.rs"), b"use foo::Bar;\0").unwrap();
        let svc = make_service(&dir);
        let result = handle_ast_deps(
            &svc,
            AstDepsParams {
                path: ".".into(),
                reverse: false,
                lang: None,
            },
        )
        .expect("one-file dir must not hard-fail");
        let text = extract_text(&result);
        assert!(
            !text.to_lowercase().contains("binary"),
            "dir walk must not name the directory as binary: {text}"
        );
    }

    #[test]
    fn ast_refs_one_file_dir_binary_is_no_refs() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("only.rs"), b"fn main() {}\0").unwrap();
        let svc = make_service(&dir);
        let result = handle_ast_refs(
            &svc,
            AstRefsParams {
                path: ".".into(),
                symbol: "main".into(),
                include_def: true,
                lang: None,
            },
        )
        .expect("one-file dir must not hard-fail");
        let text = extract_text(&result);
        assert!(
            !text.to_lowercase().contains("binary"),
            "dir walk must not name the directory as binary: {text}"
        );
    }

    #[test]
    fn ast_search_one_file_dir_binary_is_no_matches() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("only.rs"), b"fn main() {}\0").unwrap();
        let svc = make_service(&dir);
        let result = handle_ast_search(
            &svc,
            AstSearchParams {
                path: ".".into(),
                query: "(function_item) @fn".into(),
                pattern: false,
                lang: None,
                max_results: None,
            },
        )
        .expect("one-file dir must not hard-fail");
        let text = extract_text(&result);
        assert!(
            !text.to_lowercase().contains("binary"),
            "dir walk must not name the directory as binary: {text}"
        );
    }

    #[test]
    fn ast_impact_one_file_dir_binary_is_no_refs() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("only.rs"), b"fn main() {}\0").unwrap();
        let svc = make_service(&dir);
        let result = handle_ast_impact(
            &svc,
            AstImpactParams {
                path: ".".into(),
                symbol: "main".into(),
                depth: 3,
            },
        )
        .expect("one-file dir must not hard-fail");
        let text = extract_text(&result);
        assert!(
            !text.to_lowercase().contains("binary"),
            "dir walk must not name the directory as binary: {text}"
        );
    }

    #[test]
    fn ast_rename_one_file_dir_binary_is_no_matches() {
        let dir = TempDir::new().unwrap();
        let dest = dir.path().join("only.rs");
        let original = b"fn keep() {}\0";
        std::fs::write(&dest, original).unwrap();
        let svc = make_service(&dir);
        let result = handle_ast_rename(
            &svc,
            AstRenameParams {
                path: ".".into(),
                old: "absent".into(),
                new: "other".into(),
                lang: None,
            },
        )
        .expect("one-file dir must not hard-fail");
        let text = extract_text(&result);
        assert!(
            !text.contains("invalid_params"),
            "dir walk must not be invalid_params: {text}"
        );
        assert!(
            !text.to_lowercase().contains("binary"),
            "dir walk must not name the directory as binary: {text}"
        );
        let after = std::fs::read(&dest).unwrap();
        assert_eq!(after, original.as_slice());
    }

    #[test]
    fn ast_rename_unknown_lang() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("mod.py");
        let original = "def greet():\n    pass\n";
        std::fs::write(&path, original).unwrap();

        let svc = make_service(&dir);
        let params = AstRenameParams {
            path: "mod.py".into(),
            old: "greet".into(),
            new: "salute".into(),
            lang: Some("python3".into()),
        };

        let result = handle_ast_rename(&svc, params).expect("unknown lang is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "unknown lang must set isError so hosts do not retry as invalid_params"
        );
        let text = extract_text(&result);
        assert!(
            text.contains("invalid_input"),
            "unknown lang must surface invalid_input, got: {text}"
        );
        assert!(text.contains("python3"), "must name the token: {text}");
        assert!(
            text.contains("\"error_kind\""),
            "must not be protocol-only invalid_params without error_kind: {text}"
        );
        let after = std::fs::read_to_string(&path).unwrap();
        assert_eq!(after, original, "unknown lang must not mutate dest");
    }

    #[test]
    fn ast_rename_empty_new_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("rename.rs"), RUST_SAMPLE).unwrap();
        let svc = make_service(&dir);
        for new in [String::new(), "   ".into()] {
            let params = AstRenameParams {
                path: "rename.rs".into(),
                old: "greet".into(),
                new,
                lang: Some("rs".into()),
            };
            let result = handle_ast_rename(&svc, params).expect("empty new is a tool result");
            assert!(
                result.is_error.unwrap_or(false),
                "empty new must set isError"
            );
            let text = extract_text(&result);
            let v: serde_json::Value = serde_json::from_str(&text)
                .unwrap_or_else(|e| panic!("tool text must be JSON: {e}\n{text}"));
            assert_eq!(v["error_kind"].as_str(), Some("invalid_input"));
            let after = std::fs::read_to_string(dir.path().join("rename.rs")).unwrap();
            assert_eq!(after, RUST_SAMPLE, "empty new must not mutate dest");
        }
    }

    #[test]
    fn ast_insert_empty_content_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        let original = "fn foo() { let x = 1; }\n";
        std::fs::write(dir.path().join("t.rs"), original).unwrap();
        let svc = make_service(&dir);
        let params = AstInsertParams {
            path: "t.rs".into(),
            content: String::new(),
            inside: None,
            after: Some("foo".into()),
            before: None,
            position: None,
            lang: Some("rs".into()),
        };
        let result = handle_ast_insert(&svc, params).expect("empty content is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "empty insert content must set isError"
        );
        let text = extract_text(&result);
        let v: serde_json::Value = serde_json::from_str(&text)
            .unwrap_or_else(|e| panic!("tool text must be JSON: {e}\n{text}"));
        assert_eq!(v["error_kind"].as_str(), Some("invalid_input"));
        let after = std::fs::read_to_string(dir.path().join("t.rs")).unwrap();
        assert_eq!(after, original, "empty insert must not mutate dest");
    }

    #[test]
    fn ast_wrap_empty_wrapper_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        let original = "fn foo() { let x = 1; }\n";
        std::fs::write(dir.path().join("t.rs"), original).unwrap();
        let svc = make_service(&dir);
        let params = AstWrapParams {
            path: "t.rs".into(),
            symbols: Some(vec!["foo".into()]),
            lines: None,
            wrapper: String::new(),
            preamble: None,
            lang: Some("rs".into()),
        };
        let result = handle_ast_wrap(&svc, params).expect("empty wrapper is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "empty wrap wrapper must set isError"
        );
        let text = extract_text(&result);
        let v: serde_json::Value = serde_json::from_str(&text)
            .unwrap_or_else(|e| panic!("tool text must be JSON: {e}\n{text}"));
        assert_eq!(v["error_kind"].as_str(), Some("invalid_input"));
        let after = std::fs::read_to_string(dir.path().join("t.rs")).unwrap();
        assert_eq!(after, original, "empty wrap must not mutate dest");
    }

    #[test]
    fn ast_rewrite_empty_new_signature_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        let original = "fn foo() { let x = 1; }\nfn bar() {}\n";
        std::fs::write(dir.path().join("t.rs"), original).unwrap();
        let svc = make_service(&dir);
        let params = AstRewriteSignatureParams {
            path: "t.rs".into(),
            old: "foo".into(),
            new_signature: Some(String::new()),
            visibility: None,
            parameters: None,
            return_type: None,
            lang: Some("rs".into()),
        };
        let result = handle_ast_rewrite_signature(&svc, params)
            .expect("empty new_signature is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "empty new_signature must set isError"
        );
        let text = extract_text(&result);
        let v: serde_json::Value = serde_json::from_str(&text)
            .unwrap_or_else(|e| panic!("tool text must be JSON: {e}\n{text}"));
        assert_eq!(v["error_kind"].as_str(), Some("invalid_input"));
        let after = std::fs::read_to_string(dir.path().join("t.rs")).unwrap();
        assert_eq!(after, original, "empty new_signature must not mutate dest");
    }

    #[test]
    fn ast_rewrite_empty_parameters_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        let original = "fn foo(x: i32) { let x = 1; }\n";
        std::fs::write(dir.path().join("t.rs"), original).unwrap();
        let svc = make_service(&dir);
        let params = AstRewriteSignatureParams {
            path: "t.rs".into(),
            old: "foo".into(),
            new_signature: None,
            visibility: None,
            parameters: Some(String::new()),
            return_type: None,
            lang: Some("rs".into()),
        };
        let result =
            handle_ast_rewrite_signature(&svc, params).expect("empty parameters is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "empty parameters must set isError"
        );
        let text = extract_text(&result);
        let v: serde_json::Value = serde_json::from_str(&text)
            .unwrap_or_else(|e| panic!("tool text must be JSON: {e}\n{text}"));
        assert_eq!(v["error_kind"].as_str(), Some("invalid_input"));
        let after = std::fs::read_to_string(dir.path().join("t.rs")).unwrap();
        assert_eq!(after, original, "empty parameters must not mutate dest");
    }

    #[test]
    fn ast_split_empty_symbols_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        let original = "fn foo() { let x = 1; }\n";
        std::fs::write(dir.path().join("t.rs"), original).unwrap();
        let svc = make_service(&dir);
        let params = AstSplitParams {
            source: "t.rs".into(),
            targets: vec![AstSplitTargetParam {
                path: "a.rs".into(),
                symbols: vec![String::new()],
                prepend: None,
            }],
            keep_in_source: vec![],
            source_suffix: None,
            source_prefix: None,
            require_exhaustive: Some(false),
            lang: Some("rs".into()),
        };
        let result = handle_ast_split(&svc, params).expect("empty split symbol is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "empty split symbol must set isError"
        );
        let text = extract_text(&result);
        let v: serde_json::Value = serde_json::from_str(&text)
            .unwrap_or_else(|e| panic!("tool text must be JSON: {e}\n{text}"));
        assert_eq!(v["error_kind"].as_str(), Some("invalid_input"));
        let after = std::fs::read_to_string(dir.path().join("t.rs")).unwrap();
        assert_eq!(after, original, "empty split must not mutate source");
        assert!(
            !dir.path().join("a.rs").exists(),
            "empty split must not create dest"
        );
    }

    #[test]
    fn ast_move_empty_symbols_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        let original = "fn foo() { let x = 1; }\n";
        std::fs::write(dir.path().join("t.rs"), original).unwrap();
        let svc = make_service(&dir);
        let params = AstMoveParams {
            path: "t.rs".into(),
            target: "dest.rs".into(),
            symbols: vec![],
            position: None,
            target_prepend: None,
            lang: Some("rs".into()),
            update_imports: false,
            old_module_path: None,
            new_module_path: None,
        };
        let result = handle_ast_move(&svc, params).expect("empty move symbols is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "empty move symbols must set isError"
        );
        let text = extract_text(&result);
        let v: serde_json::Value = serde_json::from_str(&text)
            .unwrap_or_else(|e| panic!("tool text must be JSON: {e}\n{text}"));
        assert_eq!(v["error_kind"].as_str(), Some("invalid_input"));
        assert!(
            v["error"]
                .as_str()
                .is_some_and(|s| s.contains("must not be empty")),
            "must name empty symbols, got: {text}"
        );
        let after = std::fs::read_to_string(dir.path().join("t.rs")).unwrap();
        assert_eq!(after, original, "empty move symbols must not mutate source");
        assert!(
            !dir.path().join("dest.rs").exists(),
            "empty move symbols must not create dest"
        );
    }

    #[test]
    fn ast_group_empty_module_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        let original = "fn foo() { let x = 1; }\n";
        std::fs::write(dir.path().join("t.rs"), original).unwrap();
        let svc = make_service(&dir);
        let params = AstGroupParams {
            path: "t.rs".into(),
            module: String::new(),
            symbols: vec!["foo".into()],
            preamble: None,
            position: None,
            lang: Some("rs".into()),
        };
        let result = handle_ast_group(&svc, params).expect("empty module is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "empty group module must set isError"
        );
        let text = extract_text(&result);
        let v: serde_json::Value = serde_json::from_str(&text)
            .unwrap_or_else(|e| panic!("tool text must be JSON: {e}\n{text}"));
        assert_eq!(v["error_kind"].as_str(), Some("invalid_input"));
        let after = std::fs::read_to_string(dir.path().join("t.rs")).unwrap();
        assert_eq!(after, original, "empty group module must not mutate dest");
    }

    #[test]
    fn ast_imports_empty_add_item_is_invalid_input() {
        let dir = TempDir::new().unwrap();
        let original = "fn foo() { let x = 1; }\n";
        std::fs::write(dir.path().join("t.rs"), original).unwrap();
        let svc = make_service(&dir);
        let params = AstImportsParams {
            path: "t.rs".into(),
            add: Some(vec![String::new()]),
            remove: None,
            dedupe: false,
            lang: Some("rs".into()),
        };
        let result = handle_ast_imports(&svc, params).expect("empty add item is a tool result");
        assert!(
            result.is_error.unwrap_or(false),
            "empty import add item must set isError"
        );
        let text = extract_text(&result);
        let v: serde_json::Value = serde_json::from_str(&text)
            .unwrap_or_else(|e| panic!("tool text must be JSON: {e}\n{text}"));
        assert_eq!(v["error_kind"].as_str(), Some("invalid_input"));
        let after = std::fs::read_to_string(dir.path().join("t.rs")).unwrap();
        assert_eq!(after, original, "empty import add must not mutate dest");
    }

    #[test]
    fn ast_rename_replaces_symbol() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("rename.rs"), RUST_SAMPLE).unwrap();

        let svc = make_service(&dir);
        let params = AstRenameParams {
            path: "rename.rs".into(),
            old: "greet".into(),
            new: "salute".into(),
            lang: Some("rs".into()),
        };

        let result = handle_ast_rename(&svc, params).unwrap();
        let text = extract_text(&result);
        assert!(text.contains("\"ok\": true"));

        let content = std::fs::read_to_string(dir.path().join("rename.rs")).unwrap();
        assert!(content.contains("salute"));
        assert!(!content.contains("greet"));
    }

    #[test]
    fn ast_rename_same_name_no_match() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("sample.rs"), RUST_SAMPLE).unwrap();

        let svc = make_service(&dir);
        let params = AstRenameParams {
            path: "sample.rs".into(),
            old: "greet".into(),
            new: "greet".into(),
            lang: Some("rs".into()),
        };

        let result = handle_ast_rename(&svc, params).unwrap();
        assert!(result.is_error.unwrap_or(false));
    }

    #[test]
    fn ast_rename_missing_symbol_is_error_not_soft_success() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("sample.rs"), RUST_SAMPLE).unwrap();

        let svc = make_service(&dir);
        let params = AstRenameParams {
            path: "sample.rs".into(),
            old: "does_not_exist_symbol".into(),
            new: "other".into(),
            lang: Some("rs".into()),
        };

        let result = handle_ast_rename(&svc, params).unwrap();
        assert!(
            result.is_error.unwrap_or(false),
            "write miss must set isError so agents do not treat rename as applied"
        );
        let text = extract_text(&result);
        assert!(
            text.contains("no_matches") || text.contains("No matches"),
            "got: {text}"
        );
        let content = std::fs::read_to_string(dir.path().join("sample.rs")).unwrap();
        assert!(
            content.contains("greet"),
            "file must stay unchanged on rename miss"
        );
    }
}