mcpls-core 0.8.0

Core library for MCP to LSP protocol translation
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
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
//! Client/server routing, document-open preparation, and capability gating
//! shared by every LSP-round-trip tool-call handler.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use super::Translator;
use super::positioned::DisclosedDocument;
use crate::bridge::resources::{DiagnosticsResourceUri, parse_uri};
use crate::bridge::{
    Access, ClientPath, InFlightGuard, LinePresence, OpenRequest, Position, WorkspacePath,
};
use crate::config::{
    FileKey, LanguageId, NoServerReason, ServerId, ToolKind, ToolRouter, base_language_id,
};
use crate::error::{Error, ErrorChain, Result, ServerSpawnFailure};
use crate::lsp::LspClient;
use crate::util::{MAX_ECHOED_PATH_BYTES, escape_bounded, lock_std};

/// Total time `Translator::flush_pending_closes` may spend per call.
const FLUSH_PENDING_CLOSES_DEADLINE: std::time::Duration = std::time::Duration::from_secs(1);

/// A document opened for a handler's LSP round-trip, together with the
/// routed server and client.
///
/// Owns an [`InFlightGuard`], so the document cannot be evicted by the
/// document tracker's LRU while this value is alive (#503). Fields are
/// reachable only through borrowing accessors, so a handler must keep the
/// whole `PreparedDocument` bound until its request completes -- destructuring
/// it would drop the guard early.
#[derive(Debug)]
#[must_use = "dropping a PreparedDocument makes its document evictable mid-request"]
pub(super) struct PreparedDocument {
    server_id: ServerId,
    client: LspClient,
    uri: lsp_types::Uri,
    path: PathBuf,
    _in_flight: InFlightGuard,
}

impl PreparedDocument {
    pub(super) const fn server_id(&self) -> &ServerId {
        &self.server_id
    }

    pub(super) const fn client(&self) -> &LspClient {
        &self.client
    }

    pub(super) const fn uri(&self) -> &lsp_types::Uri {
        &self.uri
    }

    pub(super) fn path(&self) -> &Path {
        &self.path
    }
}

/// Whether opening a document waits for the routed server to finish indexing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IndexingWait {
    Wait,
    Skip,
}

/// The capability a [`Translator::prepare_gated_document`] call site gates
/// on, together with whether it also applies
/// [`Translator::wait_for_indexing_ready`], declared explicitly at the same
/// place capability-gating is declared so a newly added (or newly gated) tool
/// can't silently ship without an indexing-readiness decision either way.
///
/// Only a [`FileLocalCapability`] fits [`Self::FileLocal`], so a
/// name-resolving tool cannot skip the indexing wait by accident.
///
/// This only covers call sites that actually go through
/// `prepare_gated_document`. The disclosed tools open through
/// `prepare_disclosed_document`, which takes a [`DisclosedCapability`] and
/// answers with an `Indexed` result, and `require_routed_capability` only
/// checks a capability without opening anything. Two further production
/// handlers bypass the chokepoint entirely and so make no `IndexingGate`
/// decision at all:
/// - `handle_workspace_symbol` (`workspace_symbol_search`) has no per-file
///   document to resolve or open (it resolves via `resolve_any` instead), so
///   it cannot be routed through this chokepoint as-is. Whether/how to gate
///   it on indexing readiness was deferred as a separate open question (spec
///   FR-008) and remains a known, deliberate limitation -- see #423.
/// - `handle_diagnostics` calls the ungated `Translator::prepare_document`
///   sibling directly, so it gets neither an indexing-readiness decision nor
///   a capability check. The indexing-readiness half of that is deliberate,
///   not an oversight (#445): unlike `handle_incoming_calls`/`handle_outgoing_calls`
///   (#423), it reads from the notification-cache poll path rather than
///   issuing a live whole-workspace LSP request, so blocking it on
///   `wait_for_indexing_ready` the way `Required` does for the other
///   handlers would be the wrong fix shape (it would stall a cache read on a
///   signal the cache itself doesn't need). Instead, the `get_diagnostics`
///   MCP tool (`mcp::server::get_diagnostics`) independently resolves the
///   file's diagnostics-route server and reports its indexing state as an
///   explicit `indexing_in_progress` flag on the response
///   (`mcp::server::DiagnosticsResponse`), so a mid-index pull (which can
///   read as "no errors" while rust-analyzer is still loading) is flagged
///   rather than silently trusted. The missing capability check was not
///   analyzed as part of #445 and remains an open question.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum IndexingGate {
    /// This tool's answer depends on whole-workspace analysis (e.g. hover,
    /// definition, references, rename, completions, code actions, call
    /// hierarchy incoming/outgoing calls): wait for indexing before opening.
    Required(Capability),
    /// This tool's answer is file-local, so it is valid mid-index and carries
    /// no signal: document symbols (also used by name addressing and
    /// `enclosing_symbol`), folding ranges, selection ranges, document
    /// highlights, format document and format range.
    ///
    /// Name-resolving tools that must not stall a cold start (signature help,
    /// inlay hints, prepare call/type hierarchy; the #423 scope decision) do
    /// not fit here: they open through `Translator::prepare_disclosed_document`, whose
    /// `DisclosedDocument` can only answer with an `Indexed` result carrying
    /// `indexing_in_progress` (#668).
    FileLocal(FileLocalCapability),
}

impl IndexingGate {
    /// The capability the call site gates on.
    pub(super) fn capability(self) -> Capability {
        match self {
            Self::Required(capability) => capability,
            Self::FileLocal(capability) => capability.into(),
        }
    }
}

/// The capabilities whose answer is file-local and so valid mid-index; the
/// only ones [`IndexingGate::FileLocal`] accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum FileLocalCapability {
    /// [`Capability::DocumentSymbols`].
    DocumentSymbols,
    /// [`Capability::FoldingRange`].
    FoldingRange,
    /// [`Capability::SelectionRange`].
    SelectionRange,
    /// [`Capability::DocumentHighlights`].
    DocumentHighlights,
    /// [`Capability::FormatDocument`].
    FormatDocument,
    /// [`Capability::FormatRange`].
    FormatRange,
}

impl From<FileLocalCapability> for Capability {
    fn from(capability: FileLocalCapability) -> Self {
        match capability {
            FileLocalCapability::DocumentSymbols => Self::DocumentSymbols,
            FileLocalCapability::FoldingRange => Self::FoldingRange,
            FileLocalCapability::SelectionRange => Self::SelectionRange,
            FileLocalCapability::DocumentHighlights => Self::DocumentHighlights,
            FileLocalCapability::FormatDocument => Self::FormatDocument,
            FileLocalCapability::FormatRange => Self::FormatRange,
        }
    }
}

/// The capabilities of the name-resolving tools that must not stall a cold
/// start: they open through [`Translator::prepare_disclosed_document`], which
/// never waits for indexing, so only these four can reach it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum DisclosedCapability {
    /// [`Capability::SignatureHelp`].
    SignatureHelp,
    /// [`Capability::InlayHints`].
    InlayHints,
    /// [`Capability::CallHierarchy`].
    CallHierarchy,
    /// [`Capability::TypeHierarchy`].
    TypeHierarchy,
}

impl From<DisclosedCapability> for Capability {
    fn from(capability: DisclosedCapability) -> Self {
        match capability {
            DisclosedCapability::SignatureHelp => Self::SignatureHelp,
            DisclosedCapability::InlayHints => Self::InlayHints,
            DisclosedCapability::CallHierarchy => Self::CallHierarchy,
            DisclosedCapability::TypeHierarchy => Self::TypeHierarchy,
        }
    }
}

/// An LSP server capability mcpls gates a tool on before dispatching its request.
///
/// Ties the [`ServerCapabilities`](lsp_types::ServerCapabilities) field name
/// (used only for the error message, through `Display`) to the predicate that
/// actually checks it, so the two cannot drift apart the way two independent,
/// hand-picked call-site values could.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Capability {
    /// `completionProvider` (`textDocument/completion`).
    Completions,
    /// `signatureHelpProvider` (`textDocument/signatureHelp`).
    SignatureHelp,
    /// `inlayHintProvider` (`textDocument/inlayHint`).
    InlayHints,
    /// `hoverProvider` (`textDocument/hover`).
    Hover,
    /// `definitionProvider` (`textDocument/definition`).
    Definition,
    /// `referencesProvider` (`textDocument/references`).
    References,
    /// `implementationProvider` (`textDocument/implementation`).
    Implementation,
    /// `typeDefinitionProvider` (`textDocument/typeDefinition`).
    TypeDefinition,
    /// `callHierarchyProvider` (`textDocument/prepareCallHierarchy`,
    /// `callHierarchy/incomingCalls`, `callHierarchy/outgoingCalls`).
    CallHierarchy,
    /// `renameProvider` (`textDocument/rename`).
    Rename,
    /// `documentFormattingProvider` (`textDocument/formatting`).
    FormatDocument,
    /// `codeActionProvider` (`textDocument/codeAction`).
    CodeActions,
    /// `documentSymbolProvider` (`textDocument/documentSymbol`).
    DocumentSymbols,
    /// `workspaceSymbolProvider` (`workspace/symbol`).
    WorkspaceSymbols,
    /// `declarationProvider` (`textDocument/declaration`).
    Declaration,
    /// `typeHierarchyProvider` (`textDocument/prepareTypeHierarchy`,
    /// `typeHierarchy/supertypes`, `typeHierarchy/subtypes`).
    TypeHierarchy,
    /// `renameProvider.prepareProvider` (`textDocument/prepareRename`). Gated
    /// on the [`ToolKind::Rename`] route, so it is never the primary
    /// capability of its tool.
    PrepareRename,
    /// `documentHighlightProvider` (`textDocument/documentHighlight`).
    DocumentHighlights,
    /// `documentRangeFormattingProvider` (`textDocument/rangeFormatting`).
    FormatRange,
    /// `selectionRangeProvider` (`textDocument/selectionRange`).
    SelectionRange,
    /// `foldingRangeProvider` (`textDocument/foldingRange`).
    FoldingRange,
}

#[expect(
    clippy::indexing_slicing,
    reason = "compile-time check; the loop condition keeps `i` below `ALL.len()`"
)]
const _: () = {
    assert!(Capability::ALL.len() == Capability::FoldingRange as usize + 1);
    assert!(Capability::ALL.len() <= u32::BITS as usize);
    let mut i = 0;
    while i < Capability::ALL.len() {
        assert!(Capability::ALL[i] as usize == i);
        i += 1;
    }
};

impl Capability {
    /// Every capability, in discriminant order.
    pub(crate) const ALL: [Self; 21] = [
        Self::Completions,
        Self::SignatureHelp,
        Self::InlayHints,
        Self::Hover,
        Self::Definition,
        Self::References,
        Self::Implementation,
        Self::TypeDefinition,
        Self::CallHierarchy,
        Self::Rename,
        Self::FormatDocument,
        Self::CodeActions,
        Self::DocumentSymbols,
        Self::WorkspaceSymbols,
        Self::Declaration,
        Self::TypeHierarchy,
        Self::PrepareRename,
        Self::DocumentHighlights,
        Self::FormatRange,
        Self::SelectionRange,
        Self::FoldingRange,
    ];

    /// The [`ToolKind`] whose route this capability gates -- the single
    /// source tying a gated handler's routing to its capability check.
    pub(crate) const fn tool_kind(self) -> ToolKind {
        match self {
            Self::Completions => ToolKind::Completions,
            Self::SignatureHelp => ToolKind::SignatureHelp,
            Self::InlayHints => ToolKind::InlayHints,
            Self::Hover => ToolKind::Hover,
            Self::Definition => ToolKind::Definition,
            Self::References => ToolKind::References,
            Self::Implementation => ToolKind::Implementation,
            Self::TypeDefinition => ToolKind::TypeDefinition,
            Self::CallHierarchy => ToolKind::CallHierarchy,
            Self::Rename | Self::PrepareRename => ToolKind::Rename,
            Self::FormatDocument => ToolKind::FormatDocument,
            Self::CodeActions => ToolKind::CodeActions,
            Self::DocumentSymbols => ToolKind::DocumentSymbols,
            Self::WorkspaceSymbols => ToolKind::WorkspaceSymbols,
            Self::Declaration => ToolKind::Declaration,
            Self::TypeHierarchy => ToolKind::TypeHierarchy,
            Self::DocumentHighlights => ToolKind::DocumentHighlights,
            Self::FormatRange => ToolKind::FormatRange,
            Self::SelectionRange => ToolKind::SelectionRange,
            Self::FoldingRange => ToolKind::FoldingRange,
        }
    }

    /// Whether this is the capability [`Self::for_tool`] returns for its
    /// [`ToolKind`]. Only [`Self::PrepareRename`] is not: it shares the
    /// `Rename` route, and `Rename` precedes it in [`Self::ALL`].
    pub(crate) const fn is_primary(self) -> bool {
        !matches!(self, Self::PrepareRename)
    }

    /// The primary capability gating `tool` (the first match in
    /// [`Self::ALL`]), or `None` for a tool dispatched without a capability
    /// check (`Diagnostics`). Derived from [`Self::tool_kind`] over
    /// [`Self::ALL`], so the pairing has a single source.
    pub(crate) const fn for_tool(tool: ToolKind) -> Option<Self> {
        Self::find_gating(&Self::ALL, tool)
    }

    const fn find_gating(candidates: &[Self], tool: ToolKind) -> Option<Self> {
        match candidates {
            // `PartialEq` is not const, so compare discriminants.
            [first, rest @ ..] => {
                if first.is_primary() && first.tool_kind() as u8 == tool as u8 {
                    Some(*first)
                } else {
                    Self::find_gating(rest, tool)
                }
            }
            [] => None,
        }
    }

    /// Whether a request gated on this capability may be dispatched against
    /// a server with `caps`. Unknown capabilities (`None`) are assumed
    /// supported, mirroring [`Translator::require_capability`]'s fail-open
    /// stance.
    pub(crate) const fn is_available(self, caps: Option<&lsp_types::ServerCapabilities>) -> bool {
        match caps {
            Some(caps) => self.is_supported(caps),
            None => true,
        }
    }

