mcpls-core 0.6.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
//! Document state management.
//!
//! Tracks open documents and their versions for LSP synchronization.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex as StdMutex};
use std::time::{Duration, SystemTime};

use lsp_types::{
    DidChangeTextDocumentNotification, DidChangeTextDocumentParams,
    DidOpenTextDocumentNotification, DidOpenTextDocumentParams, TextDocumentContentChangeEvent,
    TextDocumentItem, Uri, VersionedTextDocumentIdentifier,
};
use tokio::fs;
use tokio::io::{AsyncBufReadExt, AsyncReadExt};
use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};
use tokio::time::Instant;
use url::Url;

use super::lock_std;
use crate::config::ServerId;
use crate::error::{Error, Result};
use crate::lsp::LspClient;
use crate::util::{BoundedReadOutcome, bounded_read_cap, check_bounded_utf8};

/// Debounce window for re-reading a file's content when its mtime is not yet
/// [`mtime_settled`]. The stat itself is never debounced -- only this
/// (comparatively expensive) content re-read is rate-limited, so a burst of
/// calls against a genuinely changed file still resyncs on the first stat
/// that observes the new `(mtime, size)`.
///
/// This only bounds the *stable-but-unsettled* case: the same `(mtime,
/// size)` observed repeatedly while that mtime is still within
/// [`MTIME_GRANULARITY`] of "now". A file whose `(mtime, size)` changes on
/// every stat is never debounced at all -- each such call already disagrees
/// with the cached snapshot, so it always takes the immediate re-read path
/// regardless of how recently the last one happened.
const DISK_CHECK_DEBOUNCE: Duration = Duration::from_millis(250);

/// Filesystem mtime granularity margin: covers FAT/exFAT (2s) and is a safe
/// superset of HFS+/ext3/APFS (1s or finer). An mtime observed more recently
/// than this cannot be trusted to distinguish "unchanged" from "rewritten
/// within the same tick", so such entries are re-verified by content compare
/// instead of by stat alone -- this is what closes the racy-rewrite gap.
const MTIME_GRANULARITY: Duration = Duration::from_secs(2);

/// Returns whether `mtime` is old enough, relative to `read_at`, that a write
/// landing after `read_at` could not have preserved it.
///
/// `read_at` must be captured *before* the filesystem is stat'd (not after any
/// subsequent read), otherwise a write racing the read itself could produce a
/// new mtime that still appears "settled" against a later timestamp.
fn mtime_settled(mtime: Option<SystemTime>, read_at: SystemTime) -> bool {
    mtime.is_some_and(|m| {
        m.checked_add(MTIME_GRANULARITY)
            .is_some_and(|t| t <= read_at)
    })
}

/// Rejects `file` unless its Win32 file type is `FILE_TYPE_DISK`, the
/// Windows equivalent of the Unix `fstat`-based regular-file check in
/// [`DocumentTracker::open_checked`]. `std::fs::Metadata::is_file()` alone
/// is not a reliable rejection for every special path on Windows (e.g.
/// reserved device names like `CON`, `COM1`, `NUL`); those can still block
/// indefinitely on read, so this bounds the read -- not the open itself,
/// which Win32 has no non-blocking equivalent for (see #442).
#[cfg(windows)]
fn check_disk_file_type(file: &fs::File, path: &Path) -> Result<()> {
    use std::os::windows::io::AsRawHandle;

    use windows_sys::Win32::Storage::FileSystem::{FILE_TYPE_DISK, GetFileType};

    #[allow(unsafe_code)]
    // SAFETY: `file` is a valid, still-open handle just obtained from open(); GetFileType's only precondition.
    let file_type = unsafe { GetFileType(file.as_raw_handle().cast()) };

    if file_type != FILE_TYPE_DISK {
        return Err(Error::NotARegularFile(path.to_path_buf()));
    }
    Ok(())
}

/// A snapshot of a document's on-disk filesystem state, captured the last
/// time its content was actually read and compared.
///
/// [`DocumentTracker::ensure_open`] stats the file on every call; when the
/// stat matches this snapshot and [`Self::mtime_settled`] holds, the cached
/// content is trusted without touching the file's bytes again. This is what
/// keeps the common "file unchanged" path cheap while still detecting
/// external edits (git checkout/stash, formatters, the MCP host's own
/// edits) made outside mcpls.
#[derive(Debug, Clone, Copy)]
pub struct DiskSync {
    /// Last observed modification time, or `None` if the filesystem or
    /// platform does not report one (in which case the entry is never
    /// treated as settled, forcing a content re-read outside the debounce
    /// window).
    pub mtime: Option<SystemTime>,
    /// Last observed file size in bytes.
    pub size: u64,
    /// Whether `mtime` was already old enough, relative to when it was
    /// observed, that a same-tick rewrite could not have preserved it.
    pub mtime_settled: bool,
    /// When the file's content was last actually re-read and compared.
    ///
    /// Used only to debounce the content re-read on a racy (not-yet-settled)
    /// entry; deliberately excluded from equality so two otherwise-identical
    /// snapshots don't compare unequal merely because they were checked at
    /// different instants.
    pub content_checked_at: Instant,
}

impl PartialEq for DiskSync {
    fn eq(&self, other: &Self) -> bool {
        self.mtime == other.mtime
            && self.size == other.size
            && self.mtime_settled == other.mtime_settled
    }
}

impl Eq for DiskSync {}

/// State of a single document.
///
/// All fields are private. `DocumentTracker::open` (via `Self::new`)
/// establishes the initial state: `version` starts at 1, `disk` provenance
/// starts `None`, and no server is recorded as synced. From there, every
/// mutation goes through a dedicated method (`apply_local_edit`,
/// `commit_reload`, `set_disk`, `mark_synced`, `forget_server`) rather than a
/// partial field write, so within a single tracked lifetime `version` (see
/// [`Self::version`]) only increases. This does not cover re-opening: calling
/// `DocumentTracker::open` again for an already-tracked path unconditionally
/// replaces the entry, resetting `version` to 1 and clearing `synced` -- see
/// that method's docs.
///
/// The `disk` provenance invariant: `None` means the content's on-disk
/// provenance is unknown (it came from an in-memory `open`/`update` call, not
/// a verified disk read), so `ensure_open` must always re-verify by content
/// compare rather than trusting a stat match. `DiskSync`'s hand-written
/// `PartialEq` excludes `content_checked_at` (see that field's doc comment),
/// and that exclusion propagates here: two `DocumentState`s can compare
/// equal via this struct's own hand-written `PartialEq`/`Eq` (below) despite
/// having been disk-verified at different instants. This is intentional --
/// `content_checked_at` is a debounce timer, not part of a document's
/// logical state. `last_accessed` (also excluded, for the same reason) is
/// likewise not logical state, just an LRU-eviction timestamp (#495).
#[derive(Debug, Clone)]
pub struct DocumentState {
    uri: Uri,
    language_id: String,
    version: i32,
    content: String,
    disk: Option<DiskSync>,
    synced: HashMap<ServerId, i32>,
    /// When this document was last accessed via `ensure_open`/`update`
    /// (`Self::touch`), used to pick the least-recently-used entry when
    /// `DocumentTracker::open` must evict to stay under
    /// `ResourceLimits::max_documents` (#495).
    last_accessed: Instant,
}

impl PartialEq for DocumentState {
    fn eq(&self, other: &Self) -> bool {
        // Destructured (rather than plain field access) so a future new
        // field fails to compile here until it's deliberately included or
        // excluded -- unlike a derived impl, hand-written equality gets no
        // such reminder for free.
        let Self {
            uri,
            language_id,
            version,
            content,
            disk,
            synced,
            last_accessed: _,
        } = self;
        *uri == other.uri
            && *language_id == other.language_id
            && *version == other.version
            && *content == other.content
            && *disk == other.disk
            && *synced == other.synced
    }
}

impl Eq for DocumentState {}

impl DocumentState {
    /// Creates a new document state at version 1, with unknown disk
    /// provenance and no server yet recorded as synced.
    fn new(uri: Uri, language_id: String, content: String) -> Self {
        Self {
            uri,
            language_id,
            version: 1,
            content,
            disk: None,
            synced: HashMap::new(),
            last_accessed: Instant::now(),
        }
    }

    /// Marks this document as just accessed, for LRU eviction ordering under
    /// `ResourceLimits::max_documents` (#495).
    fn touch(&mut self) {
        self.last_accessed = Instant::now();
    }

    /// Document URI.
    #[must_use]
    pub const fn uri(&self) -> &Uri {
        &self.uri
    }

    /// Language identifier.
    #[must_use]
    pub fn language_id(&self) -> &str {
        &self.language_id
    }

    /// Document version. Monotonically increasing: every mutation that
    /// changes `content` (`apply_local_edit`, `commit_reload`) also bumps
    /// this, and never decreases it.
    #[must_use]
    pub const fn version(&self) -> i32 {
        self.version
    }

    /// Document content.
    #[must_use]
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Filesystem snapshot as of the last time `content` was read from disk.
    /// See the struct-level docs for the meaning of `None`.
    const fn disk(&self) -> Option<DiskSync> {
        self.disk
    }

    /// Last document version pushed to `server` via `didOpen`/`didChange`,
    /// or `None` if `server` has never seen this document.
    ///
    /// A single document can be synced to multiple servers (e.g. hover
    /// routed to one server, diagnostics to another for the same language),
    /// each needing its own `didOpen`/`didChange` history -- a server absent
    /// from this map has never seen the document and must receive
    /// `didOpen`, not `didChange`, on its next `ensure_open` call.
    #[must_use]
    pub fn synced_version(&self, server: &ServerId) -> Option<i32> {
        self.synced.get(server).copied()
    }

    /// Whether no server has ever synced this document.
    fn has_never_synced(&self) -> bool {
        self.synced.is_empty()
    }

    /// Applies a local (non-disk) edit: bumps `version`, replaces `content`,
    /// and clears `disk` provenance, since the new content did not come from
    /// a verified disk read. Returns the new version.
    fn apply_local_edit(&mut self, content: String) -> i32 {
        self.version += 1;
        self.content = content;
        self.disk = None;
        self.version
    }

    /// Commits a disk-verified reload: sets `version`, `content`, and `disk`
    /// together. `version` must be no less than the current version,
    /// preserving the monotonicity invariant. (Not strictly greater: the
    /// caller computes `version` via `saturating_add`, which can legitimately
    /// clamp to the current value at `i32::MAX`.)
    fn commit_reload(&mut self, version: i32, content: String, snap: Option<DiskSync>) {
        debug_assert!(
            version >= self.version,
            "document version must be monotonically increasing"
        );
        self.version = version;
        self.content = content;
        self.disk = snap;
    }

    /// Sets the disk snapshot without changing `content` or `version`.
    const fn set_disk(&mut self, snap: DiskSync) {
        self.disk = Some(snap);
    }

    /// Records that `server` has synced up to `version`.
    fn mark_synced(&mut self, server: ServerId, version: i32) {
        self.synced.insert(server, version);
    }

    /// Forgets `server`'s sync history for this document.
    fn forget_server(&mut self, server: &ServerId) {
        self.synced.remove(server);
    }
}

/// Default value for [`ResourceLimits::max_documents`], also used as the
/// TOML default for `workspace.max_documents` (`config::default_max_documents`).
pub const DEFAULT_MAX_DOCUMENTS: usize = 100;

/// Default value for [`ResourceLimits::max_file_size`] (10MB), also used as
/// the TOML default for `workspace.max_file_size` (`config::default_max_file_size`).
pub const DEFAULT_MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;

/// Resource limits for document tracking.
#[derive(Debug, Clone, Copy)]
pub struct ResourceLimits {
    /// Maximum number of open documents (0 = unlimited).
    pub max_documents: usize,
    /// Maximum file size in bytes (0 = unlimited).
    pub max_file_size: u64,
}

impl Default for ResourceLimits {
    fn default() -> Self {
        Self {
            max_documents: DEFAULT_MAX_DOCUMENTS,
            max_file_size: DEFAULT_MAX_FILE_SIZE,
        }
    }
}

/// Nominal charge for a [`DocumentTracker::read_line_checked`] call whose
/// [`DocumentTracker::open_checked`] failed (path doesn't exist, isn't a
/// regular file, or already exceeds `max_file_size`) -- zero bytes were
/// actually scanned, but charging a literal `0` would let a response naming
/// many nonexistent paths (a routine, non-attacker-controlled LSP server
/// behavior -- e.g. rust-analyzer's stdlib locations without `rust-src`
/// installed) repeat that cheap-but-nonzero syscall for free against a
/// per-response I/O budget (see #474's budget-bypass follow-up). Small
/// enough to have no material effect on a legitimate response's budget
/// (~10,000 failed opens before exhausting [`DEFAULT_MAX_FILE_SIZE`]'s
/// worth of budget on their own), while still bounding the failed-open
/// amplification to the same order of magnitude as other count caps in this
/// crate.
pub const OPEN_FAILURE_CHARGE_BYTES: u64 = 4096;

/// Outcome of [`DocumentTracker::read_line_checked`]: the requested line
/// (`None` if the file has fewer lines, doesn't exist, or otherwise
/// resolved to no usable text), plus the bytes to charge a caller
/// tracking its own I/O budget across many calls (see `EncodingCtx`'s
/// per-response disk-read budget, #474) -- not always a literal count of
/// bytes scanned (see [`OPEN_FAILURE_CHARGE_BYTES`]), but always safe to
/// charge as such. Charge this rather than assuming cost is proportional
/// to `text`'s own length -- most of the cost is the lines skipped before
/// it.
#[derive(Debug, Clone)]
pub struct LineRead {
    /// The requested line's text, or `None` if the file has no such line.
    pub(crate) text: Option<String>,
    /// Bytes to charge against a caller's I/O budget for this call; see
    /// this type's own doc for when this isn't a literal scanned-byte count.
    pub(crate) bytes_read: u64,
}

/// A document evicted by [`DocumentTracker::open`]'s LRU eviction (#495).
///
/// Carries the servers whose `textDocument/didOpen`/`didChange` it had
/// received. `DocumentTracker` itself has no access to any server's
/// [`LspClient`] --
/// that registry lives one layer up, in `Translator` -- so it cannot send
/// `textDocument/didClose` itself. Instead, [`DocumentTracker::take_evicted`]
/// hands these back to a caller that does have that access, which must send
/// each of `synced_servers` a `textDocument/didClose` for `uri`, or that
/// server's own open-document set keeps growing even though mcpls's own
/// tracking evicted the entry.
#[derive(Debug, Clone)]
pub struct EvictedDocument {
    /// Filesystem path of the evicted document.
    pub path: PathBuf,
    /// URI of the evicted document, as sent to any server that had it open.
    pub uri: Uri,
    /// Servers that had this document open, each needing a
    /// `textDocument/didClose` now that mcpls itself has evicted it.
    pub synced_servers: Vec<ServerId>,
}

/// Tracks document state across the workspace.
///
/// Every method takes `&self`: the document map and the per-path locks used
/// by [`Self::ensure_open`] are both interior-mutable, so a single tracker
/// can be shared behind a plain `Arc<DocumentTracker>` with no outer lock.
/// See [`Self::ensure_open`] for the concurrency contract this maintains.
#[derive(Debug)]
pub struct DocumentTracker {
    /// Open documents by file path. Locked only for the short, synchronous
    /// section that touches it — never held across an `await`.
    documents: StdMutex<HashMap<PathBuf, DocumentState>>,
    /// Per-path locks serializing [`Self::ensure_open`] calls for the same
    /// path, so calls for different paths never wait on each other. See
    /// `lock_path` for how entries are created and evicted.
    ///
    /// Also doubles as the "has an in-flight operation" signal
    /// [`Self::open`]'s LRU eviction consults (#495): a path is present here
    /// for the whole duration of any `ensure_open`/`update` call against it
    /// (`lock_path`'s guard is held across both), so excluding every path
    /// present in this map from eviction candidates is exactly "never evict
    /// a document with an operation in flight".
    path_locks: StdMutex<HashMap<PathBuf, Arc<AsyncMutex<()>>>>,
    /// Per-server sync generation, bumped by [`Self::forget_server`].
    ///
    /// `ensure_open` captures a server's generation before doing any I/O and
    /// only commits its `synced` update if the generation is unchanged when
    /// it finishes -- see [`Self::forget_server`]'s docs for the race this
    /// closes. Absent from the map is equivalent to generation `0`.
    generations: StdMutex<HashMap<ServerId, u64>>,
    /// Resource limits for tracking.
    limits: ResourceLimits,
    /// Custom file extension to language ID mappings.
    extension_map: HashMap<String, String>,
    /// Documents evicted by [`Self::open`]'s LRU eviction, queued for
    /// [`Self::take_evicted`] to hand to a caller that can notify their
    /// servers (#495). See [`EvictedDocument`].
    evicted: StdMutex<Vec<EvictedDocument>>,
}

