pathfinder-mcp 0.19.0

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

use crate::server::helpers::{
    invalid_params_error, parse_semantic_path, pathfinder_to_error_data,
    treesitter_error_to_error_data,
};
use crate::server::types::{HealthParams, LocateParams, TraceParams, TraceScope};
use crate::server::PathfinderServer;
use pathfinder_common::types::DegradedReason;
use rmcp::model::{CallToolResult, ErrorData};

mod deep_context;
mod definition;
mod health;
mod impact;
mod overview;
mod references;
#[cfg(test)]
mod test_helpers;

/// File extensions considered source code for grep fallback filtering.
///
/// When the LSP is unavailable and we fall back to text search, we only
/// want results from actual source files, not documentation (.md), config
/// (.json, .yaml, .toml), or other non-source files.
const SOURCE_FILE_EXTENSIONS: &[&str] = &[
    "rs",   // Rust
    "go",   // Go
    "ts",   // TypeScript
    "tsx",  // TypeScript + JSX
    "js",   // JavaScript
    "jsx",  // JavaScript + JSX
    "mjs",  // JavaScript (ESM module)
    "cjs",  // JavaScript (CommonJS)
    "py",   // Python
    "pyi",  // Python type stub
    "vue",  // Vue Single-File Component
    "java", // Java
];

/// Returns `true` if the file path has a source code extension.
///
/// Used to filter out non-source files (docs, configs) from grep fallback
/// search results to reduce false positives.
fn is_source_file(file: &str) -> bool {
    let ext = std::path::Path::new(file)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("");
    SOURCE_FILE_EXTENSIONS.contains(&ext)
}

/// Returns `true` if the file path looks like a test file.
///
/// Uses language-specific heuristics:
/// - Rust: files ending in `_test.rs` or containing `mod tests`
/// - Go: files ending in `_test.go`
/// - Python: files starting with `test_` or containing test functions
/// - TypeScript/JavaScript: files ending in `.test.ts`, `.spec.ts`, `.test.js`, `.spec.js`
fn is_test_file(file: &str) -> bool {
    let path = std::path::Path::new(file);
    let filename = path.file_name().and_then(|f| f.to_str()).unwrap_or("");
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
    let file_str = file.replace('\\', "/");

    // Directory-based detection: files inside test/spec/__tests__ directories
    if file_str.contains("/tests/")
        || file_str.contains("/test/")
        || file_str.contains("/spec/")
        || file_str.contains("/specs/")
        || file_str.contains("/__tests__/")
        || file_str.contains("/__test__/")
    {
        return true;
    }

    match ext {
        "rs" => filename.ends_with("_test.rs") || filename == "test.rs",
        "go" => filename.ends_with("_test.go"),
        "py" => filename.starts_with("test_") || filename == "conftest.py",
        "java" => filename.ends_with("Test.java") || filename.ends_with("Tests.java"),
        "kt" | "kts" => filename.ends_with("Test.kt") || filename.ends_with("Spec.kt"),
        "cs" => filename.ends_with("Test.cs") || filename.ends_with("Tests.cs"),
        "rb" => filename.ends_with("_test.rb") || filename.ends_with("_spec.rb"),
        "dart" => filename.ends_with("_test.dart"),
        "ts" | "tsx" | "js" | "jsx" => {
            filename.ends_with(".test.ts")
                || filename.ends_with(".spec.ts")
                || filename.ends_with(".test.tsx")
                || filename.ends_with(".spec.tsx")
                || filename.ends_with(".test.js")
                || filename.ends_with(".spec.js")
                || filename.ends_with(".test.jsx")
                || filename.ends_with(".spec.jsx")
        }
        _ => false,
    }
}

/// Returns `true` if the file looks like it's from the user's workspace (not external/dependencies).
///
/// Uses heuristic string matching — does not perform filesystem I/O — to avoid per-reference
/// latency overhead in BFS traversal. Filters out:
/// - Absolute paths (Unix `/`, Windows `\` or `C:\`)
/// - Paths containing `node_modules/` or `vendor/` (dependency directories)
/// - Known Rust stdlib root paths (`std/`, `core/`, `alloc/`)
/// - Non-source-code files (checked via [`is_source_file`])
fn is_workspace_file(file: &str) -> bool {
    // Filter out absolute paths (stdlib, SDK files)
    // Unix: starts with `/`
    // Windows: starts with `\` or has `:` at position 1 (e.g., `C:\`)
    if file.starts_with('/') || file.starts_with('\\') {
        return false;
    }
    // Check for Windows-style absolute paths like `C:\` or `D:/`
    if file.len() >= 2 {
        let second_char = file.chars().nth(1);
        if second_char == Some(':') {
            return false;
        }
    }
    // Filter out dependency directories
    if file.contains("node_modules/")
        || file.contains("node_modules\\")
        || file.contains("vendor/")
        || file.contains("vendor\\")
    {
        return false;
    }
    // Filter out known Rust stdlib paths
    if file.starts_with("std/")
        || file.starts_with("core/")
        || file.starts_with("alloc/")
        || file.starts_with("library/std/")
        || file.starts_with("library/core/")
        || file.starts_with("library/alloc/")
        || file.starts_with("library\\std\\")
        || file.starts_with("library\\core\\")
        || file.starts_with("library\\alloc\\")
        || file == "std"
        || file == "core"
        || file == "alloc"
    {
        return false;
    }
    // Must be a source code file to be considered a workspace file
    // This filters out docs, configs, and other non-source files
    is_source_file(file)
}

/// Result of LSP call-hierarchy resolution for `read_with_deep_context`.
struct LspResolution {
    dependencies: Vec<crate::server::types::DeepContextDependency>,
    degraded: bool,
    degraded_reason: Option<DegradedReason>,
    engines: Vec<&'static str>,
    dependencies_truncated: bool,
}

static CALL_PATTERN_FULL: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();

#[allow(clippy::expect_used)]
fn call_pattern_full() -> &'static regex::Regex {
    CALL_PATTERN_FULL.get_or_init(|| {
        regex::Regex::new(r"\b([a-zA-Z_][a-zA-Z0-9_]*)\s*\(|\.([a-zA-Z_][a-zA-Z0-9_]*)\s*\(")
            .expect("call pattern full is valid regex")
    })
}

/// PATCH-005: Extract function call patterns from symbol body using language-aware regex.
///
/// Returns candidate function names that might be called by this symbol.
/// Filters out language keywords and caps at 20 candidates.
///
/// GAP 3 FIX: Uses `call_pattern_full()` for ALL languages to capture method calls
/// like `self.validate()`, `s.HandleRequest()`, `service.process()` in Rust/Go/Java.
/// Previously only TS/JS/Python/Vue used the full pattern.
fn extract_call_candidates(symbol_content: &str, language: &str) -> Vec<String> {
    let re = call_pattern_full();

    let keywords = keywords_for_language(language);

    let mut candidates = std::collections::HashSet::new();

    for caps in re.captures_iter(symbol_content) {
        let name = caps.get(1).or_else(|| caps.get(2));
        if let Some(m) = name {
            let name = m.as_str();
            if !keywords.contains(&name) {
                candidates.insert(name.to_owned());
            }
        }
    }

    let mut result: Vec<String> = candidates.into_iter().collect();
    result.truncate(20);
    result
}

/// Extract the last segment name from a semantic path's symbol chain.
///
/// Returns `None` if the semantic path has no symbol chain or the chain is empty.
/// Used by `find_callers_callees` and `read_with_deep_context` to get the symbol name
/// for grep-based fallback searches.
pub(crate) fn last_symbol_name(
    semantic_path: &pathfinder_common::types::SemanticPath,
) -> Option<String> {
    semantic_path
        .symbol_chain
        .as_ref()
        .and_then(|c| c.segments.last())
        .map(|s| s.name.clone())
}