    /// The `ServerCapabilities` field name, as reported to the MCP caller in
    /// [`Error::CapabilityNotSupported`].
    pub(crate) const fn name(self) -> &'static str {
        match self {
            Self::Completions => "completionProvider",
            Self::SignatureHelp => "signatureHelpProvider",
            Self::InlayHints => "inlayHintProvider",
            Self::Hover => "hoverProvider",
            Self::Definition => "definitionProvider",
            Self::References => "referencesProvider",
            Self::Implementation => "implementationProvider",
            Self::TypeDefinition => "typeDefinitionProvider",
            Self::CallHierarchy => "callHierarchyProvider",
            Self::Rename => "renameProvider",
            Self::FormatDocument => "documentFormattingProvider",
            Self::CodeActions => "codeActionProvider",
            Self::DocumentSymbols => "documentSymbolProvider",
            Self::WorkspaceSymbols => "workspaceSymbolProvider",
            Self::Declaration => "declarationProvider",
            Self::TypeHierarchy => "typeHierarchyProvider",
            Self::PrepareRename => "renameProvider.prepareProvider",
            Self::DocumentHighlights => "documentHighlightProvider",
            Self::FormatRange => "documentRangeFormattingProvider",
            Self::SelectionRange => "selectionRangeProvider",
            Self::FoldingRange => "foldingRangeProvider",
        }
    }

    /// Whether `caps` advertises support for this capability.
    #[allow(clippy::too_many_lines, reason = "one match arm per capability")]
    pub(crate) const fn is_supported(self, caps: &lsp_types::ServerCapabilities) -> bool {
        match self {
            Self::Completions => caps.completion_provider.is_some(),
            Self::SignatureHelp => caps.signature_help_provider.is_some(),
            Self::InlayHints => matches!(
                caps.inlay_hint_provider,
                Some(
                    lsp_types::InlayHintProvider::Bool(true)
                        | lsp_types::InlayHintProvider::InlayHintOptions(_)
                        | lsp_types::InlayHintProvider::InlayHintRegistrationOptions(_)
                )
            ),
            Self::Hover => matches!(
                caps.hover_provider,
                Some(
                    lsp_types::HoverProvider::Bool(true)
                        | lsp_types::HoverProvider::HoverOptions(_)
                )
            ),
            Self::Definition => matches!(
                caps.definition_provider,
                Some(
                    lsp_types::DefinitionProvider::Bool(true)
                        | lsp_types::DefinitionProvider::DefinitionOptions(_)
                )
            ),
            Self::References => matches!(
                caps.references_provider,
                Some(
                    lsp_types::ReferencesProvider::Bool(true)
                        | lsp_types::ReferencesProvider::ReferenceOptions(_)
                )
            ),
            Self::Implementation => matches!(
                caps.implementation_provider,
                Some(
                    lsp_types::ImplementationProvider::Bool(true)
                        | lsp_types::ImplementationProvider::ImplementationOptions(_)
                        | lsp_types::ImplementationProvider::ImplementationRegistrationOptions(_)
                )
            ),
            Self::TypeDefinition => matches!(
                caps.type_definition_provider,
                Some(
                    lsp_types::TypeDefinitionProvider::Bool(true)
                        | lsp_types::TypeDefinitionProvider::TypeDefinitionOptions(_)
                        | lsp_types::TypeDefinitionProvider::TypeDefinitionRegistrationOptions(_)
                )
            ),
            Self::CallHierarchy => matches!(
                caps.call_hierarchy_provider,
                Some(
                    lsp_types::CallHierarchyProvider::Bool(true)
                        | lsp_types::CallHierarchyProvider::CallHierarchyOptions(_)
                        | lsp_types::CallHierarchyProvider::CallHierarchyRegistrationOptions(_)
                )
            ),
            Self::Rename => matches!(
                caps.rename_provider,
                Some(
                    lsp_types::RenameProvider::Bool(true)
                        | lsp_types::RenameProvider::RenameOptions(_)
                )
            ),
            Self::FormatDocument => matches!(
                caps.document_formatting_provider,
                Some(
                    lsp_types::DocumentFormattingProvider::Bool(true)
                        | lsp_types::DocumentFormattingProvider::DocumentFormattingOptions(_)
                )
            ),
            Self::CodeActions => matches!(
                caps.code_action_provider,
                Some(
                    lsp_types::CodeActionProvider::Bool(true)
                        | lsp_types::CodeActionProvider::CodeActionOptions(_)
                )
            ),
            Self::DocumentSymbols => matches!(
                caps.document_symbol_provider,
                Some(
                    lsp_types::DocumentSymbolProvider::Bool(true)
                        | lsp_types::DocumentSymbolProvider::DocumentSymbolOptions(_)
                )
            ),
            Self::WorkspaceSymbols => matches!(
                caps.workspace_symbol_provider,
                Some(
                    lsp_types::WorkspaceSymbolProvider::Bool(true)
                        | lsp_types::WorkspaceSymbolProvider::WorkspaceSymbolOptions(_)
                )
            ),
            Self::Declaration => matches!(
                caps.declaration_provider,
                Some(
                    lsp_types::DeclarationProvider::Bool(true)
                        | lsp_types::DeclarationProvider::DeclarationOptions(_)
                        | lsp_types::DeclarationProvider::DeclarationRegistrationOptions(_)
                )
            ),
            Self::TypeHierarchy => matches!(
                caps.type_hierarchy_provider,
                Some(
                    lsp_types::TypeHierarchyProvider::Bool(true)
                        | lsp_types::TypeHierarchyProvider::TypeHierarchyOptions(_)
                        | lsp_types::TypeHierarchyProvider::TypeHierarchyRegistrationOptions(_)
                )
            ),
            Self::PrepareRename => matches!(
                caps.rename_provider,
                Some(lsp_types::RenameProvider::RenameOptions(
                    lsp_types::RenameOptions {
                        prepare_provider: Some(true),
                        ..
                    }
                ))
            ),
            Self::DocumentHighlights => matches!(
                caps.document_highlight_provider,
                Some(
                    lsp_types::DocumentHighlightProvider::Bool(true)
                        | lsp_types::DocumentHighlightProvider::DocumentHighlightOptions(_)
                )
            ),
            Self::FormatRange => matches!(
                caps.document_range_formatting_provider,
                Some(
                    lsp_types::DocumentRangeFormattingProvider::Bool(true)
                        | lsp_types::DocumentRangeFormattingProvider::DocumentRangeFormattingOptions(_)
                )
            ),
            Self::SelectionRange => matches!(
                caps.selection_range_provider,
                Some(
                    lsp_types::SelectionRangeProvider::Bool(true)
                        | lsp_types::SelectionRangeProvider::SelectionRangeOptions(_)
                        | lsp_types::SelectionRangeProvider::SelectionRangeRegistrationOptions(_)
                )
            ),
            Self::FoldingRange => matches!(
                caps.folding_range_provider,
                Some(
                    lsp_types::FoldingRangeProvider::Bool(true)
                        | lsp_types::FoldingRangeProvider::FoldingRangeOptions(_)
                        | lsp_types::FoldingRangeProvider::FoldingRangeRegistrationOptions(_)
                )
            ),
        }
    }
}

impl std::fmt::Display for Capability {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.name())
    }
}

impl serde::Serialize for Capability {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        serializer.serialize_str(self.name())
    }
}

/// Serialized as the `ServerCapabilities` field name its `Display` prints.
impl schemars::JsonSchema for Capability {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "Capability".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "string",
            "description": "LSP server capability the tool is gated on."
        })
    }
}

/// A file's detected language plus its React base-language fallback
/// (`typescriptreact` -> `typescript`), in resolution order.
///
/// Single source of the candidate order for enforcement and the
/// `get_tool_support` snapshot, so an explicit `typescriptreact` server still
/// wins over the `typescript` fallback in both.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct LanguageCandidates {
    language: LanguageId,
    base: Option<LanguageId>,
}

impl LanguageCandidates {
    pub(super) fn new(language: LanguageId) -> Self {
        let base = base_language_id(&language);
        Self { language, base }
    }

    pub(super) const fn language(&self) -> &LanguageId {
        &self.language
    }

    pub(super) fn iter(&self) -> impl Iterator<Item = &LanguageId> {
        std::iter::once(&self.language).chain(self.base.as_ref())
    }
}

/// Outcome of resolving a per-document tool route against the registries,
/// shared by enforcement ([`Translator::client_for_file`]) and the
/// `get_tool_support` snapshot so the two cannot disagree.
#[derive(Debug)]
pub(super) enum RouteLookup<T> {
    /// The routed server is registered; `T` is whatever the registry lookup returned.
    Registered(ServerId, T),
    /// The routed server is expected but has not registered yet.
    Initializing(ServerId),
    /// The routed server failed to start and no catch-all is left to wait
    /// for. Only seen while a router read races a settlement, since a settled
    /// router drops such a route.
    Failed(Box<ServerSpawnFailure>),
    /// The router names a server that is neither registered, expected nor
    /// recorded as failed.
    Dangling {
        language: LanguageId,
        server_id: ServerId,
    },
    /// No candidate language has a route for the tool.
    Unrouted,
}

/// Resolve the first candidate language with a route, then classify that
/// route's server. `resolve`, `registered`, `is_expected`,
/// `pending_catch_all` and `startup_failure` are separate closures so a caller
/// backed by independent locks never holds two at once.
///
/// A route naming a failed server whose language's catch-all is still
/// initializing (FR-007: the route is not bound to it yet) is `Initializing`
/// naming that catch-all, the retryable state, rather than a terminal failure.
pub(super) fn lookup_route<T>(
    candidates: &LanguageCandidates,
    resolve: impl Fn(&str) -> Option<ServerId>,
    registered: impl Fn(&ServerId) -> Option<T>,
    is_expected: impl Fn(&ServerId) -> bool,
    pending_catch_all: impl Fn(&str) -> Option<ServerId>,
    startup_failure: impl Fn(&ServerId) -> Option<ServerSpawnFailure>,
) -> RouteLookup<T> {
    for language in candidates.iter() {
        let Some(server_id) = resolve(language.as_str()) else {
            continue;
        };
        return if let Some(found) = registered(&server_id) {
            RouteLookup::Registered(server_id, found)
        } else if is_expected(&server_id) {
            RouteLookup::Initializing(server_id)
        } else if let Some(catch_all) = pending_catch_all(language.as_str()) {
            RouteLookup::Initializing(catch_all)
        } else if let Some(failure) = startup_failure(&server_id) {
            RouteLookup::Failed(Box::new(failure))
        } else {
            RouteLookup::Dangling {
                language: language.clone(),
                server_id,
            }
        };
    }
    RouteLookup::Unrouted
}

/// The catch-all of `language` if it is still expected to register, read from
/// the same `servers` guard as the rest of the lookup.
fn pending_catch_all(
    router: &ToolRouter,
    servers: &super::servers::Servers,
    language: &str,
) -> Option<ServerId> {
    router
        .catch_all_for(language)
        .filter(|catch_all| servers.is_expected(catch_all))
        .cloned()
}

/// Where a file's diagnostics-route server stands, as seen by the cache-only
/// diagnostics readers.
///
/// Resolved by [`Translator::diagnostics_route_for_path`] with the same rules
/// as [`Translator::client_for_file`], so reading cached diagnostics cannot
/// disagree with the pull tool about whether a server exists.
#[derive(Debug)]
pub enum DiagnosticsRoute {
    /// The routed server is registered.
    Live(ServerId),
    /// The routed server is expected but has not registered yet.
    Initializing(ServerId),
    /// The server that would have served the file failed to start.
    FailedToStart(Box<ServerSpawnFailure>),
    /// No server is configured for the file's language.
    Unrouted,
}

impl DiagnosticsRoute {
    /// The routed server's id while it is registered or still starting.
    pub(crate) const fn server_id(&self) -> Option<&ServerId> {
        match self {
            Self::Live(id) | Self::Initializing(id) => Some(id),
            Self::FailedToStart(_) | Self::Unrouted => None,
        }
    }

    /// Whether the server failed to start.
    pub(crate) const fn is_failed(&self) -> bool {
        matches!(self, Self::FailedToStart(_))
    }

    /// The startup failure, if the server failed to start.
    ///
    /// For subscription paths, where a still-starting server is fine (updates
    /// will follow) but a failed one never publishes anything.
    pub(crate) fn into_startup_failure(self) -> Option<Box<ServerSpawnFailure>> {
        match self {
            Self::FailedToStart(failure) => Some(failure),
            Self::Live(_) | Self::Initializing(_) | Self::Unrouted => None,
        }
    }

    /// Gates a cache read on the route: the live server's id, or `None` when
    /// no server is configured (an empty cache is then the honest answer).
    ///
    /// # Errors
    ///
    /// [`Error::ServerInitializing`] while the server is still starting,
    /// [`Error::ServerFailedToStart`] once it failed to start.
    pub(crate) fn into_read_result(self) -> Result<Option<ServerId>> {
        match self {
            Self::Live(id) => Ok(Some(id)),
            Self::Unrouted => Ok(None),
            Self::Initializing(server_id) => Err(Error::ServerInitializing { server_id }),
            Self::FailedToStart(failure) => Err(Error::ServerFailedToStart(failure)),
        }
    }
}

/// Outcome of resolving a workspace-wide tool route; see [`RouteLookup`].
#[derive(Debug, PartialEq, Eq)]
pub(super) enum WorkspaceRouteLookup {
    /// The resolved server is registered.
    Registered(ServerId),
    /// The resolved server is expected but has not registered yet.
    Initializing(ServerId),
    /// The router resolved a server that is neither registered nor expected.
    Dangling(ServerId),
    /// Nothing is registered yet, but servers are still expected.
    AllInitializing,
    /// Nothing is registered and nothing is expected.
    NothingConfigured,
    /// Servers are registered, but none claims the tool and none is a catch-all.
    NoClaimant,
}

/// Resolve a workspace-wide tool route and classify the resolved server.
///
/// The closures are separate so a caller backed by independent locks never
/// holds two at once, as with [`lookup_route`].
pub(super) fn lookup_workspace_route(
    resolve: impl FnOnce() -> std::result::Result<ServerId, NoServerReason>,
    is_registered: impl Fn(&ServerId) -> bool,
    is_expected: impl Fn(&ServerId) -> bool,
    expected_is_empty: impl FnOnce() -> bool,
) -> WorkspaceRouteLookup {
    match resolve() {
        Ok(id) if is_registered(&id) => WorkspaceRouteLookup::Registered(id),
        Ok(id) if is_expected(&id) => WorkspaceRouteLookup::Initializing(id),
        Ok(id) => WorkspaceRouteLookup::Dangling(id),
        Err(NoServerReason::NothingRegistered) if expected_is_empty() => {
            WorkspaceRouteLookup::NothingConfigured
        }
        Err(NoServerReason::NothingRegistered) => WorkspaceRouteLookup::AllInitializing,
        Err(NoServerReason::NoClaimant) => WorkspaceRouteLookup::NoClaimant,
    }
}

/// Fail with [`Error::CapabilityNotSupported`] if `caps` is known and does
/// not advertise `capability`.
pub(super) fn check_capability(
    server_id: &ServerId,
    caps: Option<&lsp_types::ServerCapabilities>,
    capability: Capability,
) -> Result<()> {
    capability
        .is_available(caps)
        .ok_or_else(|| Error::CapabilityNotSupported {
            server_id: server_id.clone(),
            capability,
        })
}

impl Translator {
    /// Validate that a path is within allowed workspace boundaries.
    ///
    /// # Errors
    ///
    /// Returns `Error::NoWorkspaceRoots` if no workspace roots are
    /// configured (fails closed), or `Error::PathOutsideWorkspace` if the
    /// path is outside all configured workspace roots.
    pub(crate) async fn validate_path(&self, path: &ClientPath) -> Result<WorkspacePath> {
        self.workspace_roots.validate(path).await
    }

    /// Resolve the client and routing identity for `path`/`tool`, giving the
    /// resolved server a chance to be respawned first if its process has
    /// died.
    ///
    /// Thin async wrapper around [`Self::client_for_file`] (kept
    /// synchronous so its existing unit tests don't need a runtime): this is
    /// the entry point async handlers call instead, so a dead server is
    /// transparently replaced before its stale client is handed back.
    pub(super) async fn resolve_client_for_file(
        &self,
        path: &Path,
        tool: ToolKind,
    ) -> Result<(ServerId, LspClient)> {
        let (id, client) = self.client_for_file(path, tool)?;
        self.respawn_if_dead(&id).await?;
        let client = lock_std(&self.servers).client(&id).unwrap_or(client);
        Ok((id, client))
    }