impl DocumentTracker {
    /// Create a new document tracker with custom limits and extension mappings.
    #[must_use]
    pub fn new(limits: ResourceLimits, extension_map: HashMap<String, String>) -> Self {
        Self {
            documents: StdMutex::new(HashMap::new()),
            path_locks: StdMutex::new(HashMap::new()),
            generations: StdMutex::new(HashMap::new()),
            limits,
            extension_map,
            evicted: StdMutex::new(Vec::new()),
        }
    }

    /// Drains and returns documents evicted by [`Self::open`]'s LRU eviction
    /// since the last call (#495) -- see [`EvictedDocument`]. A caller with
    /// access to each server's `LspClient` (i.e. `Translator`) should call
    /// this after every `ensure_open` that could have triggered eviction and
    /// send `textDocument/didClose` for each evicted document to each of its
    /// `synced_servers`.
    pub fn take_evicted(&self) -> Vec<EvictedDocument> {
        std::mem::take(&mut lock_std(&self.evicted))
    }

    /// Check if a document is currently open.
    #[must_use]
    pub fn is_open(&self, path: &Path) -> bool {
        lock_std(&self.documents).contains_key(path)
    }

    /// Get a clone of the state of an open document.
    #[must_use]
    pub fn get(&self, path: &Path) -> Option<DocumentState> {
        lock_std(&self.documents).get(path).cloned()
    }

    /// Text of the 0-based `line`'th line of `path`'s currently tracked
    /// content, or `None` if the document is not open or has no such line.
    ///
    /// Reads the in-memory content mcpls already sent the server via
    /// `didOpen`/`didChange` -- cheaper than a disk read (no I/O, no
    /// re-scanning the whole file) and more correct when disk and server
    /// state have diverged (e.g. an edit not yet flushed to disk).
    #[must_use]
    pub fn line_text(&self, path: &Path, line: u32) -> Option<String> {
        lock_std(&self.documents)
            .get(path)?
            .content
            .lines()
            .nth(line as usize)
            .map(str::to_string)
    }

    /// Get the number of open documents.
    #[must_use]
    pub fn len(&self) -> usize {
        lock_std(&self.documents).len()
    }