/// Returns language keywords to filter out from call-candidate extraction.
#[expect(
    clippy::too_many_lines,
    reason = "keyword lookup table; large match is natural"
)]
fn keywords_for_language(language: &str) -> &'static [&'static str] {
    match language {
        "rust" => &[
            "if", "else", "for", "while", "loop", "match", "return", "break", "continue", "let",
            "mut", "const", "static", "struct", "enum", "trait", "impl", "fn", "type", "where",
            "use", "mod", "pub", "crate", "super", "self", "Self", "move", "ref", "unsafe",
            "async", "await",
        ],
        "go" => &[
            "if",
            "else",
            "for",
            "range",
            "switch",
            "case",
            "default",
            "return",
            "break",
            "continue",
            "go",
            "defer",
            "goto",
            "fallthrough",
            "select",
            "chan",
            "make",
            "new",
            "func",
            "type",
            "var",
            "const",
            "struct",
            "interface",
            "import",
            "package",
        ],
        "typescript" | "javascript" => &[
            "if",
            "else",
            "for",
            "while",
            "switch",
            "case",
            "break",
            "continue",
            "return",
            "function",
            "class",
            "interface",
            "type",
            "const",
            "let",
            "var",
            "new",
            "this",
            "super",
            "static",
            "async",
            "await",
            "import",
            "export",
            "from",
            "as",
            "try",
            "catch",
            "finally",
            "throw",
            "yield",
            "typeof",
            "instanceof",
            "in",
        ],
        "python" => &[
            "if", "elif", "else", "for", "while", "def", "class", "return", "break", "continue",
            "yield", "async", "await", "import", "from", "as", "try", "except", "finally", "raise",
            "with", "lambda", "global", "nonlocal", "assert", "pass",
        ],
        "java" => &[
            "if",
            "else",
            "for",
            "while",
            "switch",
            "case",
            "break",
            "continue",
            "return",
            "try",
            "catch",
            "finally",
            "throw",
            "new",
            "class",
            "interface",
            "extends",
            "implements",
            "instanceof",
            "import",
            "package",
            "void",
            "int",
            "long",
            "float",
            "double",
            "boolean",
            "char",
            "byte",
            "short",
            "final",
            "static",
            "synchronized",
            "native",
            "this",
            "super",
            "assert",
        ],
        "vue" => &[
            "if",
            "else",
            "for",
            "while",
            "switch",
            "case",
            "break",
            "continue",
            "return",
            "function",
            "class",
            "interface",
            "type",
            "const",
            "let",
            "var",
            "new",
            "this",
            "super",
            "static",
            "async",
            "await",
            "import",
            "export",
            "from",
            "as",
            "try",
            "catch",
            "finally",
            "throw",
            "yield",
            "typeof",
            "instanceof",
            "in",
            "defineProps",
            "defineEmits",
            "defineExpose",
            "defineModel",
            "withDefaults",
            "ref",
            "reactive",
            "computed",
            "watch",
            "watchEffect",
            "onMounted",
            "onUnmounted",
            "provide",
            "inject",
            "toRef",
            "toRefs",
            "useSlots",
            "useAttrs",
            "useTemplateRef",
            "template",
            "script",
            "style",
            "setup",
        ],
        _ => &["if", "else", "for", "while", "return", "break", "continue"],
    }
}

/// PATCH-005: Map tree-sitter language ID to file glob pattern.
///
/// Used by `resolve_candidate_via_grep` to search for definition files.
fn language_to_file_glob(language: &str) -> &str {
    match language {
        "rust" => "**/*.rs",
        "typescript" => "**/*.{ts,tsx}",
        "javascript" => "**/*.{js,jsx}",
        "python" => "**/*.py",
        "go" => "**/*.go",
        "vue" => "**/*.{vue,ts,tsx,js,jsx,mjs,cjs}",
        "java" => "**/*.java",
        _ => "**/*",
    }
}

/// DELIVERABLE F: Java-specific regex pattern for resolving candidate definitions.
///
/// Matches Java method definitions, constructors, records, and class/interface declarations.
/// Used by grep fallback for outgoing dependency discovery.
fn java_resolve_pattern(candidate: &str) -> String {
    let escaped = regex::escape(candidate);
    format!(
        r"(?:^[ \t]*(?:(?:public|private|protected)\s+)?(?:<[^>]*?(?:<[^>]*?>[^>]*?)*>\s+)?{escaped}\s*\(|^[ \t]*(?:@\w+(?:\([^)]*\))?\s+)*(?:(?:public|private|protected|static|final|abstract|synchronized|native|default|strictfp)\s+)*(?:<[^>]*?(?:<[^>]*?>[^>]*?)*>\s+)?(?:(?:void|boolean|int|long|double|float|short|byte|char)|[A-Z][a-zA-Z0-9_]*(?:<[^>]*?(?:<[^>]*?>[^>]*?)*>)?)(?:\[\])*\s+{escaped}\s*\(|^[ \t]*(?:(?:public|private|protected|static|final)\s+)*record\s+{escaped}\s*[<(]|(?:public\s+|private\s+|protected\s+|static\s+|final\s+|abstract\s+|sealed\s+|non-sealed\s+|strictfp\s+)*(?:class|interface|enum|@interface)\s+{escaped}\b)"
    )
}

/// DELIVERABLE F: Build a regex pattern to find a candidate function's definition.
///
/// Used by grep fallback for outgoing dependency discovery in both
/// `inspect` (deep context) and `trace` (callers/callees).
fn candidate_definition_pattern(language: &str, candidate: &str) -> String {
    let escaped = regex::escape(candidate);
    match language {
        "rust" => format!(r"(?:(?:pub\s*(?:\([^)]*\)\s*)?(?:async\s*)?)?fn\s+{escaped}\b"),
        "go" => format!(r"func\s+{escaped}\b"),
        "typescript" | "tsx" | "javascript" | "vue" => {
            format!(
                r"(?:(?:export\s+(?:default\s*)?)?function\s+{escaped}\b|(?:export\s+)?(?:const|let|var)\s+{escaped}\s*[=:]|(?:{escaped}\s*:\s*)[^{{]*\([^)]*\)\s*=>)"
            )
        }
        "python" => format!(r"(?:async\s+)?def\s+{escaped}\b"),
        "java" => java_resolve_pattern(candidate),
        _ => format!(r"\b(?:fn|def|function|class|struct|type|interface)\s+{escaped}\b"),
    }
}

/// SPEC 007: Language-aware regex patterns for definition search.
///
/// Returns language-specific regex patterns for finding symbol definitions.
/// Used by `find_symbol` and `fallback_definition_grep` for grep-based fallbacks.
///
/// # Patterns
///
/// | Extension | Patterns |
/// |-----------|----------|
/// | `rs` | Functions (`fn`), types (`struct`, `enum`, `trait`, `type`, `mod`), constants (`const`, `static`) |
/// | `ts`/`tsx`/`js`/`jsx` | Functions (`function`), classes (`class`, `interface`, `type`, `enum`), variable declarations |
/// | `py` | Functions (`def`), classes (`class`), module-level assignments |
/// | `go` | Functions (`func`), types (`type`), constants (`const`, `var`) |
/// | Other | Bare word boundary fallback |
///
pub(crate) fn definition_patterns(ext: &str, symbol_name: &str) -> Vec<String> {
    let name = regex::escape(symbol_name);
    match ext {
        "invalid_regex" => vec!["[invalid".to_string()],
        "rs" => vec![
            format!(
                r"(?:pub\s*(?:\([^)]*\)\s*)?)?(?:async\s+)?(?:unsafe\s+)?(?:const\s+)?fn\s+{name}\b"
            ),
            format!(r"(?:pub\s*(?:\([^)]*\)\s*)?)?(?:struct|enum|trait|type|mod)\s+{name}\b"),
            format!(r"(?:pub\s*(?:\([^)]*\)\s*)?)?(?:const|static)\s+{name}\b"),
            format!(r"macro_rules!\s+{name}\b"),
        ],
        "ts" | "tsx" | "js" | "jsx" => vec![
            format!(r"(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+{name}\b"),
            format!(
                r"(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:class|interface|type|enum)\s+{name}\b"
            ),
            format!(r"(?:export\s+)?(?:const|let|var)\s+{name}\s*[=:]"),
            format!(
                r"(?:export\s+)?(?:const|let|var)\s+{name}\s*=\s*(?:async\s+)?\([^)]*\)\s*(?::\s*[^=]+)?\s*=>"
            ),
        ],
        "py" => vec![
            format!(r"(?:async\s+)?def\s+{name}\b"),
            format!(r"class\s+{name}\b"),
            format!(r"^{name}\s*[=:]"),
        ],
        "go" => vec![
            format!(r"func\s+(?:\([^)]+\)\s+)?{name}\b"),
            format!(r"func\s+(?:\([^)]*\[[^\]]*\][^)]*\)\s+)?{name}\b"),
            format!(r"type\s+{name}\s+"),
            format!(r"type\s+{name}\s*\["),
            format!(r"(?:const|var)\s+{name}\b"),
        ],
        "java" => {
            let parent = name.clone();
            vec![
                // P0: Class/interface/enum definitions (sealed, non-sealed, strictfp handled via modifier)
                format!(
                    r"(?:public\s+|private\s+|protected\s+|static\s+|final\s+|abstract\s+|sealed\s+|non-sealed\s+|strictfp\s+)*(?:class|interface|enum|@interface)\s+{name}\b"
                ),
                // P1: Constructor — no return type, only modifiers + optional type-params before name.
                // Line-anchored (^) prevents matching `throw new MyClass(` or `return new MyClass(`.
                format!(
                    r"^[ \t]*(?:(?:public|private|protected)\s+)?(?:<[^>]*?(?:<[^>]*?>[^>]*?)*>\s+)?{parent}\s*\("
                ),
                // P2: Record type — keyword `record` prevents false positives.
                format!(
                    r"^[ \t]*(?:(?:public|private|protected|static|final)\s+)*record\s+{name}\s*[<(]"
                ),
                // P3: Method — return type must be primitive keyword or start uppercase.
                // `new`/`throw` are lowercase non-primitives → rejected. No \s in type token.
                format!(
                    r"^[ \t]*(?:@\w+(?:\([^)]*\))?\s+)*(?:(?:public|private|protected|static|final|abstract|synchronized|native|default|strictfp)\s+)*(?:<[^>]*?(?:<[^>]*?>[^>]*?)*>\s+)?(?:(?:void|boolean|int|long|double|float|short|byte|char)|[A-Z][a-zA-Z0-9_]*(?:<[^>]*?(?:<[^>]*?>[^>]*?)*>)?)(?:\[\])*\s+{name}\s*\("
                ),
            ]
        }
        "vue" => vec![
            format!(r"(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+{name}\b"),
            format!(
                r"(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:class|interface|type|enum)\s+{name}\b"
            ),
            format!(r"(?:export\s+)?(?:const|let|var)\s+{name}\s*[=:]"),
            format!(
                r"(?:export\s+)?(?:const|let|var)\s+{name}\s*=\s*(?:async\s+)?\([^)]*\)\s*(?::\s*[^=]+)?\s*=>"
            ),
            format!(
                r"(?:const|let)\s+{name}\s*=\s*(?:defineProps|defineEmits|defineExpose|defineModel|withDefaults)[(<]"
            ),
        ],
        _ => vec![format!(r"\b{name}\b")],
    }
}