    /// Resolve the server that should handle `tool` for the file at `path`,
    /// returning both its routing identity and a cloned client.
    ///
    /// Tries the file's detected language first, then (if that has no route)
    /// its React base language (`.tsx` falling back from `typescriptreact` to
    /// `typescript`, and similarly for `.jsx`) -- in that order, so an
    /// explicit `typescriptreact` server still wins over the `typescript`
    /// fallback when both are configured.
    ///
    /// Clones the router, then reads every closure's answer from one `servers`
    /// guard (registered, expected, pending catch-all, failure) — every guard is
    /// dropped before this method returns.
    pub(super) fn client_for_file(
        &self,
        path: &Path,
        tool: ToolKind,
    ) -> Result<(ServerId, LspClient)> {
        let candidates = self.language_candidates(path);
        let router = self.router_snapshot();
        let lookup = {
            let servers = lock_std(&self.servers);
            lookup_route(
                &candidates,
                |lang| router.resolve(lang, tool).cloned(),
                |id| servers.client(id),
                |id| servers.is_expected(id),
                |lang| pending_catch_all(&router, &servers, lang),
                |id| servers.failure(id).cloned(),
            )
        };
        match lookup {
            RouteLookup::Registered(id, client) => Ok((id, client)),
            // A route naming a server that is still initializing (e.g. a
            // large Unity solution loading via OmniSharp) -- tell the caller
            // to wait and retry rather than implying no server is configured.
            RouteLookup::Initializing(server_id) => Err(Error::ServerInitializing { server_id }),
            RouteLookup::Failed(failure) => Err(Error::ServerFailedToStart(failure)),
            // Unreachable once every server has settled and the router was
            // re-derived (`Translator::rebind_router_to_settled`) -- a route
            // can only name a registered, pending or failed server. Logged rather than
            // `debug_assert!`-panicked: this method is reachable by any
            // library consumer calling `with_router` without registering
            // matching clients, not just internal misuse.
            RouteLookup::Dangling {
                language,
                server_id,
            } => {
                tracing::error!(
                    "router route names server '{server_id}' for tool '{tool}' that is neither \
                     registered nor expected"
                );
                Err(Error::NoServerForTool {
                    language_id: language,
                    tool,
                })
            }
            RouteLookup::Unrouted => {
                if let Some(failure) = self.startup_failure_for_candidates(&candidates, tool) {
                    return Err(Error::ServerFailedToStart(Box::new(failure)));
                }
                let has_language = {
                    let router = lock_std(&self.router);
                    candidates
                        .iter()
                        .any(|lang| router.has_language(lang.as_str()))
                };
                let language = candidates.language().clone();
                if has_language {
                    Err(Error::NoServerForTool {
                        language_id: language,
                        tool,
                    })
                } else {
                    Err(Error::NoServerForLanguage {
                        language,
                        file: FileKey::of(path),
                        patterns: Arc::clone(&self.file_patterns),
                    })
                }
            }
        }
    }

    /// The detected language of `path` plus its React base-language fallback.
    pub(super) fn language_candidates(&self, path: &Path) -> LanguageCandidates {
        LanguageCandidates::new(self.language_map.detect(path))
    }

    /// The startup failure of the server the pre-rebind routing table would
    /// have used for `tool` in the first of `languages` that has one.
    ///
    /// Only consulted once no live route exists: a surviving catch-all
    /// still serves the request, so a failed explicit server never masks it.
    fn startup_failure_for_candidates(
        &self,
        candidates: &LanguageCandidates,
        tool: ToolKind,
    ) -> Option<ServerSpawnFailure> {
        candidates.iter().find_map(|lang| {
            let id = self.configured_router.resolve(lang.as_str(), tool)?;
            self.startup_failure(id)
        })
    }

    /// Classify the diagnostics-route server for `path`'s detected language.
    ///
    /// Mirrors [`Self::client_for_file`]'s language-candidate order and
    /// registered/expected/failed classification, so a cache-only caller
    /// (`get_cached_diagnostics`, the diagnostics resource) can tell an empty
    /// cache from a server that is still starting or never started.
    ///
    /// The id of a [`DiagnosticsRoute::Live`] route is stable across a
    /// respawn (only the registered client behind it changes), unlike
    /// `NotificationCache::diagnostics_owner`, which a respawn clears -- so it
    /// is what the push-degraded flag (#359) is keyed on.
    #[must_use]
    pub(crate) fn diagnostics_route_for_path(&self, path: &Path) -> DiagnosticsRoute {
        let candidates = self.language_candidates(path);
        let router = self.router_snapshot();
        let lookup = {
            let servers = lock_std(&self.servers);
            lookup_route(
                &candidates,
                |lang| router.resolve(lang, ToolKind::Diagnostics).cloned(),
                |id| servers.client(id).map(|_| ()),
                |id| servers.is_expected(id),
                |lang| pending_catch_all(&router, &servers, lang),
                |id| servers.failure(id).cloned(),
            )
        };
        match lookup {
            RouteLookup::Registered(id, ()) => DiagnosticsRoute::Live(id),
            RouteLookup::Initializing(id) => DiagnosticsRoute::Initializing(id),
            RouteLookup::Failed(failure) => DiagnosticsRoute::FailedToStart(failure),
            RouteLookup::Dangling { server_id, .. } => {
                tracing::error!(
                    "router diagnostics route names server '{server_id}' that is neither \
                     registered nor expected"
                );
                DiagnosticsRoute::Unrouted
            }
            RouteLookup::Unrouted => self
                .startup_failure_for_candidates(&candidates, ToolKind::Diagnostics)
                .map_or(DiagnosticsRoute::Unrouted, |failure| {
                    DiagnosticsRoute::FailedToStart(Box::new(failure))
                }),
        }
    }

    /// As [`Self::diagnostics_route_for_path`], for a canonical diagnostics
    /// resource URI; a URI that does not parse is [`DiagnosticsRoute::Unrouted`].
    #[must_use]
    pub(crate) fn diagnostics_route_for_uri(
        &self,
        uri: &DiagnosticsResourceUri,
    ) -> DiagnosticsRoute {
        parse_uri(uri.as_str()).map_or(DiagnosticsRoute::Unrouted, |path| {
            self.diagnostics_route_for_path(path.as_path())
        })
    }

    /// Validate `file_path`, then resolve its routed client via
    /// [`Self::resolve_client_for_file`] (respawn-aware), without opening
    /// the document.
    ///
    /// Split out from [`Self::prepare_document`] so [`Self::prepare_gated_document`]
    /// can check the routed server's capabilities *before* `ensure_open` sends
    /// `textDocument/didOpen` -- a server rejected by the gate should never
    /// observe an open notification for a request it can't service.
    async fn resolve_validated_client_for_file(
        &self,
        file_path: &ClientPath,
        tool: ToolKind,
    ) -> Result<(ServerId, LspClient, WorkspacePath)> {
        let validated_path = self.validate_path(file_path).await?;
        let (server_id, client) = self
            .resolve_client_for_file(validated_path.as_path(), tool)
            .await?;
        Ok((server_id, client, validated_path))
    }

    /// As [`Self::resolve_validated_client_for_file`], but for a caller that
    /// already has a `&Path` it validated itself (e.g. `parse_file_uri`'s
    /// return value). `path` is trusted to already be validated -- this does
    /// *not* re-`canonicalize`/re-check it against workspace roots, unlike
    /// the `&str` overload above, which always validates an untrusted MCP
    /// input from scratch.
    async fn resolve_validated_client_for_path(
        &self,
        path: &WorkspacePath,
        tool: ToolKind,
    ) -> Result<(ServerId, LspClient, WorkspacePath)> {
        let (server_id, client) = self.resolve_client_for_file(path.as_path(), tool).await?;
        Ok((server_id, client, path.clone()))
    }

    /// Resolve the LSP client and ensure the document is open.
    ///
    /// This is the "prepare" phase shared by every LSP-round-trip handler:
    /// it validates the path, selects the client via
    /// [`Self::resolve_validated_client_for_file`] (respawn-aware), and
    /// calls `ensure_open`, which locks the document tracker's state only
    /// for the given path. The returned client and URI are owned values, so
    /// the caller can issue the actual LSP request (the "execute" phase)
    /// without holding any lock across the network round trip.
    ///
    /// `ensure_open`'s own awaits (a `stat`, optionally a re-read of the
    /// file, and the `textDocument/didOpen`/`didChange` notify) run under a
    /// lock scoped to `validated_path` alone — see [`DocumentTracker::ensure_open`]
    /// — so a slow or wedged language server cannot stall `prepare_document`
    /// calls for unrelated files. (Per-tool routing, #228, means the same
    /// file can be routed to more than one server; a wedged server-A notify
    /// still holds this path's lock and can therefore delay a healthy
    /// server-B call for that *same* file.)
    #[cfg(test)]
    pub(super) async fn prepare_document(
        &self,
        file_path: &ClientPath,
        tool: ToolKind,
    ) -> Result<PreparedDocument> {
        let path = self.validate_path(file_path).await?;
        self.prepare_document_for_path(&path, tool).await
    }

    /// As [`Self::prepare_document`], for a path that is already validated.
    pub(super) async fn prepare_document_for_path(
        &self,
        path: &WorkspacePath,
        tool: ToolKind,
    ) -> Result<PreparedDocument> {
        let (server_id, client, validated_path) =
            self.resolve_validated_client_for_path(path, tool).await?;
        self.open_prepared(server_id, client, &validated_path, Access::Use)
            .await
    }

    /// Marks `validated_path` in flight, then opens it via `ensure_open`.
    ///
    /// The guard is taken before `ensure_open` so there is no window between
    /// the path lock releasing and the guard taking effect (#503); it is
    /// dropped with the error on failure.
    pub(super) async fn open_prepared(
        &self,
        server_id: ServerId,
        client: LspClient,
        validated_path: &WorkspacePath,
        access: Access,
    ) -> Result<PreparedDocument> {
        let in_flight = self
            .document_tracker
            .mark_in_flight(validated_path.as_path());
        // Drained unconditionally, before propagating `ensure_open`'s
        // result: even on its error path (e.g. a `didOpen`/`didChange`
        // notify failure), `DocumentTracker::open` may already have evicted
        // a *different*, unrelated document and queued its `didClose` --
        // returning early via `?` before this would lose that queued close,
        // leaving the tracker desynced from that server (#495 S5).
        let result = self
            .document_tracker
            .ensure_open(OpenRequest::new(
                validated_path,
                &self.workspace_roots,
                &server_id,
                &client,
                access,
            ))
            .await;
        self.flush_pending_closes().await;
        let uri = result?;
        Ok(PreparedDocument {
            server_id,
            client,
            uri,
            path: validated_path.as_path().to_path_buf(),
            _in_flight: in_flight,
        })
    }

    /// Rejects a position whose line lies beyond the end of `doc`'s tracked
    /// content, before any LSP request is made.
    ///
    /// Runs after the gates in `prepare_gated_document`, so an indexing wait
    /// precedes the check. A document that is no longer tracked passes: its
    /// extent is unknown, and the server stays the authority.
    ///
    /// # Errors
    ///
    /// Returns [`Error::PositionBeyondDocument`] when the line is past the end.
    pub(super) fn require_line_in_document(
        &self,
        doc: &PreparedDocument,
        position: Position,
    ) -> Result<()> {
        let line = position.line();
        match self
            .document_tracker
            .line_presence(doc.path(), line.get().saturating_sub(1))
        {
            LinePresence::Present => Ok(()),
            LinePresence::Beyond { last_line } => {
                Err(Error::PositionBeyondDocument { line, last_line })
            }
            LinePresence::Untracked => {
                tracing::debug!(
                    line = line.get(),
                    "skipping the line check for an untracked document"
                );
                Ok(())
            }
        }
    }

    /// Like [`Self::prepare_document`], but checks `capability` against the
    /// routed server's `ServerCapabilities` *before* opening the document --
    /// see [`Self::resolve_client_for_file`]'s doc comment for why the
    /// ordering matters. When `indexing_gate` is
    /// [`IndexingGate::Required`], also waits for
    /// [`Self::wait_for_indexing_ready`] before opening the document, so a
    /// server still indexing never receives (or answers from) an opened
    /// document it would otherwise be asked about.
    ///
    /// # Errors
    ///
    /// Returns [`Error::CapabilityNotSupported`] if the routed server's
    /// `ServerCapabilities` explicitly does not advertise `capability`, or
    /// [`Error::WorkspaceIndexing`] if `indexing_gate` is
    /// [`IndexingGate::Required`] and the server is still indexing.
    pub(super) async fn prepare_gated_document(
        &self,
        file_path: &ClientPath,
        indexing_gate: IndexingGate,
    ) -> Result<PreparedDocument> {
        let (server_id, client, validated_path) = self
            .resolve_validated_client_for_file(file_path, indexing_gate.capability().tool_kind())
            .await?;
        self.finish_prepare_gated_document(server_id, client, validated_path, indexing_gate)
            .await
    }

    /// As [`Self::prepare_gated_document`], then rejects every one of
    /// `positions` whose line lies beyond the end of the opened document, so a
    /// tool taking a position or range treats an out-of-document line the same
    /// way whichever language server answers (#641).
    ///
    /// The line check runs after the capability and indexing gates, so a
    /// refusal by a gate comes first; characters are never rejected.
    ///
    /// # Errors
    ///
    /// The errors of [`Self::prepare_gated_document`], and
    /// [`Error::PositionBeyondDocument`] for the first position past the end.
    pub(super) async fn prepare_positioned_document(
        &self,
        file_path: &ClientPath,
        indexing_gate: IndexingGate,
        positions: &[Position],
    ) -> Result<PreparedDocument> {
        let doc = self
            .prepare_gated_document(file_path, indexing_gate)
            .await?;
        self.require_lines_in_document(&doc, positions)?;
        Ok(doc)
    }

    /// As [`Self::prepare_gated_document`], but for a caller that already
    /// has a `&Path` it validated itself (e.g. `handle_incoming_calls`/`handle_outgoing_calls`,
    /// via `parse_file_uri`) -- see [`Self::resolve_validated_client_for_path`]'s
    /// doc for why this skips re-validation.
    pub(super) async fn prepare_gated_document_for_path(
        &self,
        path: &WorkspacePath,
        indexing_gate: IndexingGate,
    ) -> Result<PreparedDocument> {
        let (server_id, client, validated_path) = self
            .resolve_validated_client_for_path(path, indexing_gate.capability().tool_kind())
            .await?;
        self.finish_prepare_gated_document(server_id, client, validated_path, indexing_gate)
            .await
    }