    /// Check if there are no open documents.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        lock_std(&self.documents).is_empty()
    }

    /// Open a document and track its state.
    ///
    /// Returns the document URI for use in LSP requests.
    ///
    /// When `max_documents` would otherwise be exceeded, evicts the
    /// least-recently-used tracked document that both has no
    /// `ensure_open`/`update` call currently in flight against it and is
    /// disk-verified (see `evict_lru`) to make room, rather than failing
    /// outright (#495) -- the evicted document is queued for
    /// [`Self::take_evicted`]. Only falls back to
    /// [`Error::DocumentLimitExceeded`] when no tracked document meets both
    /// conditions, so none is safe to evict.
    ///
    /// `take_evicted`'s queue is an unbounded `Vec` that only ever grows
    /// until drained -- `Translator` drains it after every `ensure_open`
    /// that could have triggered eviction, but a caller that invokes this
    /// method directly (bypassing `ensure_open`, e.g. an embedder) is
    /// responsible for draining it too, or the queue (and every
    /// `EvictedDocument`'s content) accumulates for the tracker's lifetime.
    ///
    /// Note the narrower guarantee than "no operation in flight" might
    /// suggest: the `ensure_open`/`update` lock this checks (`path_locks`)
    /// is released once that call returns, *before* the caller's actual LSP
    /// round-trip for the document runs (see `path_locks`'s doc) -- a
    /// document already past its own `ensure_open` can still be evicted
    /// while its handler's request is in flight. Harmless at the default
    /// `max_documents` (100): the just-prepared document is always the most
    /// recently used, so it's never the LRU candidate. At a very small
    /// configured limit with enough concurrent calls, two in-flight
    /// documents could in principle evict each other mid-request.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Document limit is exceeded and no document is evictable
    /// - File size limit is exceeded
    pub fn open(&self, path: PathBuf, content: String) -> Result<Uri> {
        self.check_file_size(content.len() as u64)?;

        let uri = path_to_uri(&path)?;
        let language_id = detect_language(&path, &self.extension_map);

        let state = DocumentState::new(uri.clone(), language_id, content);

        // Check document limit and insert under a single lock acquisition so
        // two concurrent `open` calls for different new paths can't both
        // pass the check and jointly exceed the limit by one. Dropped
        // explicitly right after the insert rather than at function return.
        //
        // Skipped entirely when `path` is already tracked: re-opening an
        // existing path (`insert` below overwrites its entry in place, not
        // growing the map) never needs room made for it -- checking the
        // limit anyway would needlessly evict some unrelated victim (or, if
        // `path` itself were picked as the LRU candidate, evict and then
        // immediately re-insert it, queuing a spurious `didClose`).
        let mut documents = lock_std(&self.documents);
        if self.limits.max_documents > 0
            && documents.len() >= self.limits.max_documents
            && !documents.contains_key(&path)
        {
            let Some((evicted_path, evicted_state)) =
                Self::evict_lru(&mut documents, &self.path_locks)
            else {
                return Err(Error::DocumentLimitExceeded {
                    current: documents.len(),
                    max: self.limits.max_documents,
                });
            };
            lock_std(&self.evicted).push(EvictedDocument {
                path: evicted_path,
                uri: evicted_state.uri,
                synced_servers: evicted_state.synced.into_keys().collect(),
            });
        }
        documents.insert(path, state);
        drop(documents);
        Ok(uri)
    }

    /// Removes and returns the least-recently-used entry in `documents` that
    /// is both unlocked and disk-verified -- see `path_locks`'s doc for why
    /// "present in `path_locks`" is exactly "has an `ensure_open`/`update`
    /// operation in flight" (#495), and below for why "disk-verified" is
    /// required too.
    ///
    /// A candidate whose `disk()` is `None` is skipped: that means its
    /// in-memory `content` either has never been read-back-verified against
    /// disk at all, or -- the concerning case -- has *diverged* from disk
    /// via `Self::update`'s `apply_local_edit` (a local, not-yet-`didOpen`ed
    /// edit already pushed to the server, per that method's own doc). In
    /// either case, evicting it and later reopening the path from disk on a
    /// future `ensure_open` would silently discard content mcpls has no
    /// other record of -- unlike a disk-verified candidate, whose evicted
    /// content is by definition reproducible by re-reading the file. No
    /// in-tree caller invokes `update` today, so this is a structural guard
    /// against a latent, not-yet-reachable data-loss shape rather than a
    /// currently-observed bug.
    ///
    /// Returns `None` if every tracked document is currently locked or not
    /// disk-verified, in which case the caller must not evict anything.
    fn evict_lru(
        documents: &mut HashMap<PathBuf, DocumentState>,
        path_locks: &StdMutex<HashMap<PathBuf, Arc<AsyncMutex<()>>>>,
    ) -> Option<(PathBuf, DocumentState)> {
        let locked = lock_std(path_locks)
            .keys()
            .cloned()
            .collect::<std::collections::HashSet<_>>();
        let lru_path = documents
            .iter()
            .filter(|(path, state)| !locked.contains(path.as_path()) && state.disk().is_some())
            .min_by_key(|(_, state)| state.last_accessed)
            .map(|(path, _)| path.clone())?;
        documents.remove(&lru_path).map(|state| (lru_path, state))
    }

    /// Update a document's content and increment its version.
    ///
    /// Returns `None` if the document is not open. The updated content has no
    /// known disk provenance, so the next `ensure_open` call on this path
    /// will always re-verify by content compare rather than trusting a stat.
    ///
    /// # Concurrency
    ///
    /// Takes the same per-path lock as [`Self::ensure_open`] (see
    /// `lock_path`), so this can never interleave with an `ensure_open` call
    /// for the same path -- closing the race where `ensure_open`'s disk
    /// phase reads a `(uri, version, disk snapshot)` under a short-lived
    /// lock and its sync phase later commits against that now-stale
    /// snapshot after a concurrent `update` bumped the version in between.
    ///
    /// **Warning**: `lock_path`'s mutex is not reentrant. Never call `update`
    /// from a task that already holds this same path's `lock_path` guard
    /// (e.g. from within `ensure_open`/`disk_phase`/`sync_phase`, or any
    /// future caller nested inside one) -- doing so self-deadlocks
    /// permanently, with no panic and no timeout to signal it.
    pub async fn update(&self, path: &Path, content: String) -> Option<i32> {
        let _path_guard = self.lock_path(path).await;
        lock_std(&self.documents).get_mut(path).map(|state| {
            state.touch();
            state.apply_local_edit(content)
        })
    }

    /// Returns an error if `size` exceeds the configured file size limit.
    const fn check_file_size(&self, size: u64) -> Result<()> {
        if self.limits.max_file_size > 0 && size > self.limits.max_file_size {
            return Err(Error::FileSizeLimitExceeded {
                size,
                max: self.limits.max_file_size,
            });
        }
        Ok(())
    }

    /// Sets the disk snapshot for an already-tracked document.
    ///
    /// A no-op if the path is no longer tracked; every call site runs under
    /// the per-path lock for the whole `ensure_open` call, so this should
    /// not happen in practice, but it avoids an `unwrap`/`expect` on the
    /// lookup.
    fn set_disk(&self, path: &Path, snap: DiskSync) {
        if let Some(st) = lock_std(&self.documents).get_mut(path) {
            st.set_disk(snap);
        }
    }

    /// Close a document and remove it from tracking.
    ///
    /// Returns the document state if it was open.
    pub fn close(&self, path: &Path) -> Option<DocumentState> {
        lock_std(&self.documents).remove(path)
    }

    /// Close all documents.
    pub fn close_all(&self) -> Vec<DocumentState> {
        lock_std(&self.documents)
            .drain()
            .map(|(_, state)| state)
            .collect()
    }

    /// Snapshot of the filesystem paths of all currently open documents.
    pub fn open_paths(&self) -> Vec<PathBuf> {
        lock_std(&self.documents).keys().cloned().collect()
    }

    /// Forget `server`'s last-synced version for every currently open
    /// document, so the next `ensure_open` call sends `didOpen` again
    /// instead of `didChange`.
    ///
    /// Called after `server` is respawned: the fresh process has no memory
    /// of any document the old one had open, so this tracker's per-server
    /// sync history for it must be forgotten too, or `ensure_open` would
    /// wrongly send `didChange` for a document the new process never saw.
    ///
    /// Also bumps `server`'s sync generation. Clearing `synced` alone is not
    /// enough: a call already in flight against the old (dead) connection
    /// when this runs can still have its `didOpen`/`didChange` notify
    /// "succeed" (`LspClient::notify` only enqueues onto a channel -- a dead
    /// process is not observed by the send itself), and would otherwise
    /// re-insert a stale entry after this method has already cleared it.
    /// `ensure_open` captures the generation before starting and discards
    /// its `synced` write if the generation moved in the meantime, closing
    /// that race regardless of exactly when the notify "succeeds".
    pub fn forget_server(&self, server: &ServerId) {
        *lock_std(&self.generations)
            .entry(server.clone())
            .or_insert(0) += 1;
        for state in lock_std(&self.documents).values_mut() {
            state.forget_server(server);
        }
    }

    /// Current sync generation for `server` (see [`Self::forget_server`]).
    fn generation(&self, server: &ServerId) -> u64 {
        lock_std(&self.generations)
            .get(server)
            .copied()
            .unwrap_or(0)
    }

    /// Acquire the per-path lock used by [`Self::ensure_open`], creating its
    /// entry on first use.
    ///
    /// The map of per-path locks (`path_locks`) is itself locked only for
    /// the map lookup/insert/remove — never across an `await` — so acquiring
    /// one path's lock never blocks a concurrent acquisition for a different
    /// path. Awaiting the returned path's own lock is what actually
    /// serializes calls for the same path.
    ///
    /// The returned guard evicts its `path_locks` entry when dropped, but
    /// only if no other caller is concurrently waiting on it (see
    /// [`PathLockGuard`]'s `Drop` impl) — otherwise the map would grow by
    /// one entry per distinct path ever opened, for the lifetime of the
    /// process.
    async fn lock_path(&self, path: &Path) -> PathLockGuard<'_> {
        let arc = {
            let mut locks = lock_std(&self.path_locks);
            locks
                .entry(path.to_path_buf())
                .or_insert_with(|| Arc::new(AsyncMutex::new(())))
                .clone()
        };
        let guard = Arc::clone(&arc).lock_owned().await;
        PathLockGuard {
            path_locks: &self.path_locks,
            path: path.to_path_buf(),
            arc,
            guard: Some(guard),
        }
    }

    /// Ensure a document is open *for `server`*, opening it lazily if
    /// necessary, and resynchronize it with disk and with `server` if either
    /// has fallen behind.
    ///
    /// A single path can be synced to several servers independently (e.g.
    /// hover routed to one server, diagnostics to another, for the same
    /// language) -- this call syncs only the one server it is for. Internally
    /// it runs in two phases:
    ///
    /// **Disk phase**: stats the file on every call (a cheap syscall, never
    /// debounced) to detect external changes -- `git checkout`/`stash`,
    /// formatters, or edits made by the MCP host itself outside mcpls -- and
    /// re-reads its content when the stat indicates a possible change (see
    /// `DiskSync` for the settled/debounce rules). This phase never skips
    /// the *per-server* sync check below, even when it takes a fast path
    /// that skips the disk read: a second server that has never seen this
    /// document must still receive `didOpen` even if the file has not
    /// changed since a first server was opened on it.
    ///
    /// **Sync phase**: compares `server`'s last-synced version (tracked via
    /// [`DocumentState::synced_version`]) against the version decided by the disk
    /// phase, and sends exactly one of `didOpen` (server has never seen this
    /// document), `didChange` (server is behind), or nothing (server is
    /// already caught up). A `didChange` is always a single full-replacement
    /// notification (a `TextDocumentContentChangeEvent` with `range: None`,
    /// which per the LSP spec means "this is the entire new document
    /// content"); mcpls does not consult the server's negotiated
    /// `TextDocumentSyncKind` (`LspClient` has no access to
    /// `ServerCapabilities` at this layer) -- full-replacement is accepted in
    /// practice by rust-analyzer, pyright, tsserver, gopls and clangd, but is
    /// the first place to look if a future maintainer sees sync errors from
    /// a new server. The document is never closed and reopened on a change,
    /// so `get_cached_diagnostics` keeps serving the last-known diagnostics
    /// until the server re-publishes -- there is no transient empty window.
    ///
    /// `st.version`/`st.content`/`st.disk`/`synced[server]` are all committed
    /// only after the notification succeeds. A server that is never asked
    /// again never catches up to a later edit -- which is correct, since a
    /// server that is never asked never needs the content.
    ///
    /// Two cases fall outside the disk-change-detection mechanism entirely:
    /// - A tool that restores a file with an mtime and size identical to the
    ///   last ones observed (e.g. `tar x`, `rsync -a`, `cp -p`) is
    ///   indistinguishable from "unchanged", however long ago that snapshot
    ///   was taken -- not just within the racy detection window. Once a
    ///   snapshot is `mtime_settled`, restoring its exact `(mtime, size)`
    ///   retakes the fast path forever. Closing this would require hashing
    ///   content on every access.
    /// - `workspace_symbol_search` is served from the LSP server's own
    ///   index and is unaffected by this per-document mechanism for files
    ///   mcpls has never opened.
    ///
    /// # Concurrency
    ///
    /// Calls for the *same* `path` are serialized against each other (via
    /// `lock_path`), so no two such calls can observe or mutate that
    /// path's state concurrently -- this is what prevents duplicate
    /// `didOpen`/`didChange` notifications for the same document. Calls for
    /// *different* paths run fully concurrently: neither the per-path lock
    /// nor the short, synchronous locks used to touch the shared document
    /// map are ever held across this call's disk I/O or LSP notify.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The file cannot be stat'd or read from disk
    /// - The `didOpen`/`didChange` notification fails to send
    /// - Resource limits are exceeded
    pub async fn ensure_open(
        &self,
        path: &Path,
        server: &ServerId,
        lsp_client: &LspClient,
    ) -> Result<Uri> {
        let _path_guard = self.lock_path(path).await;
        let generation = self.generation(server);
        let decision = self.disk_phase(path).await?;
        self.sync_phase(path, server, lsp_client, decision, generation)
            .await
    }

    /// Disk-verification phase of `ensure_open`: decides the version `path`
    /// should be at, reading from disk only when necessary. Never sends any
    /// LSP notification and never returns early in a way that would skip the
    /// per-server sync phase -- see `ensure_open`'s docs.
    async fn disk_phase(&self, path: &Path) -> Result<Decision> {
        if !lock_std(&self.documents).contains_key(path) {
            return self.disk_phase_new(path).await;
        }

        let read_at = SystemTime::now();
        let meta = fs::metadata(path).await.map_err(|e| Error::FileIo {
            path: path.to_path_buf(),
            source: e,
        })?;
        let mtime = meta.modified().ok();
        let size = meta.len();

        // `.map(...)` extracts an owned tuple from the lookup in a single
        // statement, so the lock releases immediately rather than staying
        // held while `fast_path` is computed. `get_mut` (rather than `get`)
        // so this same lookup can also `touch` the entry for LRU eviction
        // ordering (#495) -- every `ensure_open` call for an already-tracked
        // document reaches here, whether or not it ends up taking the fast
        // path below.
        let Some((uri, current_version, fast_path)) =
            lock_std(&self.documents).get_mut(path).map(|st| {
                st.touch();
                let stat_matches = st
                    .disk()
                    .is_some_and(|d| d.mtime == mtime && d.size == size);
                let fast_path = match st.disk() {
                    Some(d) if stat_matches && d.mtime_settled => true,
                    Some(d)
                        if stat_matches && d.content_checked_at.elapsed() < DISK_CHECK_DEBOUNCE =>
                    {
                        true
                    }
                    _ => false,
                };
                (st.uri.clone(), st.version, fast_path)
            })
        else {
            return Err(Error::DocumentNotFound(path.to_path_buf()));
        };
        if fast_path {
            return Ok(Decision::unchanged(uri, current_version));
        }

        let (fresh, ..) = self.read_to_string_checked(path).await?;
        let snap = DiskSync {
            mtime,
            size,
            mtime_settled: mtime_settled(mtime, read_at),
            content_checked_at: Instant::now(),
        };

        let Some(unchanged) = lock_std(&self.documents)
            .get(path)
            .map(|st| fresh == st.content)
        else {
            return Err(Error::DocumentNotFound(path.to_path_buf()));
        };

        if unchanged {
            self.set_disk(path, snap);
            return Ok(Decision::unchanged(uri, current_version));
        }

        Ok(Decision {
            uri,
            target_version: current_version.saturating_add(1),
            fresh_content: Some(fresh),
            snap: Some(snap),
        })
    }

    /// Reads a not-yet-tracked file from disk and opens it in the tracker at
    /// version 1. No server has synced it yet, so the sync phase always
    /// sends `didOpen` regardless of which server calls next.
    async fn disk_phase_new(&self, path: &Path) -> Result<Decision> {
        let read_at = SystemTime::now();
        let (content, mtime, size) = self.read_to_string_checked(path).await?;

        let uri = self.open(path.to_path_buf(), content)?;
        self.set_disk(
            path,
            DiskSync {
                mtime,
                size,
                mtime_settled: mtime_settled(mtime, read_at),
                content_checked_at: Instant::now(),
            },
        );

        Ok(Decision::unchanged(uri, 1))
    }

    /// Opens `path` for reading and verifies, via that same open handle's
    /// metadata, that it is a regular file within [`Self::check_file_size`]'s
    /// limit -- never a separately-stat'd path, which would let an atomic
    /// replace (e.g. a concurrent `rename`) between the check and the open
    /// swap in something else entirely.
    ///
    /// On Unix the open itself uses `O_NONBLOCK`, which has no effect on
    /// regular files but makes opening a FIFO (or other peer-waiting special
    /// file) return immediately instead of blocking indefinitely for a
    /// writer -- the file-type check below then rejects it. Without this,
    /// a FIFO substituted for an expected regular file could hang the
    /// calling task (and pin a blocking-pool thread) forever (see #418).
    ///
    /// **Known gap on Windows**: `CreateFileW` (what `fs::File::open` and
    /// `OpenOptions::open` call into) has no `O_NONBLOCK` equivalent, so the
    /// open itself can still block indefinitely on a hostile path (e.g. an
    /// oplock held by another process, or a dead network redirector) --
    /// Win32 offers nothing to bound that. What Windows does get is a
    /// content-read guarantee: the open handle is checked via `GetFileType`
    /// (see [`check_disk_file_type`]) immediately after open and before
    /// `metadata()` or any content read, rejecting anything that is not
    /// `FILE_TYPE_DISK` (e.g. reserved device names like `CON`, `COM1`,
    /// `NUL`, which `FileType::is_file()` alone does not reliably reject) --
    /// see #442. Platforms that are neither Unix nor Windows get neither
    /// protection: a plain blocking open with no file-type check beyond
    /// `is_file()`.
    async fn open_checked(&self, path: &Path) -> Result<(fs::File, std::fs::Metadata)> {
        #[cfg(unix)]
        let opened = fs::OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_NONBLOCK)
            .open(path)
            .await;
        #[cfg(not(unix))]
        let opened = fs::File::open(path).await;

        let file = opened.map_err(|e| Error::FileIo {
            path: path.to_path_buf(),
            source: e,
        })?;
        // Must precede metadata() below: GetFileInformationByHandle may fail for non-disk handles.
        #[cfg(windows)]
        check_disk_file_type(&file, path)?;
        let meta = file.metadata().await.map_err(|e| Error::FileIo {
            path: path.to_path_buf(),
            source: e,
        })?;
        if !meta.is_file() {
            return Err(Error::NotARegularFile(path.to_path_buf()));
        }
        self.check_file_size(meta.len())?;
        Ok((file, meta))
    }

    /// Reads `file`'s content as UTF-8, bounded to one byte past
    /// [`Self::check_file_size`]'s limit regardless of the already-checked
    /// stat result -- defense in depth against the file growing between the
    /// stat (in [`Self::open_checked`]) and this read completing (see #418).
    /// A read that reaches the bound is reported as oversized even though
    /// the earlier stat passed, since the file grew past what was verified.
    ///
    /// `size_hint` is the size [`Self::open_checked`] already observed via
    /// `stat`, used only to preallocate the read buffer and avoid
    /// reallocation growth on the common (non-racing) path -- it is never
    /// trusted for the size check itself, which is always re-derived from
    /// the bytes actually read.
    async fn read_string_bounded(
        &self,
        path: &Path,
        mut file: fs::File,
        size_hint: u64,
    ) -> Result<String> {
        let max = self.limits.max_file_size;
        let cap = bounded_read_cap(max);
        let mut buf = Vec::with_capacity(usize::try_from(size_hint.min(cap)).unwrap_or(0));
        let io_err = |e: std::io::Error| Error::FileIo {
            path: path.to_path_buf(),
            source: e,
        };

        (&mut file)
            .take(cap)
            .read_to_end(&mut buf)
            .await
            .map_err(io_err)?;
        match check_bounded_utf8(buf, max) {
            BoundedReadOutcome::Ok(s) => Ok(s),
            BoundedReadOutcome::TooLarge { size } => {
                Err(Error::FileSizeLimitExceeded { size, max })
            }
            BoundedReadOutcome::InvalidUtf8(e) => Err(io_err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                e,
            ))),
        }
    }

    /// Reads `path` through a single open file handle, checking its size and
    /// type via [`Self::open_checked`] and bounding the read via
    /// [`Self::read_string_bounded`].
    ///
    /// Returns the content along with the handle's own mtime and size, so
    /// callers can build a [`DiskSync`] snapshot consistent with what was
    /// actually read.
    async fn read_to_string_checked(
        &self,
        path: &Path,
    ) -> Result<(String, Option<SystemTime>, u64)> {
        let (file, meta) = self.open_checked(path).await?;
        let mtime = meta.modified().ok();
        let size = meta.len();
        let content = self.read_string_bounded(path, file, size).await?;
        Ok((content, mtime, size))
    }

    /// Reads only the 0-based `line`'th line of `path` from disk, applying
    /// the same regular-file and [`Self::check_file_size`] checks as a
    /// tracked document's disk read (see [`Self::read_to_string_checked`]),
    /// but stopping as soon as `line` is found rather than buffering the
    /// whole file just to discard everything past one line (see #474).
    ///
    /// For a document not tracked by this tracker at all -- e.g. one
    /// resolved only for encoding-conversion purposes, never opened for LSP
    /// sync -- there is otherwise no size or file-type gate on the path at
    /// all (see #427). Callers that only need best-effort text (falling back
    /// to `None` on any error) should treat every error here that way rather
    /// than surfacing it.
    ///
    /// [`LineRead::text`] is `None` if `path` doesn't resolve to an
    /// existing, readable regular file at all (see [`Self::open_checked`]),
    /// if `path` has fewer than `line + 1` lines, if the line's bytes are
    /// not valid UTF-8, or if `budget` (or `max_file_size`) was exhausted
    /// before a complete line could be read -- [`LineRead::bytes_read`] is
    /// populated in every one of these cases (see below), never silently
    /// dropped via an `Err` with no byte count. The line's trailing line
    /// ending is stripped to match `str::lines`'s convention exactly: a
    /// trailing `\n` is removed, and only then is one further trailing `\r`
    /// also removed (a real `\r\n` terminator) -- a final line with no
    /// trailing `\n` at all keeps any trailing `\r` verbatim, since it was
    /// never followed by a real line terminator, same as `str::lines`.
    ///
    /// `budget` bounds this call's own read on top of
    /// [`crate::util::bounded_read_cap`] of `max_file_size`: the actual cap
    /// used is `min(bounded_read_cap(max_file_size), budget + 1)`, enforced
    /// by wrapping the file handle itself in [`AsyncReadExt::take`] rather
    /// than checked after the fact -- so this call physically cannot scan
    /// more than one byte past `budget`, regardless of how large
    /// `max_file_size` is configured (including `max_file_size = 0`,
    /// meaning unlimited). The `+ 1` is the same disambiguation slack
    /// `bounded_read_cap` already applies to `max_file_size`: without it, a
    /// read whose remaining budget exactly equals its target line's byte
    /// length (no trailing newline) is indistinguishable from one
    /// genuinely truncated by the cap. A caller enforcing its own I/O
    /// budget across many calls (see `EncodingCtx`'s per-response
    /// disk-read budget, #474) passes its remaining allowance here and
    /// charges exactly [`LineRead::bytes_read`] afterward -- always
    /// available, on every outcome, so the budget can never be bypassed by
    /// triggering a failure mid-scan, and never overshoots by more than
    /// this one byte of slack.
    ///
    /// [`Self::open_checked`] failing (path doesn't exist, isn't a regular
    /// file, or already exceeds `max_file_size` at stat time) is reported
    /// the same way, charging [`OPEN_FAILURE_CHARGE_BYTES`] rather than a
    /// literal `0` -- zero bytes were actually scanned, but an LSP server
    /// routinely names paths that don't exist locally (e.g. rust-analyzer's
    /// `file:///rustc/<hash>/library/...` without `rust-src` installed),
    /// and a literal `0` would let a response naming many such paths repeat
    /// this cheap-but-nonzero syscall for free against the per-response
    /// budget (see #474's budget-bypass follow-up). A real mid-read I/O
    /// error (rare, not attacker-controlled by response content) is the one
    /// case that still returns a genuine `Err` with no byte count.
    ///
    /// Also closes #427/#418's TOCTOU margin without a dedicated error: if
    /// `path` grows past `max_file_size` (or past `budget`) between
    /// [`Self::open_checked`]'s stat and this read completing, the capped
    /// take-adapter simply runs out mid-line, which this method detects
    /// (`buf` doesn't end in the expected `\n`) and reports as `None` rather
    /// than returning a truncated line as if it were complete.
    pub(crate) async fn read_line_checked(
        &self,
        path: &Path,
        line: u32,
        budget: u64,
    ) -> Result<LineRead> {
        let Ok((file, _meta)) = self.open_checked(path).await else {
            return Ok(LineRead {
                text: None,
                bytes_read: OPEN_FAILURE_CHARGE_BYTES,
            });
        };
        let max = self.limits.max_file_size;
        // `+1` slack on `budget`, same trick `bounded_read_cap` already
        // applies to `max_file_size`: without it, a read whose remaining
        // budget exactly equals its target line's byte length (no trailing
        // newline) is indistinguishable from one truncated by the cap, and
        // was misreported as truncated (see #474's correctness-gate fix).
        let cap = bounded_read_cap(max).min(budget.saturating_add(1));
        let mut reader = tokio::io::BufReader::new(file.take(cap));
        let io_err = |e: std::io::Error| Error::FileIo {
            path: path.to_path_buf(),
            source: e,
        };

        let mut buf = Vec::new();
        let mut bytes_read: u64 = 0;
        let mut current_line = 0u32;
        loop {
            buf.clear();
            let n = reader.read_until(b'\n', &mut buf).await.map_err(io_err)?;
            bytes_read += n as u64;
            if n == 0 {
                // No complete line left to return either way; bytes scanned
                // are still reported so the caller can charge them.
                return Ok(LineRead {
                    text: None,
                    bytes_read,
                });
            }
            if current_line == line {
                let truncated_by_cap = bytes_read >= cap && buf.last() != Some(&b'\n');
                if truncated_by_cap {
                    return Ok(LineRead {
                        text: None,
                        bytes_read,
                    });
                }
                if buf.last() == Some(&b'\n') {
                    buf.pop();
                    if buf.last() == Some(&b'\r') {
                        buf.pop();
                    }
                }
                return Ok(LineRead {
                    text: String::from_utf8(buf).ok(),
                    bytes_read,
                });
            }
            current_line += 1;
        }
    }

    /// Per-server sync phase of `ensure_open`: sends `didOpen`, `didChange`,
    /// or nothing to `server` depending on its last-synced version, and
    /// commits the outcome only after the notification succeeds.
    ///
    /// `generation` is `server`'s sync generation as observed by the caller
    /// before this call started (see [`Self::forget_server`]): the
    /// `synced` write at the end is skipped if it no longer matches,
    /// meaning `server` was respawned while this call was in flight and its
    /// notify -- however it turned out -- was not actually delivered to the
    /// connection now on file for `server`.
    async fn sync_phase(
        &self,
        path: &Path,
        server: &ServerId,
        lsp_client: &LspClient,
        decision: Decision,
        generation: u64,
    ) -> Result<Uri> {
        let Decision {
            uri,
            target_version,
            fresh_content,
            snap,
        } = decision;

        // Cheap check first: the common case (an already-synced document,
        // which is most tool calls against a file already open elsewhere)
        // must not pay for cloning the full document content only to
        // discard it on the `up_to_date` return below. `.map(...)` extracts
        // an owned value from the lookup so the lock is released at the end
        // of this statement rather than held across the checks that follow.
        let Some(synced_version) = lock_std(&self.documents)
            .get(path)
            .map(|st| st.synced_version(server))
        else {
            return Err(Error::DocumentNotFound(path.to_path_buf()));
        };
        let up_to_date = synced_version.is_some_and(|v| v >= target_version);
        let is_first_open = synced_version.is_none();

        if up_to_date {
            return Ok(uri);
        }

        let Some((language_id, text)) = lock_std(&self.documents).get(path).map(|st| {
            let text = fresh_content.clone().unwrap_or_else(|| st.content.clone());
            (st.language_id.clone(), text)
        }) else {
            return Err(Error::DocumentNotFound(path.to_path_buf()));
        };

        let notify_result = if is_first_open {
            lsp_client
                .notify_typed::<DidOpenTextDocumentNotification>(DidOpenTextDocumentParams {
                    text_document: TextDocumentItem {
                        uri: uri.clone(),
                        language_id: language_id.into(),
                        version: target_version,
                        text,
                    },
                })
                .await
        } else {
            lsp_client
                .notify_typed::<DidChangeTextDocumentNotification>(DidChangeTextDocumentParams {
                    text_document: VersionedTextDocumentIdentifier {
                        version: target_version,
                        text_document_identifier: lsp_types::TextDocumentIdentifier {
                            uri: uri.clone(),
                        },
                    },
                    content_changes: vec![
                        TextDocumentContentChangeEvent::TextDocumentContentChangeWholeDocument(
                            lsp_types::TextDocumentContentChangeWholeDocument { text },
                        ),
                    ],
                })
                .await
        };

        if let Err(err) = notify_result {
            // The server never learned about this document. If no server at
            // all has synced this path yet, leaving it tracked would
            // permanently desync every future server from the tracker, so
            // undo the insert and let the next call retry from scratch. If
            // another server already synced successfully, the path stays
            // tracked for that server's sake; this server's `synced` entry
            // simply stays absent/stale, so its own next call retries.
            // Two short lock scopes rather than one held across the
            // conditional `remove`: safe because `ensure_open`'s per-path
            // lock already serializes every caller for this path, so
            // nothing else can observe or mutate its `synced` map between
            // them.
            let first_ever_sync = lock_std(&self.documents)
                .get(path)
                .is_some_and(DocumentState::has_never_synced);
            if is_first_open && first_ever_sync {
                lock_std(&self.documents).remove(path);
            }
            return Err(err);
        }

        // Dropped explicitly right after the commit, rather than staying
        // alive (unused) until the function returns.
        let mut documents = lock_std(&self.documents);
        let Some(st) = documents.get_mut(path) else {
            return Err(Error::DocumentNotFound(path.to_path_buf()));
        };
        if let Some(fresh) = fresh_content {
            st.commit_reload(target_version, fresh, snap);
        }
        // Read while `documents` is still held, not before: `forget_server`
        // bumps the generation strictly before it acquires `documents`
        // itself (see its docs), so checking under this same lock is
        // airtight against the TOCTOU a separate, earlier read would leave
        // open -- either this sees the new generation and skips (in which
        // case `forget_server` has already cleared `synced`, or is blocked
        // waiting for *this* guard to release before it does), or it sees
        // the old one, in which case `forget_server` cannot have started
        // clearing yet and will correctly clear the entry this commits.
        if self.generation(server) == generation {
            st.mark_synced(server.clone(), target_version);
        }
        drop(documents);

        Ok(uri)
    }
}