impl PathfinderServer {
    /// Spec 2.2 + 2.3: Enrich `did_you_mean` suggestions with:
    /// 1. Separator correction (:: → . within symbol chain)
    /// 2. Cross-file search via `find_symbol` when same-file suggestions empty
    async fn enrich_did_you_mean(
        &self,
        semantic_path_str: &str,
        original_suggestions: Vec<String>,
    ) -> Vec<String> {
        let mut suggestions = original_suggestions;

        // Spec 2.2: Separator confusion correction
        // If multiple '::' used, suggest the '.' variant
        let parts: Vec<&str> = semantic_path_str.splitn(2, "::").collect();
        if parts.len() == 2 {
            let file_part = parts[0];
            let symbol_part = parts[1];
            if symbol_part.contains("::") {
                let corrected_symbol = symbol_part.replace("::", ".");
                let corrected_path = format!("{file_part}::{corrected_symbol}");
                if !suggestions.contains(&corrected_path) {
                    suggestions.insert(0, corrected_path);
                }
            }
        }

        // Spec 2.3: Cross-file search when same-file suggestions empty
        if suggestions.is_empty() {
            if let Ok(semantic_path) = parse_semantic_path(semantic_path_str) {
                if let Some(chain) = &semantic_path.symbol_chain {
                    if let Some(base_name) = chain.segments.last() {
                        // Use find_symbol to search across files
                        let find_params = crate::server::types::SearchParams {
                            query: base_name.name.clone(),
                            mode: crate::server::types::SearchMode::Symbol,
                            kind: None,
                            path_glob: "**/*".to_owned(),
                            max_results: 3,
                            ..Default::default()
                        };
                        match self.find_symbol_impl(find_params).await {
                            Ok(response) => {
                                for symbol in response.0.symbols {
                                    if !suggestions.contains(&symbol.semantic_path) {
                                        suggestions.push(symbol.semantic_path);
                                    }
                                }
                            }
                            Err(e) => {
                                tracing::warn!(
                                    symbol = %base_name.name,
                                    error = %e,
                                    "enrich_did_you_mean: cross-file search failed — \
                                     agent will receive empty suggestions"
                                );
                            }
                        }
                    }
                }
            }
        }

        suggestions
    }

    /// Wrapper around `surgeon.read_symbol_scope` that enriches `SymbolNotFound` errors
    /// with separator correction (Spec 2.2) and cross-file search (Spec 2.3).
    async fn read_symbol_scope_enriched(
        &self,
        semantic_path: &pathfinder_common::types::SemanticPath,
        semantic_path_str: &str,
    ) -> Result<pathfinder_common::types::SymbolScope, ErrorData> {
        match self
            .surgeon
            .read_symbol_scope(self.workspace_root.path(), semantic_path)
            .await
        {
            Ok(scope) => Ok(scope),
            Err(pathfinder_treesitter::SurgeonError::SymbolNotFound { path, did_you_mean }) => {
                let enriched = self
                    .enrich_did_you_mean(semantic_path_str, did_you_mean)
                    .await;

                // Auto-retry: if the symbol part contains '::' (Rust impl method
                // convention uses '.' not '::'), try the corrected path before
                // returning the error. This eliminates the 3-step retry cycle
                // agents currently experience.
                if let Some(corrected) = Self::try_separator_correction(semantic_path_str) {
                    if let Some(corrected_path) =
                        pathfinder_common::types::SemanticPath::parse(&corrected)
                    {
                        if let Ok(scope) = self
                            .surgeon
                            .read_symbol_scope(self.workspace_root.path(), &corrected_path)
                            .await
                        {
                            tracing::info!(
                                original = %semantic_path_str,
                                corrected = %corrected,
                                "read_symbol_scope: auto-corrected '::' to '.' in symbol path"
                            );
                            return Ok(scope);
                        }
                    }
                }

                Err(pathfinder_to_error_data(
                    &pathfinder_common::error::PathfinderError::SymbolNotFound {
                        semantic_path: path,
                        did_you_mean: enriched,
                        retry_after_seconds: None,
                    },
                ))
            }
            Err(e) => Err(treesitter_error_to_error_data(e)),
        }
    }

    /// Consolidated `locate` handler.
    pub(crate) async fn locate_impl(
        &self,
        params: LocateParams,
    ) -> Result<CallToolResult, ErrorData> {
        match (params.semantic_path.as_ref(), params.file.as_ref(), params.line) {
            // Definition lookup
            (Some(_), None, None) => {
                self.get_definition_impl(params).await
            }
            // Semantic path resolution
            (None, Some(_), Some(_)) => {
                self.get_semantic_path_impl(params).await
            }
            // Ambiguous: both modes specified
            (Some(_), Some(_), _) | (Some(_), _, Some(_)) => Err(invalid_params_error(
                "provide either `semantic_path` (definition lookup) or `file`+`line` (semantic path resolution), not both",
            )),
            // Missing required fields for semantic path mode
            (None, Some(_), None) => Err(invalid_params_error(
                "`line` is required when using `file` for semantic path resolution",
            )),
            (None, None, Some(_)) => Err(invalid_params_error(
                "`file` is required when using `line` for semantic path resolution",
            )),
            // Nothing provided
            (None, None, None) => Err(invalid_params_error(
                "provide either `semantic_path` or `file`+`line`",
            )),
        }
    }

    /// Consolidated `trace` handler.
    pub(crate) async fn trace_impl(
        &self,
        params: TraceParams,
    ) -> Result<CallToolResult, ErrorData> {
        match params.scope {
            TraceScope::Callers => self.find_callers_callees_impl(params).await,
            TraceScope::References => self.find_all_references_impl(params).await,
            TraceScope::Overview => self.symbol_overview_impl(params).await,
        }
    }

    /// Consolidated `health` handler.
    pub(crate) async fn health_impl(
        &self,
        params: HealthParams,
    ) -> Result<CallToolResult, ErrorData> {
        self.lsp_health_impl(params).await
    }