    /// Opens `file_path` for a name-resolving tool that discloses indexing
    /// instead of waiting for it, after the capability gate and the line check
    /// of every one of `positions`.
    ///
    /// Takes a [`DisclosedCapability`] rather than an [`IndexingGate`]: it never
    /// waits, so only the tools that disclose indexing can reach it.
    ///
    /// # Errors
    ///
    /// The errors of [`Self::prepare_positioned_document`], without the
    /// indexing wait.
    pub(super) async fn prepare_disclosed_document(
        &self,
        file_path: &ClientPath,
        capability: DisclosedCapability,
        positions: &[Position],
    ) -> Result<DisclosedDocument<'_>> {
        let capability = Capability::from(capability);
        let (server_id, client, validated_path) = self
            .resolve_validated_client_for_file(file_path, capability.tool_kind())
            .await?;
        let doc = self
            .open_checked(
                server_id,
                client,
                &validated_path,
                capability,
                IndexingWait::Skip,
            )
            .await?;
        self.require_lines_in_document(&doc, positions)?;
        Ok(DisclosedDocument::new(self, doc))
    }

    /// Checks that the server routed for `file_path` advertises `capability`,
    /// without opening the document.
    ///
    /// # Errors
    ///
    /// Returns the routing errors of [`Self::prepare_gated_document`] and
    /// [`Error::CapabilityNotSupported`].
    pub(super) async fn require_routed_capability(
        &self,
        file_path: &ClientPath,
        capability: Capability,
    ) -> Result<()> {
        let (server_id, _client, _path) = self
            .resolve_validated_client_for_file(file_path, capability.tool_kind())
            .await?;
        self.require_capability(&server_id, capability)
    }

    /// Shared tail of [`Self::prepare_gated_document`] and
    /// [`Self::prepare_gated_document_for_path`], once each has resolved and
    /// validated its own path: capability-gate, indexing-gate, then open.
    async fn finish_prepare_gated_document(
        &self,
        server_id: ServerId,
        client: LspClient,
        validated_path: WorkspacePath,
        indexing_gate: IndexingGate,
    ) -> Result<PreparedDocument> {
        let wait = match indexing_gate {
            IndexingGate::Required(_) => IndexingWait::Wait,
            IndexingGate::FileLocal(_) => IndexingWait::Skip,
        };
        self.open_checked(
            server_id,
            client,
            &validated_path,
            indexing_gate.capability(),
            wait,
        )
        .await
    }

    /// Capability-gates, optionally waits for indexing, then opens: the tail
    /// every document preparation shares.
    async fn open_checked(
        &self,
        server_id: ServerId,
        client: LspClient,
        validated_path: &WorkspacePath,
        capability: Capability,
        wait: IndexingWait,
    ) -> Result<PreparedDocument> {
        self.require_capability(&server_id, capability)?;
        if wait == IndexingWait::Wait {
            self.wait_for_indexing_ready(&server_id).await?;
        }
        self.open_prepared(server_id, client, validated_path, Access::Use)
            .await
    }

    fn require_lines_in_document(
        &self,
        doc: &PreparedDocument,
        positions: &[Position],
    ) -> Result<()> {
        positions
            .iter()
            .try_for_each(|position| self.require_line_in_document(doc, *position))
    }

    /// Sends the `textDocument/didClose` notifications still owed after
    /// [`DocumentTracker::open`]'s LRU eviction (#495), so a server's own
    /// open-document set does not keep growing even though mcpls's own
    /// tracking has stopped counting the document.
    ///
    /// `DocumentTracker` has no access to any server's [`LspClient`] --
    /// `self.servers` is the registry for that, kept one layer up in
    /// `Translator` -- so this is the chokepoint that reconciles its pending
    /// closes against it. Called after every `ensure_open` that could have
    /// triggered eviction, unconditionally, even when `ensure_open` itself
    /// returned an error, so a different, already-evicted document's close
    /// is never lost on that path (#495 S5).
    ///
    /// Claims, notifies and releases one path at a time, so a busy path is
    /// skipped (it stays pending) and no claim outlives its own notifies.
    /// The whole flush shares one [`FLUSH_PENDING_CLOSES_DEADLINE`]: it runs
    /// inline on the request path, so a wedged server must not add latency to
    /// unrelated calls. Paths not reached before the deadline stay pending.
    ///
    /// Best-effort: a failed close is logged and its debt dropped, never
    /// failing the request that triggered the eviction. A close whose send was
    /// cut short (the call was cancelled, or the deadline passed) stays owed.
    /// A wedged or dead server is respawned, and `forget_server` clears its
    /// history anyway. A server that is no longer registered is dropped the
    /// same way.
    async fn flush_pending_closes(&self) {
        let flush = async {
            for path in self.document_tracker.pending_close_paths() {
                let Some(mut claim) = self.document_tracker.try_claim_pending_close(&path) else {
                    continue;
                };
                let owed: Vec<ServerId> = claim.servers().cloned().collect();
                for server_id in owed {
                    let Some(client) = lock_std(&self.servers).client(&server_id) else {
                        claim.settle(&server_id);
                        continue;
                    };
                    let sent = client
                        .notify_typed::<lsp_types::DidCloseTextDocumentNotification>(
                            lsp_types::DidCloseTextDocumentParams {
                                text_document: lsp_types::TextDocumentIdentifier {
                                    uri: claim.uri.clone(),
                                },
                            },
                        )
                        .await;
                    claim.settle(&server_id);
                    if let Err(err) = sent {
                        tracing::warn!(
                            %server_id,
                            path = %claim.path.display(),
                            error = %ErrorChain(&err),
                            "failed to notify evicted document's server of textDocument/didClose; \
                             dropping the close"
                        );
                    }
                }
            }
        };
        if tokio::time::timeout(FLUSH_PENDING_CLOSES_DEADLINE, flush)
            .await
            .is_err()
        {
            tracing::warn!(
                deadline = ?FLUSH_PENDING_CLOSES_DEADLINE,
                "flushing evicted documents' didClose notifications hit the deadline; paths not yet \
                 reached and the in-flight path's unsent closes stay pending"
            );
        }
    }

    /// Verify the routed server advertises support for a capability before
    /// dispatching a capability-gated LSP request.
    ///
    /// Production always registers an [`LspServer`] alongside its
    /// [`LspClient`] in the same `Translator::settle_started` step, so in
    /// practice a registered client always has known capabilities. If no
    /// `LspServer` is registered for `server_id` regardless -- a client
    /// registered without its server, which only happens in tests, or a
    /// narrow window during registration where the two maps are inserted
    /// under separate locks -- the capability is assumed supported rather
    /// than blocking the request: this mirrors the graceful-degradation
    /// stance used elsewhere in `Translator` when capability information is
    /// unavailable rather than known-absent.
    ///
    /// Note: this checks the `ServerCapabilities` snapshot captured at
    /// `initialize` time. A server that advertises a capability later via
    /// `client/registerCapability` (dynamic registration) is not reflected
    /// here and will be incorrectly rejected; mcpls does not currently apply
    /// dynamic registrations back onto the stored capabilities.
    ///
    /// # Errors
    ///
    /// Returns [`Error::CapabilityNotSupported`] if the registered server's
    /// `ServerCapabilities` explicitly does not advertise `capability`.
    pub(super) fn require_capability(
        &self,
        server_id: &ServerId,
        capability: Capability,
    ) -> Result<()> {
        let servers = lock_std(&self.servers);
        check_capability(
            server_id,
            servers
                .server(server_id)
                .map(crate::lsp::LspServer::capabilities),
            capability,
        )
    }

    /// Returns true when the routed server's `codeActionProvider` capability
    /// advertises `resolveProvider: true` (per LSP 3.16, `CodeActionOptions`),
    /// meaning it will actually answer a `codeAction/resolve` follow-up
    /// request rather than merely receiving mcpls's client-side
    /// `resolve_support` advertisement (`lsp/lifecycle.rs`) with no server
    /// implementation behind it (#432).
    ///
    /// Unlike [`Self::require_capability`], an unregistered server (only
    /// possible in tests, see that method's doc comment) is treated as
    /// *not* supporting resolve rather than assumed-supported: resolve is a
    /// best-effort enhancement, so the safe default when capability
    /// information is unavailable is to skip the extra round-trip, not to
    /// risk it against a server that may not implement it.
    pub(super) fn code_action_resolve_supported(&self, server_id: &ServerId) -> bool {
        let servers = lock_std(&self.servers);
        matches!(
            servers
                .server(server_id)
                .map(crate::lsp::LspServer::capabilities)
                .and_then(|caps| caps.code_action_provider.as_ref()),
            Some(lsp_types::CodeActionProvider::CodeActionOptions(
                lsp_types::CodeActionOptions {
                    resolve_provider: Some(true),
                    ..
                }
            ))
        )
    }

    /// Parse and validate a file URI, returning the validated path.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The URI doesn't have a file:// scheme, carries an authority, or
    ///   otherwise cannot be converted to a path (see
    ///   [`crate::bridge::state::uri_to_path`])
    /// - The path is outside workspace boundaries
    pub(super) async fn parse_file_uri(&self, uri: &lsp_types::Uri) -> Result<WorkspacePath> {
        let path = crate::bridge::state::uri_to_path(uri).ok_or_else(|| {
            Error::InvalidToolParams(format!(
                "Invalid URI, expected an absolute file:// URI but got: {}",
                escape_bounded(uri.as_ref(), MAX_ECHOED_PATH_BYTES)
            ))
        })?;

        self.validate_path(&ClientPath::try_from(path)?).await
    }
}

#[cfg(test)]
mod tests {
    use std::collections::{HashMap, HashSet};
    use std::sync::Arc;
    use std::{assert_matches, fs};

    use tempfile::TempDir;
    use tokio::io::BufReader;
    use tokio::sync::Mutex;
    use tokio::time::{Duration, timeout};
    use url::Url;

    use super::*;
    use crate::bridge::translator::dto::Position;
    use crate::bridge::translator::testing::*;
    use crate::bridge::{NotificationCache, ResultContext, WorkspaceRoots};
    use crate::config::{
        DocumentLimit, FileExtension, FilePattern, IndexingReadyTimeoutSecs, LanguageId,
        LanguageMap, LspServerConfig, PositionEncodings, SearchDepth, ServerCommand, SizeLimit,
        TimeoutSecs, ToolRouter, ToolSet,
    };
    use crate::error::Error;
    use crate::lsp::LspServer;
    use crate::test_lsp::client_path;

    type JsonValue = serde_json::Value;

    #[test]
    fn test_indexing_gate_capability_is_the_gated_capability() {
        assert_eq!(
            IndexingGate::Required(Capability::Hover).capability(),
            Capability::Hover
        );
        let file_local = [
            (
                FileLocalCapability::DocumentSymbols,
                Capability::DocumentSymbols,
            ),
            (FileLocalCapability::FoldingRange, Capability::FoldingRange),
            (
                FileLocalCapability::SelectionRange,
                Capability::SelectionRange,
            ),
            (
                FileLocalCapability::DocumentHighlights,
                Capability::DocumentHighlights,
            ),
            (
                FileLocalCapability::FormatDocument,
                Capability::FormatDocument,
            ),
            (FileLocalCapability::FormatRange, Capability::FormatRange),
        ];
        for (file_local, capability) in file_local {
            assert_eq!(IndexingGate::FileLocal(file_local).capability(), capability);
        }
    }

    #[test]
    fn test_client_for_file_server_initializing_when_expected() {
        // A configured/applicable language whose LSP client has not registered
        // yet (large solution still loading via OmniSharp) must surface
        // ServerInitializing — "wait and retry" — not NoServerForLanguage.
        let path = PathBuf::from("/ws/Assets/Scripts/Player.cs");
        let lang = LanguageMap::default().detect(&path);
        let id = ServerId::from(lang.clone());

        let translator = Translator::new().with_router(ToolRouter::catch_all([(
            id.clone(),
            LanguageId::new(lang).unwrap(),
        )]));
        let mut expected = HashSet::new();
        expected.insert(id.clone());
        translator.set_expected_servers(expected);

        let err = translator
            .client_for_file(&path, ToolKind::Hover)
            .unwrap_err();
        assert_matches!(err, Error::ServerInitializing { server_id } if server_id == id);
    }

    #[test]
    fn test_client_for_file_no_server_when_not_expected() {
        // When no route is configured for the language at all, the error
        // stays NoServerForLanguage.
        let translator = Translator::new();
        let path = PathBuf::from("/ws/Assets/Scripts/Player.cs");
        let lang = translator.language_map.detect(&path);

        let err = translator
            .client_for_file(&path, ToolKind::Hover)
            .unwrap_err();
        assert_matches!(err, Error::NoServerForLanguage { ref language, .. } if *language == lang);
    }

    use crate::test_lsp::test_extensions;

    fn not_found_failure(id: &ServerId, language: &str, command: &str) -> ServerSpawnFailure {
        ServerSpawnFailure {
            server_id: id.clone(),
            language_id: LanguageId::new(language).unwrap(),
            command: ServerCommand::new(command).unwrap(),
            reason: crate::error::StartupFailure::Spawn(Arc::new(Error::ServerNotFound {
                command: ServerCommand::new(command).unwrap(),
                io: std::io::Error::from(std::io::ErrorKind::NotFound),
            })),
        }
    }

    fn router_config(
        language: &str,
        name: &str,
        handles: Option<Vec<ToolKind>>,
    ) -> LspServerConfig {
        LspServerConfig {
            language_id: LanguageId::new(language).unwrap(),
            command: ServerCommand::from_static("sh").into(),
            args: crate::config::ServerArgs::default(),
            env: crate::config::ServerEnv::default(),
            file_patterns: vec![],
            initialization_options: None,
            settings: None,
            timeout_seconds: TimeoutSecs::new(5).unwrap(),
            request_timeout_seconds: TimeoutSecs::new(5).unwrap(),
            heuristics: None,
            name: Some(ServerId::new(name).unwrap()),
            handles: handles.map(|tools| ToolSet::new(tools).unwrap()),
            indexing: crate::bridge::IndexingPolicy::Auto,
        }
    }