/// RAII guard for the per-path lock acquired by
/// [`DocumentTracker::lock_path`].
///
/// Holds an `OwnedMutexGuard` on the path's `Arc<AsyncMutex<()>>>` for as
/// long as the guard is alive, serializing `ensure_open` calls for that
/// path. On drop, evicts the `path_locks` map entry if (and only if) no
/// other caller holds a clone of the same `Arc` -- see the `Drop` impl for
/// why that check is race-free.
struct PathLockGuard<'a> {
    path_locks: &'a StdMutex<HashMap<PathBuf, Arc<AsyncMutex<()>>>>,
    path: PathBuf,
    arc: Arc<AsyncMutex<()>>,
    guard: Option<OwnedMutexGuard<()>>,
}

impl Drop for PathLockGuard<'_> {
    fn drop(&mut self) {
        // Unlock first so a task waiting on `arc.lock_owned()` can proceed
        // as soon as possible, rather than also waiting on `path_locks`.
        self.guard.take();

        let mut locks = lock_std(self.path_locks);
        // Checked only after `self.guard` -- and the extra internal `Arc`
        // clone it held -- was already dropped above, so what's left here is:
        // this task's own `self.arc`, the map's entry, and one more
        // reference for every *other* task that has already looked up this
        // same entry in `lock_path` (each holds its own clone continuously
        // from before that lookup until its own `Drop` runs this same check)
        // but hasn't finished dropping yet. A `strong_count` of 2 means no
        // such task exists, so it's safe to evict; any later caller just
        // creates a fresh entry. Leaving it forever would instead grow this
        // map by one entry per distinct path ever opened, for the process's
        // lifetime.
        if Arc::strong_count(&self.arc) <= 2 {
            locks.remove(&self.path);
        }
    }
}

/// Outcome of `DocumentTracker::disk_phase`: the version `ensure_open`'s
/// caller should end up synced to, and -- only when this call detected an
/// as-yet-uncommitted content change -- the content and disk snapshot to
/// commit alongside it.
struct Decision {
    uri: Uri,
    target_version: i32,
    fresh_content: Option<String>,
    snap: Option<DiskSync>,
}

impl Decision {
    /// A decision where nothing changed on disk this call: `target_version`
    /// is already what's committed in `DocumentState`.
    const fn unchanged(uri: Uri, target_version: i32) -> Self {
        Self {
            uri,
            target_version,
            fresh_content: None,
            snap: None,
        }
    }
}

/// Convert a file path to a URI.
///
/// Prefer `try_path_to_uri` on paths that come from configuration or
/// otherwise untrusted input; this wrapper exists for the common case of an
/// already-canonicalized path, where the conversion is not expected to fail
/// but must still surface as an error rather than a panic to keep the
/// `panic = "abort"` release profile safe against unforeseen inputs.
///
/// # Errors
///
/// Returns [`Error::InvalidUri`] if the path cannot be represented as a
/// `file://` URI.
pub fn path_to_uri(path: &Path) -> Result<Uri> {
    try_path_to_uri(path)
        .ok_or_else(|| Error::InvalidUri(format!("cannot convert path to URI: {}", path.display())))
}

/// Convert a file path to a URI, returning `None` if the path cannot be
/// represented as a `file://` URI.
///
/// Prefer this over [`path_to_uri`] on paths that come from configuration,
/// where a bad value should surface as an error rather than a panic.
#[must_use]
pub fn try_path_to_uri(path: &Path) -> Option<Uri> {
    let uri_string = encode_rfc3986_path_chars(&file_url(path)?);
    Some(Uri::from(uri_string))
}

#[cfg(not(windows))]
fn file_url(path: &Path) -> Option<Url> {
    Url::from_file_path(path).ok()
}

#[cfg(windows)]
fn file_url(path: &Path) -> Option<Url> {
    match Url::from_file_path(path) {
        Ok(file_url) => Some(file_url),
        Err(()) if path.has_root() => windows_rooted_path_to_file_url(path),
        Err(()) => None,
    }
}

#[cfg(windows)]
fn windows_rooted_path_to_file_url(path: &Path) -> Option<Url> {
    let path_str = path.to_string_lossy();
    let stripped = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
    let mut file_url = Url::parse("file:///").ok()?;
    file_url.path_segments_mut().ok()?.clear().extend(
        stripped
            .split(['\\', '/'])
            .filter(|segment| !segment.is_empty()),
    );
    Some(file_url)
}

/// Percent-encodes the RFC 3986 §2.2 "other reserved" characters that the
/// `url` crate's default WHATWG path percent-encode set leaves untouched:
/// `[`, `]`, `^`, `|`. The remaining three characters in that set -- `{`,
/// `}`, and backtick -- are already encoded by `url` on serialization, so
/// they need no handling here; see
/// `test_path_to_uri_percent_encodes_all_rfc3986_other_reserved_chars`.
///
/// Shared with [`crate::bridge::resources::make_uri`] so `lsp-diagnostics://`
/// resource URIs get the same encoding as `file://` document URIs.
pub(super) fn encode_rfc3986_path_chars(url: &Url) -> String {
    let prefix = url[..url::Position::BeforePath].to_owned();
    let encoded = url[url::Position::BeforePath..]
        .replace('[', "%5B")
        .replace(']', "%5D")
        .replace('^', "%5E")
        .replace('|', "%7C");
    format!("{prefix}{encoded}")
}

/// Convert an LSP `file://` URI to an absolute filesystem path.
///
/// Returns `None` if the URI is not a valid `file://` URI, uses a non-file
/// scheme, or contains percent-encoding that cannot map to a valid path.
#[must_use]
pub fn uri_to_path(uri: &Uri) -> Option<PathBuf> {
    let url = Url::parse(uri.as_ref()).ok()?;
    if url.scheme() != "file" {
        return None;
    }
    // Reject authority-bearing file URIs (e.g. `file://server/share`) to
    // avoid UNC path confusion on Windows.
    if !url.host_str().unwrap_or("").is_empty() {
        return None;
    }
    url.to_file_path().ok()
}