    fn try_separator_correction(semantic_path_str: &str) -> Option<String> {
        let (file_part, symbol_part) = semantic_path_str.split_once("::")?;
        if !symbol_part.contains("::") {
            return None;
        }
        let corrected_symbol = symbol_part.replace("::", ".");
        Some(format!("{file_part}::{corrected_symbol}"))
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {

    // ── language_to_file_glob tests ─────────────────────────────────────────

    #[test]
    fn test_language_to_file_glob_rust() {
        assert_eq!(super::language_to_file_glob("rust"), "**/*.rs");
    }

    #[test]
    fn test_language_to_file_glob_typescript() {
        assert_eq!(super::language_to_file_glob("typescript"), "**/*.{ts,tsx}");
    }

    #[test]
    fn test_language_to_file_glob_javascript() {
        assert_eq!(super::language_to_file_glob("javascript"), "**/*.{js,jsx}");
    }

    #[test]
    fn test_language_to_file_glob_python() {
        assert_eq!(super::language_to_file_glob("python"), "**/*.py");
    }

    #[test]
    fn test_language_to_file_glob_go() {
        assert_eq!(super::language_to_file_glob("go"), "**/*.go");
    }

    #[test]
    fn test_language_to_file_glob_vue() {
        assert_eq!(
            super::language_to_file_glob("vue"),
            "**/*.{vue,ts,tsx,js,jsx,mjs,cjs}"
        );
    }

    #[test]
    fn test_language_to_file_glob_java() {
        assert_eq!(super::language_to_file_glob("java"), "**/*.java");
    }

    #[test]
    fn test_language_to_file_glob_unknown_defaults_to_catch_all() {
        assert_eq!(super::language_to_file_glob("haskell"), "**/*");
        assert_eq!(super::language_to_file_glob(""), "**/*");
    }

    // ── definition_patterns tests ──────────────────────────────────────────

    #[test]
    fn test_definition_patterns_rust_fn() {
        let patterns = super::definition_patterns("rs", "my_function");
        assert!(!patterns.is_empty(), "must return at least one pattern");
        // First pattern should match function definitions
        let re = regex::Regex::new(&patterns[0]).expect("valid regex");
        assert!(
            re.is_match("pub async fn my_function("),
            "must match 'pub async fn my_function('"
        );
        assert!(
            re.is_match("fn my_function("),
            "must match bare 'fn my_function('"
        );
        assert!(
            !re.is_match("let my_function = 42"),
            "must not match variable assignment"
        );
    }

    #[test]
    fn test_definition_patterns_rust_struct() {
        let patterns = super::definition_patterns("rs", "MyStruct");
        assert!(patterns.len() >= 2, "must return patterns for types too");
        let re = regex::Regex::new(&patterns[1]).expect("valid regex");
        assert!(
            re.is_match("pub(crate) struct MyStruct {"),
            "must match 'pub(crate) struct MyStruct {{'"
        );
        assert!(
            re.is_match("enum MyStruct {"),
            "must match 'enum MyStruct {{'"
        );
    }

    #[test]
    fn test_definition_patterns_ts_export_class() {
        let patterns = super::definition_patterns("ts", "AuthService");
        assert!(!patterns.is_empty());
        // Second pattern matches classes/interfaces
        let re = regex::Regex::new(&patterns[1]).expect("valid regex");
        assert!(
            re.is_match("export default class AuthService {"),
            "must match 'export default class AuthService {{'"
        );
        assert!(
            re.is_match("export interface AuthService {"),
            "must match 'export interface AuthService {{'"
        );
    }

    // ── Vue definition_patterns tests (DELIVERABLE C) ─────────────────────

    #[test]
    fn test_definition_patterns_vue_function() {
        let patterns = super::definition_patterns("vue", "handleClick");
        assert!(!patterns.is_empty(), "vue must have definition patterns");
        let re = regex::Regex::new(&patterns[0]).expect("valid regex");
        assert!(
            re.is_match("export async function handleClick("),
            "must match 'export async function handleClick('"
        );
        assert!(
            re.is_match("function handleClick("),
            "must match bare 'function handleClick('"
        );
    }

    #[test]
    fn test_definition_patterns_vue_const_assignment() {
        let patterns = super::definition_patterns("vue", "handleClick");
        assert!(patterns.len() >= 3);
        let re = regex::Regex::new(&patterns[2]).expect("valid regex");
        assert!(
            re.is_match("const handleClick = () => {}"),
            "must match 'const handleClick = () => {{}}'"
        );
        assert!(
            re.is_match("export const handleClick = () => {}"),
            "must match 'export const handleClick = () => {{}}'"
        );
        assert!(
            re.is_match("let handleClick: Handler = () => {}"),
            "must match typed assignment 'let handleClick: Handler ='"
        );
    }

    #[test]
    fn test_definition_patterns_vue_ref() {
        let patterns = super::definition_patterns("vue", "count");
        assert!(patterns.len() >= 3);
        let re = regex::Regex::new(&patterns[2]).expect("valid regex");
        assert!(
            re.is_match("const count = ref(0)"),
            "must match 'const count = ref(0)'"
        );
        assert!(
            re.is_match("const count = reactive({ value: 0 })"),
            "must match 'const count = reactive(...)'"
        );
        assert!(
            re.is_match("const count = computed(() => 0)"),
            "must match 'const count = computed(...)'"
        );
    }

    #[test]
    fn test_definition_patterns_vue_define_macros() {
        let patterns_props = super::definition_patterns("vue", "props");
        let patterns_emit = super::definition_patterns("vue", "emit");
        assert!(patterns_props.len() >= 5);
        let re_props = regex::Regex::new(&patterns_props[4]).expect("valid regex");
        let re_emit = regex::Regex::new(&patterns_emit[4]).expect("valid regex");
        assert!(
            re_props.is_match("const props = defineProps<{ id: string }>()"),
            "must match 'const props = defineProps(...)'"
        );
        assert!(
            re_emit.is_match("const emit = defineEmits<{ (e: 'save'): void }>()"),
            "must match 'const emit = defineEmits(...)'"
        );
        assert!(
            re_props.is_match("const props = withDefaults(defineProps<{ }>(), {})"),
            "must match 'const props = withDefaults(...)'"
        );
    }

    #[test]
    fn test_definition_patterns_py_async_def() {
        let patterns = super::definition_patterns("py", "process_order");
        assert!(!patterns.is_empty());
        let re = regex::Regex::new(&patterns[0]).expect("valid regex");
        assert!(
            re.is_match("async def process_order("),
            "must match 'async def process_order('"
        );
        assert!(
            re.is_match("def process_order("),
            "must match 'def process_order('"
        );
    }

    #[test]
    fn test_definition_patterns_py_class() {
        let patterns = super::definition_patterns("py", "MyClass");
        assert!(patterns.len() >= 2);
        let re = regex::Regex::new(&patterns[1]).expect("valid regex");
        assert!(re.is_match("class MyClass:"), "must match 'class MyClass:'");
    }

    #[test]
    fn test_definition_patterns_go_receiver_method() {
        let patterns = super::definition_patterns("go", "HandleRequest");
        assert!(!patterns.is_empty());
        let re = regex::Regex::new(&patterns[0]).expect("valid regex");
        assert!(
            re.is_match("func (s *Service) HandleRequest("),
            "must match receiver method"
        );
        assert!(
            re.is_match("func HandleRequest("),
            "must match bare function"
        );
    }

    #[test]
    fn test_definition_patterns_go_type() {
        let patterns = super::definition_patterns("go", "UserService");
        assert!(patterns.len() >= 3, "go must have func + type + const/var");
        let re = regex::Regex::new(&patterns[2]).expect("valid regex");
        assert!(
            re.is_match("type UserService struct {"),
            "must match 'type UserService struct {{'"
        );
    }

    #[test]
    fn test_definition_patterns_unknown_extension_uses_fallback() {
        let patterns = super::definition_patterns("java", "MyClass");
        assert!(!patterns.is_empty());
        // Java has its own patterns
        let re = regex::Regex::new(&patterns[0]).expect("valid regex");
        assert!(
            re.is_match("public class MyClass {"),
            "must match Java class declaration"
        );
    }

    #[test]
    fn test_definition_patterns_catch_all_extension() {
        let patterns = super::definition_patterns("unknown_ext", "foo");
        assert_eq!(
            patterns.len(),
            1,
            "catch-all must return exactly one pattern"
        );
        let re = regex::Regex::new(&patterns[0]).expect("valid regex");
        assert!(re.is_match("foo"), "must match bare word");
        assert!(!re.is_match("foobar"), "must not match partial word");
    }

    #[test]
    fn test_definition_patterns_special_chars_escaped() {
        // Symbol name with regex special characters must be escaped
        let patterns = super::definition_patterns("rs", "my+function");
        assert!(!patterns.is_empty());
        let re = regex::Regex::new(&patterns[0]).expect("valid regex");
        // Must match literal "my+function", not "myXfunction"
        assert!(re.is_match("fn my+function("));
        assert!(!re.is_match("fn myXfunction("));
    }

    #[test]
    fn test_definition_patterns_all_languages_compile() {
        // Verify every extension returns valid regex patterns
        let extensions = [
            "rs", "ts", "tsx", "js", "jsx", "py", "go", "java", "vue", "xyz",
        ];
        for ext in &extensions {
            let patterns = super::definition_patterns(ext, "TestSymbol");
            for (i, pattern) in patterns.iter().enumerate() {
                assert!(
                    regex::Regex::new(pattern).is_ok(),
                    "pattern {i} for ext '{ext}' must be valid regex: {pattern}"
                );
            }
        }
    }

    // ── Java definition_patterns tests (DELIVERABLE E) ───────────────────

    #[test]
    fn test_definition_patterns_java_class() {
        let patterns = super::definition_patterns("java", "MyClass");
        assert!(!patterns.is_empty(), "java must have definition patterns");
        let re = regex::Regex::new(&patterns[0]).expect("valid regex");
        assert!(
            re.is_match("public class MyClass {"),
            "must match 'public class MyClass {{'"
        );
        assert!(
            re.is_match("private static final class MyClass {"),
            "must match 'private static final class MyClass {{'"
        );
    }

    #[test]
    fn test_definition_patterns_java_constructor() {
        let patterns = super::definition_patterns("java", "MyClass");
        assert!(!patterns.is_empty(), "java must have definition patterns");
        // Look for a pattern that matches constructors
        let constructor_pattern = patterns.iter().find(|p| p.contains("MyClass\\s*\\("));
        assert!(
            constructor_pattern.is_some(),
            "java must have a constructor pattern"
        );
        let re = regex::Regex::new(constructor_pattern.unwrap()).expect("valid regex");
        assert!(
            re.is_match("public MyClass(String name) {"),
            "must match 'public MyClass(String name) {{'"
        );
        assert!(
            re.is_match("MyClass(String name, int age) {"),
            "must match bare 'MyClass(String name, int age) {{'"
        );
        assert!(
            re.is_match("private MyClass() {"),
            "must match 'private MyClass() {{'"
        );
    }

    #[test]
    fn test_definition_patterns_java_record() {
        let patterns = super::definition_patterns("java", "Person");
        assert!(!patterns.is_empty(), "java must have definition patterns");
        // Look for a pattern that matches records
        let record_pattern = patterns.iter().find(|p| p.contains("record"));
        assert!(record_pattern.is_some(), "java must have a record pattern");
        let re = regex::Regex::new(record_pattern.unwrap()).expect("valid regex");
        assert!(
            re.is_match("public record Person(String name) {"),
            "must match 'public record Person(String name) {{'"
        );
        assert!(
            re.is_match("record Person(String name, int age) {"),
            "must match bare 'record Person(String name, int age) {{'"
        );
        assert!(
            re.is_match("private final record Person(String name) {"),
            "must match 'private final record Person(String name) {{'"
        );
    }

    #[test]
    fn test_definition_patterns_java_sealed_class() {
        let patterns = super::definition_patterns("java", "Shape");
        assert!(!patterns.is_empty(), "java must have definition patterns");
        // Look for a pattern that matches sealed classes
        let sealed_pattern = patterns.iter().find(|p| p.contains("sealed"));
        assert!(
            sealed_pattern.is_some(),
            "java must have a sealed class/interface pattern"
        );
        let re = regex::Regex::new(sealed_pattern.unwrap()).expect("valid regex");
        assert!(
            re.is_match("public sealed class Shape permits Circle, Square {"),
            "must match 'public sealed class Shape permits Circle, Square {{'"
        );
        assert!(
            re.is_match("sealed interface Shape permits Circle {"),
            "must match 'sealed interface Shape permits Circle {{'"
        );
        assert!(
            re.is_match("private sealed abstract class Shape {"),
            "must match 'private sealed abstract class Shape {{'"
        );
    }

    #[test]
    fn test_definition_patterns_java_annotated_method() {
        let patterns = super::definition_patterns("java", "myService");
        // The last pattern is for methods with annotations
        let method_pattern = patterns.last().expect("java should have patterns");
        let re = regex::Regex::new(method_pattern).expect("valid regex");
        assert!(
            re.is_match("@Bean public MyService myService()"),
            "must match '@Bean public MyService myService()'"
        );
        assert!(
            re.is_match("@Override public void myService()"),
            "must match '@Override public void myService()'"
        );
        assert!(
            re.is_match("@GetMapping public Response myService()"),
            "must match '@GetMapping public Response myService()'"
        );
    }

    #[test]
    fn test_definition_patterns_java_primitive_return() {
        let patterns = super::definition_patterns("java", "process");
        assert!(!patterns.is_empty(), "java must have definition patterns");
        // The last pattern matches methods with any return type
        let method_pattern = patterns.last().expect("java should have patterns");
        let re = regex::Regex::new(method_pattern).expect("valid regex");
        assert!(re.is_match("void process()"), "must match 'void process()'");
        assert!(
            re.is_match("public boolean process()"),
            "must match 'public boolean process()'"
        );
        assert!(
            re.is_match("private int process()"),
            "must match 'private int process()'"
        );
        assert!(
            re.is_match("protected String process()"),
            "must match 'protected String process()'"
        );
        assert!(
            re.is_match("static final double process()"),
            "must match 'static final double process()'"
        );
    }

    #[test]
    fn test_definition_patterns_java_generic_return() {
        let patterns = super::definition_patterns("java", "process");
        assert!(!patterns.is_empty(), "java must have definition patterns");
        // The last pattern matches methods with generic return types
        let method_pattern = patterns.last().expect("java should have patterns");
        let re = regex::Regex::new(method_pattern).expect("valid regex");
        assert!(
            re.is_match("public List<String> process()"),
            "must match 'public List<String> process()'"
        );
        assert!(
            re.is_match("Map<String, Integer> process()"),
            "must match 'Map<String, Integer> process()'"
        );
    }

    #[test]
    fn test_definition_patterns_java_array_return() {
        let patterns = super::definition_patterns("java", "process");
        assert!(!patterns.is_empty(), "java must have definition patterns");
        let method_pattern = patterns.last().expect("java should have patterns");
        let re = regex::Regex::new(method_pattern).expect("valid regex");
        assert!(
            re.is_match("public String[] process()"),
            "must match 'public String[] process()'"
        );
        assert!(
            re.is_match("int[] process()"),
            "must match 'int[] process()'"
        );
        assert!(
            re.is_match("public int[][] process()"),
            "must match 'public int[][] process()' — multi-dimensional array"
        );
        assert!(
            re.is_match("String[][][] process()"),
            "must match 'String[][][] process()' — 3D array"
        );
    }

    #[test]
    fn test_definition_patterns_java_method_with_type_params() {
        let patterns = super::definition_patterns("java", "process");
        assert!(!patterns.is_empty(), "java must have definition patterns");
        // The last pattern matches methods with type parameters
        let method_pattern = patterns.last().expect("java should have patterns");
        let re = regex::Regex::new(method_pattern).expect("valid regex");
        assert!(
            re.is_match("public <T> T process()"),
            "must match 'public <T> T process()'"
        );
        assert!(
            re.is_match("<T, U> Map<T, U> process()"),
            "must match '<T, U> Map<T, U> process()'"
        );
    }

    // ── Java negative test cases (Deliverable E fixes) ─────────────────────

    #[test]
    fn test_definition_patterns_java_constructor_rejects_return_types() {
        // CRITICAL-2: Pattern 1 (constructor) must not match methods with return types
        let patterns = super::definition_patterns("java", "MyClass");
        let constructor_pattern = patterns
            .get(1)
            .expect("java should have constructor pattern");
        let re = regex::Regex::new(constructor_pattern).expect("valid regex");
        assert!(
            !re.is_match("public void MyClass()"),
            "must NOT match 'public void MyClass()' - this is a method, not a constructor"
        );
        assert!(
            !re.is_match("private String MyClass()"),
            "must NOT match 'private String MyClass()' - this is a method, not a constructor"
        );
        assert!(
            !re.is_match("protected int MyClass()"),
            "must NOT match 'protected int MyClass()' - this is a method, not a constructor"
        );
    }

    #[test]
    fn test_definition_patterns_java_method_pattern_rejects_new_and_throw() {
        // CRITICAL-1: Pattern 4 must NOT match new ClassName() or throw new MyError()
        let patterns = super::definition_patterns("java", "MyError");
        let method_pattern = patterns.last().expect("java should have method pattern");
        let re = regex::Regex::new(method_pattern).expect("valid regex");
        assert!(
            !re.is_match("throw new MyError(msg)"),
            "must NOT match 'throw new MyError(msg)' - false positive"
        );
        assert!(
            !re.is_match("return new MyError()"),
            "must NOT match 'return new MyError()' - false positive"
        );
        assert!(
            !re.is_match("new MyError().getMessage()"),
            "must NOT match 'new MyError().getMessage()' - false positive"
        );
    }

    #[test]
    fn test_definition_patterns_java_constructor_rejects_new_keyword() {
        let patterns = super::definition_patterns("java", "MyClass");
        let constructor_pattern = patterns
            .get(1)
            .expect("java should have constructor pattern");
        let re = regex::Regex::new(constructor_pattern).expect("valid regex");
        assert!(
            !re.is_match("new MyClass()"),
            "must NOT match 'new MyClass()' - this is a call, not a definition"
        );
        assert!(
            !re.is_match("return new MyClass()"),
            "must NOT match 'return new MyClass()' - this is a call, not a definition"
        );
    }

    #[test]
    fn test_definition_patterns_java_generic_constructor() {
        // MEDIUM-4: Support generic constructors like public <E> MyClass(E item)
        let patterns = super::definition_patterns("java", "MyClass");
        let constructor_pattern = patterns
            .get(1)
            .expect("java should have constructor pattern");
        let re = regex::Regex::new(constructor_pattern).expect("valid regex");
        assert!(
            re.is_match("public <E> MyClass(E item)"),
            "must match 'public <E> MyClass(E item)'"
        );
        assert!(
            re.is_match("<T, U> MyClass(T a, U b)"),
            "must match '<T, U> MyClass(T a, U b)'"
        );
    }

    #[test]
    fn test_definition_patterns_java_nested_generics() {
        // MEDIUM-2: Support nested generics like Map<String, List<Integer>>
        let patterns = super::definition_patterns("java", "process");
        let method_pattern = patterns.last().expect("java should have method pattern");
        let re = regex::Regex::new(method_pattern).expect("valid regex");
        assert!(
            re.is_match("public Map<String, List<Integer>> process()"),
            "must match 'public Map<String, List<Integer>> process()'"
        );
        assert!(
            re.is_match("Map<String, Map<String, Integer>> process()"),
            "must match 'Map<String, Map<String, Integer>> process()'"
        );
    }

    #[test]
    fn test_definition_patterns_java_sealed_no_trailing_whitespace() {
        // MAJOR-2: Pattern should match sealed class at end-of-line (no trailing whitespace)
        let patterns = super::definition_patterns("java", "Shape");
        let class_pattern = patterns.first().expect("java should have class pattern");
        let re = regex::Regex::new(class_pattern).expect("valid regex");
        assert!(
            re.is_match("public sealed class Shape"),
            "must match 'public sealed class Shape' at end-of-line"
        );
        assert!(
            re.is_match("sealed class Shape{"),
            "must match 'sealed class Shape{{' without space before brace"
        );
    }

    #[test]
    fn test_definition_patterns_java_strictfp_method() {
        let patterns = super::definition_patterns("java", "calculate");
        let method_pattern = patterns.last().expect("java should have method pattern");
        let re = regex::Regex::new(method_pattern).expect("valid regex");
        assert!(
            re.is_match("public strictfp void calculate()"),
            "must match 'public strictfp void calculate()'"
        );
        assert!(
            re.is_match("strictfp double calculate(int x)"),
            "must match 'strictfp double calculate(int x)'"
        );
    }

    #[test]
    fn test_definition_patterns_java_strictfp_class() {
        let patterns = super::definition_patterns("java", "MathUtils");
        let class_pattern = patterns.first().expect("java should have class pattern");
        let re = regex::Regex::new(class_pattern).expect("valid regex");
        assert!(
            re.is_match("strictfp class MathUtils"),
            "must match 'strictfp class MathUtils'"
        );
        assert!(
            re.is_match("public strictfp class MathUtils"),
            "must match 'public strictfp class MathUtils'"
        );
    }

    #[test]
    fn test_definition_patterns_java_non_sealed_class() {
        let patterns = super::definition_patterns("java", "Shape");
        let class_pattern = patterns.first().expect("java should have class pattern");
        let re = regex::Regex::new(class_pattern).expect("valid regex");
        assert!(
            re.is_match("non-sealed class Shape"),
            "must match 'non-sealed class Shape'"
        );
        assert!(
            re.is_match("public non-sealed class Shape"),
            "must match 'public non-sealed class Shape'"
        );
    }

    #[test]
    fn test_definition_patterns_java_multi_dimensional_array_return() {
        let patterns = super::definition_patterns("java", "getData");
        let method_pattern = patterns.last().expect("java should have method pattern");
        let re = regex::Regex::new(method_pattern).expect("valid regex");
        assert!(
            re.is_match("public int[][] getData()"),
            "must match 'public int[][] getData()' — 2D array"
        );
        assert!(
            re.is_match("String[][][] getData()"),
            "must match 'String[][][] getData()' — 3D array"
        );
        assert!(
            re.is_match("Map<String, Integer>[][] getData()"),
            "must match 'Map<String, Integer>[][] getData()' — generic 2D array"
        );
    }

    #[test]
    fn test_definition_patterns_java_bounded_generics() {
        let patterns = super::definition_patterns("java", "sort");
        let method_pattern = patterns.last().expect("java should have method pattern");
        let re = regex::Regex::new(method_pattern).expect("valid regex");
        assert!(
            re.is_match("public <T extends Comparable<T>> void sort(List<T> list)"),
            "must match 'public <T extends Comparable<T>> void sort(List<T> list)' — bounded generics"
        );
        let patterns_get = super::definition_patterns("java", "get");
        let method_pattern_get = patterns_get
            .last()
            .expect("java should have method pattern");
        let re_get = regex::Regex::new(method_pattern_get).expect("valid regex");
        assert!(
            re_get.is_match("<K, V extends Serializable> V get(K key)"),
            "must match '<K, V extends Serializable> V get(K key)' — multiple bounded params"
        );
        let patterns2 = super::definition_patterns("java", "MyClass");
        let constructor_pattern = patterns2
            .get(1)
            .expect("java should have constructor pattern");
        let re2 = regex::Regex::new(constructor_pattern).expect("valid regex");
        assert!(
            re2.is_match("public <T extends Comparable<T>> MyClass(T item)"),
            "must match 'public <T extends Comparable<T>> MyClass(T item)' — generic constructor with bounds"
        );
    }

    #[test]
    fn test_definition_patterns_java_static_record() {
        let patterns = super::definition_patterns("java", "Inner");
        let record_pattern = patterns.get(2).expect("java should have record pattern");
        let re = regex::Regex::new(record_pattern).expect("valid regex");
        assert!(
            re.is_match("static record Inner(String name, int value)"),
            "must match 'static record Inner(String name, int value)' — nested static record"
        );
        assert!(
            re.is_match("public static final record Inner(String name)"),
            "must match 'public static final record Inner(String name)' — full modifiers"
        );
    }

    // ── extract_call_candidates tests ──────────────────────────────────────

    #[test]
    fn test_extract_call_candidates_rust_basic() {
        let code = r"
            fn process() {
                fetch_user(id);
                validate_order(&order);
                charge_payment(amount);
            }
        ";
        let candidates = super::extract_call_candidates(code, "rust");
        assert!(candidates.contains(&"fetch_user".to_string()));
        assert!(candidates.contains(&"validate_order".to_string()));
        assert!(candidates.contains(&"charge_payment".to_string()));
    }

    #[test]
    fn test_extract_call_candidates_filters_keywords() {
        let code = r"
            fn process() {
                if condition { return; }
                for item in items { do_something(item); }
                while running { check(); }
                match value { _ => {} }
            }
        ";
        let candidates = super::extract_call_candidates(code, "rust");
        assert!(
            !candidates.contains(&"if".to_string()),
            "must filter 'if' keyword"
        );
        assert!(
            !candidates.contains(&"for".to_string()),
            "must filter 'for' keyword"
        );
        assert!(
            !candidates.contains(&"while".to_string()),
            "must filter 'while' keyword"
        );
        assert!(
            !candidates.contains(&"match".to_string()),
            "must filter 'match' keyword"
        );
        assert!(
            !candidates.contains(&"return".to_string()),
            "must filter 'return' keyword"
        );
        assert!(
            candidates.contains(&"do_something".to_string()),
            "must keep real function call"
        );
        assert!(
            candidates.contains(&"check".to_string()),
            "must keep real function call"
        );
    }

    #[test]
    fn test_extract_call_candidates_go_keywords() {
        let code = r"
            func process() {
                if err != nil { return err }
                for _, v := range items { handle(v) }
                select { case <-ch: }
            }
        ";
        let candidates = super::extract_call_candidates(code, "go");
        assert!(!candidates.contains(&"if".to_string()));
        assert!(!candidates.contains(&"for".to_string()));
        assert!(!candidates.contains(&"range".to_string()));
        assert!(!candidates.contains(&"select".to_string()));
        assert!(candidates.contains(&"handle".to_string()));
    }

    #[test]
    fn test_extract_call_candidates_python_keywords() {
        let code = r#"
def process():
    if condition:
        return result
    for item in items:
        handle(item)
    raise ValueError("bad")
        "#;
        let candidates = super::extract_call_candidates(code, "python");
        assert!(!candidates.contains(&"if".to_string()));
        assert!(!candidates.contains(&"for".to_string()));
        assert!(!candidates.contains(&"return".to_string()));
        assert!(!candidates.contains(&"raise".to_string()));
        assert!(candidates.contains(&"handle".to_string()));
    }

    #[test]
    fn test_extract_call_candidates_deduplicates() {
        let code = r"
            fn process() {
                fetch(id);
                fetch(id);
                fetch(id);
            }
        ";
        let candidates = super::extract_call_candidates(code, "rust");
        let count = candidates.iter().filter(|c| *c == "fetch").count();
        assert_eq!(count, 1, "must deduplicate call candidates");
    }

    #[test]
    #[allow(clippy::format_push_string)]
    fn test_extract_call_candidates_caps_at_20() {
        // Generate 25 unique function calls
        let mut code = String::from("fn process() {\n");
        for i in 0..25 {
            code.push_str(&format!("    func_{i}(x);\n"));
        }
        code.push('}');

        let candidates = super::extract_call_candidates(&code, "rust");
        assert!(
            candidates.len() <= 20,
            "must cap at 20 candidates, got {}",
            candidates.len()
        );
    }

    #[test]
    fn test_extract_call_candidates_typescript_method_calls() {
        let code = r"
            function process() {
                user.getName();
                order.calculateTotal();
                service.validate(data);
            }
        ";
        let candidates = super::extract_call_candidates(code, "typescript");
        // Method calls (obj.method()) should also be extracted for TS/JS
        assert!(candidates.contains(&"getName".to_string()));
        assert!(candidates.contains(&"calculateTotal".to_string()));
        assert!(candidates.contains(&"validate".to_string()));
    }

    // ── Vue extract_call_candidates test (DELIVERABLE C) ──────────────────

    #[test]
    fn test_extract_call_candidates_vue_method_calls() {
        // Vue <script setup> uses same patterns as TypeScript
        let code = r"
            const handleSubmit = () => {
                userService.login(credentials);
                router.push('/dashboard');
                toast.showSuccess();
            }
        ";
        let candidates = super::extract_call_candidates(code, "vue");
        // Method calls (obj.method()) should also be extracted for Vue
        assert!(
            candidates.contains(&"login".to_string()),
            "expected 'login' in {candidates:?}"
        );
        assert!(
            candidates.contains(&"push".to_string()),
            "expected 'push' in {candidates:?}"
        );
        assert!(
            candidates.contains(&"showSuccess".to_string()),
            "expected 'showSuccess' in {candidates:?}"
        );
    }

    #[test]
    fn test_extract_call_candidates_empty_input() {
        let candidates = super::extract_call_candidates("", "rust");
        assert!(candidates.is_empty(), "empty input must return empty vec");
    }

    #[test]
    fn test_extract_call_candidates_no_calls() {
        let code = "let x = 42;\nlet y = x + 1;";
        let candidates = super::extract_call_candidates(code, "rust");
        assert!(
            candidates.is_empty(),
            "no function calls must return empty vec"
        );
    }

    // ── keywords_for_language tests ────────────────────────────────────────

    #[test]
    fn test_keywords_for_language_rust() {
        let kw = super::keywords_for_language("rust");
        assert!(kw.contains(&"fn"), "must contain 'fn'");
        assert!(kw.contains(&"struct"), "must contain 'struct'");
        assert!(kw.contains(&"impl"), "must contain 'impl'");
        assert!(kw.contains(&"async"), "must contain 'async'");
        assert!(kw.contains(&"await"), "must contain 'await'");
        assert!(kw.len() > 20, "rust keywords must be comprehensive");
    }

    #[test]
    fn test_keywords_for_language_go() {
        let kw = super::keywords_for_language("go");
        assert!(kw.contains(&"func"), "must contain 'func'");
        assert!(kw.contains(&"defer"), "must contain 'defer'");
        assert!(kw.contains(&"select"), "must contain 'select'");
        assert!(kw.contains(&"chan"), "must contain 'chan'");
    }

    #[test]
    fn test_keywords_for_language_typescript() {
        let kw = super::keywords_for_language("typescript");
        assert!(kw.contains(&"function"), "must contain 'function'");
        assert!(kw.contains(&"class"), "must contain 'class'");
        assert!(kw.contains(&"const"), "must contain 'const'");
    }

    #[test]
    fn test_keywords_for_language_python() {
        let kw = super::keywords_for_language("python");
        assert!(kw.contains(&"def"), "must contain 'def'");
        assert!(kw.contains(&"class"), "must contain 'class'");
        assert!(kw.contains(&"raise"), "must contain 'raise'");
    }

    #[test]
    fn test_keywords_for_language_java() {
        let kw = super::keywords_for_language("java");
        assert!(kw.contains(&"class"), "must contain 'class'");
        assert!(kw.contains(&"interface"), "must contain 'interface'");
        assert!(kw.contains(&"extends"), "must contain 'extends'");
    }

    // ── Vue keywords_for_language test (DELIVERABLE C) ────────────────────

    #[test]
    fn test_keywords_for_language_vue() {
        let kw = super::keywords_for_language("vue");
        // TS/JS base keywords
        assert!(kw.contains(&"function"), "must contain 'function'");
        assert!(kw.contains(&"const"), "must contain 'const'");
        // Vue-specific composables
        assert!(kw.contains(&"ref"), "must contain 'ref'");
        assert!(kw.contains(&"reactive"), "must contain 'reactive'");
        assert!(kw.contains(&"computed"), "must contain 'computed'");
        assert!(kw.contains(&"watch"), "must contain 'watch'");
        assert!(kw.contains(&"onMounted"), "must contain 'onMounted'");
        // Vue compiler macros
        assert!(kw.contains(&"defineProps"), "must contain 'defineProps'");
        assert!(kw.contains(&"defineEmits"), "must contain 'defineEmits'");
    }

    #[test]
    fn test_keywords_for_language_unknown_uses_default() {
        let kw = super::keywords_for_language("haskell");
        assert!(kw.contains(&"if"), "default must contain 'if'");
        assert!(kw.contains(&"for"), "default must contain 'for'");
        assert!(kw.contains(&"while"), "default must contain 'while'");
        assert!(kw.contains(&"return"), "default must contain 'return'");
    }

    #[test]
    fn test_try_separator_correction_converts_double_colon_to_dot() {
        assert_eq!(
            super::PathfinderServer::try_separator_correction("cache.rs::AstCache::get_or_parse"),
            Some("cache.rs::AstCache.get_or_parse".to_string())
        );
        assert_eq!(
            super::PathfinderServer::try_separator_correction("file.rs::Struct::method::inner"),
            Some("file.rs::Struct.method.inner".to_string())
        );
        assert_eq!(
            super::PathfinderServer::try_separator_correction("file.rs::simple_symbol"),
            None
        );
        assert_eq!(
            super::PathfinderServer::try_separator_correction("file.rs"),
            None
        );
    }

    #[test]
    fn test_is_test_file_various_languages() {
        // Kotlin test files
        assert!(super::is_test_file("src/Test.kt"));
        assert!(super::is_test_file("src/MySpec.kt"));
        assert!(!super::is_test_file("src/Main.kt"));

        // C# test files
        assert!(super::is_test_file("src/Test.cs"));
        assert!(super::is_test_file("src/MyTests.cs"));
        assert!(!super::is_test_file("src/Program.cs"));

        // Ruby test files
        assert!(super::is_test_file("src/some_test.rb"));
        assert!(super::is_test_file("src/some_spec.rb"));
        assert!(!super::is_test_file("src/app.rb"));

        // Dart test files
        assert!(super::is_test_file("src/some_test.dart"));
        assert!(!super::is_test_file("src/main.dart"));

        // Directory-based detection
        assert!(super::is_test_file("src/tests/helper.rs"));
        assert!(super::is_test_file("src/test/helper.go"));
        assert!(super::is_test_file("src/spec/helper.js"));
        assert!(super::is_test_file("src/specs/helper.ts"));
        assert!(super::is_test_file("src/__tests__/helper.tsx"));
        assert!(super::is_test_file("src/__test__/helper.py"));
    }

    #[test]
    fn test_is_workspace_file_heuristics() {
        // Unix absolute paths are not workspace files
        assert!(!super::is_workspace_file("/usr/bin/src/main.rs"));

        // Windows absolute paths are not workspace files
        assert!(!super::is_workspace_file("C:\\projects\\main.rs"));
        assert!(!super::is_workspace_file("D:/projects/main.rs"));
        assert!(!super::is_workspace_file("\\network\\main.rs"));

        // Dependency directories are not workspace files
        assert!(!super::is_workspace_file("node_modules/lodash/index.js"));
        assert!(!super::is_workspace_file("node_modules\\lodash\\index.js"));
        assert!(!super::is_workspace_file(
            "vendor/github.com/pkg/errors/errors.go"
        ));
        assert!(!super::is_workspace_file(
            "vendor\\github.com\\pkg\\errors\\errors.go"
        ));

        // Rust stdlib paths are not workspace files
        assert!(!super::is_workspace_file("std/src/lib.rs"));
        assert!(!super::is_workspace_file("core/src/lib.rs"));
        assert!(!super::is_workspace_file("alloc/src/lib.rs"));
        assert!(!super::is_workspace_file("std"));
        assert!(!super::is_workspace_file("core"));
        assert!(!super::is_workspace_file("alloc"));
        assert!(!super::is_workspace_file("library/std/src/path.rs"));
        assert!(!super::is_workspace_file("library/core/src/lib.rs"));
        assert!(!super::is_workspace_file("library/alloc/src/lib.rs"));
        assert!(!super::is_workspace_file("library\\std\\src\\path.rs"));
        assert!(!super::is_workspace_file("library\\core\\src\\lib.rs"));
        assert!(!super::is_workspace_file("library\\alloc\\src\\lib.rs"));

        // Regular relative source files are workspace files
        assert!(super::is_workspace_file("src/main.rs"));
        assert!(super::is_workspace_file("lib/utils.ts"));

        // Non-source code files are not workspace files
        assert!(!super::is_workspace_file("README.md"));
        assert!(!super::is_workspace_file("package.json"));
    }

    #[tokio::test]
    async fn test_enrich_did_you_mean_all_cases() {
        use super::test_helpers::{make_server_with_lawyer, make_temp_workspace};
        use pathfinder_common::config::PathfinderConfig;
        use pathfinder_common::sandbox::Sandbox;
        use pathfinder_common::types::WorkspaceRoot;
        use pathfinder_treesitter::mock::MockSurgeon;

        let mock_surgeon = std::sync::Arc::new(MockSurgeon::new());
        let mock_lawyer = std::sync::Arc::new(pathfinder_lsp::MockLawyer::default());
        let (server, _temp_dir) =
            make_server_with_lawyer(mock_surgeon.clone(), mock_lawyer.clone());

        // Case 1: Separator confusion correction: corrected path not already in suggestions
        let original_suggestions = vec!["src/auth.rs::AuthService".to_string()];
        let enriched = server
            .enrich_did_you_mean("src/auth.rs::AuthService::login", original_suggestions)
            .await;
        assert_eq!(enriched.len(), 2);
        assert_eq!(enriched[0], "src/auth.rs::AuthService.login");
        assert_eq!(enriched[1], "src/auth.rs::AuthService");

        // Case 2: Separator confusion correction: corrected path IS already in suggestions (should not duplicate)
        let original_suggestions = vec![
            "src/auth.rs::AuthService.login".to_string(),
            "src/auth.rs::AuthService".to_string(),
        ];
        let enriched = server
            .enrich_did_you_mean("src/auth.rs::AuthService::login", original_suggestions)
            .await;
        assert_eq!(enriched.len(), 2);
        assert_eq!(enriched[0], "src/auth.rs::AuthService.login");
        assert_eq!(enriched[1], "src/auth.rs::AuthService");

        // Case 3: Empty suggestions -> calls cross-file search find_symbol_impl which succeeds
        let mock_scout = std::sync::Arc::new(pathfinder_search::MockScout::default());
        mock_scout.set_result(Ok(pathfinder_search::SearchResult {
            matches: vec![pathfinder_search::SearchMatch {
                file: "src/auth.rs".to_owned(),
                line: 1,
                column: 1,
                content: "fn login() {}".to_owned(),
                context_before: vec![],
                context_after: vec![],
                enclosing_semantic_path: None,
                version_hash: "hash".to_owned(),
                is_definition: None,
                known: None,
            }],
            total_matches: 1,
            truncated: false,
            files_searched: 1,
            files_in_scope: 1,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        }));

        // Enclosing symbol calls: we need to push Ok(None) to mock_surgeon enclosing_symbol_detail_results.
        // find_symbol_impl uses enclosing_symbol_detail() for treesitter-based kind classification.
        // Let's push 100 times to be safe since find_symbol_impl will run parallel searches.
        for _ in 0..100 {
            mock_surgeon
                .enclosing_symbol_detail_results
                .lock()
                .unwrap()
                .push(Ok(None));
        }

        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);
        let server_with_scout = super::PathfinderServer::with_all_engines(
            ws,
            config,
            sandbox,
            mock_scout,
            mock_surgeon.clone(),
            mock_lawyer.clone(),
        );

        let enriched = server_with_scout
            .enrich_did_you_mean("src/auth.rs::login", vec![])
            .await;
        assert!(enriched.contains(&"src/auth.rs::login".to_string()));

        // Case 4: Empty suggestions -> calls cross-file search find_symbol_impl which returns error (path separator in symbol name)
        let enriched_err = server_with_scout
            .enrich_did_you_mean("src/auth.rs::login/error", vec![])
            .await;
        assert!(enriched_err.is_empty());
    }

    #[tokio::test]
    async fn test_read_symbol_scope_enriched_all_cases() {
        use super::test_helpers::{make_scope, make_server_with_lawyer};
        use pathfinder_treesitter::mock::MockSurgeon;

        let mock_surgeon = std::sync::Arc::new(MockSurgeon::new());
        let mock_lawyer = std::sync::Arc::new(pathfinder_lsp::MockLawyer::default());
        let (server, _temp_dir) =
            make_server_with_lawyer(mock_surgeon.clone(), mock_lawyer.clone());

        // Case 1: Surgeon returns Ok(scope) -> read_symbol_scope_enriched returns Ok(scope)
        let scope = make_scope();
        mock_surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(scope.clone()));
        let semantic_path =
            pathfinder_common::types::SemanticPath::parse("src/auth.rs::login").unwrap();
        let res = server
            .read_symbol_scope_enriched(&semantic_path, "src/auth.rs::login")
            .await;
        assert!(res.is_ok());
        assert_eq!(res.unwrap().content, scope.content);

        // Case 2: Surgeon returns SymbolNotFound error with original suggestions,
        // and semantic path has NO double colons in the symbol chain.
        // It should enrich did_you_mean and return Err(SymbolNotFound).
        mock_surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Err(pathfinder_treesitter::SurgeonError::SymbolNotFound {
                path: "src/auth.rs::login".to_owned(),
                did_you_mean: vec![],
            }));
        let res = server
            .read_symbol_scope_enriched(&semantic_path, "src/auth.rs::login")
            .await;
        assert!(res.is_err());
        let err = res.unwrap_err();
        let data = err.data.as_ref().expect("error should contain JSON data");
        assert_eq!(data["error"], "SYMBOL_NOT_FOUND");

        // Case 3: Surgeon returns SymbolNotFound error, and semantic path HAS double colons in symbol chain.
        // First try fails with SymbolNotFound.
        // Auto-retry corrects the path (:: -> .) and calls surgeon again, which succeeds.
        let corrected_scope = make_scope();
        mock_surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Err(pathfinder_treesitter::SurgeonError::SymbolNotFound {
                path: "src/auth.rs::AuthService::login".to_owned(),
                did_you_mean: vec![],
            }));
        mock_surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(corrected_scope.clone()));

        let semantic_path_with_confusion =
            pathfinder_common::types::SemanticPath::parse("src/auth.rs::AuthService::login")
                .unwrap();
        let res = server
            .read_symbol_scope_enriched(
                &semantic_path_with_confusion,
                "src/auth.rs::AuthService::login",
            )
            .await;
        assert!(res.is_ok());
        assert_eq!(res.unwrap().content, corrected_scope.content);
    }
}