    /// #527: the sole server for a language failed to spawn, so the routing
    /// error carries the spawn failure and its install guidance instead of
    /// "no LSP server configured".
    #[test]
    fn test_client_for_file_reports_startup_failure_of_sole_server() {
        let id = ServerId::from_static("rust");
        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("rust"),
            )]));
        translator.record_startup_failures(&[not_found_failure(&id, "rust", "rust-analyzer")]);
        translator.rebind_router(&HashSet::new());
        translator.clear_expected_servers();

        let err = translator
            .client_for_file(Path::new("/ws/main.rs"), ToolKind::Hover)
            .unwrap_err();

        let Error::ServerFailedToStart(failure) = &err else {
            panic!("expected ServerFailedToStart, got {err:?}");
        };
        assert_eq!(failure.server_id, id);
        let message = err.to_string();
        assert!(
            message.contains("rustup component add rust-analyzer"),
            "{message}"
        );
    }

    #[test]
    fn test_client_for_file_ignores_startup_failure_of_other_language() {
        let id = ServerId::from_static("rust");
        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("rust"),
            )]));
        translator.record_startup_failures(&[not_found_failure(&id, "rust", "rust-analyzer")]);
        translator.rebind_router(&HashSet::new());
        translator.clear_expected_servers();

        let err = translator
            .client_for_file(Path::new("/ws/script.py"), ToolKind::Hover)
            .unwrap_err();

        assert_matches!(err, Error::NoServerForLanguage { .. }, "got {err:?}");
    }

    /// A failed explicit server must not mask a live catch-all it was
    /// rebound to.
    #[tokio::test]
    async fn test_client_for_file_live_catch_all_wins_over_failed_explicit_server() {
        let configs = [
            router_config("rust", "hover-only", Some(vec![ToolKind::Hover])),
            router_config("rust", "catch-all", None),
        ];
        let router = ToolRouter::from_configs(configs.iter()).unwrap();
        let hover_id = ServerId::from_static("hover-only");
        let live_id = ServerId::from_static("catch-all");

        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(router);
        let (client, _server) = fake_lsp_client();
        translator.register_client(live_id.clone(), client);
        translator.record_startup_failures(&[not_found_failure(&hover_id, "rust", "sh")]);
        translator.rebind_router(&HashSet::from([live_id.clone()]));
        translator.clear_expected_servers();

        let (id, _client) = translator
            .client_for_file(Path::new("/ws/main.rs"), ToolKind::Hover)
            .unwrap();

        assert_eq!(id, live_id);
    }

    /// A failed catch-all is reported for a tool the live explicit server
    /// does not claim.
    #[tokio::test]
    async fn test_client_for_file_reports_failed_catch_all_for_unclaimed_tool() {
        let configs = [
            router_config("rust", "hover-only", Some(vec![ToolKind::Hover])),
            router_config("rust", "catch-all", None),
        ];
        let router = ToolRouter::from_configs(configs.iter()).unwrap();
        let hover_id = ServerId::from_static("hover-only");
        let failed_id = ServerId::from_static("catch-all");

        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(router);
        let (client, _server) = fake_lsp_client();
        translator.register_client(hover_id.clone(), client);
        translator.record_startup_failures(&[not_found_failure(&failed_id, "rust", "sh")]);
        translator.rebind_router(&HashSet::from([hover_id]));
        translator.clear_expected_servers();

        let err = translator
            .client_for_file(Path::new("/ws/main.rs"), ToolKind::Definition)
            .unwrap_err();

        assert_matches!(&err, Error::ServerFailedToStart(f) if f.server_id == failed_id,
            "got {err:?}"
        );
    }

    /// `.tsx` resolves through its `typescript` base language, so a failure
    /// of the `typescript` server is reported for it too.
    #[test]
    fn test_client_for_file_reports_startup_failure_through_react_base_language() {
        let id = ServerId::from_static("typescript");
        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("typescript"),
            )]));
        translator.record_startup_failures(&[not_found_failure(
            &id,
            "typescript",
            "typescript-language-server",
        )]);
        translator.rebind_router(&HashSet::new());
        translator.clear_expected_servers();

        let err = translator
            .client_for_file(Path::new("/ws/app.tsx"), ToolKind::Hover)
            .unwrap_err();

        assert_matches!(&err, Error::ServerFailedToStart(f) if f.server_id == id,
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn test_validate_path_no_workspace_roots_rejects_any_path() {
        let translator = Translator::new();
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("test.rs");
        fs::write(&test_file, "fn main() {}").unwrap();

        // With no workspace roots configured, access is rejected (fail closed)
        let result = translator.validate_path(&client_path(test_file)).await;
        assert_matches!(result, Err(Error::NoWorkspaceRoots(_)));
    }

    #[tokio::test]
    async fn test_validate_path_within_workspace() {
        let mut translator = Translator::new();
        let temp_dir = TempDir::new().unwrap();
        let workspace_root = temp_dir.path().to_path_buf();
        translator.set_workspace_roots(WorkspaceRoots::from_paths(&[workspace_root]).unwrap());

        let test_file = temp_dir.path().join("test.rs");
        fs::write(&test_file, "fn main() {}").unwrap();

        let result = translator.validate_path(&client_path(test_file)).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_validate_path_outside_workspace() {
        let mut translator = Translator::new();
        let temp_dir1 = TempDir::new().unwrap();
        let temp_dir2 = TempDir::new().unwrap();

        // Set workspace root to temp_dir1
        translator.set_workspace_roots(
            WorkspaceRoots::from_paths(&[temp_dir1.path().to_path_buf()]).unwrap(),
        );

        // Create file in temp_dir2 (outside workspace)
        let test_file = temp_dir2.path().join("test.rs");
        fs::write(&test_file, "fn main() {}").unwrap();

        let result = translator.validate_path(&client_path(test_file)).await;
        assert_matches!(result, Err(Error::PathOutsideWorkspace(_)));
    }

    /// #533: an outside path that does not exist must be rejected as outside
    /// the workspace, not leak its absence as `FileIo`.
    #[test]
    fn test_validate_path_nonexistent_outside_path_is_outside_workspace() {
        let root = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        let roots = WorkspaceRoots::from_paths(&[root.path().to_path_buf()]).unwrap();

        let result = roots
            .validate_blocking(&client_path(outside.path().join("missing.rs")))
            .map(crate::bridge::WorkspacePath::into_path_buf);

        assert_matches!(result, Err(Error::PathOutsideWorkspace(_)));
    }

    #[test]
    fn test_validate_path_dotdot_escape_is_outside_workspace() {
        let root = TempDir::new().unwrap();
        let roots = WorkspaceRoots::from_paths(&[root.path().to_path_buf()]).unwrap();

        let result = roots
            .validate_blocking(&client_path(root.path().join("../escape.rs")))
            .map(crate::bridge::WorkspacePath::into_path_buf);

        assert_matches!(result, Err(Error::PathOutsideWorkspace(_)));
    }

    #[test]
    fn test_validate_path_dot_segments_inside_root_are_accepted() {
        let root = TempDir::new().unwrap();
        fs::create_dir(root.path().join("a")).unwrap();
        fs::write(root.path().join("b.rs"), "").unwrap();
        let roots = WorkspaceRoots::from_paths(&[root.path().to_path_buf()]).unwrap();

        let result = roots
            .validate_blocking(&client_path(root.path().join("./a/../b.rs")))
            .map(crate::bridge::WorkspacePath::into_path_buf);

        assert_eq!(
            result.unwrap(),
            dunce::canonicalize(root.path().join("b.rs")).unwrap()
        );
    }

    /// A client naming the workspace through a symlinked alias of the
    /// canonical root is admitted when the alias was precomputed.
    #[cfg(unix)]
    #[test]
    fn test_validate_path_symlink_alias_of_root_is_accepted() {
        let AliasFixture {
            dir: _dir,
            real,
            alias,
            roots,
        } = alias_fixture();
        fs::write(real.join("a.rs"), "").unwrap();

        let result = roots
            .validate_blocking(&client_path(alias.join("a.rs")))
            .map(crate::bridge::WorkspacePath::into_path_buf);

        assert_eq!(
            result.unwrap(),
            dunce::canonicalize(real.join("a.rs")).unwrap()
        );
    }

    /// `..` right after an alias root leaves both the alias and the canonical
    /// root, so the pre-check rejects it.
    #[cfg(unix)]
    #[test]
    fn test_validate_path_dotdot_after_alias_root_is_outside_workspace() {
        let AliasFixture {
            dir, alias, roots, ..
        } = alias_fixture();
        fs::write(dir.path().join("outside.rs"), "").unwrap();

        let result = roots
            .validate_blocking(&client_path(alias.join("../outside.rs")))
            .map(crate::bridge::WorkspacePath::into_path_buf);

        assert_matches!(result, Err(Error::PathOutsideWorkspace(_)));
    }

    /// Inside an alias root the pre-check admits the path, so a missing file
    /// is a plain I/O error.
    #[cfg(unix)]
    #[test]
    fn test_validate_path_missing_file_under_alias_root_is_file_io() {
        let AliasFixture {
            dir: _dir,
            alias,
            roots,
            ..
        } = alias_fixture();

        let result = roots
            .validate_blocking(&client_path(alias.join("missing.rs")))
            .map(crate::bridge::WorkspacePath::into_path_buf);

        assert_matches!(result, Err(Error::FileIo { .. }), "{result:?}");
    }

    /// A symlink inside an alias root that escapes the workspace is still
    /// rejected by the canonical check.
    #[cfg(unix)]
    #[test]
    fn test_validate_path_escaping_symlink_under_alias_root_is_outside_workspace() {
        let AliasFixture {
            dir: _dir,
            real,
            alias,
            roots,
        } = alias_fixture();
        let outside = TempDir::new().unwrap();
        fs::write(outside.path().join("secret.rs"), "").unwrap();
        std::os::unix::fs::symlink(outside.path(), real.join("link")).unwrap();

        let result = roots
            .validate_blocking(&client_path(alias.join("link/secret.rs")))
            .map(crate::bridge::WorkspacePath::into_path_buf);

        assert_matches!(result, Err(Error::PathOutsideWorkspace(_)));
    }

    /// A symlink inside the root pointing outside passes the lexical
    /// pre-check but must still fail the authoritative canonical check.
    #[cfg(unix)]
    #[test]
    fn test_validate_path_symlink_escaping_root_is_outside_workspace() {
        let root = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        fs::write(outside.path().join("secret.rs"), "").unwrap();
        std::os::unix::fs::symlink(outside.path(), root.path().join("link")).unwrap();
        let roots = WorkspaceRoots::from_paths(&[root.path().to_path_buf()]).unwrap();

        let result = roots
            .validate_blocking(&client_path(root.path().join("link/secret.rs")))
            .map(crate::bridge::WorkspacePath::into_path_buf);

        assert_matches!(result, Err(Error::PathOutsideWorkspace(_)));
    }

    /// Regression guard: `prepare_gated_document`'s `&str` overload (used by
    /// `handle_hover` and nearly every other gated handler) must still
    /// reject an out-of-workspace path end-to-end, i.e.
    /// `resolve_validated_client_for_file` must validate independently
    /// rather than ever delegating to the `&Path` overload (whose
    /// `resolve_validated_client_for_path` sibling trusts its caller to have
    /// already validated and does not check workspace roots itself). Pins
    /// down a near-miss caught during the #423/#425 refactor, where
    /// `prepare_gated_document` briefly delegated through the `&Path`
    /// overload and would have silently skipped this check for every
    /// `&str`-based handler.
    #[tokio::test]
    async fn test_handle_hover_blocked_when_path_outside_workspace() {
        let workspace_dir = TempDir::new().unwrap();
        let outside_dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &workspace_dir,
            &server_id,
            lsp_types::ServerCapabilities {
                hover_provider: Some(lsp_types::HoverProvider::Bool(true)),
                ..Default::default()
            },
        );

        let outside_path = outside_dir.path().join("outside.rs");
        fs::write(&outside_path, "fn outside() {}").unwrap();

        let result = translator
            .handle_hover(
                client_path(outside_path.to_string_lossy().into_owned()),
                pos(1, 1),
            )
            .await;

        assert_matches!(result, Err(Error::PathOutsideWorkspace(_)));
    }

    #[tokio::test]
    async fn test_parse_file_uri_invalid_scheme() {
        let translator = Translator::new();
        let uri: lsp_types::Uri = lsp_types::Uri::from("http://example.com/file.rs");
        let result = translator.parse_file_uri(&uri).await;
        assert_matches!(result, Err(Error::InvalidToolParams(_)));
    }

    #[tokio::test]
    async fn test_parse_file_uri_valid_scheme() {
        let mut translator = Translator::new();
        let temp_dir = TempDir::new().unwrap();
        translator.set_workspace_roots(
            WorkspaceRoots::from_paths(&[temp_dir.path().to_path_buf()]).unwrap(),
        );
        let test_file = temp_dir.path().join("test.rs");
        fs::write(&test_file, "fn main() {}").unwrap();

        // Use url crate for cross-platform file URI creation
        let file_url = Url::from_file_path(&test_file).unwrap();
        let uri: lsp_types::Uri = lsp_types::Uri::from(file_url.as_str());
        let result = translator.parse_file_uri(&uri).await;
        assert!(result.is_ok());
    }

    /// #411 regression: a raw-sliced (non-decoded) URI keeps `%20`/`%C3%A9`
    /// literally in the path, so `canonicalize()` fails with `ENOENT` for
    /// any file whose path contains a space or a non-ASCII character, even
    /// though the file exists. `parse_file_uri` must percent-decode first.
    #[tokio::test]
    async fn test_parse_file_uri_percent_decodes_space_and_non_ascii() {
        let mut translator = Translator::new();
        let temp_dir = TempDir::new().unwrap();
        translator.set_workspace_roots(
            WorkspaceRoots::from_paths(&[temp_dir.path().to_path_buf()]).unwrap(),
        );
        let test_file = temp_dir.path().join("my file café.rs");
        fs::write(&test_file, "fn main() {}").unwrap();

        let file_url = Url::from_file_path(&test_file).unwrap();
        assert!(
            file_url.as_str().contains("%20"),
            "test fixture must exercise percent-encoding"
        );
        let uri: lsp_types::Uri = lsp_types::Uri::from(file_url.as_str());
        let result = translator.parse_file_uri(&uri).await.unwrap();
        assert_eq!(result.as_path(), dunce::canonicalize(&test_file).unwrap());
    }

    /// #411: an authority-bearing `file://` URI (e.g. `file://host/path`)
    /// must be rejected, not silently resolved to a path relative to the
    /// process's cwd -- see `uri_to_path`'s authority check.
    #[tokio::test]
    async fn test_parse_file_uri_rejects_authority() {
        let translator = Translator::new();
        let uri: lsp_types::Uri = lsp_types::Uri::from("file://host/some/path.rs");
        let result = translator.parse_file_uri(&uri).await;
        assert_matches!(result, Err(Error::InvalidToolParams(_)));
    }

    #[test]
    fn test_client_for_file_uses_custom_extension() {
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("script.nu");
        fs::write(&test_file, "echo hello").unwrap();

        let mut extension_map = HashMap::new();
        extension_map.insert(
            FileExtension::from_static("nu"),
            LanguageId::from_static("nushell"),
        );

        let translator = Translator::new().with_extensions(extension_map);

        let result = translator.client_for_file(&test_file, ToolKind::Hover);

        assert!(result.is_err());
        if let Err(Error::NoServerForLanguage { language, file, .. }) = result {
            assert_eq!(language, "nushell");
            assert_eq!(file, FileKey::Extension(FileExtension::from_static("nu")));
        } else {
            panic!("Expected NoServerForLanguage(nushell) error");
        }
    }

    #[test]
    fn test_client_for_file_reports_an_extensionless_name() {
        let mut language_map = LanguageMap::default();
        language_map.insert(
            crate::config::PatternTarget::Name(crate::config::FileName::from_static("Makefile")),
            LanguageId::from_static("make"),
        );
        let translator = Translator::new().with_extensions(language_map);

        let result = translator.client_for_file(Path::new("/ws/Makefile"), ToolKind::Hover);
        assert_matches!(
            result,
            Err(Error::NoServerForLanguage { language, .. }) if language == "make"
        );

        let result = translator.client_for_file(Path::new("/ws/Dockerfile"), ToolKind::Hover);
        assert_matches!(
            result,
            Err(Error::NoServerForLanguage { file: FileKey::Name(name), .. }) if name == "Dockerfile"
        );
    }

    #[test]
    fn test_client_for_file_falls_back_to_default() {
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("unknown.xyz");
        fs::write(&test_file, "content").unwrap();

        let mut extension_map = HashMap::new();
        extension_map.insert(
            FileExtension::from_static("rs"),
            LanguageId::from_static("rust"),
        );

        let translator = Translator::new()
            .with_extensions(extension_map)
            .with_file_patterns([FilePattern::from_static("**/*.rs")]);

        let result = translator.client_for_file(&test_file, ToolKind::Hover);

        assert!(result.is_err());
        if let Err(Error::NoServerForLanguage {
            language,
            file,
            patterns,
        }) = result
        {
            assert_eq!(language, "plaintext");
            assert_eq!(file, FileKey::Extension(FileExtension::from_static("xyz")));
            assert_eq!(&*patterns, [FilePattern::from_static("**/*.rs")]);
        } else {
            panic!("Expected NoServerForLanguage(plaintext) error");
        }
    }

    #[test]
    fn test_client_for_file_routes_tsx_to_typescript_server() {
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("component.tsx");
        fs::write(&test_file, "export const Component = () => <div />").unwrap();

        let mut extension_map = HashMap::new();
        extension_map.insert(
            FileExtension::from_static("tsx"),
            LanguageId::from_static("typescriptreact"),
        );

        let translator = Translator::new()
            .with_extensions(extension_map)
            .with_router(ToolRouter::catch_all([(
                ServerId::from_static("typescript"),
                LanguageId::from_static("typescript"),
            )]));
        translator.register_client(
            ServerId::from_static("typescript"),
            LspClient::new(crate::config::LspServerConfig::typescript()),
        );

        let (_id, client) = translator
            .client_for_file(&test_file, ToolKind::Hover)
            .unwrap();
        assert_eq!(client.language_id(), "typescript");
    }

    #[test]
    fn test_client_for_file_prefers_exact_react_server() {
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("component.tsx");
        fs::write(&test_file, "export const Component = () => <div />").unwrap();

        let mut extension_map = HashMap::new();
        extension_map.insert(
            FileExtension::from_static("tsx"),
            LanguageId::from_static("typescriptreact"),
        );

        let typescript_react_config = crate::config::LspServerConfig {
            language_id: LanguageId::from_static("typescriptreact"),
            command: ServerCommand::from_static("typescript-language-server").into(),
            args: crate::config::ServerArgs::try_from(vec!["--stdio".to_string()]).unwrap(),
            env: crate::config::ServerEnv::default(),
            file_patterns: vec![FilePattern::from_static("**/*.tsx")],
            initialization_options: None,
            settings: None,
            timeout_seconds: TimeoutSecs::new(30).unwrap(),
            request_timeout_seconds: TimeoutSecs::new(30).unwrap(),
            heuristics: None,
            name: None,
            handles: None,
            indexing: crate::bridge::IndexingPolicy::Auto,
        };

        let translator = Translator::new()
            .with_extensions(extension_map)
            .with_router(ToolRouter::catch_all([
                (
                    ServerId::from_static("typescript"),
                    LanguageId::from_static("typescript"),
                ),
                (
                    ServerId::from_static("typescriptreact"),
                    LanguageId::from_static("typescriptreact"),
                ),
            ]));
        translator.register_client(
            ServerId::from_static("typescript"),
            LspClient::new(crate::config::LspServerConfig::typescript()),
        );
        translator.register_client(
            ServerId::from(LanguageId::from_static("typescriptreact")),
            LspClient::new(typescript_react_config),
        );

        let (_id, client) = translator
            .client_for_file(&test_file, ToolKind::Hover)
            .unwrap();
        assert_eq!(client.language_id(), "typescriptreact");
    }

    /// #359: a registered server's route id stays resolvable (it is what the
    /// push-degraded flag is keyed on) across a respawn, which swaps the
    /// client behind the id without unregistering it.
    #[test]
    fn test_diagnostics_route_for_path_live_when_registered() {
        let id = ServerId::from_static("rust");
        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("rust"),
            )]));
        translator.register_client(
            id.clone(),
            LspClient::new(crate::config::LspServerConfig::rust_analyzer()),
        );

        let route = translator.diagnostics_route_for_path(Path::new("/ws/main.rs"));

        assert_matches!(&route, DiagnosticsRoute::Live(live) if *live == id,
            "{route:?}"
        );
        assert_eq!(route.server_id(), Some(&id));
        assert_eq!(route.into_read_result().unwrap(), Some(id));
    }

    /// A routed server that is expected but not yet registered reads as
    /// retryable "still starting", not as an empty cache.
    #[test]
    fn test_diagnostics_route_for_path_initializing_while_expected() {
        let id = ServerId::from_static("rust");
        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("rust"),
            )]));
        translator.set_expected_servers(HashSet::from([id.clone()]));

        let route = translator.diagnostics_route_for_path(Path::new("/ws/main.rs"));

        assert_matches!(&route, DiagnosticsRoute::Initializing(i) if *i == id,
            "{route:?}"
        );
        assert_eq!(route.server_id(), Some(&id));
        let err = route.into_read_result().unwrap_err();
        assert_matches!(&err, Error::ServerInitializing { server_id } if *server_id == id,
            "{err:?}"
        );
    }

    /// #535: a server that failed to start is reported, not read as empty.
    #[test]
    fn test_diagnostics_route_for_path_failed_to_start() {
        let id = ServerId::from_static("rust");
        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("rust"),
            )]));
        translator.record_startup_failures(&[not_found_failure(&id, "rust", "rust-analyzer")]);
        translator.rebind_router(&HashSet::new());
        translator.clear_expected_servers();

        let route = translator.diagnostics_route_for_path(Path::new("/ws/main.rs"));

        assert!(route.is_failed(), "{route:?}");
        assert_eq!(route.server_id(), None);
        let err = route.into_read_result().unwrap_err();
        assert_matches!(&err, Error::ServerFailedToStart(f) if f.server_id == id,
            "{err:?}"
        );
    }

    /// A language with no configured route is unrouted, and the failure of an
    /// unrelated language's server does not leak into it.
    #[test]
    fn test_diagnostics_route_for_path_unrouted_reads_empty() {
        let id = ServerId::from_static("rust");
        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("rust"),
            )]));
        translator.record_startup_failures(&[not_found_failure(&id, "rust", "rust-analyzer")]);
        translator.rebind_router(&HashSet::new());
        translator.clear_expected_servers();

        let route = translator.diagnostics_route_for_path(Path::new("/ws/script.py"));

        assert_matches!(route, DiagnosticsRoute::Unrouted, "{route:?}");
        assert_eq!(route.into_read_result().unwrap(), None);
    }

    /// A router entry naming a server that is neither registered nor expected
    /// is logged and treated as unrouted.
    #[test]
    fn test_diagnostics_route_for_path_dangling_is_unrouted() {
        let id = ServerId::from_static("rust");
        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(ToolRouter::catch_all([(
                id,
                LanguageId::from_static("rust"),
            )]));

        let route = translator.diagnostics_route_for_path(Path::new("/ws/main.rs"));

        assert_matches!(route, DiagnosticsRoute::Unrouted, "{route:?}");
    }

    /// A live catch-all the router was rebound to beats a failed explicit
    /// server, as for `client_for_file`.
    #[tokio::test]
    async fn test_diagnostics_route_for_path_live_catch_all_wins_over_failed_explicit_server() {
        let configs = [
            router_config("rust", "diag-only", Some(vec![ToolKind::Diagnostics])),
            router_config("rust", "catch-all", None),
        ];
        let router = ToolRouter::from_configs(configs.iter()).unwrap();
        let failed_id = ServerId::from_static("diag-only");
        let live_id = ServerId::from_static("catch-all");
        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(router);
        let (client, _server) = fake_lsp_client();
        translator.register_client(live_id.clone(), client);
        translator.record_startup_failures(&[not_found_failure(&failed_id, "rust", "sh")]);
        translator.rebind_router(&HashSet::from([live_id.clone()]));
        translator.clear_expected_servers();

        let route = translator.diagnostics_route_for_path(Path::new("/ws/main.rs"));

        assert_matches!(&route, DiagnosticsRoute::Live(id) if *id == live_id,
            "{route:?}"
        );
    }

    /// The failure is found through the React base language, like routing.
    #[test]
    fn test_diagnostics_route_for_path_reports_failure_through_react_base_language() {
        let id = ServerId::from_static("typescript");
        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("typescript"),
            )]));
        translator.record_startup_failures(&[not_found_failure(
            &id,
            "typescript",
            "typescript-language-server",
        )]);
        translator.rebind_router(&HashSet::new());
        translator.clear_expected_servers();

        let route = translator.diagnostics_route_for_path(Path::new("/ws/app.tsx"));

        assert_matches!(&route, DiagnosticsRoute::FailedToStart(f) if f.server_id == id,
            "{route:?}"
        );
    }

    /// A failed server whose route excludes diagnostics is not the diagnostics
    /// route, so its failure must not surface for diagnostics reads.
    #[test]
    fn test_diagnostics_route_for_path_ignores_failure_of_server_without_diagnostics_route() {
        let configs = [router_config(
            "rust",
            "hover-only",
            Some(vec![ToolKind::Hover]),
        )];
        let router = ToolRouter::from_configs(configs.iter()).unwrap();
        let failed = ServerId::from_static("hover-only");
        let translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(router);
        translator.record_startup_failures(&[not_found_failure(&failed, "rust", "sh")]);
        translator.rebind_router(&HashSet::new());
        translator.clear_expected_servers();

        let route = translator.diagnostics_route_for_path(Path::new("/ws/main.rs"));

        assert_matches!(route, DiagnosticsRoute::Unrouted, "{route:?}");
    }

    /// The live pull path (`get_diagnostics`) also reports the failure.
    #[tokio::test]
    async fn test_handle_diagnostics_reports_failed_server_start() {
        let dir = TempDir::new().unwrap();
        let file = dunce::canonicalize(dir.path()).unwrap().join("main.rs");
        fs::write(&file, "fn main() {}").unwrap();
        let id = ServerId::from_static("rust");
        let mut translator = Translator::new()
            .with_extensions(test_extensions())
            .with_router(ToolRouter::catch_all([(
                id.clone(),
                LanguageId::from_static("rust"),
            )]));
        translator
            .set_workspace_roots(WorkspaceRoots::from_paths(&[dir.path().to_path_buf()]).unwrap());
        translator.record_startup_failures(&[not_found_failure(&id, "rust", "sh")]);
        translator.rebind_router(&HashSet::new());
        translator.clear_expected_servers();
        let cache = Mutex::new(crate::bridge::NotificationCache::new());

        let err = translator
            .handle_diagnostics(
                client_path(file.to_string_lossy().into_owned()),
                ResultContext::None,
                &cache,
            )
            .await
            .unwrap_err();

        assert_matches!(&err, Error::ServerFailedToStart(f) if f.server_id == id,
            "got {err:?}"
        );
    }

    /// `dir/real` (the canonical root) with `dir/alias` symlinked to it, and
    /// roots admitting both spellings.
    #[cfg(unix)]
    struct AliasFixture {
        dir: TempDir,
        real: PathBuf,
        alias: PathBuf,
        roots: WorkspaceRoots,
    }

    #[cfg(unix)]
    fn alias_fixture() -> AliasFixture {
        let dir = TempDir::new().unwrap();
        let real = dir.path().join("real");
        fs::create_dir(&real).unwrap();
        let alias = dir.path().join("alias");
        std::os::unix::fs::symlink(&real, &alias).unwrap();
        let roots = WorkspaceRoots::from_paths(std::slice::from_ref(&alias)).unwrap();
        AliasFixture {
            dir,
            real,
            alias,
            roots,
        }
    }

    #[test]
    fn test_client_for_file_routes_jsx_to_javascript_server() {
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("component.jsx");
        fs::write(&test_file, "export const Component = () => <div />").unwrap();

        let mut extension_map = HashMap::new();
        extension_map.insert(
            FileExtension::from_static("jsx"),
            LanguageId::from_static("javascriptreact"),
        );

        let javascript_config = crate::config::LspServerConfig {
            language_id: LanguageId::from_static("javascript"),
            command: ServerCommand::from_static("typescript-language-server").into(),
            args: crate::config::ServerArgs::try_from(vec!["--stdio".to_string()]).unwrap(),
            env: crate::config::ServerEnv::default(),
            file_patterns: vec![
                FilePattern::from_static("**/*.js"),
                FilePattern::from_static("**/*.jsx"),
            ],
            initialization_options: None,
            settings: None,
            timeout_seconds: TimeoutSecs::new(30).unwrap(),
            request_timeout_seconds: TimeoutSecs::new(30).unwrap(),
            heuristics: None,
            name: None,
            handles: None,
            indexing: crate::bridge::IndexingPolicy::Auto,
        };
        let translator = Translator::new()
            .with_extensions(extension_map)
            .with_router(ToolRouter::catch_all([(
                ServerId::from_static("javascript"),
                LanguageId::from_static("javascript"),
            )]));
        translator.register_client(
            ServerId::from_static("javascript"),
            LspClient::new(javascript_config),
        );

        let (_id, client) = translator
            .client_for_file(&test_file, ToolKind::Hover)
            .unwrap();
        assert_eq!(client.language_id(), "javascript");
    }

    #[tokio::test]
    async fn test_serve_initializes_translator_with_extensions() {
        use crate::config::{LanguageExtensionMapping, WorkspaceConfig};

        let language_extensions = vec![
            LanguageExtensionMapping {
                extensions: vec![FileExtension::from_static("nu")],
                language_id: LanguageId::from_static("nushell"),
            },
            LanguageExtensionMapping {
                extensions: vec![FileExtension::from_static("rs")],
                language_id: LanguageId::from_static("rust"),
            },
        ];

        let config = crate::config::ServerConfig {
            mcp: crate::config::McpConfig::default(),
            workspace: WorkspaceConfig {
                roots: vec![crate::config::ConfiguredRoot::new("/tmp/test-workspace").unwrap()],
                position_encodings: PositionEncodings::DEFAULT,
                language_extensions: language_extensions.clone(),
                heuristics_max_depth: SearchDepth::DEFAULT,
                max_documents: DocumentLimit::DEFAULT,
                max_file_size: SizeLimit::DEFAULT,
                indexing_ready_timeout_seconds: IndexingReadyTimeoutSecs::DEFAULT,
                max_concurrent_server_starts: crate::config::ServerStartConcurrency::DEFAULT,
            },
            lsp_servers: vec![],
            project_config_status: crate::ProjectConfigStatus::NotIgnored,
            workspace_trust: crate::config::WorkspaceTrust::default(),
        };

        let language_map = config.build_effective_language_map();
        assert_eq!(language_map.detect(Path::new("a.nu")), "nushell");
        assert_eq!(language_map.detect(Path::new("a.rs")), "rust");

        // serve() starts in protocol-only mode when no LSP servers are configured;
        // it may return a transport error but must not report a startup failure.
        let result = crate::serve(config).await;
        if let Err(ref err) = result {
            assert!(
                !matches!(err, crate::error::Error::AllServersFailedToInit { .. }),
                "serve() must not report init failures for empty lsp_servers config"
            );
        }
    }

    #[tokio::test]
    async fn test_concurrent_handlers_on_different_files_do_not_serialize() {
        // Before the fix, Translator was shared as Arc<Mutex<Translator>>, so
        // handling one LSP request held that lock across the `.await` on the
        // response -- blocking every other tool call, even for a completely
        // different file and language server, until the first request
        // completed or timed out (up to 30s). With interior mutability, a
        // concurrent call for a different file must complete without waiting
        // on an unrelated in-flight request.
        let dir = TempDir::new().unwrap();
        let mut extensions = HashMap::new();
        extensions.insert(
            FileExtension::from_static("aa"),
            LanguageId::from_static("lang_a"),
        );
        extensions.insert(
            FileExtension::from_static("bb"),
            LanguageId::from_static("lang_b"),
        );

        let mut translator =
            Translator::new()
                .with_extensions(extensions)
                .with_router(ToolRouter::catch_all([
                    (
                        ServerId::from_static("lang_a"),
                        LanguageId::from_static("lang_a"),
                    ),
                    (
                        ServerId::from_static("lang_b"),
                        LanguageId::from_static("lang_b"),
                    ),
                ]));
        translator
            .set_workspace_roots(WorkspaceRoots::from_paths(&[dir.path().to_path_buf()]).unwrap());

        let (client_a, mut server_a) = fake_lsp_client();
        let (client_b, mut server_b) = fake_lsp_client();
        translator.register_client(ServerId::from_static("lang_a"), client_a);
        translator.register_client(ServerId::from_static("lang_b"), client_b);

        let path_a = dir.path().join("file.aa");
        let path_b = dir.path().join("file.bb");
        fs::write(&path_a, "content a").unwrap();
        fs::write(&path_b, "content b").unwrap();

        let translator = Arc::new(translator);

        // `server_a` is never given a response, simulating a slow server. If
        // any translator-held lock still spanned the LSP round trip, this
        // task blocking forever would also block the "fast" call below.
        let slow = {
            let translator = Arc::clone(&translator);
            let path = path_a.to_string_lossy().to_string();
            tokio::spawn(async move {
                translator
                    .handle_hover(client_path(path), Position::at(1, 1))
                    .await
            })
        };

        // Wait for the slow task to actually reach its LSP request (i.e. the
        // request bytes were written to the wire) before treating it as
        // "in-flight", so the test doesn't race the spawned task's startup.
        let mut wire_a = BufReader::new(&mut server_a.write_stdout);
        let opened_a = read_framed_message(&mut wire_a).await;
        assert_eq!(opened_a["method"], "textDocument/didOpen");
        let hover_request_a = read_framed_message(&mut wire_a).await;
        assert_eq!(hover_request_a["method"], "textDocument/hover");

        // The fast path: a concurrent call for a different file/server.
        let fast = {
            let translator = Arc::clone(&translator);
            let path = path_b.to_string_lossy().to_string();
            tokio::spawn(async move {
                translator
                    .handle_hover(client_path(path), Position::at(1, 1))
                    .await
            })
        };

        let mut wire_b = BufReader::new(&mut server_b.write_stdout);
        let opened_b = read_framed_message(&mut wire_b).await;
        assert_eq!(opened_b["method"], "textDocument/didOpen");
        let hover_request_b = read_framed_message(&mut wire_b).await;
        assert_eq!(hover_request_b["method"], "textDocument/hover");
        write_response(
            &mut server_b.read_half_stdin,
            &hover_request_b["id"],
            JsonValue::Null,
        )
        .await;

        let fast_result = timeout(Duration::from_secs(2), fast)
            .await
            .expect("fast call must not be blocked by the slow in-flight request")
            .unwrap();
        assert!(fast_result.is_ok());

        assert!(
            !slow.is_finished(),
            "slow call should still be waiting on its (never-sent) response"
        );
        slow.abort();
    }

    #[tokio::test]
    async fn test_concurrent_ensure_open_same_path_sends_single_did_open() {
        // Regression test: concurrent handler calls for the SAME path must
        // serialize on that path's `ensure_open` lock (see `DocumentTracker::lock_path`)
        // so they can't both observe "not open yet" and both send didOpen.
        let dir = TempDir::new().unwrap();
        let mut extensions = HashMap::new();
        extensions.insert(
            FileExtension::from_static("aa"),
            LanguageId::from_static("lang_a"),
        );

        let mut translator =
            Translator::new()
                .with_extensions(extensions)
                .with_router(ToolRouter::catch_all([(
                    ServerId::from_static("lang_a"),
                    LanguageId::from_static("lang_a"),
                )]));
        translator
            .set_workspace_roots(WorkspaceRoots::from_paths(&[dir.path().to_path_buf()]).unwrap());

        let (client, mut server) = fake_lsp_client();
        translator.register_client(ServerId::from_static("lang_a"), client);

        let path = dir.path().join("file.aa");
        fs::write(&path, "content").unwrap();

        let concurrent_calls = 4;

        let translator = Arc::new(translator);
        let path_str = path.to_string_lossy().to_string();

        let handles: Vec<_> = (0..concurrent_calls)
            .map(|_| {
                let translator = Arc::clone(&translator);
                let path_str = path_str.clone();
                tokio::spawn(async move {
                    translator
                        .handle_hover(client_path(path_str), Position::at(1, 1))
                        .await
                })
            })
            .collect();

        let mut wire = BufReader::new(&mut server.write_stdout);
        let opened = read_framed_message(&mut wire).await;
        assert_eq!(opened["method"], "textDocument/didOpen");

        for _ in 0..concurrent_calls {
            let request = read_framed_message(&mut wire).await;
            assert_eq!(
                request["method"], "textDocument/hover",
                "no second didOpen must appear ahead of the hover requests"
            );
            write_response(&mut server.read_half_stdin, &request["id"], JsonValue::Null).await;
        }

        for handle in handles {
            let result = timeout(Duration::from_secs(2), handle)
                .await
                .expect("handler call should not hang")
                .unwrap();
            assert!(result.is_ok());
        }
    }

    /// Translator routing `.aa` files to one fake server, tracking at most one
    /// document so a second open must evict or be refused.
    fn single_document_translator(dir: &TempDir) -> (Translator, crate::test_lsp::FakeServer) {
        use crate::bridge::state::ResourceLimits;

        let mut extensions = HashMap::new();
        extensions.insert(
            FileExtension::from_static("aa"),
            LanguageId::from_static("lang_a"),
        );

        let mut translator = Translator::new()
            .with_extensions(extensions)
            .with_router(ToolRouter::catch_all([(
                ServerId::from_static("lang_a"),
                LanguageId::from_static("lang_a"),
            )]))
            .with_resource_limits(ResourceLimits {
                max_documents: DocumentLimit::new(1),
                max_file_size: SizeLimit::UNLIMITED,
            });
        translator
            .set_workspace_roots(WorkspaceRoots::from_paths(&[dir.path().to_path_buf()]).unwrap());

        let (client, server) = fake_lsp_client();
        translator.register_client(ServerId::from_static("lang_a"), client);
        (translator, server)
    }

    /// #515: a close that fails for one server must not stop the other
    /// server's close, and the failed debt is dropped, not re-owed.
    #[tokio::test]
    async fn test_flush_pending_closes_drops_failed_servers_debt() {
        let dir = TempDir::new().unwrap();
        let (translator, mut server_a) = single_document_translator(&dir);
        let (client_d, _server_d) = fake_lsp_client();

        let tracker = &translator.document_tracker;
        let path = dir.path().join("p.aa");
        std::fs::write(&path, "p").unwrap();
        let other = dir.path().join("q.aa");
        std::fs::write(&other, "q").unwrap();
        let client_a = lock_std(&translator.servers)
            .client(&ServerId::from_static("lang_a"))
            .unwrap();
        tracker
            .ensure_open_for_test(&path, &ServerId::from_static("lang_a"), &client_a)
            .await
            .unwrap();
        tracker
            .ensure_open_for_test(&path, &ServerId::from_static("lang_d"), &client_d)
            .await
            .unwrap();
        tracker
            .ensure_open_for_test(&other, &ServerId::from_static("lang_a"), &client_a)
            .await
            .unwrap();

        translator.register_client(ServerId::from_static("lang_d"), client_d.clone());
        client_d.shutdown().await.unwrap();

        translator.flush_pending_closes().await;

        let mut wire = tokio::io::BufReader::new(&mut server_a.write_stdout);
        for method in [
            "textDocument/didOpen",
            "textDocument/didOpen",
            "textDocument/didClose",
        ] {
            assert_eq!(read_framed_message(&mut wire).await["method"], method);
        }
        assert!(
            tracker.pending_close_paths().is_empty(),
            "a failed close is dropped, not re-owed"
        );
    }

    /// #687 FR-027: a flush abandoned while it waits on one server leaves
    /// every close it did not deliver owed, and none it delivered.
    #[tokio::test(start_paused = true)]
    async fn test_flush_pending_closes_dropped_midway_keeps_undelivered_closes_owed() {
        let dir = TempDir::new().unwrap();
        let (translator, mut server_a) = single_document_translator(&dir);
        let (client_d, _probe_d) =
            LspClient::with_command_channel(crate::config::LspServerConfig::rust_analyzer(), 2);
        let (a, d) = (
            ServerId::from_static("lang_a"),
            ServerId::from_static("lang_d"),
        );

        let tracker = &translator.document_tracker;
        let path = dir.path().join("p.aa");
        std::fs::write(&path, "p").unwrap();
        let other = dir.path().join("q.aa");
        std::fs::write(&other, "q").unwrap();
        let client_a = lock_std(&translator.servers).client(&a).unwrap();
        tracker
            .ensure_open_for_test(&path, &a, &client_a)
            .await
            .unwrap();
        tracker
            .ensure_open_for_test(&path, &d, &client_d)
            .await
            .unwrap();
        tracker
            .ensure_open_for_test(&other, &a, &client_a)
            .await
            .unwrap();
        translator.register_client(d.clone(), client_d.clone());
        client_d
            .notify("test/fill", serde_json::json!({}))
            .await
            .unwrap();

        {
            let flush = translator.flush_pending_closes();
            let mut flush = std::pin::pin!(flush);
            assert!(futures::poll!(flush.as_mut()).is_pending());
        }

        let mut wire = tokio::io::BufReader::with_capacity(1, &mut server_a.write_stdout);
        for method in ["textDocument/didOpen", "textDocument/didOpen"] {
            assert_eq!(read_framed_message(&mut wire).await["method"], method);
        }
        let a_close_delivered =
            tokio::time::timeout(Duration::from_millis(100), read_framed_message(&mut wire))
                .await
                .is_ok();
        let owed: Vec<ServerId> = tracker
            .try_claim_pending_close(&path)
            .unwrap()
            .servers()
            .cloned()
            .collect();
        assert!(
            owed.contains(&d),
            "the close nobody delivered must stay owed"
        );
        assert_eq!(
            owed.contains(&a),
            !a_close_delivered,
            "a close is owed exactly when it was not delivered: {owed:?}"
        );
    }

    /// #495: once `DocumentTracker::open`'s LRU eviction reclaims a document
    /// to make room under `max_documents`, `prepare_document` must notify
    /// that document's server with `textDocument/didClose` -- `DocumentTracker`
    /// itself has no `LspClient` access to do this, so it's `Translator`'s
    /// job (`flush_pending_closes`) once `ensure_open` returns.
    #[tokio::test]
    async fn test_prepare_document_sends_didclose_for_evicted_document() {
        let dir = TempDir::new().unwrap();
        let (translator, mut server) = single_document_translator(&dir);

        let path_a = dir.path().join("a.aa");
        fs::write(&path_a, "content a").unwrap();
        let path_b = dir.path().join("b.aa");
        fs::write(&path_b, "content b").unwrap();

        drop(
            translator
                .prepare_document(
                    &client_path(path_a.to_string_lossy().into_owned()),
                    ToolKind::Hover,
                )
                .await
                .unwrap(),
        );

        let mut wire = BufReader::new(&mut server.write_stdout);
        let opened_a = read_framed_message(&mut wire).await;
        assert_eq!(opened_a["method"], "textDocument/didOpen");

        drop(
            translator
                .prepare_document(
                    &client_path(path_b.to_string_lossy().into_owned()),
                    ToolKind::Hover,
                )
                .await
                .unwrap(),
        );

        let opened_b = read_framed_message(&mut wire).await;
        assert_eq!(opened_b["method"], "textDocument/didOpen");
        let closed_a = read_framed_message(&mut wire).await;
        assert_eq!(
            closed_a["method"], "textDocument/didClose",
            "evicting `a` to make room for `b` under max_documents: 1 must notify its server"
        );
        assert_eq!(
            closed_a["params"]["textDocument"]["uri"], opened_a["params"]["textDocument"]["uri"],
            "the didClose must name the evicted document, not the newly opened one"
        );
    }

    /// #503: a handler still holding its `PreparedDocument` (i.e. mid LSP
    /// round-trip) keeps that document out of eviction, so a concurrent
    /// `prepare_document` for another path at `max_documents: 1` fails with
    /// `DocumentLimitExceeded` instead of evicting it; once the first
    /// `PreparedDocument` drops, the second path opens and evicts the first.
    #[tokio::test]
    async fn test_prepared_document_blocks_eviction_until_dropped() {
        let dir = TempDir::new().unwrap();
        let (translator, _server) = single_document_translator(&dir);

        let path_a = dir.path().join("a.aa");
        fs::write(&path_a, "content a").unwrap();
        let path_b = dir.path().join("b.aa");
        fs::write(&path_b, "content b").unwrap();

        let doc_a = translator
            .prepare_document(
                &client_path(path_a.to_string_lossy().into_owned()),
                ToolKind::Hover,
            )
            .await
            .unwrap();

        let err = translator
            .prepare_document(
                &client_path(path_b.to_string_lossy().into_owned()),
                ToolKind::Hover,
            )
            .await
            .unwrap_err();
        assert_matches!(err, Error::DocumentLimitExceeded { .. });

        drop(doc_a);
        drop(
            translator
                .prepare_document(
                    &client_path(path_b.to_string_lossy().into_owned()),
                    ToolKind::Hover,
                )
                .await
                .unwrap(),
        );
    }

    /// #503: two handlers holding the same path concurrently each own a
    /// guard; the path stays protected until the *second* one drops.
    #[tokio::test]
    async fn test_two_prepared_documents_on_same_path_are_refcounted() {
        let dir = TempDir::new().unwrap();
        let (translator, _server) = single_document_translator(&dir);

        let path_a = dir.path().join("a.aa");
        fs::write(&path_a, "content a").unwrap();
        let path_b = dir.path().join("b.aa");
        fs::write(&path_b, "content b").unwrap();
        let canonical_a = dunce::canonicalize(&path_a).unwrap();

        let first = translator
            .prepare_document(
                &client_path(path_a.to_string_lossy().into_owned()),
                ToolKind::Hover,
            )
            .await
            .unwrap();
        let second = translator
            .prepare_document(
                &client_path(path_a.to_string_lossy().into_owned()),
                ToolKind::Hover,
            )
            .await
            .unwrap();
        assert_eq!(translator.document_tracker.in_flight_count(&canonical_a), 2);

        drop(first);
        let err = translator
            .prepare_document(
                &client_path(path_b.to_string_lossy().into_owned()),
                ToolKind::Hover,
            )
            .await
            .unwrap_err();
        assert_matches!(err, Error::DocumentLimitExceeded { .. });

        drop(second);
        assert_eq!(translator.document_tracker.in_flight_count(&canonical_a), 0);
        drop(
            translator
                .prepare_document(
                    &client_path(path_b.to_string_lossy().into_owned()),
                    ToolKind::Hover,
                )
                .await
                .unwrap(),
        );
    }

    /// #503: when `ensure_open` fails, `prepare_document` returns the error
    /// without leaving the path marked in flight.
    #[tokio::test]
    async fn test_prepare_document_releases_in_flight_guard_when_ensure_open_fails() {
        let dir = TempDir::new().unwrap();
        let mut extensions = HashMap::new();
        extensions.insert(
            FileExtension::from_static("bb"),
            LanguageId::from_static("lang_b"),
        );

        let mut translator =
            Translator::new()
                .with_extensions(extensions)
                .with_router(ToolRouter::catch_all([(
                    ServerId::from_static("lang_b"),
                    LanguageId::from_static("lang_b"),
                )]));
        translator
            .set_workspace_roots(WorkspaceRoots::from_paths(&[dir.path().to_path_buf()]).unwrap());

        let (client, _server) = fake_lsp_client();
        translator.register_client(ServerId::from_static("lang_b"), client.clone());

        let path_b = dir.path().join("b.bb");
        fs::write(&path_b, "content b").unwrap();
        let canonical_b = dunce::canonicalize(&path_b).unwrap();

        client.shutdown().await.unwrap();
        let err = translator
            .prepare_document(
                &client_path(path_b.to_string_lossy().into_owned()),
                ToolKind::Hover,
            )
            .await
            .unwrap_err();

        assert_matches!(err, Error::ServerTerminated);
        assert_eq!(translator.document_tracker.in_flight_count(&canonical_b), 0);
    }

    /// #495 S5: even when `ensure_open` itself fails for the document being
    /// opened (here: its own `didOpen` notify fails), a `didClose` already
    /// queued for a *different* document evicted earlier in that same call
    /// must still be sent -- `prepare_document` must not lose it by
    /// returning early via `?` before flushing pending closes. Uses two
    /// separate servers (`lang_a` stays healthy, `lang_b`'s connection is
    /// broken) so the evicted document's own `didClose` delivery can be
    /// observed independently of the failure that aborts this call.
    #[tokio::test]
    async fn test_prepare_document_still_sends_didclose_when_ensure_open_itself_fails() {
        use crate::bridge::state::ResourceLimits;

        let dir = TempDir::new().unwrap();
        let mut extensions = HashMap::new();
        extensions.insert(
            FileExtension::from_static("aa"),
            LanguageId::from_static("lang_a"),
        );
        extensions.insert(
            FileExtension::from_static("bb"),
            LanguageId::from_static("lang_b"),
        );

        let mut translator = Translator::new()
            .with_extensions(extensions)
            .with_router(ToolRouter::catch_all([
                (
                    ServerId::from_static("lang_a"),
                    LanguageId::from_static("lang_a"),
                ),
                (
                    ServerId::from_static("lang_b"),
                    LanguageId::from_static("lang_b"),
                ),
            ]))
            .with_resource_limits(ResourceLimits {
                max_documents: DocumentLimit::new(1),
                max_file_size: SizeLimit::UNLIMITED,
            });
        translator
            .set_workspace_roots(WorkspaceRoots::from_paths(&[dir.path().to_path_buf()]).unwrap());

        let (client_a, mut server_a) = fake_lsp_client();
        translator.register_client(ServerId::from_static("lang_a"), client_a);
        let (client_b, _server_b) = fake_lsp_client();
        translator.register_client(ServerId::from_static("lang_b"), client_b.clone());

        let path_a = dir.path().join("a.aa");
        fs::write(&path_a, "content a").unwrap();
        let path_b = dir.path().join("b.bb");
        fs::write(&path_b, "content b").unwrap();

        drop(
            translator
                .prepare_document(
                    &client_path(path_a.to_string_lossy().into_owned()),
                    ToolKind::Hover,
                )
                .await
                .unwrap(),
        );

        let mut wire_a = BufReader::new(&mut server_a.write_stdout);
        let opened_a = read_framed_message(&mut wire_a).await;
        assert_eq!(opened_a["method"], "textDocument/didOpen");

        // Break only `lang_b`'s connection -- see
        // `test_first_open_self_heals_when_did_open_notify_fails` (state.rs)
        // for why shutting down a clone deterministically fails the next
        // `notify()` on any other clone of the same client.
        client_b.shutdown().await.unwrap();

        let err = translator
            .prepare_document(
                &client_path(path_b.to_string_lossy().into_owned()),
                ToolKind::Hover,
            )
            .await
            .unwrap_err();
        assert_matches!(err, Error::ServerTerminated);

        // `a` was evicted (LRU, to make room for `b`) before `b`'s own
        // notify failed, and its didClose must still have gone out on
        // `lang_a`'s still-healthy connection.
        let closed_a = read_framed_message(&mut wire_a).await;
        assert_eq!(closed_a["method"], "textDocument/didClose");
        assert_eq!(
            closed_a["params"]["textDocument"]["uri"],
            opened_a["params"]["textDocument"]["uri"]
        );
    }

    /// #174 §12's own headline dispatch scenario: "pyright/pylsp fixture --
    /// hover -> pyright, diagnostics -> pylsp, rename (unclaimed) ->
    /// `NoServerForTool`", exercised through `Translator`'s public handlers
    /// end to end rather than through `ToolRouter`'s unit tests alone.
    #[tokio::test]
    async fn test_dispatch_routes_hover_and_diagnostics_to_different_servers() {
        let dir = TempDir::new().unwrap();
        let mut extensions = HashMap::new();
        extensions.insert(
            FileExtension::from_static("py"),
            LanguageId::from_static("python"),
        );

        let pyright_id = ServerId::from_static("pyright");
        let pylsp_id = ServerId::from_static("pylsp");
        let pyright = LspServerConfig {
            language_id: LanguageId::from_static("python"),
            command: ServerCommand::from_static("pyright-langserver").into(),
            args: crate::config::ServerArgs::default(),
            env: crate::config::ServerEnv::default(),
            file_patterns: vec![],
            initialization_options: None,
            settings: None,
            timeout_seconds: TimeoutSecs::new(30).unwrap(),
            request_timeout_seconds: TimeoutSecs::new(30).unwrap(),
            heuristics: None,
            name: Some(ServerId::from_static("pyright")),
            handles: Some(ToolSet::single(ToolKind::Hover)),
            indexing: crate::bridge::IndexingPolicy::Auto,
        };
        let pylsp = LspServerConfig {
            command: ServerCommand::from_static("pylsp").into(),
            name: Some(ServerId::from_static("pylsp")),
            handles: Some(ToolSet::single(ToolKind::Diagnostics)),
            ..pyright.clone()
        };
        let configs = vec![pyright, pylsp];
        let router = ToolRouter::from_configs(&configs).unwrap();

        let mut translator = Translator::new()
            .with_extensions(extensions)
            .with_router(router);
        translator
            .set_workspace_roots(WorkspaceRoots::from_paths(&[dir.path().to_path_buf()]).unwrap());

        let (client_pyright, mut server_pyright) = fake_lsp_client();
        let (client_pylsp, mut server_pylsp) = fake_lsp_client();
        translator.register_client(pyright_id, client_pyright);
        translator.register_client(pylsp_id, client_pylsp);

        let path = dir.path().join("main.py");
        fs::write(&path, "x = 1").unwrap();
        let file = client_path(&path);

        let translator = Arc::new(translator);

        // rename is claimed by neither server -> NoServerForTool, checked
        // first so it can't be masked by either server's wire state.
        let rename_result = translator
            .handle_rename(
                file.clone(),
                pos(1, 1),
                crate::bridge::NewName::new("renamed").unwrap(),
            )
            .await;
        assert_matches!(
            rename_result,
            Err(Error::NoServerForTool {
                tool: ToolKind::Rename,
                ..
            }),
            "expected NoServerForTool for rename, got {rename_result:?}"
        );

        // hover must route to pyright: didOpen + hover request on its wire.
        let hover = {
            let translator = Arc::clone(&translator);
            let file = file.clone();
            tokio::spawn(async move { translator.handle_hover(file, pos(1, 1)).await })
        };
        let mut wire_pyright = BufReader::new(&mut server_pyright.write_stdout);
        let opened = read_framed_message(&mut wire_pyright).await;
        assert_eq!(opened["method"], "textDocument/didOpen");
        let hover_request = read_framed_message(&mut wire_pyright).await;
        assert_eq!(hover_request["method"], "textDocument/hover");
        write_response(
            &mut server_pyright.read_half_stdin,
            &hover_request["id"],
            JsonValue::Null,
        )
        .await;
        hover
            .await
            .unwrap()
            .expect("hover routed to pyright must succeed");

        // diagnostics must route to pylsp, independently of pyright: its own
        // didOpen (a second server's first sync of the same path) followed
        // by the diagnostic request on pylsp's wire, never pyright's.
        let diagnostics = {
            let translator = Arc::clone(&translator);
            let notification_cache = Arc::new(Mutex::new(NotificationCache::new()));
            tokio::spawn(async move {
                translator
                    .handle_diagnostics(file, ResultContext::None, &notification_cache)
                    .await
            })
        };
        let mut wire_pylsp = BufReader::new(&mut server_pylsp.write_stdout);
        let opened = read_framed_message(&mut wire_pylsp).await;
        assert_eq!(opened["method"], "textDocument/didOpen");
        let diag_request = read_framed_message(&mut wire_pylsp).await;
        assert_eq!(diag_request["method"], "textDocument/diagnostic");
        // Routing is proven by the request landing on pylsp's wire; abort
        // rather than crafting a well-formed DocumentDiagnosticReportResult.
        diagnostics.abort();
    }

    /// No `LspServer` registered for `server_id` (only a raw `LspClient`, as
    /// most tests in this module do) -- capability is unknown, so the gate
    /// must not block the request.
    #[test]
    fn test_require_capability_ok_when_server_not_registered() {
        let translator = Translator::new();
        let result =
            translator.require_capability(&ServerId::from_static("rust"), Capability::Rename);
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_require_capability_ok_when_capability_present() {
        let translator = Translator::new();
        let server_id = ServerId::from_static("rust");
        let caps = lsp_types::ServerCapabilities {
            rename_provider: Some(lsp_types::RenameProvider::Bool(true)),
            ..Default::default()
        };
        translator.register_server(server_id.clone(), LspServer::new_for_test(caps));

        let result = translator.require_capability(&server_id, Capability::Rename);
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_require_capability_err_when_capability_absent() {
        let translator = Translator::new();
        let server_id = ServerId::from_static("rust");
        let caps = lsp_types::ServerCapabilities::default();
        translator.register_server(server_id.clone(), LspServer::new_for_test(caps));

        let result = translator.require_capability(&server_id, Capability::Rename);
        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::Rename,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_rename_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_rename(
                client_path(path.to_string_lossy().into_owned()),
                Position::at(1, 1),
                crate::bridge::NewName::new("renamed").unwrap(),
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::Rename,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_code_actions_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_code_actions(
                client_path(path.to_string_lossy().into_owned()),
                bounded(Position::at(1, 1), Position::at(1, 5)),
                None,
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::CodeActions,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_signature_help_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_signature_help(
                client_path(path.to_string_lossy().into_owned()),
                Position::at(1, 1),
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::SignatureHelp,
                ..
            })
        );
    }

    /// `handle_incoming_calls` resolves its server via `client_for_file`
    /// directly (not `prepare_document`), a separate code path from the other
    /// gated handlers -- exercise it explicitly.
    #[tokio::test]
    async fn test_handle_incoming_calls_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();
        let uri = Url::from_file_path(&path).unwrap().to_string();

        let item = serde_json::json!({
            "name": "test_function",
            "kind": 12,
            "uri": uri,
            "range": {
                "start": {"line": 1, "character": 1},
                "end": {"line": 1, "character": 10}
            },
            "selectionRange": {
                "start": {"line": 1, "character": 1},
                "end": {"line": 1, "character": 10}
            }
        });

        let result = translator
            .handle_incoming_calls(checked_hierarchy_item(item))
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::CallHierarchy,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_outgoing_calls_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();
        let uri = Url::from_file_path(&path).unwrap().to_string();

        let item = serde_json::json!({
            "name": "test_function",
            "kind": 12,
            "uri": uri,
            "range": {
                "start": {"line": 1, "character": 1},
                "end": {"line": 1, "character": 10}
            },
            "selectionRange": {
                "start": {"line": 1, "character": 1},
                "end": {"line": 1, "character": 10}
            }
        });

        let result = translator
            .handle_outgoing_calls(checked_hierarchy_item(item))
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::CallHierarchy,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_format_document_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_format_document(
                client_path(path.to_string_lossy().into_owned()),
                crate::bridge::TabSize::default(),
                true,
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::FormatDocument,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_call_hierarchy_prepare_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_call_hierarchy_prepare(
                client_path(path.to_string_lossy().into_owned()),
                Position::at(1, 1),
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::CallHierarchy,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_inlay_hints_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_inlay_hints(
                client_path(path.to_string_lossy().into_owned()),
                span(Position::at(1, 1), Position::at(10, 1)),
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::InlayHints,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_hover_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_hover(
                client_path(path.to_string_lossy().into_owned()),
                Position::at(1, 1),
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::Hover,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_definition_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_definition(
                client_path(path.to_string_lossy().into_owned()),
                Position::at(1, 1),
                ResultContext::None,
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::Definition,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_references_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_references(
                client_path(path.to_string_lossy().into_owned()),
                Position::at(1, 1),
                false,
                ResultContext::None,
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::References,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_completions_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_completions(
                client_path(path.to_string_lossy().into_owned()),
                Position::at(1, 1),
                None,
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::Completions,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_document_symbols_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_document_symbols(client_path(path.to_string_lossy().into_owned()))
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::DocumentSymbols,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_workspace_symbol_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let result = translator
            .handle_workspace_symbol("main".to_string(), None, 100)
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::WorkspaceSymbols,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_implementation_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_implementation(
                client_path(path.to_string_lossy().into_owned()),
                Position::at(1, 1),
                ResultContext::None,
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::Implementation,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_type_definition_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_type_definition(
                client_path(path.to_string_lossy().into_owned()),
                Position::at(1, 1),
                ResultContext::None,
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::TypeDefinition,
                ..
            })
        );
    }

    #[tokio::test]
    async fn test_handle_declaration_blocked_when_capability_not_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let (translator, _server) = translator_with_capabilities(
            &dir,
            &server_id,
            lsp_types::ServerCapabilities::default(),
        );

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let result = translator
            .handle_declaration(
                client_path(&path),
                Position::at(1, 1),
                crate::bridge::ResultContext::None,
            )
            .await;

        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::Declaration,
                ..
            })
        );
    }

    /// Explicit `Some(RenameProvider::Bool(false))` -- as distinct from an absent
    /// (`None`) field -- must also be rejected: some servers advertise a
    /// provider field with an explicit `false` rather than omitting it.
    #[tokio::test]
    async fn test_require_capability_err_when_capability_explicitly_false() {
        let translator = Translator::new();
        let server_id = ServerId::from_static("rust");
        let caps = lsp_types::ServerCapabilities {
            rename_provider: Some(lsp_types::RenameProvider::Bool(false)),
            ..Default::default()
        };
        translator.register_server(server_id.clone(), LspServer::new_for_test(caps));

        let result = translator.require_capability(&server_id, Capability::Rename);
        assert_matches!(
            result,
            Err(Error::CapabilityNotSupported {
                capability: Capability::Rename,
                ..
            })
        );
    }

    /// Positive path: when the routed server *does* advertise the gated
    /// capability, the gate must let the request proceed into dispatch rather
    /// than short-circuiting with `CapabilityNotSupported`. Drives the fake
    /// wire to answer the request so the call completes quickly instead of
    /// idling out its internal 30s request timeout.
    #[tokio::test]
    async fn test_handle_rename_proceeds_when_capability_supported() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from_static("rust");
        let caps = lsp_types::ServerCapabilities {
            rename_provider: Some(lsp_types::RenameProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, mut server) = translator_with_capabilities(&dir, &server_id, caps);

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();
        let path_str = path.to_string_lossy().to_string();

        let translator = Arc::new(translator);
        let handle = {
            let translator = Arc::clone(&translator);
            tokio::spawn(async move {
                translator
                    .handle_rename(
                        client_path(path_str),
                        Position::at(1, 1),
                        crate::bridge::NewName::new("renamed").unwrap(),
                    )
                    .await
            })
        };

        let mut wire = BufReader::new(&mut server.write_stdout);
        let opened = read_framed_message(&mut wire).await;
        assert_eq!(opened["method"], "textDocument/didOpen");
        let rename_request = read_framed_message(&mut wire).await;
        assert_eq!(rename_request["method"], "textDocument/rename");
        write_response(
            &mut server.read_half_stdin,
            &rename_request["id"],
            JsonValue::Null,
        )
        .await;

        let result = timeout(Duration::from_secs(2), handle)
            .await
            .expect("handler call should not hang")
            .unwrap();

        assert!(
            !matches!(result, Err(Error::CapabilityNotSupported { .. })),
            "capability is supported, gate must not block dispatch, got {result:?}"
        );
        assert!(
            result.is_ok(),
            "fake server answered, expected Ok: {result:?}"
        );
    }

    /// `forms` are the provider forms that advertise the capability.
    fn assert_gates_on_provider_forms<P>(
        supported: impl Fn(Option<P>) -> bool,
        forms: impl IntoIterator<Item = P>,
        disabled: P,
    ) {
        for form in forms {
            assert!(supported(Some(form)));
        }
        assert!(!supported(Some(disabled)));
        assert!(!supported(None));
    }

    #[test]
    fn selection_range_capability_gates_on_every_provider_form() {
        use lsp_types::SelectionRangeProvider as Provider;

        assert_gates_on_provider_forms(
            |provider| {
                Capability::SelectionRange.is_supported(&lsp_types::ServerCapabilities {
                    selection_range_provider: provider,
                    ..Default::default()
                })
            },
            [
                Provider::Bool(true),
                Provider::SelectionRangeOptions(lsp_types::SelectionRangeOptions::default()),
                Provider::SelectionRangeRegistrationOptions(
                    lsp_types::SelectionRangeRegistrationOptions::default(),
                ),
            ],
            Provider::Bool(false),
        );
    }

    #[test]
    fn folding_range_capability_gates_on_every_provider_form() {
        use lsp_types::FoldingRangeProvider as Provider;

        assert_gates_on_provider_forms(
            |provider| {
                Capability::FoldingRange.is_supported(&lsp_types::ServerCapabilities {
                    folding_range_provider: provider,
                    ..Default::default()
                })
            },
            [
                Provider::Bool(true),
                Provider::FoldingRangeOptions(lsp_types::FoldingRangeOptions::default()),
                Provider::FoldingRangeRegistrationOptions(
                    lsp_types::FoldingRangeRegistrationOptions::default(),
                ),
            ],
            Provider::Bool(false),
        );
    }
}