/// Detect the language ID from a file path.
///
/// Consults the extension map to determine the language ID for a file.
/// If the extension is not found in the map, returns "plaintext".
#[must_use]
pub fn detect_language(path: &Path, extension_map: &HashMap<String, String>) -> String {
    let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("");

    extension_map
        .get(extension)
        .cloned()
        .unwrap_or_else(|| "plaintext".to_string())
}

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

    #[test]
    fn test_detect_language() {
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());
        map.insert("py".to_string(), "python".to_string());
        map.insert("ts".to_string(), "typescript".to_string());

        assert_eq!(detect_language(Path::new("main.rs"), &map), "rust");
        assert_eq!(detect_language(Path::new("script.py"), &map), "python");
        assert_eq!(detect_language(Path::new("app.ts"), &map), "typescript");
        assert_eq!(detect_language(Path::new("unknown.xyz"), &map), "plaintext");
    }

    #[tokio::test]
    async fn test_document_tracker() {
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(ResourceLimits::default(), map);
        let path = PathBuf::from("/test/file.rs");

        assert!(!tracker.is_open(&path));

        tracker
            .open(path.clone(), "fn main() {}".to_string())
            .unwrap();
        assert!(tracker.is_open(&path));
        assert_eq!(tracker.len(), 1);

        let state = tracker.get(&path).unwrap();
        assert_eq!(state.version(), 1);
        assert_eq!(state.language_id(), "rust");

        let new_version = tracker
            .update(&path, "fn main() { println!() }".to_string())
            .await;
        assert_eq!(new_version, Some(2));

        tracker.close(&path);
        assert!(!tracker.is_open(&path));
        assert!(tracker.is_empty());
    }

    /// #249: after a respawn, `forget_server` must clear only the respawned
    /// server's sync history so the next `ensure_open` call for it sends
    /// `didOpen` again -- while leaving other servers synced to the same
    /// document untouched (a path can be synced to more than one server,
    /// e.g. hover routed to one, diagnostics to another).
    #[test]
    fn test_forget_server_clears_only_that_servers_synced_version() {
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        let path = PathBuf::from("/test/file.rs");
        tracker
            .open(path.clone(), "fn main() {}".to_string())
            .unwrap();

        let respawned = ServerId::from("rust-respawned");
        let untouched = ServerId::from("rust-diagnostics");
        lock_std(&tracker.documents)
            .get_mut(&path)
            .unwrap()
            .synced
            .insert(respawned.clone(), 1);
        lock_std(&tracker.documents)
            .get_mut(&path)
            .unwrap()
            .synced
            .insert(untouched.clone(), 1);

        tracker.forget_server(&respawned);

        let state = tracker.get(&path).unwrap();
        assert!(state.synced_version(&respawned).is_none());
        assert!(state.synced_version(&untouched).is_some());
    }

    /// #249 S1 regression: a `sync_phase` call that captured `server`'s
    /// generation *before* a concurrent `forget_server` bumped it must not
    /// commit its `synced` write, even though its notification against the
    /// now-superseded connection reports success (`fake_lsp_client`'s
    /// `DuplexStream` peer, held alive by the test's `FakeServer`, always
    /// accepts writes, standing in for the window where a server's process
    /// has already died but its message loop has not yet observed that).
    /// Without this, a document synced against the old (crashed) process
    /// would be wrongly marked as already open on the respawned one,
    /// permanently desyncing it.
    #[tokio::test]
    async fn test_sync_phase_skips_commit_when_generation_is_stale() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("race.rs");
        std::fs::write(&path, "fn main() {}").unwrap();
        set_mtime(&path, settled_past());

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        let server = ServerId::from("rust");
        let generation_before_respawn = 0; // fresh tracker: generation starts at 0

        // A respawn happens "concurrently" with the in-flight call that
        // captured the generation above before this ran.
        tracker.forget_server(&server);

        let (stale_client, _guard) = fake_lsp_client();
        let decision = tracker.disk_phase(&path).await.unwrap();
        tracker
            .sync_phase(
                &path,
                &server,
                &stale_client,
                decision,
                generation_before_respawn,
            )
            .await
            .unwrap();

        let state = tracker.get(&path).unwrap();
        assert!(
            state.synced_version(&server).is_none(),
            "a sync_phase call that captured a stale generation must not \
             commit `synced`, even though its notify against the \
             superseded connection succeeded"
        );
    }

    /// Companion to the regression above: the ordinary, non-racing path
    /// (`ensure_open` capturing and committing against the *current*
    /// generation) must still work -- the generation check must not
    /// suppress a legitimate commit.
    #[tokio::test]
    async fn test_ensure_open_commits_when_generation_is_current() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("no_race.rs");
        std::fs::write(&path, "fn main() {}").unwrap();

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        let server = ServerId::from("rust");
        let (client, _guard) = fake_lsp_client();

        tracker.ensure_open(&path, &server, &client).await.unwrap();

        let state = tracker.get(&path).unwrap();
        assert_eq!(state.synced_version(&server), Some(1));
    }

    /// Marks `path`'s tracked document as disk-verified, for a test that
    /// opens a document directly via `open` (bypassing `ensure_open`'s
    /// `disk_phase`, which is what normally sets this) but still needs it
    /// eligible for `evict_lru`'s LRU eviction -- disk-verified is a
    /// precondition for eviction, not just unlocked (#495 S4).
    fn mark_disk_verified(tracker: &DocumentTracker, path: &Path) {
        tracker.set_disk(
            path,
            DiskSync {
                mtime: None,
                size: 0,
                mtime_settled: false,
                content_checked_at: Instant::now(),
            },
        );
    }

    /// #495: at capacity with every existing document unlocked and
    /// disk-verified, `open` must evict the least-recently-used one to make
    /// room rather than fail -- the evicted document is queued for
    /// `take_evicted`.
    #[test]
    fn test_document_limit_evicts_lru_instead_of_failing() {
        let limits = ResourceLimits {
            max_documents: 2,
            max_file_size: 100,
        };
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(limits, map);

        tracker
            .open(PathBuf::from("/test/file1.rs"), "fn test1() {}".to_string())
            .unwrap();
        mark_disk_verified(&tracker, Path::new("/test/file1.rs"));
        tracker
            .open(PathBuf::from("/test/file2.rs"), "fn test2() {}".to_string())
            .unwrap();
        mark_disk_verified(&tracker, Path::new("/test/file2.rs"));

        tracker
            .open(PathBuf::from("/test/file3.rs"), "fn test3() {}".to_string())
            .unwrap();

        assert_eq!(tracker.len(), 2);
        assert!(!tracker.is_open(Path::new("/test/file1.rs")));
        assert!(tracker.is_open(Path::new("/test/file2.rs")));
        assert!(tracker.is_open(Path::new("/test/file3.rs")));

        let evicted = tracker.take_evicted();
        assert_eq!(evicted.len(), 1);
        assert_eq!(evicted[0].path, PathBuf::from("/test/file1.rs"));
        assert!(
            evicted[0].synced_servers.is_empty(),
            "opened directly via `open`, never synced to any server"
        );
    }

    /// #495: `open` must fall back to `DocumentLimitExceeded` when every
    /// tracked document currently has an operation in flight against it
    /// (simulated here by inserting its `path_locks` entry directly, which
    /// is exactly what `evict_lru` checks for) -- evicting a locked document
    /// would pull it out from under that in-flight operation.
    #[test]
    fn test_document_limit_falls_back_to_error_when_only_candidate_is_locked() {
        let limits = ResourceLimits {
            max_documents: 1,
            max_file_size: 100,
        };
        let tracker = DocumentTracker::new(limits, HashMap::new());

        let locked_path = PathBuf::from("/test/locked.rs");
        tracker
            .open(locked_path.clone(), "fn locked() {}".to_string())
            .unwrap();
        lock_std(&tracker.path_locks).insert(locked_path.clone(), Arc::new(AsyncMutex::new(())));

        let result = tracker.open(PathBuf::from("/test/other.rs"), "fn other() {}".to_string());
        assert!(matches!(result, Err(Error::DocumentLimitExceeded { .. })));
        assert!(
            tracker.is_open(&locked_path),
            "the locked document must not be evicted"
        );
        assert!(tracker.take_evicted().is_empty());
    }

    /// #495 S4: a document whose content has diverged from disk (via
    /// `update`, which clears `disk` -- see `DocumentState::apply_local_edit`)
    /// must never be evicted even though it is unlocked -- evicting it would
    /// silently discard in-memory content mcpls has no other record of. No
    /// in-tree caller invokes `update` today; this guards a structural,
    /// not-yet-reachable data-loss shape rather than a currently-observed bug.
    #[tokio::test]
    async fn test_evict_lru_skips_document_with_diverged_unsaved_content() {
        let dir = TempDir::new().unwrap();
        let path_a = dir.path().join("a.rs");
        std::fs::write(&path_a, "AAAA").unwrap();
        set_mtime(&path_a, settled_past());

        let limits = ResourceLimits {
            max_documents: 1,
            max_file_size: 0,
        };
        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(limits, HashMap::new());
        let server_id = ServerId::from("rust");

        tracker
            .ensure_open(&path_a, &server_id, &client)
            .await
            .unwrap();
        // Diverge from disk: an in-memory edit not yet reflected on disk.
        tracker
            .update(&path_a, "AAAA-edited".to_string())
            .await
            .unwrap();

        let path_b = dir.path().join("b.rs");
        std::fs::write(&path_b, "BBBB").unwrap();

        let result = tracker.open(path_b, "BBBB".to_string());
        assert!(matches!(result, Err(Error::DocumentLimitExceeded { .. })));
        assert!(
            tracker.is_open(&path_a),
            "the diverged, not-disk-verified document must not be evicted"
        );
        assert_eq!(tracker.get(&path_a).unwrap().content(), "AAAA-edited");
        assert!(tracker.take_evicted().is_empty());
    }

    /// #495: `ensure_open` must bump a document's LRU recency (via
    /// `disk_phase`'s `touch`), so a document that was merely opened first
    /// but has since been re-accessed is not the one evicted -- eviction
    /// order must reflect actual usage, not just insertion order.
    #[tokio::test]
    async fn test_ensure_open_touch_changes_lru_eviction_order() {
        let dir = TempDir::new().unwrap();
        let path_a = dir.path().join("a.rs");
        let path_b = dir.path().join("b.rs");
        std::fs::write(&path_a, "AAAA").unwrap();
        std::fs::write(&path_b, "BBBB").unwrap();
        set_mtime(&path_a, settled_past());
        set_mtime(&path_b, settled_past());

        let limits = ResourceLimits {
            max_documents: 2,
            max_file_size: 0,
        };
        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(limits, HashMap::new());
        let server_id = ServerId::from("rust");

        tracker
            .ensure_open(&path_a, &server_id, &client)
            .await
            .unwrap();
        tracker
            .ensure_open(&path_b, &server_id, &client)
            .await
            .unwrap();

        // Re-access `a` so it becomes the more-recently-used of the two,
        // leaving `b` as the LRU entry despite having been opened second.
        tracker
            .ensure_open(&path_a, &server_id, &client)
            .await
            .unwrap();

        let path_c = dir.path().join("c.rs");
        std::fs::write(&path_c, "CCCC").unwrap();
        set_mtime(&path_c, settled_past());
        tracker
            .ensure_open(&path_c, &server_id, &client)
            .await
            .unwrap();

        assert!(
            tracker.is_open(&path_a),
            "recently re-accessed, must survive"
        );
        assert!(
            !tracker.is_open(&path_b),
            "least-recently-used, must be evicted"
        );
        assert!(tracker.is_open(&path_c));

        let evicted = tracker.take_evicted();
        assert_eq!(evicted.len(), 1);
        assert_eq!(evicted[0].path, path_b);
        assert_eq!(evicted[0].synced_servers, vec![server_id]);
    }

    #[test]
    fn test_file_size_limit() {
        let limits = ResourceLimits {
            max_documents: 10,
            max_file_size: 10,
        };
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(limits, map);

        // Small file should succeed
        tracker
            .open(PathBuf::from("/test/small.rs"), "fn f(){}".to_string())
            .unwrap();

        // Large file should fail
        let large_content = "x".repeat(100);
        let result = tracker.open(PathBuf::from("/test/large.rs"), large_content);
        assert!(matches!(result, Err(Error::FileSizeLimitExceeded { .. })));
    }

    #[test]
    fn test_resource_limits_default() {
        let limits = ResourceLimits::default();
        assert_eq!(limits.max_documents, 100);
        assert_eq!(limits.max_file_size, 10 * 1024 * 1024);
    }

    #[test]
    fn test_resource_limits_custom() {
        let limits = ResourceLimits {
            max_documents: 50,
            max_file_size: 5 * 1024 * 1024,
        };
        assert_eq!(limits.max_documents, 50);
        assert_eq!(limits.max_file_size, 5 * 1024 * 1024);
    }

    #[test]
    fn test_resource_limits_zero_unlimited() {
        let limits = ResourceLimits {
            max_documents: 0,
            max_file_size: 0,
        };
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(limits, map);

        // Should allow many documents when limit is 0
        for i in 0..200 {
            tracker
                .open(
                    PathBuf::from(format!("/test/file{i}.rs")),
                    "content".to_string(),
                )
                .unwrap();
        }
        assert_eq!(tracker.len(), 200);

        // Should allow large files when limit is 0
        let huge_content = "x".repeat(100_000_000);
        tracker
            .open(PathBuf::from("/test/huge.rs"), huge_content)
            .unwrap();
    }

    #[test]
    fn test_document_state_clone() {
        let state = DocumentState {
            uri: Uri::from("file:///test.rs"),
            language_id: "rust".to_string(),
            version: 5,
            content: "fn main() {}".to_string(),
            disk: None,
            synced: HashMap::new(),
            last_accessed: Instant::now(),
        };

        #[allow(clippy::redundant_clone)]
        let cloned = state.clone();
        assert_eq!(cloned.uri(), state.uri());
        assert_eq!(cloned.language_id(), state.language_id());
        assert_eq!(cloned.version(), 5);
        assert_eq!(cloned.content(), state.content());
    }

    #[tokio::test]
    async fn test_update_nonexistent_document() {
        let map = HashMap::new();
        let tracker = DocumentTracker::new(ResourceLimits::default(), map);
        let path = PathBuf::from("/test/nonexistent.rs");

        let version = tracker.update(&path, "new content".to_string()).await;
        assert_eq!(
            version, None,
            "Updating non-existent document should return None"
        );
    }

    #[test]
    fn test_close_nonexistent_document() {
        let map = HashMap::new();
        let tracker = DocumentTracker::new(ResourceLimits::default(), map);
        let path = PathBuf::from("/test/nonexistent.rs");

        let state = tracker.close(&path);
        assert_eq!(
            state, None,
            "Closing non-existent document should return None"
        );
    }

    #[test]
    fn test_close_all_documents() {
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(ResourceLimits::default(), map);

        tracker
            .open(PathBuf::from("/test/file1.rs"), "content1".to_string())
            .unwrap();
        tracker
            .open(PathBuf::from("/test/file2.rs"), "content2".to_string())
            .unwrap();
        tracker
            .open(PathBuf::from("/test/file3.rs"), "content3".to_string())
            .unwrap();

        assert_eq!(tracker.len(), 3);

        let closed = tracker.close_all();
        assert_eq!(closed.len(), 3);
        assert!(tracker.is_empty());
    }

    #[test]
    fn test_get_nonexistent_document() {
        let map = HashMap::new();
        let tracker = DocumentTracker::new(ResourceLimits::default(), map);
        let path = PathBuf::from("/test/nonexistent.rs");

        let state = tracker.get(&path);
        assert!(
            state.is_none(),
            "Getting non-existent document should return None"
        );
    }

    #[tokio::test]
    async fn test_document_version_increments() {
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(ResourceLimits::default(), map);
        let path = PathBuf::from("/test/versioned.rs");

        tracker.open(path.clone(), "v1".to_string()).unwrap();
        assert_eq!(tracker.get(&path).unwrap().version(), 1);

        tracker.update(&path, "v2".to_string()).await;
        assert_eq!(tracker.get(&path).unwrap().version(), 2);

        tracker.update(&path, "v3".to_string()).await;
        assert_eq!(tracker.get(&path).unwrap().version(), 3);

        tracker.update(&path, "v4".to_string()).await;
        assert_eq!(tracker.get(&path).unwrap().version(), 4);
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn test_detect_language_all_extensions() {
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());
        map.insert("py".to_string(), "python".to_string());
        map.insert("pyw".to_string(), "python".to_string());
        map.insert("pyi".to_string(), "python".to_string());
        map.insert("js".to_string(), "javascript".to_string());
        map.insert("mjs".to_string(), "javascript".to_string());
        map.insert("cjs".to_string(), "javascript".to_string());
        map.insert("ts".to_string(), "typescript".to_string());
        map.insert("mts".to_string(), "typescript".to_string());
        map.insert("cts".to_string(), "typescript".to_string());
        map.insert("tsx".to_string(), "typescriptreact".to_string());
        map.insert("jsx".to_string(), "javascriptreact".to_string());
        map.insert("go".to_string(), "go".to_string());
        map.insert("c".to_string(), "c".to_string());
        map.insert("h".to_string(), "c".to_string());
        map.insert("cpp".to_string(), "cpp".to_string());
        map.insert("cc".to_string(), "cpp".to_string());
        map.insert("cxx".to_string(), "cpp".to_string());
        map.insert("hpp".to_string(), "cpp".to_string());
        map.insert("hh".to_string(), "cpp".to_string());
        map.insert("hxx".to_string(), "cpp".to_string());
        map.insert("java".to_string(), "java".to_string());
        map.insert("rb".to_string(), "ruby".to_string());
        map.insert("php".to_string(), "php".to_string());
        map.insert("swift".to_string(), "swift".to_string());
        map.insert("kt".to_string(), "kotlin".to_string());
        map.insert("kts".to_string(), "kotlin".to_string());
        map.insert("scala".to_string(), "scala".to_string());
        map.insert("sc".to_string(), "scala".to_string());
        map.insert("zig".to_string(), "zig".to_string());
        map.insert("lua".to_string(), "lua".to_string());
        map.insert("sh".to_string(), "shellscript".to_string());
        map.insert("bash".to_string(), "shellscript".to_string());
        map.insert("zsh".to_string(), "shellscript".to_string());
        map.insert("json".to_string(), "json".to_string());
        map.insert("toml".to_string(), "toml".to_string());
        map.insert("yaml".to_string(), "yaml".to_string());
        map.insert("yml".to_string(), "yaml".to_string());
        map.insert("xml".to_string(), "xml".to_string());
        map.insert("html".to_string(), "html".to_string());
        map.insert("htm".to_string(), "html".to_string());
        map.insert("css".to_string(), "css".to_string());
        map.insert("scss".to_string(), "scss".to_string());
        map.insert("less".to_string(), "less".to_string());
        map.insert("md".to_string(), "markdown".to_string());
        map.insert("markdown".to_string(), "markdown".to_string());

        assert_eq!(detect_language(Path::new("main.rs"), &map), "rust");
        assert_eq!(detect_language(Path::new("script.py"), &map), "python");
        assert_eq!(detect_language(Path::new("script.pyw"), &map), "python");
        assert_eq!(detect_language(Path::new("script.pyi"), &map), "python");
        assert_eq!(detect_language(Path::new("app.js"), &map), "javascript");
        assert_eq!(detect_language(Path::new("app.mjs"), &map), "javascript");
        assert_eq!(detect_language(Path::new("app.cjs"), &map), "javascript");
        assert_eq!(detect_language(Path::new("app.ts"), &map), "typescript");
        assert_eq!(detect_language(Path::new("app.mts"), &map), "typescript");
        assert_eq!(detect_language(Path::new("app.cts"), &map), "typescript");
        assert_eq!(
            detect_language(Path::new("component.tsx"), &map),
            "typescriptreact"
        );
        assert_eq!(
            detect_language(Path::new("component.jsx"), &map),
            "javascriptreact"
        );
        assert_eq!(detect_language(Path::new("main.go"), &map), "go");
        assert_eq!(detect_language(Path::new("main.c"), &map), "c");
        assert_eq!(detect_language(Path::new("header.h"), &map), "c");
        assert_eq!(detect_language(Path::new("main.cpp"), &map), "cpp");
        assert_eq!(detect_language(Path::new("main.cc"), &map), "cpp");
        assert_eq!(detect_language(Path::new("main.cxx"), &map), "cpp");
        assert_eq!(detect_language(Path::new("header.hpp"), &map), "cpp");
        assert_eq!(detect_language(Path::new("header.hh"), &map), "cpp");
        assert_eq!(detect_language(Path::new("header.hxx"), &map), "cpp");
        assert_eq!(detect_language(Path::new("Main.java"), &map), "java");
        assert_eq!(detect_language(Path::new("script.rb"), &map), "ruby");
        assert_eq!(detect_language(Path::new("index.php"), &map), "php");
        assert_eq!(detect_language(Path::new("App.swift"), &map), "swift");
        assert_eq!(detect_language(Path::new("Main.kt"), &map), "kotlin");
        assert_eq!(detect_language(Path::new("script.kts"), &map), "kotlin");
        assert_eq!(detect_language(Path::new("Main.scala"), &map), "scala");
        assert_eq!(detect_language(Path::new("script.sc"), &map), "scala");
        assert_eq!(detect_language(Path::new("main.zig"), &map), "zig");
        assert_eq!(detect_language(Path::new("script.lua"), &map), "lua");
        assert_eq!(detect_language(Path::new("script.sh"), &map), "shellscript");
        assert_eq!(
            detect_language(Path::new("script.bash"), &map),
            "shellscript"
        );
        assert_eq!(
            detect_language(Path::new("script.zsh"), &map),
            "shellscript"
        );
        assert_eq!(detect_language(Path::new("data.json"), &map), "json");
        assert_eq!(detect_language(Path::new("config.toml"), &map), "toml");
        assert_eq!(detect_language(Path::new("config.yaml"), &map), "yaml");
        assert_eq!(detect_language(Path::new("config.yml"), &map), "yaml");
        assert_eq!(detect_language(Path::new("data.xml"), &map), "xml");
        assert_eq!(detect_language(Path::new("index.html"), &map), "html");
        assert_eq!(detect_language(Path::new("index.htm"), &map), "html");
        assert_eq!(detect_language(Path::new("styles.css"), &map), "css");
        assert_eq!(detect_language(Path::new("styles.scss"), &map), "scss");
        assert_eq!(detect_language(Path::new("styles.less"), &map), "less");
        assert_eq!(detect_language(Path::new("README.md"), &map), "markdown");
        assert_eq!(
            detect_language(Path::new("README.markdown"), &map),
            "markdown"
        );
        assert_eq!(detect_language(Path::new("unknown.xyz"), &map), "plaintext");
        assert_eq!(
            detect_language(Path::new("no_extension"), &map),
            "plaintext"
        );
    }

    #[test]
    fn test_path_to_uri_unix() {
        #[cfg(not(windows))]
        {
            let path = Path::new("/home/user/project/main.rs");
            let uri = path_to_uri(path).unwrap();
            assert!(
                uri.as_ref()
                    .starts_with("file:///home/user/project/main.rs")
            );
        }
    }

    #[test]
    fn test_path_to_uri_with_special_chars() {
        let path = Path::new("/home/user/project-test/main.rs");
        let uri = path_to_uri(path).unwrap();
        assert!(uri.as_ref().starts_with("file://"));
        assert!(uri.as_ref().contains("project-test"));
    }

    #[test]
    fn test_path_to_uri_percent_encodes_reserved_chars() {
        #[cfg(windows)]
        let path = Path::new(r"C:\home\user\routes\api\[...]^|.ts");
        #[cfg(not(windows))]
        let path = Path::new("/home/user/routes/api/[...]^|.ts");

        let uri = path_to_uri(path).unwrap();

        #[cfg(windows)]
        let expected = "file:///C:/home/user/routes/api/%5B...%5D%5E%7C.ts";
        #[cfg(not(windows))]
        let expected = "file:///home/user/routes/api/%5B...%5D%5E%7C.ts";

        assert_eq!(uri.as_ref(), expected);
        assert_eq!(
            uri_to_path(&uri).as_deref(),
            Some(path),
            "encoded file URI should round-trip to the original path"
        );
    }

    #[test]
    fn test_try_path_to_uri_returns_none_for_relative_path() {
        assert_eq!(try_path_to_uri(Path::new("relative/file.ts")), None);
    }

    /// #234 regression: `path_to_uri` must surface a conversion failure as
    /// `Err`, not panic -- the whole point of the fix was making this path
    /// testable instead of aborting the process.
    #[test]
    fn test_path_to_uri_returns_err_for_relative_path() {
        let err = path_to_uri(Path::new("relative/file.ts")).unwrap_err();
        assert!(matches!(err, Error::InvalidUri(_)));
    }

    #[cfg(windows)]
    #[test]
    fn test_try_path_to_uri_encodes_synthetic_windows_root() {
        let uri = try_path_to_uri(Path::new("/home/user/#work %23")).unwrap();

        assert_eq!(uri.as_ref(), "file:///home/user/%23work%20%2523");
    }

    /// A rooted-but-not-absolute Windows path (`\foo`, no drive/UNC prefix)
    /// satisfies `Path::has_root()` but not `Path::is_absolute()`.
    /// `file_url`'s `#[cfg(windows)]` variant deliberately falls back to
    /// `windows_rooted_path_to_file_url` on this exact case -- pinned here so
    /// a future change to `try_path_to_uri` (e.g. swapping the fallible
    /// `.parse()` this migration replaced for an `is_absolute()` guard)
    /// cannot silently narrow this without failing a test.
    #[cfg(windows)]
    #[test]
    fn test_try_path_to_uri_accepts_rooted_but_not_absolute_windows_path() {
        let path = Path::new(r"\foo");
        assert!(path.has_root());
        assert!(!path.is_absolute());

        let uri = try_path_to_uri(path).unwrap();

        assert_eq!(uri.as_ref(), "file:///foo");
    }

    #[test]
    fn test_path_to_uri_percent_encodes_reserved_chars_in_short_path() {
        // Regression: reserved chars near the URI start must still be encoded.
        #[cfg(windows)]
        let path = Path::new(r"C:\[a].ts");
        #[cfg(not(windows))]
        let path = Path::new("/[a].ts");

        let uri = path_to_uri(path).unwrap();

        assert!(
            uri.as_ref().ends_with("%5Ba%5D.ts"),
            "short path should percent-encode reserved chars, got {}",
            uri.as_ref()
        );
        assert_eq!(uri_to_path(&uri).as_deref(), Some(path));
    }

    #[test]
    fn test_path_to_uri_percent_encodes_all_rfc3986_other_reserved_chars() {
        // RFC 3986 §2.2 "other reserved" characters. The `url` crate already
        // percent-encodes `{`, `}`, and backtick when serializing; `[`, `]`,
        // `^`, `|` are handled explicitly by `encode_rfc3986_path_chars`.
        #[cfg(windows)]
        let path = Path::new(r"C:\home\user\test[]^|{}`.ts");
        #[cfg(not(windows))]
        let path = Path::new("/home/user/test[]^|{}`.ts");

        let uri = try_path_to_uri(path).unwrap();
        let uri_str = uri.as_ref();

        for (raw, encoded) in [
            ('[', "%5B"),
            (']', "%5D"),
            ('^', "%5E"),
            ('|', "%7C"),
            ('{', "%7B"),
            ('}', "%7D"),
            ('`', "%60"),
        ] {
            assert!(
                uri_str.contains(encoded),
                "expected {raw:?} to be percent-encoded as {encoded} in {uri_str}"
            );
        }
        assert!(
            !uri_str.contains(['[', ']', '^', '|', '{', '}', '`']),
            "no raw reserved characters should remain in {uri_str}"
        );
    }

    #[tokio::test]
    async fn test_document_tracker_concurrent_operations() {
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(ResourceLimits::default(), map);
        let path1 = PathBuf::from("/test/file1.rs");
        let path2 = PathBuf::from("/test/file2.rs");

        tracker.open(path1.clone(), "content1".to_string()).unwrap();
        tracker.open(path2.clone(), "content2".to_string()).unwrap();

        assert_eq!(tracker.len(), 2);
        assert!(tracker.is_open(&path1));
        assert!(tracker.is_open(&path2));

        tracker.update(&path1, "new content1".to_string()).await;
        assert_eq!(tracker.get(&path1).unwrap().content(), "new content1");
        assert_eq!(tracker.get(&path2).unwrap().content(), "content2");

        tracker.close(&path1);
        assert_eq!(tracker.len(), 1);
        assert!(!tracker.is_open(&path1));
        assert!(tracker.is_open(&path2));
    }

    #[test]
    fn test_empty_content() {
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(ResourceLimits::default(), map);
        let path = PathBuf::from("/test/empty.rs");

        tracker.open(path.clone(), String::new()).unwrap();
        assert!(tracker.is_open(&path));
        assert_eq!(tracker.get(&path).unwrap().content(), "");
    }

    #[test]
    fn test_unicode_content() {
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(ResourceLimits::default(), map);
        let path = PathBuf::from("/test/unicode.rs");
        let content = "fn テスト() { println!(\"こんにちは\"); }";

        tracker.open(path.clone(), content.to_string()).unwrap();
        assert_eq!(tracker.get(&path).unwrap().content(), content);
    }

    /// #495: at exactly `max_documents`, `open` must evict the LRU entry
    /// (here `file0`, the first opened) rather than fail, since none of the
    /// existing documents are locked and all are disk-verified.
    #[test]
    fn test_document_limit_exact_boundary() {
        let limits = ResourceLimits {
            max_documents: 5,
            max_file_size: 1000,
        };
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(limits, map);

        for i in 0..5 {
            let path = PathBuf::from(format!("/test/file{i}.rs"));
            tracker.open(path.clone(), "content".to_string()).unwrap();
            mark_disk_verified(&tracker, &path);
        }

        assert_eq!(tracker.len(), 5);

        tracker
            .open(PathBuf::from("/test/file6.rs"), "content".to_string())
            .unwrap();

        assert_eq!(tracker.len(), 5);
        assert!(!tracker.is_open(Path::new("/test/file0.rs")));
        assert!(tracker.is_open(Path::new("/test/file6.rs")));
    }

    #[test]
    fn test_file_size_exact_boundary() {
        let limits = ResourceLimits {
            max_documents: 10,
            max_file_size: 100,
        };
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(limits, map);

        let exact_size_content = "x".repeat(100);
        tracker
            .open(PathBuf::from("/test/exact.rs"), exact_size_content)
            .unwrap();

        let over_size_content = "x".repeat(101);
        let result = tracker.open(PathBuf::from("/test/over.rs"), over_size_content);
        assert!(matches!(result, Err(Error::FileSizeLimitExceeded { .. })));
    }

    #[test]
    fn test_detect_language_with_custom_extension() {
        let mut map = HashMap::new();
        map.insert("nu".to_string(), "nushell".to_string());

        assert_eq!(detect_language(Path::new("script.nu"), &map), "nushell");

        let empty_map = HashMap::new();
        assert_eq!(
            detect_language(Path::new("script.nu"), &empty_map),
            "plaintext"
        );
    }

    #[test]
    fn test_detect_language_custom_overrides_default() {
        let mut custom_map = HashMap::new();
        custom_map.insert("rs".to_string(), "custom-rust".to_string());

        assert_eq!(
            detect_language(Path::new("main.rs"), &custom_map),
            "custom-rust"
        );

        let mut default_map = HashMap::new();
        default_map.insert("rs".to_string(), "rust".to_string());

        assert_eq!(detect_language(Path::new("main.rs"), &default_map), "rust");
    }

    #[test]
    fn test_detect_language_fallback_to_plaintext() {
        let mut map = HashMap::new();
        map.insert("nu".to_string(), "nushell".to_string());

        // .rs not in custom map, should return plaintext
        assert_eq!(detect_language(Path::new("main.rs"), &map), "plaintext");
    }

    #[test]
    fn test_detect_language_empty_map() {
        let map = HashMap::new();
        assert_eq!(detect_language(Path::new("main.rs"), &map), "plaintext");
    }

    #[test]
    fn test_document_tracker_with_extensions() {
        let mut map = HashMap::new();
        map.insert("nu".to_string(), "nushell".to_string());

        let tracker = DocumentTracker::new(ResourceLimits::default(), map);

        let path = PathBuf::from("/test/script.nu");
        tracker
            .open(path.clone(), "# nushell script".to_string())
            .unwrap();

        let state = tracker.get(&path).unwrap();
        assert_eq!(state.language_id(), "nushell");
    }

    #[test]
    fn test_document_tracker_uses_provided_map() {
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());

        let tracker = DocumentTracker::new(ResourceLimits::default(), map);
        let path = PathBuf::from("/test/main.rs");
        tracker
            .open(path.clone(), "fn main() {}".to_string())
            .unwrap();

        let state = tracker.get(&path).unwrap();
        assert_eq!(state.language_id(), "rust");
    }

    #[test]
    fn test_multiple_extensions_same_language() {
        let mut map = HashMap::new();
        map.insert("cpp".to_string(), "c++".to_string());
        map.insert("cc".to_string(), "c++".to_string());
        map.insert("cxx".to_string(), "c++".to_string());

        assert_eq!(detect_language(Path::new("main.cpp"), &map), "c++");
        assert_eq!(detect_language(Path::new("main.cc"), &map), "c++");
        assert_eq!(detect_language(Path::new("main.cxx"), &map), "c++");
    }

    #[test]
    fn test_case_sensitive_extensions() {
        let mut map = HashMap::new();
        map.insert("NU".to_string(), "nushell".to_string());

        // Lowercase .nu should not match uppercase "NU" in map
        assert_eq!(detect_language(Path::new("script.nu"), &map), "plaintext");
    }

    // ------------------------------------------------------------------
    // uri_to_path
    // ------------------------------------------------------------------

    #[cfg(unix)]
    #[test]
    fn test_uri_to_path_file_scheme() {
        let uri: Uri = Uri::from("file:///home/user/main.rs");
        let path = uri_to_path(&uri).unwrap();
        assert_eq!(path, PathBuf::from("/home/user/main.rs"));
    }

    #[test]
    fn test_uri_to_path_non_file_scheme_returns_none() {
        let uri: Uri = Uri::from("https://example.com/file.rs");
        assert!(uri_to_path(&uri).is_none());
    }

    #[test]
    fn test_uri_to_path_lsp_diagnostics_scheme_returns_none() {
        // Custom scheme must not be decoded by uri_to_path.
        let uri: Uri = Uri::from("lsp-diagnostics:///home/user/main.rs");
        assert!(uri_to_path(&uri).is_none());
    }

    #[test]
    fn test_uri_to_path_with_authority_returns_none() {
        // Authority-bearing file URIs must be rejected (UNC path defence).
        // lsp_types::Uri may or may not accept this string; either way
        // uri_to_path should return None.
        let result = uri_to_path(&Uri::from("file://server/share/path.rs"));
        assert!(result.is_none());
    }

    // ------------------------------------------------------------------
    // open_paths
    // ------------------------------------------------------------------

    #[test]
    fn test_open_paths_empty_tracker() {
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        assert_eq!(tracker.open_paths().len(), 0);
    }

    #[test]
    fn test_open_paths_populated_tracker() {
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());
        let tracker = DocumentTracker::new(ResourceLimits::default(), map);
        tracker.open(PathBuf::from("/a.rs"), String::new()).unwrap();
        tracker.open(PathBuf::from("/b.rs"), String::new()).unwrap();
        let mut paths = tracker.open_paths();
        paths.sort();
        assert_eq!(paths, [PathBuf::from("/a.rs"), PathBuf::from("/b.rs")]);
    }

    #[test]
    fn test_open_paths_after_close() {
        let mut map = HashMap::new();
        map.insert("rs".to_string(), "rust".to_string());
        let tracker = DocumentTracker::new(ResourceLimits::default(), map);
        tracker.open(PathBuf::from("/a.rs"), String::new()).unwrap();
        tracker.close(Path::new("/a.rs"));
        assert_eq!(tracker.open_paths().len(), 0);
    }

    // ------------------------------------------------------------------
    // ensure_open resync (issue #102)
    // ------------------------------------------------------------------

    use tempfile::TempDir;
    use tokio::io::BufReader;

    use crate::test_lsp::{fake_lsp_client, read_framed_message};

    /// Backdates or forwards a file's mtime for deterministic disk-sync tests.
    ///
    /// Opened with `write(true)` rather than [`std::fs::File::open`]: on
    /// Windows, `set_modified` needs a handle with write access, and a
    /// read-only handle fails with `PermissionDenied` (Unix's
    /// `utimensat`-based implementation has no such requirement, which is
    /// why a read-only handle works there).
    fn set_mtime(path: &Path, time: SystemTime) {
        let file = std::fs::OpenOptions::new().write(true).open(path).unwrap();
        file.set_modified(time).unwrap();
    }

    fn settled_past() -> SystemTime {
        SystemTime::now() - Duration::from_secs(10)
    }

    #[test]
    fn test_mtime_settled_boundary() {
        let read_at = SystemTime::now();
        assert!(!mtime_settled(None, read_at), "no mtime is never settled");
        assert!(
            mtime_settled(Some(read_at - Duration::from_secs(3)), read_at),
            "3s older than read_at is past the 2s granularity margin"
        );
        assert!(
            !mtime_settled(Some(read_at - Duration::from_secs(1)), read_at),
            "1s older than read_at is within the 2s granularity margin"
        );
        assert!(
            !mtime_settled(Some(read_at + Duration::from_secs(10)), read_at),
            "an mtime after read_at is never settled"
        );
    }

    #[tokio::test]
    async fn test_ensure_open_unchanged_file_is_fast_path() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn main() {}").unwrap();
        set_mtime(&path, settled_past());

        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());

        let uri1 = tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        assert_eq!(tracker.get(&path).unwrap().version(), 1);

        let uri2 = tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        assert_eq!(uri1, uri2);
        assert_eq!(tracker.get(&path).unwrap().version(), 1);
        assert_eq!(tracker.get(&path).unwrap().content(), "fn main() {}");
    }

    #[tokio::test]
    async fn test_ensure_open_resyncs_on_size_change() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn main() {}").unwrap();
        set_mtime(&path, settled_past());

        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();

        std::fs::write(&path, "fn main() { println!(\"hi\"); }").unwrap();
        set_mtime(&path, settled_past());

        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        let state = tracker.get(&path).unwrap();
        assert_eq!(state.version(), 2);
        assert_eq!(state.content(), "fn main() { println!(\"hi\"); }");
    }

    #[tokio::test(start_paused = true)]
    async fn test_ensure_open_regression_102_103_racy_same_size_rewrite() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "AAAA").unwrap();
        // Leave the mtime at "now" (racy) rather than backdating it.

        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        let original_mtime = std::fs::metadata(&path).unwrap().modified().unwrap();

        // Same-length rewrite with the mtime forced back to the recorded
        // value -- exactly the same-tick rewrite issue #102/#103 missed.
        std::fs::write(&path, "BBBB").unwrap();
        set_mtime(&path, original_mtime);

        tokio::time::advance(DISK_CHECK_DEBOUNCE + Duration::from_millis(1)).await;

        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        let state = tracker.get(&path).unwrap();
        assert_eq!(
            state.version(),
            2,
            "must resync despite identical (mtime, size)"
        );
        assert_eq!(state.content(), "BBBB");
    }

    #[tokio::test(start_paused = true)]
    async fn test_ensure_open_regression_102_103_settled_mtime_is_the_documented_limit() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "AAAA").unwrap();
        set_mtime(&path, settled_past());

        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        let original_mtime = std::fs::metadata(&path).unwrap().modified().unwrap();

        // Same-length rewrite restoring an already-settled mtime: this is
        // the documented residual limitation (e.g. `tar x`, `rsync -a`),
        // not a bug -- it is out of reach without hashing on every access.
        std::fs::write(&path, "BBBB").unwrap();
        set_mtime(&path, original_mtime);

        tokio::time::advance(DISK_CHECK_DEBOUNCE + Duration::from_millis(1)).await;

        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        let state = tracker.get(&path).unwrap();
        assert_eq!(state.version(), 1, "documented limitation: fast path taken");
        assert_eq!(state.content(), "AAAA");
    }

    #[tokio::test(start_paused = true)]
    async fn test_ensure_open_stat_is_never_debounced() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "AAAA").unwrap();
        set_mtime(&path, settled_past());

        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();

        // Different-size rewrite with no time advance at all: must resync
        // immediately, proving the debounce never gates the stat itself.
        std::fs::write(&path, "BBBBBBBB").unwrap();
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();

        let state = tracker.get(&path).unwrap();
        assert_eq!(state.version(), 2);
        assert_eq!(state.content(), "BBBBBBBB");
    }

    #[tokio::test(start_paused = true)]
    async fn test_ensure_open_debounce_gates_reread_only() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "AAAA").unwrap();
        // Racy: leave the mtime at "now".

        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        let original_mtime = std::fs::metadata(&path).unwrap().modified().unwrap();

        std::fs::write(&path, "BBBB").unwrap(); // same size
        set_mtime(&path, original_mtime); // stat matches, entry stays racy

        // Inside the debounce window: the re-read is gated, cache wins.
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        assert_eq!(tracker.get(&path).unwrap().version(), 1);

        tokio::time::advance(Duration::from_millis(300)).await;
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        let state = tracker.get(&path).unwrap();
        assert_eq!(state.version(), 2);
        assert_eq!(state.content(), "BBBB");
    }

    #[tokio::test]
    async fn test_ensure_open_deleted_file_errors_state_untouched() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn main() {}").unwrap();
        set_mtime(&path, settled_past());

        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();

        std::fs::remove_file(&path).unwrap();

        let result = tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await;
        assert!(matches!(result, Err(Error::FileIo { .. })));
        assert!(tracker.is_open(&path));
        assert_eq!(tracker.get(&path).unwrap().version(), 1);
        assert_eq!(tracker.get(&path).unwrap().content(), "fn main() {}");
    }

    #[tokio::test]
    async fn test_ensure_open_grows_past_limit_errors_state_intact() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "small").unwrap();
        set_mtime(&path, settled_past());

        let limits = ResourceLimits {
            max_documents: 10,
            max_file_size: 10,
        };
        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(limits, HashMap::new());
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();

        std::fs::write(&path, "x".repeat(100)).unwrap();

        let result = tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await;
        assert!(matches!(result, Err(Error::FileSizeLimitExceeded { .. })));
        assert_eq!(tracker.get(&path).unwrap().content(), "small");
        assert_eq!(tracker.get(&path).unwrap().version(), 1);
    }

    #[tokio::test]
    async fn test_ensure_open_resync_at_document_capacity() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "AAAA").unwrap();
        set_mtime(&path, settled_past());

        let limits = ResourceLimits {
            max_documents: 1,
            max_file_size: 0,
        };
        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(limits, HashMap::new());
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        assert_eq!(tracker.len(), 1);

        std::fs::write(&path, "BBBBBBBB").unwrap();
        let result = tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await;
        assert!(
            result.is_ok(),
            "resync must not re-run the doc-count check on an already-tracked path"
        );
        assert_eq!(tracker.len(), 1);
        assert_eq!(tracker.get(&path).unwrap().version(), 2);
    }

    #[tokio::test]
    async fn test_update_clears_disk_provenance() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn main() {}").unwrap();
        set_mtime(&path, settled_past());

        let (client, _server) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();
        assert!(tracker.get(&path).unwrap().disk.is_some());

        tracker
            .update(&path, "fn main() { updated(); }".to_string())
            .await;
        assert!(
            tracker.get(&path).unwrap().disk.is_none(),
            "update() must clear disk provenance so the next ensure_open re-verifies by content"
        );
    }

    #[tokio::test]
    async fn test_first_open_self_heals_when_did_open_notify_fails() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn main() {}").unwrap();

        let (client, _server) = fake_lsp_client();
        // A clone shares the same command channel. Shutting down the
        // original (which owns the receiver task) blocks until the
        // background message loop has fully exited and dropped that
        // channel's receiver -- so the clone's next `notify()` fails
        // deterministically, with no race against process teardown.
        let notify_will_fail = client.clone();
        client.shutdown().await.unwrap();

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        let result = tracker
            .ensure_open(&path, &ServerId::from("rust"), &notify_will_fail)
            .await;

        assert!(result.is_err(), "notify failure must propagate as an error");
        assert!(
            !tracker.is_open(&path),
            "a failed didOpen must not leave the document tracked, or the server \
             and tracker would stay permanently desynced"
        );
    }

    #[tokio::test]
    async fn test_resync_sends_didchange_with_full_replacement_over_the_wire() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn main() {}").unwrap();
        set_mtime(&path, settled_past());

        let (client, mut server) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();

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

        std::fs::write(&path, "fn main() { println!(\"hi\"); }").unwrap();
        set_mtime(&path, settled_past());
        tracker
            .ensure_open(&path, &ServerId::from("rust"), &client)
            .await
            .unwrap();

        let changed = read_framed_message(&mut wire).await;
        assert_eq!(changed["method"], "textDocument/didChange");
        let params = &changed["params"];
        assert_eq!(params["textDocument"]["version"], 2);
        let change = &params["contentChanges"][0];
        assert!(
            change.get("range").is_none(),
            "range must be omitted, not null, for a full-replacement change"
        );
        assert!(
            change.get("rangeLength").is_none(),
            "rangeLength must be omitted, not null, for a full-replacement change"
        );
        assert_eq!(change["text"], "fn main() { println!(\"hi\"); }");
    }

    /// Regression for #174 §7.1: a second server must receive `didOpen` even
    /// when the file has not changed since a first server was opened on it --
    /// the disk-phase fast path only skips the disk read, never the
    /// per-server sync decision. Exercises the settled-mtime fast path.
    #[tokio::test]
    async fn test_ensure_open_second_server_gets_didopen_no_disk_change() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn main() {}").unwrap();
        set_mtime(&path, settled_past());

        let (client_a, mut server_a) = fake_lsp_client();
        let (client_b, mut server_b) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());

        let id_a = ServerId::from("server-a");
        let id_b = ServerId::from("server-b");

        tracker.ensure_open(&path, &id_a, &client_a).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");

        // No disk change between calls: server B's ensure_open must still
        // take the disk-phase fast path (settled mtime) but still send B its
        // own didOpen.
        tracker.ensure_open(&path, &id_b, &client_b).await.unwrap();
        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");
        assert_eq!(opened_b["params"]["textDocument"]["version"], 1);
        assert_eq!(opened_b["params"]["textDocument"]["text"], "fn main() {}");
    }

    /// Same as above but through the unchanged-content re-read path (racy,
    /// unsettled mtime past the debounce window, forcing a real content
    /// compare) rather than the settled-mtime fast path.
    #[tokio::test(start_paused = true)]
    async fn test_ensure_open_second_server_gets_didopen_unchanged_content_path() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn main() {}").unwrap();
        // Leave mtime racy (unsettled) rather than backdating it.

        let (client_a, _server_a) = fake_lsp_client();
        let (client_b, mut server_b) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());

        tracker
            .ensure_open(&path, &ServerId::from("server-a"), &client_a)
            .await
            .unwrap();

        // Past the debounce window: server B's call must genuinely re-read
        // and compare content rather than taking either fast-path leg.
        tokio::time::advance(DISK_CHECK_DEBOUNCE + Duration::from_millis(1)).await;

        tracker
            .ensure_open(&path, &ServerId::from("server-b"), &client_b)
            .await
            .unwrap();
        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");
    }

    /// Regression for #174 §6.2/§12: `prepare_call_hierarchy` and
    /// `incoming_calls`/`outgoing_calls` must resolve to the same server, since
    /// only `prepare` calls `ensure_open` -- pinned here at the tracker level
    /// by asserting a second `ensure_open` for the same server is a no-op
    /// once synced, so a caller that reuses the same `ServerId` for both
    /// calls never double-opens.
    #[tokio::test]
    async fn test_ensure_open_same_server_twice_sends_nothing_second_time() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn main() {}").unwrap();
        set_mtime(&path, settled_past());

        let (client, mut server) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        let id = ServerId::from("rust");

        tracker.ensure_open(&path, &id, &client).await.unwrap();
        tracker.ensure_open(&path, &id, &client).await.unwrap();

        let mut wire = BufReader::new(&mut server.write_stdout);
        let opened = read_framed_message(&mut wire).await;
        assert_eq!(opened["method"], "textDocument/didOpen");
        assert_eq!(
            tracker.get(&path).unwrap().synced_version(&id),
            Some(1),
            "second call for the same server must not re-open or re-change"
        );
    }

    /// Regression for #174 §7.2/S6: a failing `didChange` for one server must
    /// leave that server's `synced` entry untouched (self-heals on retry)
    /// without disturbing another server that already synced successfully.
    #[tokio::test]
    async fn test_sync_phase_failed_didchange_does_not_disturb_other_server() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn main() {}").unwrap();
        set_mtime(&path, settled_past());

        let (client_a, _server_a) = fake_lsp_client();
        let (client_b, _server_b) = fake_lsp_client();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        let id_a = ServerId::from("server-a");
        let id_b = ServerId::from("server-b");

        tracker.ensure_open(&path, &id_a, &client_a).await.unwrap();
        tracker.ensure_open(&path, &id_b, &client_b).await.unwrap();

        // Shut down B's client so its next notify fails, then change the file
        // so both servers have version 2 to catch up to.
        let client_b_will_fail = client_b.clone();
        client_b.shutdown().await.unwrap();

        std::fs::write(&path, "fn main() { updated(); }").unwrap();
        set_mtime(&path, settled_past());

        let result = tracker.ensure_open(&path, &id_b, &client_b_will_fail).await;
        assert!(result.is_err(), "B's didChange must fail and propagate");

        // No commit happens before a successful notify: content, version and
        // both servers' `synced` entries all stay exactly as they were
        // before this call, so the next attempt retries from the same
        // starting point rather than drifting the tracker out of sync with
        // what was actually acknowledged over the wire.
        assert!(tracker.is_open(&path));
        assert_eq!(tracker.get(&path).unwrap().content(), "fn main() {}");
        assert_eq!(tracker.get(&path).unwrap().version(), 1);
        assert_eq!(tracker.get(&path).unwrap().synced_version(&id_a), Some(1));
        assert_eq!(tracker.get(&path).unwrap().synced_version(&id_b), Some(1));

        // A's next call must independently detect the disk change (B's
        // failure did not consume it) and successfully advance both the
        // shared content/version and its own synced entry.
        tracker.ensure_open(&path, &id_a, &client_a).await.unwrap();
        assert_eq!(
            tracker.get(&path).unwrap().content(),
            "fn main() { updated(); }"
        );
        assert_eq!(tracker.get(&path).unwrap().synced_version(&id_a), Some(2));
        assert_eq!(tracker.get(&path).unwrap().synced_version(&id_b), Some(1));
    }

    // ------------------------------------------------------------------
    // ensure_open concurrency (issue #227)
    // ------------------------------------------------------------------

    /// Regression for #227: `ensure_open` for one path must not block
    /// `ensure_open` for an unrelated path, even while the first call is
    /// stuck inside its own disk I/O.
    ///
    /// Path A's own `ensure_open` call is genuinely parked on path A's
    /// per-path lock: `path_a_guard` (held via `lock_path`, the exact
    /// primitive `ensure_open` acquires before its disk I/O) is taken first,
    /// then a *real*, spawned `ensure_open(path_a)` call is raced against
    /// it, so the serialization point under test is inside `ensure_open`
    /// itself, not merely the standalone `lock_path` guard. Previously this
    /// used a FIFO, whose `open()` for read blocked deterministically until
    /// a writer connected; that is no longer usable for this purpose now
    /// that `open_checked` opens with `O_NONBLOCK` and rejects non-regular
    /// files immediately (see #418) -- a FIFO can no longer be coaxed into
    /// blocking `ensure_open`'s `open()` call at all. Under the old design
    /// (a single lock spanning all of `ensure_open`, including disk I/O),
    /// path B would hang until path A's lock is released below; the
    /// per-path lock added here must let it through immediately instead.
    #[tokio::test]
    async fn test_ensure_open_different_paths_do_not_serialize() {
        let dir = TempDir::new().unwrap();
        let path_a = dir.path().join("a.rs");
        let path_b = dir.path().join("b.rs");

        std::fs::write(&path_a, "fn a() {}").unwrap();
        std::fs::write(&path_b, "fn b() {}").unwrap();
        set_mtime(&path_a, settled_past());
        set_mtime(&path_b, settled_past());

        let (client_a, _server_a) = fake_lsp_client();
        let (client_b, _server_b) = fake_lsp_client();
        let tracker = Arc::new(DocumentTracker::new(
            ResourceLimits::default(),
            HashMap::new(),
        ));

        let path_a_guard = tracker.lock_path(&path_a).await;

        // Spawned so a real `ensure_open(path_a)` call is genuinely parked
        // on path A's lock (held by `path_a_guard` above) while path B's
        // call below runs.
        let tracker_for_a = Arc::clone(&tracker);
        let path_a_for_task = path_a.clone();
        let handle_a = tokio::spawn(async move {
            tracker_for_a
                .ensure_open(&path_a_for_task, &ServerId::from("server-a"), &client_a)
                .await
        });

        // Give the spawned task a chance to actually reach and block on
        // path A's lock before racing path B's call against it below.
        tokio::time::sleep(Duration::from_millis(200)).await;

        // A `timeout` error here means path B is blocked by path A's stuck
        // ensure_open -- the exact regression #227 fixes.
        tokio::time::timeout(
            Duration::from_secs(5),
            tracker.ensure_open(&path_b, &ServerId::from("server-b"), &client_b),
        )
        .await
        .unwrap()
        .unwrap();

        drop(path_a_guard);

        handle_a.await.unwrap().unwrap();
        assert_eq!(tracker.get(&path_a).unwrap().content(), "fn a() {}");
    }

    /// Regression for #358: `update` must serialize against a concurrent
    /// `ensure_open` for the *same* path via the shared per-path lock, not
    /// just against other `ensure_open` calls.
    ///
    /// A real, spawned `ensure_open(path)` call is genuinely parked on the
    /// path's lock (held via `lock_path`, the exact primitive `ensure_open`
    /// acquires before its disk I/O) while `update` is raced against it --
    /// see `test_ensure_open_different_paths_do_not_serialize` for why a
    /// standalone `lock_path` guard alone is not enough, and for why this
    /// replaced the previous FIFO-blocking idiom. Before the #358 fix,
    /// `update` took no per-path lock at all and would have raced straight
    /// through instead of blocking.
    #[tokio::test]
    async fn test_update_serializes_with_concurrent_ensure_open_same_path() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn a() {}").unwrap();
        set_mtime(&path, settled_past());

        let (client, _server) = fake_lsp_client();
        let tracker = Arc::new(DocumentTracker::new(
            ResourceLimits::default(),
            HashMap::new(),
        ));

        let path_guard = tracker.lock_path(&path).await;

        // Spawned so a real `ensure_open(path)` call is genuinely parked on
        // the path's lock (held by `path_guard` above) while `update` is
        // raced against it below.
        let tracker_for_open = Arc::clone(&tracker);
        let path_for_task = path.clone();
        let handle_open = tokio::spawn(async move {
            tracker_for_open
                .ensure_open(&path_for_task, &ServerId::from("rust"), &client)
                .await
        });

        // Give the spawned task a chance to actually reach and block on the
        // path's lock before racing `update` against it below.
        tokio::time::sleep(Duration::from_millis(200)).await;

        // A successful (non-timeout) result here would mean `update` raced
        // straight past `ensure_open`'s still-held per-path lock -- the
        // exact regression #358 fixes.
        let update_while_blocked = tokio::time::timeout(
            Duration::from_millis(300),
            tracker.update(&path, "raced content".to_string()),
        )
        .await;
        assert!(
            update_while_blocked.is_err(),
            "update() must block while ensure_open holds the per-path lock for the same path"
        );

        drop(path_guard);

        handle_open.await.unwrap().unwrap();
        assert_eq!(tracker.get(&path).unwrap().content(), "fn a() {}");
        assert_eq!(tracker.get(&path).unwrap().version(), 1);

        // With the lock released, `update` must now proceed and observably
        // apply on top of `ensure_open`'s committed state.
        let new_version = tracker
            .update(&path, "fn a() { updated(); }".to_string())
            .await;
        assert_eq!(new_version, Some(2));
        assert_eq!(
            tracker.get(&path).unwrap().content(),
            "fn a() { updated(); }"
        );
    }

    /// Regression for #227: N concurrent `ensure_open` calls for the same
    /// path and the same server must still collapse into exactly one
    /// `didOpen` -- the per-path lock introduced to let different paths run
    /// concurrently must not weaken the existing same-path serialization
    /// that prevents duplicate opens.
    #[tokio::test]
    async fn test_ensure_open_concurrent_same_path_single_didopen() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("a.rs");
        std::fs::write(&path, "fn main() {}").unwrap();
        set_mtime(&path, settled_past());

        let (client, mut server) = fake_lsp_client();
        let tracker = Arc::new(DocumentTracker::new(
            ResourceLimits::default(),
            HashMap::new(),
        ));
        let id = ServerId::from("rust");

        let mut handles = Vec::new();
        for _ in 0..8 {
            let tracker = Arc::clone(&tracker);
            let client = client.clone();
            let path = path.clone();
            let id = id.clone();
            handles.push(tokio::spawn(async move {
                tracker.ensure_open(&path, &id, &client).await
            }));
        }
        for handle in handles {
            handle.await.unwrap().unwrap();
        }

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

        // No further notification should have been queued -- proves the 8
        // concurrent callers collapsed into exactly one `didOpen`.
        let extra =
            tokio::time::timeout(Duration::from_millis(200), read_framed_message(&mut wire)).await;
        assert!(
            extra.is_err(),
            "expected no additional notification after the single didOpen"
        );

        assert_eq!(tracker.get(&path).unwrap().synced_version(&id), Some(1));
        assert_eq!(tracker.get(&path).unwrap().version(), 1);
    }

    /// Regression for #227: `lock_path`'s guard must evict its `path_locks`
    /// entry once no caller is left waiting on it, or the map grows by one
    /// entry per distinct path ever opened for the lifetime of the process.
    /// Exercises three concurrent distinct paths (not just the two used in
    /// `test_ensure_open_different_paths_do_not_serialize`) to rule out an
    /// eviction bug that only manifests with more than two live entries.
    #[tokio::test]
    async fn test_ensure_open_path_locks_evicted_after_completion() {
        let dir = TempDir::new().unwrap();
        let paths: Vec<_> = ["a.rs", "b.rs", "c.rs"]
            .iter()
            .map(|name| dir.path().join(name))
            .collect();
        for path in &paths {
            std::fs::write(path, "fn f() {}").unwrap();
            set_mtime(path, settled_past());
        }

        let tracker = Arc::new(DocumentTracker::new(
            ResourceLimits::default(),
            HashMap::new(),
        ));
        let id = ServerId::from("rust");

        let mut handles = Vec::new();
        let mut servers = Vec::new();
        for path in paths.clone() {
            let tracker = Arc::clone(&tracker);
            let (client, server) = fake_lsp_client();
            servers.push(server);
            let id = id.clone();
            handles.push(tokio::spawn(async move {
                tracker.ensure_open(&path, &id, &client).await
            }));
        }
        for handle in handles {
            handle.await.unwrap().unwrap();
        }
        drop(servers);

        assert!(
            lock_std(&tracker.path_locks).is_empty(),
            "path_locks must be fully evicted once every ensure_open call \
             for every path has completed, otherwise the map grows \
             unbounded for the lifetime of the process"
        );
    }

    /// Regression for #418: `read_to_string_checked` must reject a FIFO
    /// rather than trust its (always-zero) reported size and either hang
    /// reading it or return an unbounded stream of bytes.
    ///
    /// Unlike `test_ensure_open_different_paths_do_not_serialize`'s use of
    /// the same `mkfifo` idiom, this test needs no background writer and no
    /// timeout race to prove non-blocking behavior: `open_checked`'s
    /// `O_NONBLOCK` open is the fix under test, so a correct implementation
    /// returns an error immediately, with no peer ever connecting. The
    /// outer `timeout` is only a safety net so a regression here fails fast
    /// instead of hanging the test suite.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_read_to_string_checked_rejects_fifo() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("fifo");
        let status = std::process::Command::new("mkfifo")
            .arg(&path)
            .status()
            .unwrap();
        assert!(status.success(), "mkfifo must succeed to set up this test");

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        // A timeout here means the fix failed and open() is still blocking
        // indefinitely on the FIFO -- the exact regression #418 fixes.
        let result = tokio::time::timeout(
            Duration::from_secs(5),
            tracker.read_to_string_checked(&path),
        )
        .await
        .unwrap();

        assert!(matches!(result, Err(Error::NotARegularFile(_))));
    }

    /// Direct regression for #442: `check_disk_file_type` itself, isolated
    /// from `open_checked`'s surrounding `is_file()` check. Unlike
    /// `test_read_to_string_checked_rejects_nul_device` below, this fails if
    /// `check_disk_file_type` were ever bypassed or deleted -- both checks
    /// currently produce the identical `Error::NotARegularFile` variant, so
    /// an end-to-end test alone can't tell them apart.
    #[cfg(windows)]
    #[tokio::test]
    async fn test_check_disk_file_type_accepts_regular_rejects_nul() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("regular.txt");
        std::fs::write(&path, "hello").unwrap();

        let regular = fs::File::open(&path).await.unwrap();
        assert!(check_disk_file_type(&regular, &path).is_ok());

        let nul_path = PathBuf::from("NUL");
        let nul = fs::File::open(&nul_path).await.unwrap();
        assert!(matches!(
            check_disk_file_type(&nul, &nul_path),
            Err(Error::NotARegularFile(_))
        ));
    }

    /// Regression for #442: `read_to_string_checked` must reject the `NUL`
    /// device on Windows via `GetFileType`, not `FileType::is_file()` --
    /// which does not reliably classify reserved device names as
    /// non-regular. This is the Windows counterpart of
    /// `test_read_to_string_checked_rejects_fifo`; `NUL` opens immediately
    /// (unlike a FIFO with no writer), so the outer `timeout` here is only a
    /// safety net, not proof of non-blocking behavior on its own -- the
    /// `GetFileType` check itself is what's under test.
    #[cfg(windows)]
    #[tokio::test]
    async fn test_read_to_string_checked_rejects_nul_device() {
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        let path = PathBuf::from("NUL");
        let result = tokio::time::timeout(
            Duration::from_secs(5),
            tracker.read_to_string_checked(&path),
        )
        .await
        .unwrap();

        assert!(matches!(result, Err(Error::NotARegularFile(_))));
    }

    /// Boundary regression for #427/#418's shared size gate: a file of
    /// exactly `max_file_size` bytes must succeed through
    /// `read_to_string_checked` (the disk-read path `ensure_open` uses),
    /// and one byte more must fail as `FileSizeLimitExceeded` -- not just
    /// "some file well over the limit is rejected".
    #[tokio::test]
    async fn test_read_to_string_checked_size_boundary() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("boundary.rs");
        let tracker = DocumentTracker::new(
            ResourceLimits {
                max_documents: 100,
                max_file_size: 10,
            },
            HashMap::new(),
        );

        std::fs::write(&path, "a".repeat(10)).unwrap();
        let (content, ..) = tracker.read_to_string_checked(&path).await.unwrap();
        assert_eq!(content.len(), 10);

        std::fs::write(&path, "a".repeat(11)).unwrap();
        let result = tracker.read_to_string_checked(&path).await;
        assert!(matches!(
            result,
            Err(Error::FileSizeLimitExceeded { size: 11, max: 10 })
        ));
    }

    /// Regression for #474: `read_line_checked` must stop reading (and
    /// UTF-8-decoding) once it has the requested line, not buffer/validate
    /// the rest of the file. The file's second line is invalid UTF-8, which
    /// would fail a whole-file read (as the pre-#474 `read_checked` +
    /// `.lines().nth(...)` path did); reading line 0 must still succeed.
    #[tokio::test]
    async fn test_read_line_checked_does_not_read_past_target_line() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("partial.rs");
        let mut content = b"hello\n".to_vec();
        content.extend_from_slice(&[0xFF, 0xFE]);
        content.push(b'\n');
        std::fs::write(&path, &content).unwrap();

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        let line = tracker.read_line_checked(&path, 0, u64::MAX).await.unwrap();
        assert_eq!(line.text.as_deref(), Some("hello"));
    }

    /// Regression for M3: an off-by-one in `current_line` (e.g. returning
    /// line `N + 1` for `N`) would ship green if every test used line 0.
    /// Exercises a non-zero target line on a multi-line fixture.
    #[tokio::test]
    async fn test_read_line_checked_returns_requested_non_zero_line() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("multi.rs");
        std::fs::write(&path, "first\nsecond\nthird\nfourth\n").unwrap();

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        assert_eq!(
            tracker
                .read_line_checked(&path, 2, u64::MAX)
                .await
                .unwrap()
                .text
                .as_deref(),
            Some("third")
        );
    }

    /// `read_line_checked` must report `Ok(None)`, not an error, when `line`
    /// is past the file's last line -- distinguishing "file has fewer lines
    /// than requested" from an actual read failure.
    #[tokio::test]
    async fn test_read_line_checked_returns_none_past_last_line() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("short.rs");
        std::fs::write(&path, "only one line").unwrap();

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        assert_eq!(
            tracker
                .read_line_checked(&path, 5, u64::MAX)
                .await
                .unwrap()
                .text,
            None
        );
    }

    /// A requested line with no trailing `\n` at all (the file's only line,
    /// never terminated) must still be returned -- distinct from
    /// `test_read_line_checked_returns_none_past_last_line`, which requests a
    /// line number past this same kind of file instead of the line itself.
    #[tokio::test]
    async fn test_read_line_checked_reads_last_line_without_trailing_newline() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("no_newline.rs");
        std::fs::write(&path, "only one line").unwrap();

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        assert_eq!(
            tracker
                .read_line_checked(&path, 0, u64::MAX)
                .await
                .unwrap()
                .text
                .as_deref(),
            Some("only one line")
        );
    }

    #[tokio::test]
    async fn test_read_line_checked_empty_file_returns_none() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("empty.rs");
        std::fs::write(&path, "").unwrap();

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        assert_eq!(
            tracker
                .read_line_checked(&path, 0, u64::MAX)
                .await
                .unwrap()
                .text,
            None
        );
    }

    /// `read_until(b'\n', ..)` splits lines on `\n` alone, so a `\r` ahead of
    /// it is left in `buf` until the trailing-separator strip loop removes
    /// it -- pins that CRLF-terminated lines come out identical to LF-only
    /// ones.
    #[tokio::test]
    async fn test_read_line_checked_strips_crlf_line_ending() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("crlf.rs");
        std::fs::write(&path, "first\r\nsecond\r\n").unwrap();

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        assert_eq!(
            tracker
                .read_line_checked(&path, 0, u64::MAX)
                .await
                .unwrap()
                .text
                .as_deref(),
            Some("first")
        );
        assert_eq!(
            tracker
                .read_line_checked(&path, 1, u64::MAX)
                .await
                .unwrap()
                .text
                .as_deref(),
            Some("second")
        );
    }

    /// Regression for M2: `str::lines` strips at most one trailing `\r` per
    /// line, not every trailing `\r`, and only when it precedes an actual
    /// `\n` terminator -- a final, untermined line keeps a trailing `\r`
    /// verbatim. Uses `str::lines` itself as the oracle on the exact inputs
    /// that distinguish these from a naive "strip every trailing `\r`/`\n`"
    /// implementation.
    #[tokio::test]
    async fn test_read_line_checked_matches_str_lines_crlf_semantics() {
        let dir = TempDir::new().unwrap();
        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());

        let double_cr = "abc\r\r\n";
        let path_a = dir.path().join("double_cr.rs");
        std::fs::write(&path_a, double_cr).unwrap();
        assert_eq!(
            tracker
                .read_line_checked(&path_a, 0, u64::MAX)
                .await
                .unwrap()
                .text
                .as_deref(),
            double_cr.lines().next()
        );

        let trailing_cr_no_newline = "abc\r";
        let path_b = dir.path().join("trailing_cr_no_newline.rs");
        std::fs::write(&path_b, trailing_cr_no_newline).unwrap();
        assert_eq!(
            tracker
                .read_line_checked(&path_b, 0, u64::MAX)
                .await
                .unwrap()
                .text
                .as_deref(),
            trailing_cr_no_newline.lines().next()
        );
    }

    /// Regression for the `bounded_read_cap` off-by-one: a file whose size
    /// is exactly `max_file_size` must not be misreported as oversized when
    /// a request (for a line past the file's content) forces a full read to
    /// EOF. The cap is `max_file_size + 1` precisely so this exact-boundary
    /// case is distinguishable from a genuinely oversized file.
    #[tokio::test]
    async fn test_read_line_checked_exact_max_file_size_reads_to_eof_without_error() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("exact.rs");
        let content = "a".repeat(20);
        std::fs::write(&path, &content).unwrap();

        let limits = ResourceLimits {
            max_documents: 100,
            max_file_size: 20,
        };
        let tracker = DocumentTracker::new(limits, HashMap::new());

        assert_eq!(
            tracker
                .read_line_checked(&path, 0, u64::MAX)
                .await
                .unwrap()
                .text
                .as_deref(),
            Some(content.as_str())
        );
        assert_eq!(
            tracker
                .read_line_checked(&path, 1, u64::MAX)
                .await
                .unwrap()
                .text,
            None,
            "a line past an exact-max_file_size file's only line must read to EOF cleanly, not \
             be misreported as truncated"
        );
    }

    /// Regression for the S1 budget-bypass fix: `budget` must physically
    /// bound the read (via the take-adapter), not just gate whether a read
    /// is attempted -- a read that starts with budget left must still stop
    /// at exactly that many bytes, never at the full `max_file_size`.
    /// Distinguishes this from `bounded_read_cap(max_file_size)` alone by
    /// using a `budget` far smaller than `max_file_size`.
    #[tokio::test]
    async fn test_read_line_checked_bounds_read_by_budget_not_just_max_file_size() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("budget.rs");
        std::fs::write(&path, "a".repeat(1000)).unwrap();

        let limits = ResourceLimits {
            max_documents: 100,
            max_file_size: 1000,
        };
        let tracker = DocumentTracker::new(limits, HashMap::new());

        let read = tracker.read_line_checked(&path, 0, 10).await.unwrap();
        assert_eq!(
            read.text, None,
            "a single line far longer than the budget must not be returned as if complete"
        );
        assert_eq!(
            read.bytes_read, 11,
            "the read must stop at exactly the budget's +1 slack (see the correctness-gate fix \
             below), not at max_file_size"
        );
    }

    /// Regression for a correctness-gate finding: `cap`'s `budget` component
    /// needs the same `+1` disambiguation slack `bounded_read_cap` already
    /// applies to `max_file_size` -- without it, a read whose remaining
    /// budget exactly equals its target line's byte length (no trailing
    /// newline) is indistinguishable from one genuinely truncated by the
    /// cap, and was misreported as truncated (`text: None`) even though the
    /// read fully succeeded.
    #[tokio::test]
    async fn test_read_line_checked_exact_budget_match_on_unterminated_line_not_truncated() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("exact_budget.rs");
        let content = "twelve chars";
        std::fs::write(&path, content).unwrap();

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        let read = tracker
            .read_line_checked(&path, 0, content.len() as u64)
            .await
            .unwrap();
        assert_eq!(
            read.text.as_deref(),
            Some(content),
            "budget exactly matching the line's byte length must not be misreported as truncated"
        );
        assert_eq!(read.bytes_read, content.len() as u64);
    }

    /// Regression for the S1 budget-bypass fix: an invalid-UTF-8 line (the
    /// realistic attack shape -- a `.rlib`/image/pack file under
    /// `max_file_size`) must still report an accurate `bytes_read` on
    /// `LineRead::text == None`, not lose it down an `Err` path with no byte
    /// count -- that loss is exactly what let a hostile response scan
    /// unlimited bytes while charging the per-response budget zero.
    #[tokio::test]
    async fn test_read_line_checked_reports_bytes_read_for_invalid_utf8_line() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("invalid_utf8.rs");
        let mut content = vec![0xFFu8, 0xFE, 0xFD];
        content.push(b'\n');
        std::fs::write(&path, &content).unwrap();

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        let read = tracker.read_line_checked(&path, 0, u64::MAX).await.unwrap();
        assert_eq!(read.text, None);
        assert_eq!(
            read.bytes_read,
            content.len() as u64,
            "bytes scanned must be reported even though the line wasn't valid UTF-8"
        );
    }

    /// Regression for the open-failure-charge fix: a path that doesn't
    /// exist (the realistic, non-attacker case -- e.g. an LSP server naming
    /// a stdlib location not present locally) must resolve to `Ok(None)`,
    /// not `Err`, and must charge the small nominal
    /// `OPEN_FAILURE_CHARGE_BYTES` amount rather than `0` (which would let
    /// a response repeat this for free) or the full budget (the previous
    /// round's regression, which zeroed the whole per-response budget on
    /// the very first such location).
    #[tokio::test]
    async fn test_read_line_checked_charges_nominal_amount_for_nonexistent_path() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("does_not_exist.rs");

        let tracker = DocumentTracker::new(ResourceLimits::default(), HashMap::new());
        // A nonexistent path must resolve to Ok(None), not Err.
        let read = tracker.read_line_checked(&path, 0, u64::MAX).await.unwrap();
        assert_eq!(read.text, None);
        assert_eq!(read.bytes_read, OPEN_FAILURE_CHARGE_BYTES);
    }
}