mcpls-core 0.8.0

Core library for MCP to LSP protocol translation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
//! LSP client implementation with async request/response handling.

use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
use std::sync::{Arc, Mutex as StdMutex, PoisonError};

use lsp_types::{
    ErrorCodes, LspErrorCodes, LspRequestMethod, Notification as _, PublishDiagnosticsParams,
};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use tokio::sync::{Mutex, mpsc, oneshot};
use tokio::task::JoinHandle;
use tokio::time::{Duration, Instant, timeout, timeout_at};
use tracing::{debug, error, trace, warn};

use crate::config::{LanguageId, LspServerConfig, LspSettings, ServerId};
use crate::error::{BackgroundTask, Error, Result};
use crate::lsp::transport::{LspTransport, LspTransportReader};
use crate::lsp::types::{
    InboundMessage, JsonRpcError, JsonRpcNotification, JsonRpcOutcome, JsonRpcReply,
    JsonRpcRequest, JsonRpcResponse, JsonRpcVersion, LspNotification, RequestId,
};
use crate::lsp::{DropCounter, DropLog, Lane, NotificationSink, ServerMessage};
use crate::redaction::{RedactedText, Redactions};
use crate::util::MAX_ERROR_MESSAGE_CALLER_BYTES;

mod cancel;
mod notification;

use cancel::{InFlightRequest, PendingRequests, Resolution};
use notification::OutboundNotification;

/// Maximum number of retry attempts for server-cancelled requests.
const SERVER_CANCELLED_MAX_RETRIES: u32 = 3;

/// Initial backoff delay for server-cancelled retries (milliseconds).
const SERVER_CANCELLED_INITIAL_DELAY_MS: u64 = 500;

/// Bounded capacity for the channel carrying fully-decoded inbound LSP
/// messages from [`spawn_reader_task`]'s background task to
/// [`LspClient::message_loop_inner`].
///
/// Backpressured (`send().await`, not `try_send`) unlike the best-effort
/// notification/lifecycle lanes: dropping a frame here would desync
/// request/response correlation or silently swallow a server-initiated
/// request. Matches the command channel's capacity -- both lanes carry
/// protocol-critical traffic at a similar cadence.
const READER_CHANNEL_CAPACITY: usize = 100;

/// How long [`LspClient::message_loop`] waits, after aborting the reader
/// task it no longer drains, for that task to actually finish dropping its
/// [`LspTransportReader`] (and the `ChildStdout` it owns).
///
/// `abort()` only requests cancellation -- the task's locals are dropped
/// once the runtime next polls it, not synchronously at the call site.
/// Mirrors `await_lsp_init_handle`'s reasoning in `crate::lib` for the same
/// pattern. Short: the task is either already parked in a cancel-safe
/// `.await` (aborts promptly) or has nothing left to do.
const READER_TASK_ABORT_GRACE: Duration = Duration::from_secs(1);

/// Deadline for a full LSP server shutdown (`shutdown` request, `exit`
/// notification, message-loop stop and child exit). Cleanup after an abort
/// may overrun it by a 50 ms settle.
pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);

/// How many undecodable inbound frames in a row the reader tolerates before it
/// treats the connection as broken.
///
/// A single frame that is not a valid message is dropped, so one bad message
/// does not take the server down. A server that emits only garbage never makes
/// progress, though: after this many consecutive undecodable frames the
/// connection is torn down and the server respawned like any other lost
/// connection.
pub const MAX_CONSECUTIVE_UNDECODABLE_FRAMES: u32 = 64;

const _: () = assert!(MAX_CONSECUTIVE_UNDECODABLE_FRAMES > 0);

/// How long [`LspClient::shutdown_until`] waits for an aborted message loop
/// to drop its command receiver before failing the pending requests.
const SHUTDOWN_ABORT_SETTLE: Duration = Duration::from_millis(50);

/// LSP request methods for which a `-32801` (`ContentModified`) error
/// response is safe to retry automatically -- also declared to servers via
/// `general.staleRequestSupport.retryOnContentModified` during initialize
/// (see [`crate::lsp::LspServer`]'s handshake).
///
/// Per the LSP spec, `ContentModified` means the server noticed the document
/// changed while it was computing a response; the (possibly stale) result may
/// still be useful, or the client may choose to cancel the request instead.
/// mcpls chooses to retry, which is safe for a read-only/idempotent request
/// (hover, references, diagnostics, ...): a stale response is simply
/// discarded and superseded by a fresh one.
///
/// Deliberately excludes every method in
/// `crate::bridge::translator::edits` (`textDocument/rename`,
/// `textDocument/formatting`, `textDocument/codeAction`): their result is an
/// edit the MCP caller applies, and `-32801` means the document changed since
/// the request was issued, so a retry at the original position could return
/// an edit for content the caller no longer expects (e.g. renaming a
/// different symbol than the one originally at that position).
///
/// This list only gates `-32801`. `-32802` (`ServerCancelled`) retry is
/// unaffected and keeps retrying unconditionally for every method, as before.
pub const CONTENT_MODIFIED_RETRY_METHODS: &[LspRequestMethod<'static>] = &[
    LspRequestMethod::TextDocumentSignatureHelp,
    LspRequestMethod::TextDocumentInlayHint,
    LspRequestMethod::TextDocumentCompletion,
    LspRequestMethod::TextDocumentPrepareCallHierarchy,
    LspRequestMethod::CallHierarchyIncomingCalls,
    LspRequestMethod::CallHierarchyOutgoingCalls,
    LspRequestMethod::TextDocumentDiagnostic,
    LspRequestMethod::TextDocumentHover,
    LspRequestMethod::TextDocumentDefinition,
    LspRequestMethod::TextDocumentReferences,
    LspRequestMethod::TextDocumentImplementation,
    LspRequestMethod::TextDocumentTypeDefinition,
    LspRequestMethod::TextDocumentDocumentSymbol,
    LspRequestMethod::WorkspaceSymbol,
];

/// Upper bound on the effective timeout for completion requests, regardless
/// of `request_timeout_seconds`.
///
/// Completions are latency-sensitive: a completion list that takes longer
/// than this is no longer useful to the caller. This is a deliberate MVP
/// ceiling, not an oversight — completions cannot be configured above this
/// value today. See [`LspClient::completion_timeout`].
const COMPLETION_TIMEOUT_CAP: Duration = Duration::from_secs(10);

/// Upper bound on the effective timeout for a single `codeAction/resolve`
/// request, regardless of `request_timeout_seconds`.
///
/// `handle_code_actions` (`bridge::translator::edits`) resolves up to
/// `MAX_CODE_ACTION_RESOLVES` deferred actions concurrently after the
/// initial `textDocument/codeAction` response; an uncapped per-resolve
/// timeout would let a large `request_timeout_seconds` configuration make
/// one tool call wait far longer than a caller expects for what is meant to
/// be a best-effort follow-up. Mirrors [`COMPLETION_TIMEOUT_CAP`]'s
/// reasoning. See [`LspClient::code_action_resolve_timeout`].
const CODE_ACTION_RESOLVE_TIMEOUT_CAP: Duration = Duration::from_secs(10);

/// Spawns the dedicated background task that owns `reader` exclusively and
/// decodes inbound LSP frames in a loop, handing each one to
/// [`LspClient::message_loop_inner`] over the returned channel.
///
/// This is the fix for #451: [`LspTransportReader::receive`] is not
/// cancel-safe, so it must never run as a branch of the `select!` in
/// `message_loop_inner`, which also waits on `command_rx`. Running it here
/// instead, on a task driven only by its own `.await`s, means it can never
/// be cancelled mid-frame.
///
/// The task exits after sending one `Err` (I/O failure or EOF), once
/// `message_loop_inner` drops its end of the channel (e.g. on shutdown), or
/// when the returned [`JoinHandle`] is aborted. Callers must abort it once
/// they stop draining the channel -- see [`LspClient::message_loop`], the
/// only caller -- otherwise it stays parked in a blocking read holding the
/// underlying `ChildStdout` open indefinitely: not itself a correctness bug
/// (`LspServer::is_dead`, lifecycle.rs, checks the child process directly via
/// `try_wait()` and doesn't care whether we still hold its stdout open), but
/// a leaked task and file descriptor for the lifetime of that connection.
fn spawn_reader_task(
    mut reader: LspTransportReader,
) -> (JoinHandle<()>, mpsc::Receiver<Result<InboundMessage>>) {
    let (tx, rx) = mpsc::channel(READER_CHANNEL_CAPACITY);
    let handle = tokio::spawn(async move {
        let mut run = UndecodableRun::default();
        loop {
            let message = reader
                .receive()
                .await
                .and_then(|message| run.observe(message));
            let is_err = message.is_err();
            if tx.send(message).await.is_err() || is_err {
                break;
            }
        }
    });
    (handle, rx)
}

/// The current run of consecutive undecodable inbound frames.
#[derive(Debug, Default)]
struct UndecodableRun {
    in_a_row: u32,
    drops: DropCounter,
}

impl UndecodableRun {
    /// Passes `message` on. A decodable message ends the run; an undecodable
    /// one extends it. Drops are logged at `warn` at most once a minute, with
    /// the number dropped since the last line, and at `debug` otherwise, so a
    /// server that spams garbage cannot flood the log.
    ///
    /// # Errors
    ///
    /// [`Error::LspProtocolError`] once the run reaches
    /// [`MAX_CONSECUTIVE_UNDECODABLE_FRAMES`], so the connection is torn down.
    fn observe(&mut self, message: InboundMessage) -> Result<InboundMessage> {
        self.observe_at(message, std::time::Instant::now())
    }

    fn observe_at(
        &mut self,
        message: InboundMessage,
        now: std::time::Instant,
    ) -> Result<InboundMessage> {
        if !message.is_undecodable() {
            self.in_a_row = 0;
            return Ok(message);
        }
        self.in_a_row = self.in_a_row.saturating_add(1);
        if self.in_a_row >= MAX_CONSECUTIVE_UNDECODABLE_FRAMES {
            return Err(Error::LspProtocolError(RedactedText::fixed(
                "too many consecutive undecodable messages",
            )));
        }
        if let Some(suppressed) = self.drops.record(now) {
            warn!(
                "Dropped an undecodable LSP message ({suppressed} others dropped since the last \
                 warning); further ones are logged at debug for a minute"
            );
        } else {
            debug!(
                "Dropped an undecodable LSP message ({} in a row)",
                self.in_a_row
            );
        }
        Ok(message)
    }
}

/// Why requests still pending on a client are being failed, and so which
/// error they resolve with.
#[derive(Debug, Clone, Default)]
pub enum PendingFailure {
    /// The connection is gone.
    #[default]
    Terminated,
    /// The server was deliberately restarted; the caller may retry.
    Restarted(ServerId),
}

impl PendingFailure {
    fn error(&self) -> Error {
        match self {
            Self::Terminated => Error::ServerTerminated,
            Self::Restarted(server_id) => Error::ServerRestarted {
                server_id: server_id.clone(),
            },
        }
    }
}

/// LSP client with async request/response handling.
///
/// This client manages communication with an LSP server, handling:
/// - Concurrent requests with unique ID tracking
/// - Background message loop for receiving responses
/// - Timeout support for all requests
/// - Graceful shutdown
#[derive(Debug)]
pub struct LspClient {
    /// Configuration for this LSP server.
    config: LspServerConfig,

    /// Current server state.
    state: Arc<Mutex<super::ServerState>>,

    /// Atomic counter for request IDs.
    request_counter: Arc<AtomicI64>,

    /// Command sender for outbound messages.
    command_tx: mpsc::Sender<ClientCommand>,

    /// Requests awaiting a response, shared with the background message loop.
    ///
    /// Exposed here (not just captured by the loop) so [`Self::request`] can
    /// remove its own entry on timeout instead of leaking it, and so a
    /// connection known to be dead can fail its stragglers immediately via
    /// [`Self::fail_pending_requests`] rather than leaving each to discover
    /// that only when its own timeout elapses.
    pending_requests: PendingRequests,

    /// Set once the `shutdown` request is issued or the client shuts down:
    /// from then on no `$/cancelRequest` is sent. Shared by every clone.
    closing: Arc<AtomicBool>,

    /// The error stragglers in `pending_requests` fail with, shared by every
    /// clone and by the message loop's exit-path drain.
    pending_failure: Arc<StdMutex<PendingFailure>>,

    /// Background receiver task handle.
    receiver_task: Option<JoinHandle<Result<()>>>,

    /// Secrets hidden from text derived from server output.
    redactions: Arc<Redactions>,

    /// Identity of the connection, shared by every clone.
    connection_id: ConnectionId,
}

/// Identity of one client connection, and so of one server process.
///
/// Clones of a client share it; every client built by this process gets a
/// distinct one, so a result tied to a replaced process is told apart from the
/// running one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConnectionId(u64);

impl ConnectionId {
    fn next() -> Self {
        static NEXT: AtomicU64 = AtomicU64::new(1);
        Self(NEXT.fetch_add(1, Ordering::Relaxed))
    }
}

impl Clone for LspClient {
    /// Creates a clone that shares the underlying connection.
    ///
    /// The clone does not own the receiver task and cannot perform shutdown.
    /// All clones share the same command channel for sending requests.
    fn clone(&self) -> Self {
        Self {
            config: self.config.clone(),
            state: Arc::clone(&self.state),
            request_counter: Arc::clone(&self.request_counter),
            command_tx: self.command_tx.clone(),
            pending_requests: self.pending_requests.clone(),
            closing: Arc::clone(&self.closing),
            pending_failure: Arc::clone(&self.pending_failure),
            receiver_task: None,
            redactions: Arc::clone(&self.redactions),
            connection_id: self.connection_id,
        }
    }
}

/// The lanes inbound notifications are forwarded to; a client has both or
/// neither.
#[derive(Debug)]
struct Lanes {
    notifications: NotificationSink,
    lifecycle: mpsc::Sender<LspNotification>,
}

/// Where an inbound notification goes, with the sender that takes it; see
/// [`LspClient::route`].
#[derive(Debug)]
enum Route<'a> {
    /// The diagnostics mailbox.
    Mailbox(&'a NotificationSink, PublishDiagnosticsParams),
    /// The log and `showMessage` lane.
    Messages(&'a NotificationSink, ServerMessage),
    /// The lifecycle lane.
    Lifecycle(&'a mpsc::Sender<LspNotification>, LspNotification),
    /// Nowhere: the notification is deliberately not forwarded.
    Floor,
}

/// What became of a routed notification.
#[derive(Debug, PartialEq, Eq)]
enum Delivery {
    /// Sent to its lane, or there was nothing to send.
    Delivered,
    /// The lane was full or closed and the frame was dropped.
    Dropped(Lane),
}

/// The receiving end of a test client's command channel.
#[cfg(test)]
#[derive(Debug)]
pub struct CommandProbe(mpsc::Receiver<ClientCommand>);

#[cfg(test)]
impl CommandProbe {
    /// The method of the next queued command, `None` when the queue is empty.
    pub(crate) fn next_method(&mut self) -> Option<String> {
        match self.0.try_recv().ok()? {
            ClientCommand::SendRequest { request } => Some(request.method),
            ClientCommand::SendNotification { method, .. } => Some(method),
            ClientCommand::Shutdown => Some("<shutdown>".to_owned()),
        }
    }
}

/// Commands for client control.
#[derive(Debug)]
enum ClientCommand {
    /// Send a request and wait for response.
    SendRequest { request: JsonRpcRequest },
    /// Send a notification (no response expected).
    SendNotification {
        method: String,
        params: Option<Value>,
    },
    /// Shutdown the client.
    Shutdown,
}

impl LspClient {
    /// Create a new LSP client with the given configuration.
    ///
    /// The client starts in an uninitialized state. Call `initialize()` to
    /// start the server and complete the initialization handshake.
    #[must_use]
    pub fn new(config: LspServerConfig) -> Self {
        // Placeholder channel - the receiver is intentionally dropped since
        // the client starts uninitialized. A real channel is created when
        // `from_transport` or `from_transport_with_notifications` is called.
        let (command_tx, _command_rx) = mpsc::channel(1); // Minimal capacity for placeholder

        Self {
            config,
            state: Arc::new(Mutex::new(super::ServerState::Uninitialized)),
            request_counter: Arc::new(AtomicI64::new(1)),
            command_tx,
            pending_requests: PendingRequests::default(),
            closing: Arc::default(),
            pending_failure: Arc::default(),
            receiver_task: None,
            redactions: Arc::default(),
            connection_id: ConnectionId::next(),
        }
    }

    /// A client over a command channel of `capacity` that the test drains
    /// itself, standing in for the message loop.
    #[cfg(test)]
    pub(crate) fn with_command_channel(
        config: LspServerConfig,
        capacity: usize,
    ) -> (Self, CommandProbe) {
        let (command_tx, command_rx) = mpsc::channel(capacity);
        (
            Self {
                command_tx,
                ..Self::new(config)
            },
            CommandProbe(command_rx),
        )
    }

    /// Create client from transport (for testing or custom spawning).
    ///
    /// This method initializes the background message loop with the provided transport.
    #[cfg(test)]
    pub(crate) fn from_transport(
        config: LspServerConfig,
        transport: (LspTransport, LspTransportReader),
    ) -> Self {
        Self::spawn(config, transport, None, Arc::default())
    }

    /// Create client from transport with notification forwarding.
    ///
    /// Notifications are parsed and split across two lanes (P3): diagnostics/
    /// log/showMessage go through `notification_tx`; `$/progress` `begin`/
    /// `end` frames and unrecognized notifications (`LspNotification::Other`,
    /// which carries rust-analyzer's `experimental/serverStatus`) go through
    /// `lifecycle_tx` instead. A `$/progress` `report` frame is never
    /// enqueued on either lane -- see [`Self::message_loop_inner`].
    pub(crate) fn from_transport_with_notifications(
        config: LspServerConfig,
        transport: (LspTransport, LspTransportReader),
        notification_tx: NotificationSink,
        lifecycle_tx: mpsc::Sender<LspNotification>,
        redactions: Arc<Redactions>,
    ) -> Self {
        let lanes = Lanes {
            notifications: notification_tx,
            lifecycle: lifecycle_tx,
        };
        Self::spawn(config, transport, Some(lanes), redactions)
    }

    /// Starts the message loop over `transport` and returns the client that owns it.
    fn spawn(
        config: LspServerConfig,
        transport: (LspTransport, LspTransportReader),
        lanes: Option<Lanes>,
        redactions: Arc<Redactions>,
    ) -> Self {
        let pending_requests = PendingRequests::default();
        let pending_failure = Arc::<StdMutex<PendingFailure>>::default();

        let (command_tx, command_rx) = mpsc::channel(100);

        let receiver_task = tokio::spawn(Self::message_loop(
            transport,
            command_rx,
            pending_requests.clone(),
            Arc::clone(&pending_failure),
            lanes,
            Arc::clone(&redactions),
            Self::shared_settings(&config),
        ));

        Self {
            config,
            state: Arc::new(Mutex::new(super::ServerState::Initializing)),
            request_counter: Arc::new(AtomicI64::new(1)),
            command_tx,
            pending_requests,
            closing: Arc::default(),
            pending_failure,
            receiver_task: Some(receiver_task),
            redactions,
            connection_id: ConnectionId::next(),
        }
    }

    /// The configured settings, shared with the message loop.
    fn shared_settings(config: &LspServerConfig) -> Option<Arc<LspSettings>> {
        config.settings.clone().map(Arc::new)
    }

    /// Identity of the connection this client and its clones talk over.
    pub(crate) const fn connection_id(&self) -> ConnectionId {
        self.connection_id
    }

    /// Secrets this client hides from text derived from server output.
    pub(crate) const fn redactions(&self) -> &Arc<Redactions> {
        &self.redactions
    }

    /// Get the language ID for this client.
    #[must_use]
    pub const fn language_id(&self) -> &LanguageId {
        &self.config.language_id
    }

    /// Get the current server state.
    pub async fn state(&self) -> super::ServerState {
        *self.state.lock().await
    }

    /// The timeout applied to a single LSP request attempt, derived from
    /// [`LspServerConfig::request_timeout_seconds`].
    ///
    /// This bounds one attempt, not a whole tool call: [`Self::request`]
    /// retries up to `SERVER_CANCELLED_MAX_RETRIES` (3) additional times on a
    /// `-32802` (`ServerCancelled`) or `-32801` (`ContentModified`) response,
    /// sharing one attempt budget between the two codes, so the worst-case
    /// latency for a single tool call is `4 * request_timeout() + 3.5s` (the
    /// sum of the retry backoff delays).
    ///
    /// Exception: `get_code_actions` (`bridge::translator::edits`) can add a
    /// second, concurrent round of requests on top of this bound -- up to
    /// `MAX_CODE_ACTION_RESOLVES` `codeAction/resolve` calls, each retried
    /// under the same rules but bounded by [`Self::code_action_resolve_timeout`]
    /// rather than this timeout. Since those run concurrently with each
    /// other (not with the initial `textDocument/codeAction` request), the
    /// worst case for that one tool call is
    /// `(4 * request_timeout() + 3.5s) + (4 * code_action_resolve_timeout() + 3.5s)`,
    /// not a multiple scaling with the number of resolved actions.
    ///
    /// The value is a [`TimeoutSecs`], so it is already within 1 second to
    /// [`MAX_TIMEOUT_SECONDS`] and needs no clamping here.
    ///
    /// [`TimeoutSecs`]: crate::config::TimeoutSecs
    /// [`MAX_TIMEOUT_SECONDS`]: crate::config::MAX_TIMEOUT_SECONDS
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// use mcpls_core::config::{LspServerConfig, TimeoutSecs};
    /// use mcpls_core::lsp::LspClient;
    ///
    /// let mut config = LspServerConfig::rust_analyzer();
    /// config.request_timeout_seconds = TimeoutSecs::new(45).unwrap();
    /// let client = LspClient::new(config);
    ///
    /// assert_eq!(client.request_timeout(), Duration::from_secs(45));
    /// ```
    #[must_use]
    pub const fn request_timeout(&self) -> Duration {
        self.config.request_timeout_seconds.as_duration()
    }

    /// The timeout applied to completion (`textDocument/completion`) requests.
    ///
    /// Equal to [`Self::request_timeout`], capped at 10 seconds. Completions
    /// cannot be configured above this cap by any
    /// value of `request_timeout_seconds` — if that proves insufficient in
    /// practice, the fix is a dedicated `completion_timeout_seconds` field,
    /// not raising this cap.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// use mcpls_core::config::{LspServerConfig, TimeoutSecs};
    /// use mcpls_core::lsp::LspClient;
    ///
    /// let mut config = LspServerConfig::rust_analyzer();
    /// config.request_timeout_seconds = TimeoutSecs::new(300).unwrap();
    /// let client = LspClient::new(config);
    ///
    /// // Capped at 10s even though request_timeout_seconds is 300.
    /// assert_eq!(client.completion_timeout(), Duration::from_secs(10));
    /// assert!(client.completion_timeout() <= client.request_timeout());
    /// ```
    #[must_use]
    pub fn completion_timeout(&self) -> Duration {
        self.request_timeout().min(COMPLETION_TIMEOUT_CAP)
    }

    /// The timeout applied to a single `codeAction/resolve` request.
    ///
    /// Equal to [`Self::request_timeout`], capped at 10 seconds.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// use mcpls_core::config::{LspServerConfig, TimeoutSecs};
    /// use mcpls_core::lsp::LspClient;
    ///
    /// let mut config = LspServerConfig::rust_analyzer();
    /// config.request_timeout_seconds = TimeoutSecs::new(300).unwrap();
    /// let client = LspClient::new(config);
    ///
    /// // Capped at 10s even though request_timeout_seconds is 300.
    /// assert_eq!(client.code_action_resolve_timeout(), Duration::from_secs(10));
    /// assert!(client.code_action_resolve_timeout() <= client.request_timeout());
    /// ```
    #[must_use]
    pub fn code_action_resolve_timeout(&self) -> Duration {
        self.request_timeout().min(CODE_ACTION_RESOLVE_TIMEOUT_CAP)
    }

    /// Registers the request before enqueuing it (not before the message
    /// loop's own transport read), so a reply can never beat its entry. The
    /// returned guard cancels the request on the server if it is dropped while
    /// the request is outstanding.
    async fn register_and_send_request(
        &self,
        request: JsonRpcRequest,
        responder: oneshot::Sender<Result<Value>>,
    ) -> Result<InFlightRequest<'_>> {
        let mut in_flight = InFlightRequest::register(self, request.id.clone(), responder);
        self.command_tx
            .send(ClientCommand::SendRequest { request })
            .await
            .map_err(|_| Error::ServerTerminated)?;
        in_flight.mark_sent();
        Ok(in_flight)
    }

    /// Send request and wait for response with timeout.
    ///
    /// Automatically retries up to 3 times when the server returns error code
    /// -32802 (`ServerCancelled`, any method) or -32801 (`ContentModified`,
    /// only for methods in `CONTENT_MODIFIED_RETRY_METHODS`) -- gated by
    /// `data.retriggerRequest` when present -- using exponential backoff
    /// starting at 500 ms. Both codes share the same attempt budget: a
    /// request that hits -32801 then -32802 does not get 8 attempts, only 4.
    ///
    /// # Cancellation
    ///
    /// Dropping the returned future while the request is outstanding sends
    /// `$/cancelRequest` for it to the server, once, and ends any retry
    /// backoff without allocating another request id. A request that exceeds
    /// `timeout_duration` is cancelled the same way before
    /// [`Error::Timeout`] is returned. The server's late reply is dropped
    /// quietly. Nothing is sent for a request that already has its reply, was
    /// failed in bulk, or was issued after cancels were suppressed (the client is shutting down).
    ///
    /// This method owns the severity of LSP error-response logging (#392):
    /// a transient error about to be retried logs at `warn!`, while `error!`
    /// is reserved for an error actually surfaced to the caller -- retry
    /// exhaustion or a non-retryable code/method combination. This is
    /// deliberately not decided in `message_loop_inner`, which parses the
    /// response before knowing whether a retry will follow.
    ///
    /// # Type Parameters
    ///
    /// * `P` - The type of the request parameters (must be serializable)
    /// * `R` - The type of the response result (must be deserializable)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Server has shut down
    /// - Request times out
    /// - Response cannot be deserialized
    /// - LSP server returns an error
    pub async fn request<P, R>(
        &self,
        method: &str,
        params: P,
        timeout_duration: Duration,
    ) -> Result<R>
    where
        P: Serialize,
        R: DeserializeOwned,
    {
        Box::pin(self.request_inner(method, params, timeout_duration))
            .await
            .map_err(UnclassifiedError::surface)
    }

    async fn request_inner<P, R>(
        &self,
        method: &str,
        params: P,
        timeout_duration: Duration,
    ) -> std::result::Result<R, UnclassifiedError>
    where
        P: Serialize,
        R: DeserializeOwned,
    {
        let params_value = Self::omit_null_params(
            serde_json::to_value(params).map_err(|e| UnclassifiedError::logged(e.into()))?,
        );
        let mut delay_ms = SERVER_CANCELLED_INITIAL_DELAY_MS;

        for attempt in 0..=SERVER_CANCELLED_MAX_RETRIES {
            if attempt > 0 {
                debug!(
                    "Retrying {} (attempt {}/{}), backoff={}ms",
                    method, attempt, SERVER_CANCELLED_MAX_RETRIES, delay_ms
                );
                tokio::time::sleep(Duration::from_millis(delay_ms)).await;
                delay_ms = delay_ms.saturating_mul(2);
            }

            let id = RequestId::Number(self.request_counter.fetch_add(1, Ordering::SeqCst));
            let (response_tx, response_rx) = oneshot::channel();
            let request = JsonRpcRequest {
                jsonrpc: JsonRpcVersion,
                id: id.clone(),
                method: method.to_string(),
                params: params_value.clone(),
            };

            debug!("Sending request: {} (id={:?})", method, id);

            let mut in_flight = self
                .register_and_send_request(request, response_tx)
                .await
                .map_err(UnclassifiedError::logged)?;

            let outcome = match timeout(timeout_duration, response_rx).await {
                Ok(received) => {
                    in_flight.mark_settled();
                    received.map_err(|_| UnclassifiedError::logged(Error::ServerTerminated))?
                }
                Err(_elapsed) => {
                    // The server is slow, not necessarily dead: tell it to stop
                    // and keep a tombstone so its late reply is dropped quietly
                    // rather than warned about as an unknown id.
                    in_flight.expire();
                    return Err(UnclassifiedError::logged(Error::Timeout(timeout_duration)));
                }
            };

            match outcome {
                Ok(result_value) => {
                    return serde_json::from_value(result_value).map_err(|e| {
                        UnclassifiedError::logged(
                            self.redactions.protocol_error(format_args!(
                                "Failed to deserialize response: {e}"
                            )),
                        )
                    });
                }
                Err(Error::LspServerError(response)) if Self::retries(&response, method) => {
                    if attempt == SERVER_CANCELLED_MAX_RETRIES {
                        // Same "LSP error response: ..." prefix as the
                        // non-retryable branch below -- a log-grep alert on
                        // that prefix must catch every error actually
                        // surfaced to the caller, retry exhaustion included.
                        error!(
                            "LSP error response: {} (code {}) on '{}' (id={:?}), retries exhausted",
                            Self::truncate_error_message_for_log(&response.message),
                            response.code,
                            method,
                            id
                        );
                        return Err(UnclassifiedError::logged(Error::LspServerError(response)));
                    }
                    warn!(
                        "LSP error response: {} (code {}) on '{}' (id={:?}), will retry",
                        Self::truncate_error_message_for_log(&response.message),
                        response.code,
                        method,
                        id
                    );
                    // continue loop for next attempt
                }
                Err(Error::LspServerError(response)) => {
                    return Err(UnclassifiedError::server_response(response, method, id));
                }
                Err(e) => return Err(UnclassifiedError::logged(e)),
            }
        }

        Err(UnclassifiedError::logged(Error::ServerTerminated))
    }

    /// Whether `response` to `method` is one the client sends again: a
    /// cancelled request always, a modified document only for the methods in
    /// [`CONTENT_MODIFIED_RETRY_METHODS`], and both only when the server asks
    /// to retrigger.
    fn retries(response: &JsonRpcError, method: &str) -> bool {
        let retryable = match LspErrorCodes::from(response.code) {
            LspErrorCodes::ServerCancelled => true,
            LspErrorCodes::ContentModified => {
                CONTENT_MODIFIED_RETRY_METHODS.contains(&LspRequestMethod::from(method))
            }
            _ => false,
        };
        retryable && Self::should_retrigger(response.data.as_ref())
    }

    /// Like [`Self::request_typed`], but a server error response is returned
    /// unlogged, wrapped in an [`UnclassifiedError`] so the caller decides
    /// whether it is an error surfaced to the user or an expected outcome.
    ///
    /// # Errors
    ///
    /// See [`Self::request`].
    pub(crate) async fn request_typed_classified<R>(
        &self,
        params: R::Params,
        timeout_duration: Duration,
    ) -> std::result::Result<R::Result, UnclassifiedError>
    where
        R: lsp_types::Request,
    {
        Box::pin(self.request_inner(R::METHOD.as_str(), params, timeout_duration)).await
    }

    /// Send a typed LSP request, deriving both the method string and the
    /// result type from `R`'s [`lsp_types::Request`] implementation so they
    /// cannot drift independently -- unlike [`Self::request`], which takes
    /// the method string and result type as two unchecked, hand-picked
    /// values.
    ///
    /// # Errors
    ///
    /// See [`Self::request`].
    pub async fn request_typed<R>(
        &self,
        params: R::Params,
        timeout_duration: Duration,
    ) -> Result<R::Result>
    where
        R: lsp_types::Request,
    {
        self.request(R::METHOD.as_str(), params, timeout_duration)
            .await
    }

    /// Returns true when the error data from a retryable "please retry" LSP
    /// response (`ServerCancelled` -32802 or `ContentModified` -32801)
    /// indicates a retry should happen.
    ///
    /// The LSP spec defines `data.retriggerRequest` only for diagnostic
    /// requests' `ServerCancelled` responses (`DiagnosticServerCancellationData`)
    /// -- it is not part of the general `ServerCancelled` or `ContentModified`
    /// contract for other methods. mcpls checks this field whenever it is
    /// present regardless of method (harmless for non-diagnostic methods,
    /// since a compliant server won't send it there) and defaults to
    /// retrying when the field is absent, since retrying is the more useful
    /// default for a request that would otherwise surface as a hard error to
    /// the MCP caller.
    fn should_retrigger(data: Option<&Value>) -> bool {
        data.is_none_or(|v| {
            v.get("retriggerRequest")
                .and_then(Value::as_bool)
                .unwrap_or(true)
        })
    }

    /// Whether the message loop this client owns has stopped (it returned
    /// or panicked), leaving the connection permanently dead.
    ///
    /// Always `false` for a clone or a placeholder client: only the owning
    /// client holds the loop handle.
    pub(crate) fn is_message_loop_finished(&self) -> bool {
        self.receiver_task
            .as_ref()
            .is_some_and(JoinHandle::is_finished)
    }

    /// Fail every request still parked in `pending_requests` with
    /// `Error::ServerTerminated`, instead of leaving each to discover a dead
    /// connection only when its own timeout elapses.
    ///
    /// Intended for a client that is about to be discarded -- e.g.
    /// superseded by a respawned replacement for the same server -- so
    /// callers still waiting on it unblock immediately.
    pub(crate) fn fail_pending_requests(&self) {
        Self::drain_and_fail_pending(&self.pending_requests, &self.pending_failure);
    }

    /// Make every request still pending, or failed later by the loop's exit
    /// drain, resolve with [`Error::ServerRestarted`] instead of
    /// [`Error::ServerTerminated`].
    pub(crate) fn mark_restarted(&self, server_id: ServerId) {
        *self
            .pending_failure
            .lock()
            .unwrap_or_else(PoisonError::into_inner) = PendingFailure::Restarted(server_id);
    }

    /// Drains `pending`, resolving each remaining sender to
    /// `Err(Error::ServerTerminated)`. Shared by [`Self::fail_pending_requests`]
    /// and [`Self::message_loop`]'s exit-path cleanup (#458).
    fn drain_and_fail_pending(pending: &PendingRequests, failure: &StdMutex<PendingFailure>) {
        for sender in pending.drain_waiting() {
            let error = failure
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .error();
            let _ = sender.send(Err(error));
        }
    }

    /// Send notification (fire-and-forget, no response expected).
    ///
    /// # Errors
    ///
    /// Returns an error if the server has shut down.
    pub async fn notify<P>(&self, method: &str, params: P) -> Result<()>
    where
        P: Serialize,
    {
        let notification = OutboundNotification::new(method, params)?;

        debug!("Sending notification: {}", method);

        self.send_notification(notification).await
    }

    /// Send a typed LSP notification, deriving the method string from `N`'s
    /// [`lsp_types::Notification`] implementation so it cannot drift from the
    /// params type -- the notification counterpart to [`Self::request_typed`].
    ///
    /// # Errors
    ///
    /// See [`Self::notify`].
    pub async fn notify_typed<N>(&self, params: N::Params) -> Result<()>
    where
        N: lsp_types::Notification,
    {
        self.notify(N::METHOD.as_str(), params).await
    }

    /// Shutdown client gracefully, with a deadline of [`SHUTDOWN_TIMEOUT`].
    ///
    /// This sends a shutdown command to the background task and waits for it to complete.
    /// Only the client that owns the message loop (the one held by
    /// [`LspServer`](crate::lsp::LspServer)) can abort a wedged loop; calling this on a
    /// clone still stops the shared loop for every clone but cannot abort it.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ShutdownTimeout`] if the loop did not stop in time (it is then
    /// aborted and every pending request fails with [`Error::ServerTerminated`]), or
    /// another error if the background task failed.
    #[allow(
        clippy::arithmetic_side_effects,
        reason = "SHUTDOWN_TIMEOUT is a small constant"
    )]
    pub async fn shutdown(mut self) -> Result<()> {
        self.shutdown_until(Instant::now() + SHUTDOWN_TIMEOUT).await
    }

    /// As [`Self::shutdown`], with a caller-chosen absolute deadline.
    pub(crate) async fn shutdown_until(&mut self, deadline: Instant) -> Result<()> {
        debug!("Shutting down LSP client");

        self.suppress_cancels();
        let mut task = self.receiver_task.take();
        let command_tx = &self.command_tx;
        let outcome = timeout_at(deadline, async {
            let _ = command_tx.send(ClientCommand::Shutdown).await;
            match task.as_mut() {
                Some(task) => match task.await {
                    Ok(result) => result,
                    Err(source) => Err(Error::TaskFailed {
                        task: BackgroundTask::LspReceiver,
                        source,
                    }),
                },
                None => Ok(()),
            }
        })
        .await;

        let result = outcome.unwrap_or(Err(Error::ShutdownTimeout));
        if matches!(result, Err(Error::ShutdownTimeout)) {
            if let Some(task) = task {
                task.abort();
                // Lets the aborted loop drop `command_rx`, so a racing
                // request cannot enqueue after the drain below (#458).
                let _ = timeout(SHUTDOWN_ABORT_SETTLE, task).await;
            }
            Self::drain_and_fail_pending(&self.pending_requests, &self.pending_failure);
        }

        *self.state.lock().await = super::ServerState::Shutdown;

        result
    }

    /// Background task: handle message I/O.
    ///
    /// This task runs in the background, handling:
    /// - Outbound requests and notifications
    /// - Inbound responses and server notifications
    /// - Matching responses to pending requests
    #[allow(
        clippy::too_many_arguments,
        reason = "one-to-one with the spawned loop's channels and shared state"
    )]
    async fn message_loop(
        transport: (LspTransport, LspTransportReader),
        mut command_rx: mpsc::Receiver<ClientCommand>,
        pending_requests: PendingRequests,
        pending_failure: Arc<StdMutex<PendingFailure>>,
        lanes: Option<Lanes>,
        redactions: Arc<Redactions>,
        settings: Option<Arc<LspSettings>>,
    ) -> Result<()> {
        debug!("Message loop started");
        let (mut transport, reader) = transport;
        let (reader_handle, mut msg_rx) = spawn_reader_task(reader);
        let result = {
            // Aborts the reader task the instant `message_loop_inner` returns, even via `?` (#451).
            let _abort_reader_on_drop = crate::util::AbortOnDrop(&reader_handle);
            Self::message_loop_inner(
                &mut transport,
                &mut msg_rx,
                &mut command_rx,
                &pending_requests,
                lanes.as_ref(),
                &redactions,
                settings.as_deref(),
            )
            .await
        };
        let _ = timeout(READER_TASK_ABORT_GRACE, reader_handle).await;
        // Dropped before the drain, not just at fn-exit: otherwise a
        // `register_and_send_request` racing the drain could still insert
        // into `pending_requests` and succeed its `command_tx.send(..)`,
        // leaving that entry unfailed until its own timeout (#458 S1). Once
        // this is gone, every later `send` fails and the caller cleans up
        // its own entry.
        drop(command_rx);
        // Runs after `message_loop_inner` returns, so a response the Shutdown
        // drain (#451) already resolved is gone from the map by now -- only
        // requests with no answer get failed here (#458).
        Self::drain_and_fail_pending(&pending_requests, &pending_failure);
        if let Err(ref e) = result {
            error!("Message loop exiting with error: {}", e);
        } else {
            debug!("Message loop exiting normally");
        }
        result
    }

    /// Maps a `null` params value to an omitted `params` field. LSP methods
    /// with `params: void` (`shutdown`, `exit`) must go out without the key:
    /// tsgo rejects `"params": null` with `-32602 expected empty, got: null`.
    fn omit_null_params(params: Value) -> Option<Value> {
        if params.is_null() { None } else { Some(params) }
    }

    /// Truncate an LSP server's error message for the `tracing::error!` log
    /// line, bounding it to at most [`crate::util::MAX_LOG_STRING_BYTES`]
    /// bytes (the full formatted string is slightly longer).
    ///
    /// Log-line use only -- the message forwarded to the MCP caller in
    /// [`Error::LspServerError`] is truncated separately, to the larger
    /// [`MAX_ERROR_MESSAGE_CALLER_BYTES`] (#313).
    fn truncate_error_message_for_log(message: &str) -> String {
        crate::util::truncate_str(message, crate::util::MAX_LOG_STRING_BYTES)
    }

    /// Decides where `notification` goes: the diagnostics mailbox, the
    /// log/`showMessage` lane, the lifecycle lane, or nowhere (the floor).
    ///
    /// The notification lane (diagnostics, log, `showMessage`) and the
    /// lifecycle lane (`$/progress` `begin`/`end` frames and `Other`, which
    /// carries e.g. rust-analyzer's `experimental/serverStatus`) are split so
    /// a high-volume diagnostics publisher can never starve out a low-volume
    /// readiness signal, or vice versa.
    ///
    /// A `$/progress` `report` frame -- the high-volume case a
    /// `report`-per-package emitter like gopls can produce -- is classified
    /// via [`crate::lsp::types::ProgressKind::from_value`] (shared with
    /// `bridge::indexing::IndexingTracker::observe_progress` so the two can't
    /// drift out of sync on which `kind`s are recognized) and goes to the
    /// floor. So does an *unparseable* `$/progress` notification (e.g.
    /// missing the mandatory `token` field), which falls back to
    /// `LspNotification::Other { method: "$/progress", .. }` at parse time:
    /// otherwise a server whose `report` payloads fail to deserialize could
    /// bypass the `kind`-based filter with malformed frames.
    fn route(notification: LspNotification, lanes: Option<&Lanes>) -> Route<'_> {
        let Some(lanes) = lanes else {
            return Route::Floor;
        };
        match notification {
            LspNotification::PublishDiagnostics(params) => {
                Route::Mailbox(&lanes.notifications, params)
            }
            LspNotification::LogMessage(params) => {
                Route::Messages(&lanes.notifications, ServerMessage::Log(params))
            }
            LspNotification::ShowMessage(params) => {
                Route::Messages(&lanes.notifications, ServerMessage::Show(params))
            }
            LspNotification::Progress(params)
                if crate::lsp::types::ProgressKind::from_value(&params.value).is_some() =>
            {
                Route::Lifecycle(&lanes.lifecycle, LspNotification::Progress(params))
            }
            LspNotification::Other { method, params }
                if method.as_ref() != lsp_types::ProgressNotification::METHOD.as_str() =>
            {
                Route::Lifecycle(&lanes.lifecycle, LspNotification::Other { method, params })
            }
            LspNotification::Progress(_) | LspNotification::Other { .. } => Route::Floor,
        }
    }

    /// Sends `route` to its lane. The mailbox coalesces per file and records
    /// what it cannot hold, so a diagnostics burst is never dropped
    /// unrecorded; the other lanes report a full or closed channel.
    fn deliver(route: Route<'_>) -> Delivery {
        let delivery = |lane, delivered: bool| {
            if delivered {
                Delivery::Delivered
            } else {
                Delivery::Dropped(lane)
            }
        };
        match route {
            Route::Mailbox(sink, params) => {
                debug!(
                    "Forwarding diagnostics for {}: {} items",
                    params.uri.as_ref(),
                    params.diagnostics.len()
                );
                sink.publishes().publish(params);
                Delivery::Delivered
            }
            Route::Messages(sink, message) => delivery(
                Lane::Notification,
                sink.messages().try_send(message).is_ok(),
            ),
            Route::Lifecycle(tx, notification) => {
                delivery(Lane::Lifecycle, tx.try_send(notification).is_ok())
            }
            Route::Floor => Delivery::Delivered,
        }
    }

    #[allow(
        clippy::too_many_lines,
        clippy::too_many_arguments,
        reason = "one select loop over the transport, channels and shared state"
    )]
    async fn message_loop_inner(
        transport: &mut LspTransport,
        msg_rx: &mut mpsc::Receiver<Result<InboundMessage>>,
        command_rx: &mut mpsc::Receiver<ClientCommand>,
        pending_requests: &PendingRequests,
        lanes: Option<&Lanes>,
        redactions: &Redactions,
        settings: Option<&LspSettings>,
    ) -> Result<()> {
        loop {
            tokio::select! {
                Some(command) = command_rx.recv() => {
                    match command {
                        ClientCommand::SendRequest { request } => {
                            let value = serde_json::to_value(&request)?;
                            transport.send(&value).await?;
                        }
                        ClientCommand::SendNotification { method, params } => {
                            let notification = serde_json::to_value(JsonRpcNotification {
                                jsonrpc: JsonRpcVersion,
                                method,
                                params,
                            })?;
                            transport.send(&notification).await?;
                        }
                        ClientCommand::Shutdown => {
                            debug!("Client shutdown requested");
                            // The reader task can run ahead of us (#451): drain whatever it
                            // already queued instead of dropping it, or a response to a
                            // concurrent caller's in-flight request would be silently lost.
                            while let Ok(message) = msg_rx.try_recv() {
                                match message {
                                    Ok(m) => {
                                        Self::handle_inbound_message(
                                            transport,
                                            m,
                                            pending_requests,
                                            lanes,
                                            redactions,
                                            settings,
                                        )
                                        .await?;
                                    }
                                    Err(e) => {
                                        error!("Transport receive error while draining on shutdown: {}", e);
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }

                // Cancel-safe, unlike the `transport.receive()` this replaces (#451): reading itself happens off this `select!`.
                message = msg_rx.recv() => {
                    let message = match message {
                        Some(Ok(m)) => m,
                        Some(Err(e)) => {
                            error!("Transport receive error: {}", e);
                            return Err(e);
                        }
                        None => {
                            // Reader task only exits after sending an `Err`, so this means it panicked.
                            error!("Transport receive error: reader task ended unexpectedly");
                            return Err(Error::ServerTerminated);
                        }
                    };
                    Self::handle_inbound_message(
                        transport,
                        message,
                        pending_requests,
                        lanes,
                        redactions,
                        settings,
                    )
                    .await?;
                }
            }
        }

        Ok(())
    }

    /// Hands `response` to the request waiting for it, if any.
    fn complete_pending(
        pending_requests: &PendingRequests,
        response: JsonRpcResponse,
        redactions: &Redactions,
    ) {
        trace!("Received response: id={:?}", response.id);

        match pending_requests.resolve(&response.id) {
            Resolution::Waiting(sender) => match response.outcome {
                JsonRpcOutcome::Error(error) => {
                    // Deliberately not logged at `error!` here: this fires
                    // for every attempt, before `LspClient::request`'s retry
                    // loop knows whether the error is transient and about to
                    // be retried (-32802, or -32801 for an allowlisted
                    // method). Logging unconditionally at this point would
                    // emit a spurious ERROR line for errors that are retried
                    // and succeed. `request` logs at `warn!` on retry and
                    // `error!` once the error is actually surfaced to the
                    // caller (retry exhaustion or a non-retryable error);
                    // the response id is already traced above.
                    let message = redactions.apply(&error.message);
                    trace!(
                        "LSP error response: {} (code {})",
                        Self::truncate_error_message_for_log(&message),
                        error.code
                    );
                    // Truncated separately from the log line, to the larger
                    // MAX_ERROR_MESSAGE_CALLER_BYTES -- the raw message is
                    // unbounded and attacker-influenceable (#313), but a
                    // log-line-sized cut would also clip legitimate long
                    // errors before the model ever sees them (S2).
                    let caller_message =
                        crate::util::truncate_str(&message, MAX_ERROR_MESSAGE_CALLER_BYTES);
                    let _ = sender.send(Err(Error::LspServerError(JsonRpcError {
                        code: error.code,
                        message: caller_message,
                        data: error.data,
                    })));
                }
                JsonRpcOutcome::Result(result) => {
                    let _ = sender.send(Ok(result));
                }
            },
            Resolution::Cancelled(cause) => {
                trace!(
                    "Dropped the reply to a request mcpls cancelled ({cause:?}): id={:?}",
                    response.id
                );
            }
            Resolution::Unknown => {
                warn!(
                    "Received response for unknown request ID: {:?}",
                    response.id
                );
            }
        }
    }

    /// Processes one fully-decoded inbound LSP message: resolves a matching
    /// pending request, answers a server-initiated request, or forwards a
    /// notification to its lane. Shared by `message_loop_inner`'s normal
    /// `msg_rx.recv()` branch and its `Shutdown` drain, so a message handled
    /// during either path behaves identically.
    async fn handle_inbound_message(
        transport: &mut LspTransport,
        message: InboundMessage,
        pending_requests: &PendingRequests,
        lanes: Option<&Lanes>,
        redactions: &Redactions,
        settings: Option<&LspSettings>,
    ) -> Result<()> {
        match message {
            InboundMessage::Response(response) => {
                Self::complete_pending(pending_requests, response, redactions);
            }
            InboundMessage::UndecodableResponse { id } => {
                warn!("Failed the request answered by an undecodable response: id={id:?}");
                if let Resolution::Waiting(sender) = pending_requests.resolve(&id) {
                    let _ = sender.send(Err(Error::LspProtocolError(RedactedText::fixed(
                        "undecodable response",
                    ))));
                }
            }
            InboundMessage::UndecodableRequest { id } => {
                debug!("Answering an undecodable server request with an error: id={id:?}");
                let reply = JsonRpcReply::new(
                    id,
                    JsonRpcOutcome::Error(JsonRpcError::new(
                        ErrorCodes::InvalidRequest,
                        "Invalid Request: the request could not be decoded",
                    )),
                );
                transport.send(&serde_json::to_value(&reply)?).await?;
            }
            InboundMessage::UndecodableNotification | InboundMessage::UndecodableFrame => {}
            InboundMessage::Request(request) => {
                debug!(
                    "Received server request: {} (id={:?})",
                    request.method, request.id
                );
                let reply = Self::server_request_reply(request, settings);
                let value = serde_json::to_value(&reply)?;
                transport.send(&value).await?;
            }
            InboundMessage::Notification(notification) => {
                debug!("Received notification: {}", notification.method);

                // Parse notification into typed variant
                let mut typed = LspNotification::parse(&notification.method, notification.params);
                Self::redact_notification(&mut typed, redactions);

                let route = Self::route(typed, lanes);
                if tracing::enabled!(tracing::Level::TRACE) {
                    let forwarded: Option<&dyn std::fmt::Debug> = match &route {
                        Route::Messages(_, message) => Some(message),
                        Route::Lifecycle(_, notification) => Some(notification),
                        Route::Mailbox(..) | Route::Floor => None,
                    };
                    if let Some(payload) = forwarded {
                        trace!(
                            "Forwarding notification: {}",
                            redactions.apply(&format!("{payload:?}"))
                        );
                    }
                }

                if let Delivery::Dropped(lane) = Self::deliver(route) {
                    DropLog::of(lane).record(&notification.method);
                }
            }
        }

        Ok(())
    }

    /// Redacts the human-readable text a server controls before it reaches
    /// the notification cache, from where MCP tools and the diagnostics
    /// resource return it.
    pub(crate) fn redact_notification(notification: &mut LspNotification, redactions: &Redactions) {
        if redactions.is_empty() {
            return;
        }
        match notification {
            LspNotification::LogMessage(params) => {
                redactions.redact_in_place(&mut params.message);
            }
            LspNotification::ShowMessage(params) => {
                redactions.redact_in_place(&mut params.message);
            }
            LspNotification::PublishDiagnostics(params) => {
                for diagnostic in &mut params.diagnostics {
                    redactions.redact_diagnostic(diagnostic);
                }
            }
            LspNotification::Progress(params) => redactions.redact_progress(&mut params.value),
            LspNotification::Other { .. } => {}
        }
    }

    fn server_request_reply(
        request: JsonRpcRequest,
        settings: Option<&LspSettings>,
    ) -> JsonRpcReply {
        let outcome =
            Self::server_request_result(&request.method, request.params.as_ref(), settings);
        JsonRpcReply::new(request.id, outcome.into())
    }

    fn server_request_result(
        method: &str,
        params: Option<&Value>,
        settings: Option<&LspSettings>,
    ) -> std::result::Result<Value, JsonRpcError> {
        match LspRequestMethod::from(method) {
            LspRequestMethod::ClientRegisterCapability
            | LspRequestMethod::ClientUnregisterCapability
            | LspRequestMethod::WorkspaceWorkspaceFolders
            | LspRequestMethod::WorkspaceDiagnosticRefresh
            | LspRequestMethod::WorkspaceSemanticTokensRefresh
            | LspRequestMethod::WorkspaceInlayHintRefresh
            | LspRequestMethod::WorkspaceCodeLensRefresh
            | LspRequestMethod::WindowShowMessageRequest
            | LspRequestMethod::WindowWorkDoneProgressCreate => Ok(Value::Null),
            LspRequestMethod::WorkspaceConfiguration => {
                Self::workspace_configuration_result(params, settings)
            }
            LspRequestMethod::WorkspaceApplyEdit => Ok(serde_json::json!({ "applied": false })),
            _ => Err(JsonRpcError::new(
                ErrorCodes::MethodNotFound,
                format!("Unhandled server request: {method}"),
            )),
        }
    }

    /// Answers `workspace/configuration`: one entry per requested item.
    ///
    /// Without settings every item gets `Null`, whatever its shape and even
    /// when `items` is absent (the reply before settings existed). With
    /// settings an item gets its section (the whole object when `section` is
    /// absent, `Null` when it is unknown, not a string, or the item is not an
    /// object); only a missing
    /// `items` list is answered with `-32602`. `scopeUri` is never read.
    fn workspace_configuration_result(
        params: Option<&Value>,
        settings: Option<&LspSettings>,
    ) -> std::result::Result<Value, JsonRpcError> {
        let items = params
            .and_then(|params| params.get("items"))
            .and_then(Value::as_array);
        let Some(settings) = settings else {
            return Ok(Value::Array(vec![Value::Null; items.map_or(0, Vec::len)]));
        };
        let items = items.ok_or_else(|| {
            JsonRpcError::new(
                ErrorCodes::InvalidParams,
                "Invalid params for workspace/configuration",
            )
        })?;
        let sections = items
            .iter()
            .map(|item| match ConfigurationItem::parse(item) {
                ConfigurationItem::Whole => settings.section(None),
                ConfigurationItem::Section(section) => settings.section(Some(section)),
                ConfigurationItem::Uninterpretable => Value::Null,
            })
            .collect();
        Ok(Value::Array(sections))
    }
}

/// Logs a server error response that reached the caller, under the prefix a
/// log-grep alert watches for.
fn log_surfaced_error(method: &str, id: &RequestId, code: i32, message: &str) {
    error!(
        "LSP error response: {} (code {}) on '{}' (id={:?})",
        LspClient::truncate_error_message_for_log(message),
        code,
        method,
        id
    );
}

/// A failed request whose severity is still undecided.
///
/// A server error response is logged only once the caller says whether it is
/// surfaced as an error ([`Self::surface`], ERROR) or turned into an expected
/// outcome ([`Self::handled`], DEBUG). There is deliberately no conversion
/// into [`Error`], so `?` does not compile and the choice cannot be skipped.
#[derive(Debug)]
#[must_use = "call `surface()` or `handled()` to log and unwrap the error"]
pub struct UnclassifiedError(Box<Unclassified>);

/// The two states of an [`UnclassifiedError`]: a failure already logged where
/// it happened, and a server error response nobody has logged yet.
#[derive(Debug)]
enum Unclassified {
    Logged(Error),
    ServerResponse {
        error: JsonRpcError,
        method: String,
        id: RequestId,
    },
}

impl Unclassified {
    /// Hands over the error, first passing an unlogged server error response
    /// to `report` as (method, id, code, message).
    fn finish(self, report: impl FnOnce(&str, &RequestId, i32, &str)) -> Error {
        match self {
            Self::Logged(error) => error,
            Self::ServerResponse { error, method, id } => {
                report(&method, &id, error.code, &error.message);
                Error::LspServerError(error)
            }
        }
    }
}

fn log_handled_error(method: &str, id: &RequestId, code: i32, message: &str) {
    debug!(
        "LSP error response handled by the caller: {} (code {}) on '{}' (id={:?})",
        LspClient::truncate_error_message_for_log(message),
        code,
        method,
        id
    );
}

impl UnclassifiedError {
    fn logged(error: Error) -> Self {
        Self(Box::new(Unclassified::Logged(error)))
    }

    fn server_response(response: JsonRpcError, method: &str, id: RequestId) -> Self {
        Self(Box::new(Unclassified::ServerResponse {
            error: response,
            method: method.to_owned(),
            id,
        }))
    }

    /// Hands over the state, leaving a logged placeholder behind so that the
    /// `Drop` below has nothing left to report.
    fn take(mut self) -> Unclassified {
        std::mem::replace(&mut *self.0, Unclassified::Logged(Error::ServerTerminated))
    }

    /// The server's error response, for classification before logging.
    pub(crate) fn server_error(&self) -> Option<&JsonRpcError> {
        match &*self.0 {
            Unclassified::Logged(Error::LspServerError(response))
            | Unclassified::ServerResponse {
                error: response, ..
            } => Some(response),
            Unclassified::Logged(_) => None,
        }
    }

    /// Whether the request timed out.
    pub(crate) fn timed_out(&self) -> bool {
        matches!(&*self.0, Unclassified::Logged(Error::Timeout(_)))
    }

    /// The error returned to the caller as a failure; a server error response
    /// is logged at ERROR.
    pub(crate) fn surface(self) -> Error {
        self.take().finish(log_surfaced_error)
    }

    /// The error of an expected outcome; a server error response is logged at
    /// DEBUG.
    pub(crate) fn handled(self) -> Error {
        self.take().finish(log_handled_error)
    }
}

/// A dropped, unclassified server error response is logged at ERROR, so
/// `.ok()`, `let _ =` or an ignoring match arm cannot hide it.
impl Drop for UnclassifiedError {
    fn drop(&mut self) {
        let inner = std::mem::replace(&mut *self.0, Unclassified::Logged(Error::ServerTerminated));
        drop(inner.finish(log_surfaced_error));
    }
}

/// How one `workspace/configuration` item selects part of the settings.
enum ConfigurationItem<'a> {
    Whole,
    Section(&'a str),
    Uninterpretable,
}

impl<'a> ConfigurationItem<'a> {
    fn parse(item: &'a Value) -> Self {
        let Value::Object(object) = item else {
            return Self::Uninterpretable;
        };
        match object.get("section") {
            None | Some(Value::Null) => Self::Whole,
            Some(Value::String(section)) => Self::Section(section),
            Some(_) => Self::Uninterpretable,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::assert_matches;

    use super::*;
    use crate::config::TimeoutSecs;
    use crate::lsp::types::JsonRpcResponse;

    #[test]
    fn test_unclassified_server_response_always_reports_code_and_message() {
        let unclassified = UnclassifiedError::server_response(
            JsonRpcError {
                code: -32001,
                message: "boom".to_owned(),
                data: None,
            },
            "textDocument/hover",
            RequestId::Number(3),
        );
        let mut reported = None;

        let error = unclassified.take().finish(|method, id, code, message| {
            reported = Some((method.to_owned(), id.clone(), code, message.to_owned()));
        });

        assert_eq!(
            reported,
            Some((
                "textDocument/hover".to_owned(),
                RequestId::Number(3),
                -32001,
                "boom".to_owned()
            ))
        );
        assert_matches!(
            error,
            Error::LspServerError(JsonRpcError { code: -32001, .. })
        );
    }

    /// The `trace!` of a forwarded notification must not print a configured
    /// secret that the server echoed into an unrecognized notification.
    #[tokio::test]
    async fn test_forwarded_notification_trace_is_redacted() {
        use tracing_subscriber::prelude::*;

        use crate::test_lsp::CapturedLogs;

        let redactions =
            Redactions::new([("API_TOKEN".to_owned(), "SuperSecretValue123".to_owned())]);
        let logs = CapturedLogs::default();
        let _guard = tracing::subscriber::set_default(
            tracing_subscriber::registry()
                .with(tracing_subscriber::filter::LevelFilter::TRACE)
                .with(logs.clone()),
        );
        let (mut transport, _reader) = LspTransport::new(tokio::io::sink(), tokio::io::empty());
        let (lanes, mut lifecycle_rx) = open_lanes();
        let pending = PendingRequests::default();
        let notification = InboundMessage::Notification(JsonRpcNotification {
            jsonrpc: JsonRpcVersion,
            method: "custom/echo".to_string(),
            params: Some(serde_json::json!({"env": "SuperSecretValue123"})),
        });

        LspClient::handle_inbound_message(
            &mut transport,
            notification,
            &pending,
            Some(&lanes),
            &redactions,
            None,
        )
        .await
        .unwrap();

        assert!(lifecycle_rx.recv().await.is_some());
        let output = logs.messages().join("\n");
        assert!(output.contains("Forwarding notification"), "{output}");
        assert!(!output.contains("SuperSecretValue123"), "{output}");
    }

    fn secret_diagnostics_params() -> Value {
        let range = serde_json::json!({
            "start": {"line": 0, "character": 0},
            "end": {"line": 0, "character": 1}
        });
        serde_json::json!({
            "uri": "file:///w/main.rs",
            "diagnostics": [{
                "range": range,
                "message": "leak SuperSecretValue123",
                "data": {"hint": ["SuperSecretValue123"]}
            }]
        })
    }

    /// #583: the reader task redacts a pushed diagnostic before it reaches the
    /// notification lane, from where the cache and the MCP tools read it.
    #[tokio::test]
    async fn test_reader_task_forwards_pushed_diagnostics_redacted() {
        use crate::test_lsp::{fake_lsp_client_with_redactions, write_notification};

        let redactions =
            Redactions::new([("API_TOKEN".to_owned(), "SuperSecretValue123".to_owned())]);
        let (_client, mut server, mut lanes) = fake_lsp_client_with_redactions(redactions);

        write_notification(
            &mut server.read_half_stdin,
            "textDocument/publishDiagnostics",
            secret_diagnostics_params(),
        )
        .await;

        let forwarded = timeout(Duration::from_secs(2), lanes.publishes.recv())
            .await
            .unwrap()
            .unwrap();
        let shown = format!("{forwarded:?}");
        assert!(shown.contains("[redacted:API_TOKEN]"), "{shown}");
        assert!(!shown.contains("SuperSecretValue123"), "{shown}");
    }

    /// With nothing to hide the notification is forwarded as received.
    #[test]
    fn test_redact_notification_leaves_text_alone_without_secrets() {
        let mut notification = LspNotification::parse(
            "textDocument/publishDiagnostics",
            Some(secret_diagnostics_params()),
        );
        let before = format!("{notification:?}");

        LspClient::redact_notification(&mut notification, &Redactions::default());
        assert_eq!(format!("{notification:?}"), before);

        let unrelated = Redactions::new([("API_TOKEN".to_owned(), "NotInTheText99".to_owned())]);
        LspClient::redact_notification(&mut notification, &unrelated);
        assert_eq!(format!("{notification:?}"), before);

        let matching =
            Redactions::new([("API_TOKEN".to_owned(), "SuperSecretValue123".to_owned())]);
        LspClient::redact_notification(&mut notification, &matching);
        assert!(!format!("{notification:?}").contains("SuperSecretValue123"));
    }

    #[test]
    fn test_request_id_generation() {
        let counter = AtomicI64::new(1);

        let id1 = counter.fetch_add(1, Ordering::SeqCst);
        let id2 = counter.fetch_add(1, Ordering::SeqCst);
        let id3 = counter.fetch_add(1, Ordering::SeqCst);

        assert_eq!(id1, 1);
        assert_eq!(id2, 2);
        assert_eq!(id3, 3);
    }

    #[test]
    fn test_client_creation() {
        let config = LspServerConfig::rust_analyzer();

        let client = LspClient::new(config);
        assert_eq!(client.language_id(), "rust");
    }

    #[test]
    fn test_client_clone() {
        let config = LspServerConfig::rust_analyzer();
        let client = LspClient::new(config);

        #[allow(clippy::redundant_clone, reason = "the test exercises `Clone` itself")]
        let cloned = client.clone();
        assert_eq!(cloned.language_id(), "rust");

        assert!(
            cloned.receiver_task.is_none(),
            "Cloned client should not own receiver task"
        );
    }

    #[test]
    fn test_request_timeout_and_completion_timeout_at_default() {
        let config = LspServerConfig::rust_analyzer();
        let client = LspClient::new(config);

        assert_eq!(client.request_timeout(), Duration::from_secs(30));
        assert_eq!(client.completion_timeout(), Duration::from_secs(10));
    }

    #[test]
    fn test_completion_timeout_clamps_to_ten_seconds() {
        for secs in [1, 2, 3, 30, 300] {
            let mut config = LspServerConfig::rust_analyzer();
            config.request_timeout_seconds = TimeoutSecs::new(secs).unwrap();
            let client = LspClient::new(config);

            assert_eq!(
                client.completion_timeout(),
                Duration::from_secs(secs.min(10)),
                "request_timeout_seconds={secs}"
            );
            assert!(client.completion_timeout() <= client.request_timeout());
        }
    }

    #[test]
    fn test_code_action_resolve_timeout_clamps_to_ten_seconds() {
        for secs in [1, 2, 3, 30, 300] {
            let mut config = LspServerConfig::rust_analyzer();
            config.request_timeout_seconds = TimeoutSecs::new(secs).unwrap();
            let client = LspClient::new(config);

            assert_eq!(
                client.code_action_resolve_timeout(),
                Duration::from_secs(secs.min(10)),
                "request_timeout_seconds={secs}"
            );
            assert!(client.code_action_resolve_timeout() <= client.request_timeout());
        }
    }

    #[test]
    fn test_request_timeout_independent_per_server() {
        let mut config_a = LspServerConfig::rust_analyzer();
        config_a.request_timeout_seconds = TimeoutSecs::new(5).unwrap();
        let mut config_b = LspServerConfig::pyright();
        config_b.request_timeout_seconds = TimeoutSecs::new(15).unwrap();

        let client_a = LspClient::new(config_a);
        let client_b = LspClient::new(config_b);

        assert_eq!(client_a.request_timeout(), Duration::from_secs(5));
        assert_eq!(client_b.request_timeout(), Duration::from_secs(15));
    }

    #[test]
    fn test_register_capability_request_is_acknowledged() {
        let request = JsonRpcRequest {
            jsonrpc: JsonRpcVersion,
            id: RequestId::String("ts1".to_string()),
            method: "client/registerCapability".to_string(),
            params: Some(serde_json::json!({ "registrations": [] })),
        };

        let reply = reply_json(request);

        assert_eq!(reply["id"], serde_json::json!("ts1"));
        assert_eq!(reply["jsonrpc"], serde_json::json!("2.0"));
        assert_eq!(reply["result"], Value::Null);
        assert!(reply.get("error").is_none());
    }

    #[test]
    fn test_workspace_configuration_request_returns_null_per_item_without_settings() {
        let result = LspClient::workspace_configuration_result(
            Some(&serde_json::json!({
                "items": [{ "section": "typescript" }, { "section": "editor" }]
            })),
            None,
        );

        assert_eq!(result.unwrap(), serde_json::json!([null, null]));
    }

    fn sample_settings() -> LspSettings {
        serde_json::from_value(serde_json::json!({
            "python.analysis.typeCheckingMode": "strict",
            "gopls": { "ui.semanticTokens": true }
        }))
        .unwrap()
    }

    #[test]
    fn test_workspace_configuration_serves_settings_sections() {
        let settings = sample_settings();
        let result = LspClient::workspace_configuration_result(
            Some(&serde_json::json!({
                "items": [
                    { "section": "python.analysis" },
                    { "section": "gopls", "scopeUri": "file:///ignored" },
                    { "section": "missing" },
                    {}
                ]
            })),
            Some(&settings),
        )
        .unwrap();

        assert_eq!(
            result,
            serde_json::json!([
                { "typeCheckingMode": "strict" },
                { "ui.semanticTokens": true },
                null,
                settings.to_value()
            ])
        );
    }

    #[test]
    fn test_workspace_configuration_non_object_item_gets_null() {
        let settings = sample_settings();
        let result = LspClient::workspace_configuration_result(
            Some(&serde_json::json!({
                "items": [
                    { "section": "python.analysis" },
                    { "section": "missing.x" },
                    {},
                    { "section": 5 },
                    "x",
                    null,
                    7
                ]
            })),
            Some(&settings),
        )
        .unwrap();

        assert_eq!(
            result,
            serde_json::json!([
                { "typeCheckingMode": "strict" },
                null,
                settings.to_value(),
                null,
                null,
                null,
                null
            ])
        );
    }

    #[tokio::test]
    async fn test_message_loop_answers_workspace_configuration_from_settings() {
        use tokio::io::BufReader;

        use crate::test_lsp::{fake_lsp_client_with_config, read_framed_message, write_request};

        let mut config = LspServerConfig::rust_analyzer();
        config.settings = Some(sample_settings());
        let (_client, mut server) = fake_lsp_client_with_config(config);

        write_request(
            &mut server.read_half_stdin,
            &serde_json::json!(7),
            "workspace/configuration",
            serde_json::json!({ "items": [{ "section": "python.analysis", "scopeUri": 1 }] }),
        )
        .await;
        let mut reader = BufReader::new(&mut server.write_stdout);
        let response = read_framed_message(&mut reader).await;

        assert_eq!(response["id"], 7);
        assert_eq!(
            response["result"],
            serde_json::json!([{ "typeCheckingMode": "strict" }])
        );
    }

    #[test]
    fn test_workspace_configuration_is_lenient_about_item_shape() {
        let settings = sample_settings();
        let params = serde_json::json!({
            "items": [
                { "section": 5 },
                { "section": null },
                3,
                { "section": "gopls", "scopeUri": 42 }
            ]
        });

        let with = LspClient::workspace_configuration_result(Some(&params), Some(&settings));
        let without = LspClient::workspace_configuration_result(Some(&params), None);

        assert_eq!(
            with.unwrap(),
            serde_json::json!([
                null,
                settings.to_value(),
                null,
                { "ui.semanticTokens": true }
            ])
        );
        assert_eq!(
            without.unwrap(),
            serde_json::json!([null, null, null, null])
        );
    }

    #[test]
    fn test_workspace_configuration_without_settings_matches_the_old_reply_for_bad_params() {
        for params in [
            None,
            Some(serde_json::json!({})),
            Some(serde_json::json!({ "items": "x" })),
        ] {
            let result = LspClient::workspace_configuration_result(params.as_ref(), None);
            assert_eq!(result.unwrap(), serde_json::json!([]));
        }
    }

    #[test]
    fn test_workspace_configuration_with_settings_rejects_missing_items() {
        for params in [None, Some(serde_json::json!({ "items": "nope" }))] {
            let error = LspClient::workspace_configuration_result(
                params.as_ref(),
                Some(&sample_settings()),
            )
            .unwrap_err();
            assert_eq!(error.code, -32602);
        }
    }

    /// P1: without this, no spec-compliant LSP server may ever initiate
    /// `$/progress` at all (per LSP 3.17, a server needs a successful
    /// `window/workDoneProgress/create` response before it may report
    /// server-initiated progress for a token).
    #[test]
    fn test_work_done_progress_create_request_is_acknowledged() {
        let request = JsonRpcRequest {
            jsonrpc: JsonRpcVersion,
            id: RequestId::String("wdp1".to_string()),
            method: "window/workDoneProgress/create".to_string(),
            params: Some(serde_json::json!({ "token": "indexing" })),
        };

        let reply = reply_json(request);

        assert_eq!(reply["result"], Value::Null);
        assert!(reply.get("error").is_none());
    }

    fn progress(value: serde_json::Value) -> LspNotification {
        LspNotification::Progress(lsp_types::ProgressParams {
            token: lsp_types::ProgressToken::Int(1),
            value,
        })
    }

    fn other(method: &'static str) -> LspNotification {
        LspNotification::Other {
            method: std::borrow::Cow::Borrowed(method),
            params: None,
        }
    }

    fn open_lanes() -> (Lanes, mpsc::Receiver<LspNotification>) {
        let (messages_tx, _messages_rx) = mpsc::channel(1);
        let (notifications, _reader) = NotificationSink::new(messages_tx);
        let (lifecycle, lifecycle_rx) = mpsc::channel(4);
        (
            Lanes {
                notifications,
                lifecycle,
            },
            lifecycle_rx,
        )
    }

    /// S3 (Fix 7): a `report`-kind `$/progress` frame must never be
    /// enqueued on either notification lane -- the actual mechanism
    /// protecting against a `report`-per-package emitter like gopls
    /// overrunning the bounded lifecycle channel.
    #[test]
    fn test_report_progress_frame_goes_to_the_floor() {
        let report = progress(serde_json::json!({ "kind": "report", "percentage": 50 }));

        let (lanes, _rx) = open_lanes();

        assert_matches!(LspClient::route(report, Some(&lanes)), Route::Floor);
    }

    /// Fix 3 / M1: an unparseable `$/progress` notification (e.g. missing
    /// the mandatory `token` field) falls back to `LspNotification::Other {
    /// method: "$/progress", .. }` at parse time -- this must be dropped
    /// the same as a well-formed `report` frame, not routed to the
    /// lifecycle lane, or a server whose payloads fail to deserialize could
    /// bypass the kind-based filter entirely.
    #[test]
    fn test_malformed_progress_other_goes_to_the_floor() {
        let (lanes, _rx) = open_lanes();

        assert_matches!(
            LspClient::route(other("$/progress"), Some(&lanes)),
            Route::Floor
        );
    }

    /// P3 sanity check alongside the two tests above: a `begin` frame and a
    /// genuine `Other` notification (e.g. rust-analyzer's
    /// `experimental/serverStatus`) must still reach the lifecycle lane --
    /// the report/malformed filters must not have overcorrected.
    #[test]
    fn test_begin_and_other_notifications_reach_lifecycle_lane() {
        let begin = progress(serde_json::json!({ "kind": "begin", "title": "Indexing" }));
        let end = progress(serde_json::json!({ "kind": "end" }));

        let (lanes, _rx) = open_lanes();

        for notification in [begin, end, other("experimental/serverStatus")] {
            assert_matches!(
                LspClient::route(notification, Some(&lanes)),
                Route::Lifecycle(..)
            );
        }
    }

    #[test]
    fn test_route_covers_every_notification_shape() {
        let publish = || {
            LspNotification::PublishDiagnostics(PublishDiagnosticsParams {
                uri: lsp_types::Uri::from("file:///a.rs".to_owned()),
                diagnostics: Vec::new(),
                version: None,
            })
        };
        let log = || {
            LspNotification::LogMessage(lsp_types::LogMessageParams {
                kind: lsp_types::MessageType::Info,
                message: "m".to_owned(),
            })
        };
        let show = || {
            LspNotification::ShowMessage(lsp_types::ShowMessageParams {
                kind: lsp_types::MessageType::Info,
                message: "m".to_owned(),
            })
        };

        let (lanes, _rx) = open_lanes();

        assert_matches!(
            LspClient::route(publish(), Some(&lanes)),
            Route::Mailbox(..)
        );
        assert_matches!(
            LspClient::route(log(), Some(&lanes)),
            Route::Messages(_, ServerMessage::Log(_))
        );
        assert_matches!(
            LspClient::route(show(), Some(&lanes)),
            Route::Messages(_, ServerMessage::Show(_))
        );
        for notification in [
            progress(serde_json::json!({ "kind": "begin" })),
            other("experimental/serverStatus"),
        ] {
            assert_matches!(
                LspClient::route(notification, Some(&lanes)),
                Route::Lifecycle(..)
            );
        }
        for notification in [publish(), log(), show(), other("custom/x")] {
            assert_matches!(LspClient::route(notification, None), Route::Floor);
        }
    }

    #[test]
    fn test_deliver_reports_the_lane_that_dropped_a_frame() {
        let (lifecycle_tx, lifecycle_rx) = mpsc::channel(1);
        drop(lifecycle_rx);

        let delivery = LspClient::deliver(Route::Lifecycle(
            &lifecycle_tx,
            other("experimental/serverStatus"),
        ));

        assert_eq!(delivery, Delivery::Dropped(Lane::Lifecycle));
        assert_eq!(LspClient::deliver(Route::Floor), Delivery::Delivered);
    }

    #[test]
    fn test_unknown_server_request_returns_method_not_found() {
        let request = JsonRpcRequest {
            jsonrpc: JsonRpcVersion,
            id: RequestId::String("unknown-1".to_string()),
            method: "custom/request".to_string(),
            params: None,
        };

        let reply = reply_json(request);

        assert!(reply.get("result").is_none());
        assert_eq!(reply["error"]["code"], serde_json::json!(-32601));
        assert_eq!(
            reply["error"]["message"],
            serde_json::json!("Unhandled server request: custom/request")
        );
    }

    fn reply_json(request: JsonRpcRequest) -> Value {
        serde_json::to_value(LspClient::server_request_reply(request, None)).unwrap()
    }

    #[tokio::test]
    async fn test_null_response_handling() {
        use crate::lsp::types::{JsonRpcResponse, RequestId};

        let pending_requests = PendingRequests::default();

        let (response_tx, response_rx) = oneshot::channel::<Result<Value>>();

        pending_requests.register(RequestId::Number(1), response_tx);

        let null_response = JsonRpcResponse {
            jsonrpc: JsonRpcVersion,
            id: RequestId::Number(1),
            outcome: JsonRpcOutcome::Result(Value::Null),
        };

        let Resolution::Waiting(sender) = pending_requests.resolve(&null_response.id) else {
            panic!("the request must be waiting");
        };
        let _ = sender.send(Ok(Value::Null));

        let timeout_result =
            tokio::time::timeout(tokio::time::Duration::from_millis(100), response_rx).await;

        assert!(timeout_result.is_ok(), "Should not timeout");

        let channel_result = timeout_result.unwrap();
        assert!(
            channel_result.is_ok(),
            "Channel should not be closed: {:?}",
            channel_result.err()
        );

        let response = channel_result.unwrap();
        assert!(
            response.is_ok(),
            "Should receive Ok(Value::Null), not Err: {:?}",
            response.err()
        );

        let value = response.unwrap();
        assert_eq!(value, Value::Null, "Should receive Value::Null");
    }

    #[tokio::test]
    async fn test_error_response_handling() {
        use crate::lsp::types::{JsonRpcError, JsonRpcResponse, RequestId};

        let pending_requests = PendingRequests::default();
        let (response_tx, response_rx) = oneshot::channel::<Result<Value>>();

        pending_requests.register(RequestId::Number(1), response_tx);

        let error_response = JsonRpcResponse {
            jsonrpc: JsonRpcVersion,
            id: RequestId::Number(1),
            outcome: JsonRpcOutcome::Error(JsonRpcError {
                code: -32601,
                message: "Method not found".to_string(),
                data: None,
            }),
        };

        if let Resolution::Waiting(sender) = pending_requests.resolve(&error_response.id)
            && let JsonRpcOutcome::Error(error) = error_response.outcome
        {
            let _ = sender.send(Err(Error::LspServerError(error)));
        }

        let result = response_rx.await.unwrap();
        assert!(result.is_err(), "Should receive error");

        if let Err(Error::LspServerError(JsonRpcError { code, message, .. })) = result {
            assert_eq!(code, -32601);
            assert_eq!(message, "Method not found");
        } else {
            panic!("Expected LspServerError");
        }
    }

    #[tokio::test]
    async fn test_unknown_request_id() {
        use crate::lsp::types::{JsonRpcResponse, RequestId};

        let pending_requests = PendingRequests::default();

        let response = JsonRpcResponse {
            jsonrpc: JsonRpcVersion,
            id: RequestId::Number(999),
            outcome: JsonRpcOutcome::Result(Value::Null),
        };

        assert_matches!(
            pending_requests.resolve(&response.id),
            Resolution::Unknown,
            "Should not find sender for unknown ID"
        );
    }

    #[test]
    fn test_truncate_error_message_for_log_handles_multibyte_boundary() {
        // 199 ASCII bytes followed by a 3-byte UTF-8 char ('€') straddles the byte-200 cut.
        let message = format!("{}€{}", "x".repeat(199), "y".repeat(50));

        let truncated = LspClient::truncate_error_message_for_log(&message);

        // Cutting before the multi-byte char keeps the message valid UTF-8 (no panic) and
        // pins the payload to 199 bytes, not 200.
        assert_eq!(truncated, format!("{}... (truncated)", "x".repeat(199)));
    }

    #[test]
    fn test_truncate_error_message_for_log_no_truncation_at_or_below_limit() {
        let exact = "x".repeat(200);
        assert_eq!(LspClient::truncate_error_message_for_log(&exact), exact);
        assert_eq!(LspClient::truncate_error_message_for_log(""), "");
    }

    #[test]
    fn test_truncate_error_message_for_log_truncates_just_above_limit() {
        let message = "x".repeat(201);
        assert_eq!(
            LspClient::truncate_error_message_for_log(&message),
            format!("{}... (truncated)", "x".repeat(200))
        );
    }

    #[test]
    fn test_truncate_error_message_for_log_handles_wide_char_at_limit() {
        // A 4-byte emoji run straddling every possible alignment near the byte-200 boundary.
        let message = format!("{}{}", "x".repeat(197), "🦀".repeat(10));

        let truncated = LspClient::truncate_error_message_for_log(&message);

        assert_eq!(truncated, format!("{}... (truncated)", "x".repeat(197)));
    }

    #[tokio::test]
    async fn test_concurrent_request_ids() {
        let counter = Arc::new(AtomicI64::new(1));

        let counter1 = Arc::clone(&counter);
        let counter2 = Arc::clone(&counter);
        let counter3 = Arc::clone(&counter);

        let handles = vec![
            tokio::spawn(async move { counter1.fetch_add(1, Ordering::SeqCst) }),
            tokio::spawn(async move { counter2.fetch_add(1, Ordering::SeqCst) }),
            tokio::spawn(async move { counter3.fetch_add(1, Ordering::SeqCst) }),
        ];

        let mut ids = Vec::new();
        for handle in handles {
            ids.push(handle.await.unwrap());
        }

        ids.sort_unstable();
        assert_eq!(ids, vec![1, 2, 3], "IDs should be unique and sequential");
    }

    #[test]
    fn test_jsonrpc_version_constant() {
        assert_eq!(
            serde_json::to_value(JsonRpcVersion).unwrap(),
            serde_json::json!("2.0")
        );
    }

    /// #239 regression: a request that times out must remove its own entry
    /// from `pending_requests` instead of leaking it. `sleep` is used as the
    /// "server": it never writes anything to stdout, so no response can ever
    /// arrive and the request is guaranteed to time out rather than race a
    /// real answer.
    ///
    /// Unix-only: spawns a real `sleep` subprocess, which is unavailable on
    /// the Windows CI runner.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_request_timeout_removes_pending_entry() {
        let mut child = tokio::process::Command::new("sleep")
            .arg("2")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        let stdin = child.stdin.take().unwrap();
        let stdout = child.stdout.take().unwrap();

        let transport = LspTransport::new(stdin, stdout);
        let client = LspClient::from_transport(LspServerConfig::rust_analyzer(), transport);

        let result: Result<Value> = client
            .request(
                "textDocument/hover",
                serde_json::json!({}),
                Duration::from_millis(50),
            )
            .await;

        assert_matches!(result, Err(Error::Timeout(_)), "got {result:?}");
        assert!(
            client.pending_requests.no_waiting(),
            "timed-out request must not remain in pending_requests"
        );
    }

    /// #249 continuation: a client about to be discarded (e.g. superseded by
    /// a respawned replacement) must fail every still-pending request
    /// immediately rather than leaving callers to wait out their timeout.
    #[tokio::test]
    async fn test_fail_pending_requests_resolves_all_as_server_terminated() {
        let pending_requests = PendingRequests::default();
        let (command_tx, _command_rx) = mpsc::channel(1);

        let client = LspClient {
            config: LspServerConfig::rust_analyzer(),
            state: Arc::new(Mutex::new(super::super::ServerState::Ready)),
            request_counter: Arc::new(AtomicI64::new(1)),
            command_tx,
            pending_requests: pending_requests.clone(),
            closing: Arc::default(),
            pending_failure: Arc::default(),
            receiver_task: None,
            redactions: Arc::default(),
            connection_id: ConnectionId::next(),
        };

        let (tx1, rx1) = oneshot::channel::<Result<Value>>();
        let (tx2, rx2) = oneshot::channel::<Result<Value>>();
        pending_requests.register(RequestId::Number(1), tx1);
        pending_requests.register(RequestId::Number(2), tx2);

        client.fail_pending_requests();

        assert!(pending_requests.no_waiting());
        assert_matches!(rx1.await.unwrap(), Err(Error::ServerTerminated));
        assert_matches!(rx2.await.unwrap(), Err(Error::ServerTerminated));
    }

    /// Pins where a request is cancelled (#518): once the request is on the
    /// wire, a timeout or a dropped caller must leave the client able to
    /// serve the next request, with no stale reply crossing over to it. The
    /// paused clock makes the timeout deterministic.
    mod timeout_cancellation {
        use tokio::io::BufReader;
        use tokio::task::JoinHandle;

        use super::*;
        use crate::test_lsp::{fake_lsp_client, read_framed_message, write_response};

        const TIMEOUT: Duration = Duration::from_secs(5);

        fn spawn_hover(client: &LspClient) -> JoinHandle<Result<Value>> {
            let client = client.clone();
            tokio::spawn(async move {
                client
                    .request("textDocument/hover", serde_json::json!({}), TIMEOUT)
                    .await
            })
        }

        #[tokio::test(start_paused = true)]
        async fn test_timeout_while_awaiting_reply_clears_pending_and_discards_late_reply() {
            let (client, mut server) = fake_lsp_client();
            let mut reader = BufReader::new(&mut server.write_stdout);

            let first = spawn_hover(&client);
            let first_request = read_framed_message(&mut reader).await;

            tokio::time::advance(TIMEOUT + Duration::from_secs(1)).await;
            assert_matches!(
                first.await.unwrap(),
                Err(Error::Timeout(limit)) if limit == TIMEOUT,
                "request awaiting its reply must time out"
            );
            assert!(
                client.pending_requests.no_waiting(),
                "timed-out request must not remain in pending_requests"
            );
            let cancel = read_framed_message(&mut reader).await;
            assert_eq!(cancel["method"], "$/cancelRequest");
            assert_eq!(cancel["params"]["id"], first_request["id"]);

            write_response(
                &mut server.read_half_stdin,
                &first_request["id"],
                serde_json::json!("stale"),
            )
            .await;

            let second = spawn_hover(&client);
            let second_request = read_framed_message(&mut reader).await;
            assert_ne!(second_request["id"], first_request["id"]);
            write_response(
                &mut server.read_half_stdin,
                &second_request["id"],
                serde_json::json!("fresh"),
            )
            .await;

            assert_eq!(second.await.unwrap().unwrap(), serde_json::json!("fresh"));
            assert!(client.pending_requests.no_waiting());
        }

        #[tokio::test]
        async fn test_undecodable_response_fails_only_its_request() {
            use crate::test_lsp::write_raw_frame;

            let (client, mut server) = fake_lsp_client();
            let mut reader = BufReader::new(&mut server.write_stdout);

            let first = spawn_hover(&client);
            let first_request = read_framed_message(&mut reader).await;
            let deep = format!("{}1{}", "{\"parent\":".repeat(200), "}".repeat(200));
            write_raw_frame(
                &mut server.read_half_stdin,
                &format!(
                    r#"{{"jsonrpc":"2.0","id":{},"result":{deep}}}"#,
                    first_request["id"]
                ),
            )
            .await;

            assert_matches!(
                first.await.unwrap(),
                Err(Error::LspProtocolError(message)) if message.as_str() == "undecodable response"
            );

            let second = spawn_hover(&client);
            let second_request = read_framed_message(&mut reader).await;
            write_response(
                &mut server.read_half_stdin,
                &second_request["id"],
                serde_json::json!("alive"),
            )
            .await;
            assert_eq!(second.await.unwrap().unwrap(), serde_json::json!("alive"));
            assert!(client.pending_requests.no_waiting());
        }

        fn deeply_nested() -> String {
            format!("{}1{}", "{\"parent\":".repeat(200), "}".repeat(200))
        }

        /// #681: invalid UTF-8 in a response body fails its own request only.
        #[tokio::test]
        async fn test_invalid_utf8_response_fails_only_its_request() {
            use tokio::io::AsyncWriteExt as _;

            let (client, mut server) = fake_lsp_client();
            let mut reader = BufReader::new(&mut server.write_stdout);

            let first = spawn_hover(&client);
            let first_request = read_framed_message(&mut reader).await;
            let mut body = format!(
                r#"{{"jsonrpc":"2.0","id":{},"result":"x"#,
                first_request["id"]
            )
            .into_bytes();
            body.extend_from_slice(&[0xff, 0xfe]);
            body.extend_from_slice(br#"y"}"#);
            let stdin = &mut server.read_half_stdin;
            stdin
                .write_all(format!("Content-Length: {}\r\n\r\n", body.len()).as_bytes())
                .await
                .unwrap();
            stdin.write_all(&body).await.unwrap();
            stdin.flush().await.unwrap();

            assert_matches!(
                first.await.unwrap(),
                Err(Error::LspProtocolError(message)) if message.as_str() == "undecodable response"
            );

            let second = spawn_hover(&client);
            let second_request = read_framed_message(&mut reader).await;
            write_response(
                &mut server.read_half_stdin,
                &second_request["id"],
                serde_json::json!("alive"),
            )
            .await;
            assert_eq!(second.await.unwrap().unwrap(), serde_json::json!("alive"));
        }

        /// #681: undecodable frames are warned about at most once a minute,
        /// with the number dropped silently since the last warning.
        #[test]
        fn test_undecodable_warning_is_time_limited_and_counts_the_suppressed() {
            use tracing_subscriber::layer::SubscriberExt as _;

            let captured = crate::test_lsp::CapturedLogs::default();
            let _guard = tracing::subscriber::set_default(
                tracing_subscriber::registry().with(captured.clone()),
            );
            let mut run = UndecodableRun::default();
            let start = std::time::Instant::now();
            let at = |secs| start + Duration::from_secs(secs);
            for secs in [0, 1, 2, 30] {
                run.observe_at(InboundMessage::UndecodableFrame, at(secs))
                    .unwrap();
            }
            run.observe_at(InboundMessage::UndecodableFrame, at(61))
                .unwrap();

            let warnings: Vec<_> = captured
                .entries()
                .into_iter()
                .filter(|(level, _)| *level == tracing::Level::WARN)
                .map(|(_, message)| message)
                .collect();
            assert_eq!(warnings.len(), 2, "{warnings:?}");
            assert!(warnings[0].contains("(0 others"), "{warnings:?}");
            assert!(warnings[1].contains("(3 others"), "{warnings:?}");
        }

        #[tokio::test]
        async fn test_undecodable_server_request_is_answered_with_an_error() {
            use crate::test_lsp::write_raw_frame;

            let (client, mut server) = fake_lsp_client();
            let mut reader = BufReader::new(&mut server.write_stdout);

            write_raw_frame(
                &mut server.read_half_stdin,
                &format!(
                    r#"{{"jsonrpc":"2.0","id":"srv-1","method":"client/registerCapability","params":{}}}"#,
                    deeply_nested()
                ),
            )
            .await;
            let reply = read_framed_message(&mut reader).await;

            assert_eq!(reply["id"], serde_json::json!("srv-1"));
            assert_eq!(reply["error"]["code"], serde_json::json!(-32600));

            let hover = spawn_hover(&client);
            let request = read_framed_message(&mut reader).await;
            write_response(
                &mut server.read_half_stdin,
                &request["id"],
                serde_json::json!("alive"),
            )
            .await;
            assert_eq!(hover.await.unwrap().unwrap(), serde_json::json!("alive"));
        }

        #[tokio::test]
        async fn test_undecodable_notification_is_dropped_and_the_connection_stays_up() {
            use crate::test_lsp::write_raw_frame;

            let (client, mut server) = fake_lsp_client();
            let mut reader = BufReader::new(&mut server.write_stdout);
            let hover = spawn_hover(&client);
            let request = read_framed_message(&mut reader).await;

            write_raw_frame(
                &mut server.read_half_stdin,
                &format!(
                    r#"{{"jsonrpc":"2.0","method":"window/logMessage","params":{}}}"#,
                    deeply_nested()
                ),
            )
            .await;
            write_response(
                &mut server.read_half_stdin,
                &request["id"],
                serde_json::json!("alive"),
            )
            .await;

            assert_eq!(hover.await.unwrap().unwrap(), serde_json::json!("alive"));
        }

        #[tokio::test]
        async fn test_a_run_of_undecodable_frames_ends_the_connection() {
            use crate::test_lsp::write_raw_frame;

            let (client, mut server) = fake_lsp_client();
            let mut reader = BufReader::new(&mut server.write_stdout);
            let hover = spawn_hover(&client);
            let _request = read_framed_message(&mut reader).await;

            for _ in 0..MAX_CONSECUTIVE_UNDECODABLE_FRAMES {
                write_raw_frame(&mut server.read_half_stdin, "{not json").await;
            }

            assert_matches!(hover.await.unwrap(), Err(Error::ServerTerminated));
        }

        #[tokio::test]
        async fn test_a_decodable_message_ends_a_run_of_undecodable_frames() {
            use crate::test_lsp::write_raw_frame;

            let (client, mut server) = fake_lsp_client();
            let mut reader = BufReader::new(&mut server.write_stdout);
            let hover = spawn_hover(&client);
            let request = read_framed_message(&mut reader).await;

            let almost = MAX_CONSECUTIVE_UNDECODABLE_FRAMES - 1;
            for _ in 0..2 {
                for _ in 0..almost {
                    write_raw_frame(&mut server.read_half_stdin, "{not json").await;
                }
                write_raw_frame(
                    &mut server.read_half_stdin,
                    r#"{"jsonrpc":"2.0","method":"$/progress"}"#,
                )
                .await;
            }
            write_response(
                &mut server.read_half_stdin,
                &request["id"],
                serde_json::json!("alive"),
            )
            .await;

            assert_eq!(hover.await.unwrap().unwrap(), serde_json::json!("alive"));
        }

        #[tokio::test(start_paused = true)]
        async fn test_dropped_caller_after_send_is_cleared_by_late_reply() {
            let (client, mut server) = fake_lsp_client();
            let mut reader = BufReader::new(&mut server.write_stdout);

            let first = spawn_hover(&client);
            let first_request = read_framed_message(&mut reader).await;
            first.abort();
            assert!(first.await.unwrap_err().is_cancelled());
            let cancel = read_framed_message(&mut reader).await;
            assert_eq!(cancel["method"], "$/cancelRequest");
            assert_eq!(cancel["params"]["id"], first_request["id"]);

            write_response(
                &mut server.read_half_stdin,
                &first_request["id"],
                serde_json::json!("orphaned"),
            )
            .await;

            let second = spawn_hover(&client);
            let second_request = read_framed_message(&mut reader).await;
            write_response(
                &mut server.read_half_stdin,
                &second_request["id"],
                serde_json::json!("fresh"),
            )
            .await;

            assert_eq!(second.await.unwrap().unwrap(), serde_json::json!("fresh"));
            assert!(
                client.pending_requests.no_waiting(),
                "the orphaned reply must clear the abandoned entry"
            );
        }
    }

    #[test]
    fn test_should_retrigger_defaults_to_true_when_data_absent() {
        assert!(LspClient::should_retrigger(None));
    }

    #[test]
    fn test_should_retrigger_false_when_flag_false() {
        assert!(!LspClient::should_retrigger(Some(&serde_json::json!({
            "retriggerRequest": false
        }))));
    }

    #[test]
    fn test_should_retrigger_true_when_flag_true() {
        assert!(LspClient::should_retrigger(Some(&serde_json::json!({
            "retriggerRequest": true
        }))));
    }

    /// Wire-level checks that `params: void` LSP methods go out without a
    /// `params` key. tsgo rejects `"params": null` on `shutdown` with
    /// `-32602 expected empty, got: null` and then ignores the `exit` that
    /// follows, so mcpls fell through to the kill-on-timeout path.
    mod void_params_wire {
        use tokio::io::BufReader;

        use super::*;
        use crate::test_lsp::{fake_lsp_client, read_framed_message, write_response};

        #[tokio::test]
        async fn test_request_with_null_params_omits_params_key() {
            let (client, mut server) = fake_lsp_client();

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>("shutdown", Value::Null, Duration::from_secs(5))
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let request = read_framed_message(&mut reader).await;

            assert_eq!(request["method"], "shutdown");
            assert!(
                request.get("params").is_none(),
                "null params must be omitted, got: {request}"
            );

            write_response(&mut server.read_half_stdin, &request["id"], Value::Null).await;
            request_task.await.unwrap().unwrap();
        }

        #[tokio::test]
        async fn test_notify_with_null_params_omits_params_key() {
            let (client, mut server) = fake_lsp_client();

            client.notify("exit", Value::Null).await.unwrap();

            let mut reader = BufReader::new(&mut server.write_stdout);
            let notification = read_framed_message(&mut reader).await;

            assert_eq!(notification["method"], "exit");
            assert!(
                notification.get("params").is_none(),
                "null params must be omitted, got: {notification}"
            );
        }

        #[tokio::test]
        async fn test_notify_with_empty_object_params_keeps_params_key() {
            let (client, mut server) = fake_lsp_client();

            client
                .notify("initialized", lsp_types::InitializedParams {})
                .await
                .unwrap();

            let mut reader = BufReader::new(&mut server.write_stdout);
            let notification = read_framed_message(&mut reader).await;

            assert_eq!(notification["method"], "initialized");
            assert_eq!(
                notification["params"],
                serde_json::json!({}),
                "non-null params must still be sent"
            );
        }
    }

    mod retry_behavior {
        use tokio::io::{AsyncWriteExt, BufReader, DuplexStream};

        use super::*;
        use crate::test_lsp::{
            CapturedLogs, fake_lsp_client, read_framed_message, write_error_response,
            write_response as write_success_response,
        };

        /// Writes a framed JSON-RPC retryable error response — either
        /// `ServerCancelled` (-32802) or `ContentModified` (-32801) — with a
        /// `data.retriggerRequest` flag.
        ///
        /// Kept local rather than promoted to the shared `test_lsp` harness:
        /// the `data.retriggerRequest` field is specific to this retry-logic
        /// test suite, unlike the generic success/error responses above.
        async fn write_retryable_error_response(
            stdin: &mut DuplexStream,
            id: &Value,
            code: i32,
            message: &str,
            retrigger: bool,
        ) {
            let response = serde_json::json!({
                "jsonrpc": "2.0",
                "id": id,
                "error": {
                    "code": code,
                    "message": message,
                    "data": { "retriggerRequest": retrigger },
                },
            });
            let content = serde_json::to_string(&response).unwrap();
            let header = format!("Content-Length: {}\r\n\r\n", content.len());
            stdin.write_all(header.as_bytes()).await.unwrap();
            stdin.write_all(content.as_bytes()).await.unwrap();
            stdin.flush().await.unwrap();
        }

        // Not `start_paused`: the retry loop's real backoff sleeps
        // interleave with real async I/O on the duplex pipes below, and
        // paused virtual time does not reliably auto-advance across both.
        //
        // Also captures tracing output (#392): retry exhaustion is the one
        // scenario where every attempt but the last logs `warn!` and only
        // the last logs `error!`, so this doubles as that regression test
        // rather than duplicating the same ~3.5s wire choreography in a
        // second test just to assert on log severity.
        #[tokio::test]
        async fn test_retry_exhaustion_returns_original_server_cancelled_error() {
            use tracing_subscriber::layer::SubscriberExt as _;

            let (client, mut server) = fake_lsp_client();
            let captured = CapturedLogs::default();
            let subscriber = tracing_subscriber::registry().with(captured.clone());
            let guard = tracing::subscriber::set_default(subscriber);

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);
            // Initial attempt plus SERVER_CANCELLED_MAX_RETRIES retries: every
            // attempt gets ServerCancelled, so retries must exhaust rather
            // than loop forever or swallow the error.
            for _ in 0..=SERVER_CANCELLED_MAX_RETRIES {
                let request = read_framed_message(&mut reader).await;
                let id = request["id"].clone();
                write_retryable_error_response(
                    &mut server.read_half_stdin,
                    &id,
                    i32::from(LspErrorCodes::ServerCancelled),
                    "server cancelled the request",
                    true,
                )
                .await;
            }

            let result = request_task.await.unwrap();

            match result {
                Err(Error::LspServerError(JsonRpcError {
                    code,
                    message,
                    data,
                })) => {
                    // Assert the exact original error surfaces, not merely
                    // "some error with this code" -- a freshly constructed
                    // placeholder error would satisfy a code-only check.
                    assert_eq!(code, i32::from(LspErrorCodes::ServerCancelled));
                    assert_eq!(message, "server cancelled the request");
                    assert_eq!(data, Some(serde_json::json!({ "retriggerRequest": true })));
                }
                other => panic!("expected exhausted ServerCancelled error, got {other:?}"),
            }

            drop(guard);
            let logs = captured.entries();
            assert_eq!(
                logs.iter()
                    .filter(|(level, _)| *level == tracing::Level::ERROR)
                    .count(),
                1,
                "exactly the final exhausted attempt must log at ERROR, got: {logs:?}"
            );
            assert!(
                logs.iter()
                    .any(|(level, msg)| *level == tracing::Level::ERROR
                        && msg.contains("LSP error response")
                        && msg.contains("retries exhausted")),
                "expected an ERROR log sharing the 'LSP error response' prefix and naming \
                 retry exhaustion, got: {logs:?}"
            );
            assert_eq!(
                logs.iter()
                    .filter(
                        |(level, msg)| *level == tracing::Level::WARN && msg.contains("will retry")
                    )
                    .count(),
                usize::try_from(SERVER_CANCELLED_MAX_RETRIES).unwrap(),
                "every attempt before the last must log a WARN 'will retry' line, got: {logs:?}"
            );
        }

        #[tokio::test]
        async fn test_retrigger_false_returns_immediately_without_retry() {
            let (client, mut server) = fake_lsp_client();

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let request = read_framed_message(&mut reader).await;
            let id = request["id"].clone();
            write_retryable_error_response(
                &mut server.read_half_stdin,
                &id,
                i32::from(LspErrorCodes::ServerCancelled),
                "server cancelled the request",
                false,
            )
            .await;

            // With `retriggerRequest: false`, `should_retrigger`'s gate on
            // the retry branch must short-circuit the loop: the error
            // returns well under the first 500ms backoff, and no second
            // request is ever sent. If the `&& Self::should_retrigger(..)`
            // guard were ever dropped from the retry match arm, this would
            // instead retry and both assertions below would fail.
            let result = tokio::time::timeout(Duration::from_millis(200), request_task)
                .await
                .unwrap()
                .unwrap();

            match result {
                Err(Error::LspServerError(JsonRpcError { code, .. })) => {
                    assert_eq!(code, i32::from(LspErrorCodes::ServerCancelled));
                }
                other => panic!("expected immediate ServerCancelled error, got {other:?}"),
            }

            let second_request =
                tokio::time::timeout(Duration::from_millis(200), read_framed_message(&mut reader))
                    .await;
            assert!(
                second_request.is_err(),
                "no retry should have been sent after retriggerRequest: false"
            );
        }

        #[tokio::test]
        async fn test_retry_succeeds_after_one_server_cancelled_response() {
            let (client, mut server) = fake_lsp_client();

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);

            // First attempt is cancelled and must retrigger.
            let first = read_framed_message(&mut reader).await;
            write_retryable_error_response(
                &mut server.read_half_stdin,
                &first["id"].clone(),
                i32::from(LspErrorCodes::ServerCancelled),
                "server cancelled the request",
                true,
            )
            .await;

            // Second attempt (after backoff) succeeds -- proves the loop
            // genuinely re-sends the request rather than just counting down.
            let second = read_framed_message(&mut reader).await;
            assert_ne!(
                first["id"], second["id"],
                "retry must use a fresh request id"
            );
            let expected_result = serde_json::json!({ "contents": "resolved on retry" });
            write_success_response(
                &mut server.read_half_stdin,
                &second["id"].clone(),
                expected_result.clone(),
            )
            .await;

            let result = request_task.await.unwrap();
            assert_eq!(result.unwrap(), expected_result);
        }

        #[tokio::test]
        async fn test_retry_exhaustion_returns_original_content_modified_error() {
            let (client, mut server) = fake_lsp_client();

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);
            // Initial attempt plus SERVER_CANCELLED_MAX_RETRIES retries: every
            // attempt gets ContentModified, so retries must exhaust rather
            // than loop forever or swallow the error. -32801 shares the same
            // attempt budget as -32802 (FR-002), not an independent one.
            for _ in 0..=SERVER_CANCELLED_MAX_RETRIES {
                let request = read_framed_message(&mut reader).await;
                let id = request["id"].clone();
                write_retryable_error_response(
                    &mut server.read_half_stdin,
                    &id,
                    i32::from(LspErrorCodes::ContentModified),
                    "content modified",
                    true,
                )
                .await;
            }

            let result = request_task.await.unwrap();

            match result {
                Err(Error::LspServerError(JsonRpcError {
                    code,
                    message,
                    data,
                })) => {
                    // Assert the exact original error surfaces, not merely
                    // "some error with this code" -- a freshly constructed
                    // placeholder error would satisfy a code-only check.
                    assert_eq!(code, i32::from(LspErrorCodes::ContentModified));
                    assert_eq!(message, "content modified");
                    assert_eq!(data, Some(serde_json::json!({ "retriggerRequest": true })));
                }
                other => panic!("expected exhausted ContentModified error, got {other:?}"),
            }
        }

        #[tokio::test]
        async fn test_retrigger_false_returns_immediately_without_retry_for_content_modified() {
            let (client, mut server) = fake_lsp_client();

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let request = read_framed_message(&mut reader).await;
            let id = request["id"].clone();
            write_retryable_error_response(
                &mut server.read_half_stdin,
                &id,
                i32::from(LspErrorCodes::ContentModified),
                "content modified",
                false,
            )
            .await;

            // Same `should_retrigger` gate as -32802: a non-spec-compliant
            // server sending `retriggerRequest: false` on -32801 must still
            // be honored (FR-006 resolution), short-circuiting the loop well
            // under the first 500ms backoff.
            let result = tokio::time::timeout(Duration::from_millis(200), request_task)
                .await
                .unwrap()
                .unwrap();

            match result {
                Err(Error::LspServerError(JsonRpcError { code, .. })) => {
                    assert_eq!(code, i32::from(LspErrorCodes::ContentModified));
                }
                other => panic!("expected immediate ContentModified error, got {other:?}"),
            }

            let second_request =
                tokio::time::timeout(Duration::from_millis(200), read_framed_message(&mut reader))
                    .await;
            assert!(
                second_request.is_err(),
                "no retry should have been sent after retriggerRequest: false"
            );
        }

        #[tokio::test]
        async fn test_retry_succeeds_after_one_content_modified_response() {
            let (client, mut server) = fake_lsp_client();

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);

            // First attempt gets ContentModified and must retrigger.
            let first = read_framed_message(&mut reader).await;
            write_retryable_error_response(
                &mut server.read_half_stdin,
                &first["id"].clone(),
                i32::from(LspErrorCodes::ContentModified),
                "content modified",
                true,
            )
            .await;

            // Second attempt (after backoff) succeeds -- proves the loop
            // genuinely re-sends the request rather than just counting down.
            let second = read_framed_message(&mut reader).await;
            assert_ne!(
                first["id"], second["id"],
                "retry must use a fresh request id"
            );
            let expected_result = serde_json::json!({ "contents": "resolved on retry" });
            write_success_response(
                &mut server.read_half_stdin,
                &second["id"].clone(),
                expected_result.clone(),
            )
            .await;

            let result = request_task.await.unwrap();
            assert_eq!(result.unwrap(), expected_result);
        }

        /// #737: a frame carrying both `result` and `error` keeps the server's
        /// code, so a -32801 in it still triggers the retry.
        #[tokio::test]
        async fn test_retry_follows_the_error_of_a_frame_with_both_result_and_error() {
            let (client, mut server) = fake_lsp_client();

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let first = read_framed_message(&mut reader).await;
            let both = serde_json::json!({
                "jsonrpc": "2.0",
                "id": first["id"],
                "result": null,
                "error": {
                    "code": i32::from(LspErrorCodes::ContentModified),
                    "message": "content modified",
                    "data": { "retriggerRequest": true },
                },
            })
            .to_string();
            let frame = format!("Content-Length: {}\r\n\r\n{both}", both.len());
            server
                .read_half_stdin
                .write_all(frame.as_bytes())
                .await
                .unwrap();
            server.read_half_stdin.flush().await.unwrap();

            let second = read_framed_message(&mut reader).await;
            assert_ne!(first["id"], second["id"]);
            let expected = serde_json::json!({ "contents": "resolved on retry" });
            write_success_response(
                &mut server.read_half_stdin,
                &second["id"].clone(),
                expected.clone(),
            )
            .await;

            assert_eq!(request_task.await.unwrap().unwrap(), expected);
        }

        #[tokio::test]
        async fn test_content_modified_on_non_allowlisted_method_does_not_retry() {
            let (client, mut server) = fake_lsp_client();

            // `textDocument/rename` is deliberately excluded from
            // `CONTENT_MODIFIED_RETRY_METHODS` (its result is an edit the
            // caller applies at a position that may no longer be valid once
            // the document changed) -- a -32801 response for it must return
            // immediately even though `retriggerRequest: true` would pass
            // `should_retrigger`'s gate on its own.
            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/rename",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let request = read_framed_message(&mut reader).await;
            let id = request["id"].clone();
            write_retryable_error_response(
                &mut server.read_half_stdin,
                &id,
                i32::from(LspErrorCodes::ContentModified),
                "content modified",
                true,
            )
            .await;

            let result = tokio::time::timeout(Duration::from_millis(200), request_task)
                .await
                .unwrap()
                .unwrap();

            match result {
                Err(Error::LspServerError(JsonRpcError { code, .. })) => {
                    assert_eq!(code, i32::from(LspErrorCodes::ContentModified));
                }
                other => panic!("expected immediate ContentModified error, got {other:?}"),
            }

            let second_request =
                tokio::time::timeout(Duration::from_millis(200), read_framed_message(&mut reader))
                    .await;
            assert!(
                second_request.is_err(),
                "no retry should have been sent for a non-allowlisted method"
            );
        }

        /// #313: an oversized, server-controlled error message must be
        /// truncated before it reaches the MCP caller in
        /// `Error::LspServerError`, not just before it is logged. Routes
        /// through the real `message_loop_inner` (via `fake_lsp_client`)
        /// rather than constructing the error by hand, so it actually
        /// exercises the fix.
        #[tokio::test]
        async fn test_oversized_error_message_truncated_for_caller() {
            let (client, mut server) = fake_lsp_client();

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let request = read_framed_message(&mut reader).await;
            let id = request["id"].clone();
            let oversized_message = "x".repeat(MAX_ERROR_MESSAGE_CALLER_BYTES + 500);
            write_error_response(&mut server.read_half_stdin, &id, -32603, &oversized_message)
                .await;

            let result = request_task.await.unwrap();

            match result {
                Err(Error::LspServerError(JsonRpcError { code, message, .. })) => {
                    assert_eq!(code, -32603);
                    assert!(
                        message.len() < oversized_message.len(),
                        "caller-facing message must be truncated, got {} bytes",
                        message.len()
                    );
                    assert!(message.ends_with("... (truncated)"));
                }
                other => panic!("expected truncated LspServerError, got {other:?}"),
            }
        }

        /// #313 S2: a legitimate error message longer than the log-line cap
        /// (`crate::util::MAX_LOG_STRING_BYTES`, 200 bytes) but shorter than
        /// the caller-facing cap must reach the MCP caller intact -- the
        /// caller-facing budget must not silently collapse to the log
        /// budget.
        #[tokio::test]
        async fn test_error_message_between_log_and_caller_caps_reaches_caller_intact() {
            let (client, mut server) = fake_lsp_client();

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let request = read_framed_message(&mut reader).await;
            let id = request["id"].clone();
            let message = "x".repeat(crate::util::MAX_LOG_STRING_BYTES + 50);
            write_error_response(&mut server.read_half_stdin, &id, -32603, &message).await;

            let result = request_task.await.unwrap();

            match result {
                Err(Error::LspServerError(JsonRpcError {
                    message: returned, ..
                })) => {
                    assert_eq!(
                        returned, message,
                        "message under the caller cap must not be truncated"
                    );
                }
                other => panic!("expected untruncated LspServerError, got {other:?}"),
            }
        }

        /// #392: a `-32802`/`-32801` error that gets retried and then
        /// succeeds must not log at `error!` -- only a `warn!` "will retry"
        /// line -- so log-based monitoring does not false-positive on a
        /// transient error the retry loop silently recovers from.
        #[tokio::test]
        async fn test_retried_error_that_recovers_does_not_log_error_level() {
            use tracing_subscriber::layer::SubscriberExt as _;

            let (client, mut server) = fake_lsp_client();
            let captured = CapturedLogs::default();
            let subscriber = tracing_subscriber::registry().with(captured.clone());
            let guard = tracing::subscriber::set_default(subscriber);

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);

            let first = read_framed_message(&mut reader).await;
            write_retryable_error_response(
                &mut server.read_half_stdin,
                &first["id"].clone(),
                i32::from(LspErrorCodes::ServerCancelled),
                "server cancelled the request",
                true,
            )
            .await;

            let second = read_framed_message(&mut reader).await;
            write_success_response(
                &mut server.read_half_stdin,
                &second["id"].clone(),
                serde_json::json!({ "contents": "resolved on retry" }),
            )
            .await;

            let result = request_task.await.unwrap();
            assert!(result.is_ok(), "expected retry to recover, got {result:?}");

            drop(guard);
            let logs = captured.entries();
            assert!(
                !logs
                    .iter()
                    .any(|(level, _)| *level == tracing::Level::ERROR),
                "a retried-and-recovered error must not log at ERROR, got: {logs:?}"
            );
            assert!(
                logs.iter().any(
                    |(level, msg)| *level == tracing::Level::WARN && msg.contains("will retry")
                ),
                "expected a WARN 'will retry' log line, got: {logs:?}"
            );
        }

        /// #392: a `-32801` (`ContentModified`) error for a method outside
        /// `CONTENT_MODIFIED_RETRY_METHODS` is never retried, so it must
        /// still surface at `error!` on the very first attempt.
        #[tokio::test]
        async fn test_non_retryable_error_logs_error_level() {
            use tracing_subscriber::layer::SubscriberExt as _;

            let (client, mut server) = fake_lsp_client();
            let captured = CapturedLogs::default();
            let subscriber = tracing_subscriber::registry().with(captured.clone());
            let guard = tracing::subscriber::set_default(subscriber);

            let request_task = tokio::spawn(async move {
                client
                    .request::<_, Value>(
                        "textDocument/rename",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let request = read_framed_message(&mut reader).await;
            let id = request["id"].clone();
            write_retryable_error_response(
                &mut server.read_half_stdin,
                &id,
                i32::from(LspErrorCodes::ContentModified),
                "content modified",
                true,
            )
            .await;

            let result = request_task.await.unwrap();
            assert!(result.is_err(), "expected a non-retryable error");

            drop(guard);
            let logs = captured.entries();
            assert!(
                logs.iter()
                    .any(|(level, msg)| *level == tracing::Level::ERROR
                        && msg.contains("LSP error response")
                        && msg.contains("content modified")),
                "a non-retryable error must still surface an ERROR log sharing the \
                 'LSP error response' prefix, got: {logs:?}"
            );
        }
    }

    /// Regression coverage for #451 (`LspTransportReader::receive` moved off
    /// the `select!` and onto a dedicated reader task, see
    /// [`super::spawn_reader_task`]).
    mod reader_task_regression {
        use tokio::io::BufReader;

        use super::*;
        use crate::test_lsp::{
            fake_lsp_client, inert_transport, read_framed_message, write_response,
        };

        /// The reader task only ever sends `Err` through the channel before
        /// exiting (see `spawn_reader_task`) -- a `None` from `msg_rx.recv()`
        /// means the task disappeared some other way (e.g. panicked). This is
        /// the one branch in `message_loop_inner` that has no equivalent in
        /// the pre-#451 code, so it needs its own direct test rather than
        /// relying on the full `fake_lsp_client` harness to provoke it.
        #[tokio::test]
        async fn test_message_loop_inner_treats_reader_channel_close_as_server_terminated() {
            let (mut transport, _reader) = inert_transport();
            let (_command_tx, mut command_rx) = mpsc::channel::<ClientCommand>(1);
            let (msg_tx, mut msg_rx) = mpsc::channel::<Result<InboundMessage>>(1);
            let pending_requests = PendingRequests::default();

            drop(msg_tx);

            let result = LspClient::message_loop_inner(
                &mut transport,
                &mut msg_rx,
                &mut command_rx,
                &pending_requests,
                None,
                &Redactions::default(),
                None,
            )
            .await;

            assert_matches!(result, Err(Error::ServerTerminated), "got {result:?}");
        }

        /// As above, with a real pending request parked at the time the
        /// reader task disappears -- `message_loop_inner` itself never
        /// touches `pending_requests` on this branch, so a caller blocked on
        /// it only unblocks via `message_loop`'s post-loop
        /// `drain_and_fail_pending` (#458), invoked here the same way
        /// `message_loop` does after `message_loop_inner` returns. Driving
        /// this exact branch through the real `message_loop` would require
        /// the reader task to panic (the only other way `msg_rx.recv()`
        /// returns `None`), which isn't reproducible without a production
        /// seam -- see `test_message_loop_fails_pending_requests_on_transport_error_exit`
        /// for the sibling exit path exercised through the real function.
        #[tokio::test]
        async fn test_message_loop_inner_reader_gone_then_drain_fails_pending_request() {
            let (mut transport, _reader) = inert_transport();
            let (_command_tx, mut command_rx) = mpsc::channel::<ClientCommand>(1);
            let (msg_tx, mut msg_rx) = mpsc::channel::<Result<InboundMessage>>(1);
            let pending_requests = PendingRequests::default();

            let (response_tx, response_rx) = oneshot::channel::<Result<Value>>();
            pending_requests.register(RequestId::Number(1), response_tx);

            drop(msg_tx);

            let result = LspClient::message_loop_inner(
                &mut transport,
                &mut msg_rx,
                &mut command_rx,
                &pending_requests,
                None,
                &Redactions::default(),
                None,
            )
            .await;
            assert_matches!(result, Err(Error::ServerTerminated), "got {result:?}");

            LspClient::drain_and_fail_pending(&pending_requests, &StdMutex::default());

            let received = response_rx.await.unwrap();
            assert_matches!(received, Err(Error::ServerTerminated), "got {received:?}");
            assert!(pending_requests.no_waiting());
        }

        /// The reader task can run ahead of `select!` and have already queued
        /// a fully-decoded response in `msg_rx` by the time a concurrent
        /// `Shutdown` command is what `select!` happens to pick. Before the
        /// drain fix, that queued response was silently dropped instead of
        /// resolving its caller's pending request -- the caller would then
        /// block until its own `request_timeout_seconds` elapsed instead of
        /// failing fast or succeeding.
        #[tokio::test]
        async fn test_shutdown_drains_buffered_responses_instead_of_dropping_them() {
            let (mut transport, _reader) = inert_transport();
            let (command_tx, mut command_rx) = mpsc::channel::<ClientCommand>(1);
            let (msg_tx, mut msg_rx) = mpsc::channel::<Result<InboundMessage>>(1);
            let pending_requests = PendingRequests::default();

            let id = RequestId::Number(1);
            let (response_tx, response_rx) = oneshot::channel::<Result<Value>>();
            pending_requests.register(id.clone(), response_tx);

            msg_tx
                .send(Ok(InboundMessage::Response(JsonRpcResponse {
                    jsonrpc: JsonRpcVersion,
                    id: id.clone(),
                    outcome: JsonRpcOutcome::Result(serde_json::json!({ "ok": true })),
                })))
                .await
                .unwrap();
            command_tx.send(ClientCommand::Shutdown).await.unwrap();
            drop(command_tx);

            let result = LspClient::message_loop_inner(
                &mut transport,
                &mut msg_rx,
                &mut command_rx,
                &pending_requests,
                None,
                &Redactions::default(),
                None,
            )
            .await;

            assert!(result.is_ok(), "got {result:?}");
            // `Err` here means the sender was dropped without a reply -- i.e. the
            // buffered response was lost instead of resolving this request.
            let received = response_rx.await.unwrap();
            assert_eq!(received.unwrap(), serde_json::json!({ "ok": true }));
            assert!(
                pending_requests.no_waiting(),
                "the drained response must resolve its pending request entry"
            );
        }

        /// #458: before the fix, none of `message_loop`'s exit paths failed
        /// requests still parked in `pending_requests` -- each caller stayed
        /// blocked in its own `timeout(..)` until `request_timeout` elapsed.
        /// Drives the real `message_loop` (not `_inner`) over
        /// [`inert_transport`], whose reader side is dropped, so the reader
        /// task hits a transport receive error immediately and
        /// `message_loop` exits through that path.
        #[tokio::test]
        async fn test_message_loop_fails_pending_requests_on_transport_error_exit() {
            let (transport, reader) = inert_transport();
            let (_command_tx, command_rx) = mpsc::channel::<ClientCommand>(1);
            let pending_requests = PendingRequests::default();

            let (response_tx, response_rx) = oneshot::channel::<Result<Value>>();
            pending_requests.register(RequestId::Number(1), response_tx);

            let result = LspClient::message_loop(
                (transport, reader),
                command_rx,
                pending_requests.clone(),
                Arc::default(),
                None,
                Arc::default(),
                None,
            )
            .await;

            assert!(result.is_err(), "got {result:?}");
            let received = response_rx.await.unwrap();
            assert_matches!(received, Err(Error::ServerTerminated), "got {received:?}");
            assert!(pending_requests.no_waiting());
        }

        /// #458: unit-level check that composing `message_loop_inner`'s
        /// Shutdown `try_recv` drain (#451) with a subsequent
        /// `drain_and_fail_pending` call -- the same two pieces
        /// `message_loop` itself calls in that order -- does not re-fail a
        /// request already resolved by a buffered response, while still
        /// failing a truly unanswered one. This does not exercise
        /// `message_loop`'s own statement ordering (see
        /// `test_message_loop_end_to_end_resolves_answered_then_fails_unanswered_on_shutdown`
        /// for that, driven through the real function).
        #[tokio::test]
        async fn test_message_loop_shutdown_resolves_answered_and_fails_unanswered_pending() {
            let (mut transport, _reader) = inert_transport();
            let (command_tx, mut command_rx) = mpsc::channel::<ClientCommand>(1);
            let (msg_tx, mut msg_rx) = mpsc::channel::<Result<InboundMessage>>(1);
            let pending_requests = PendingRequests::default();

            let answered_id = RequestId::Number(1);
            let (answered_tx, answered_rx) = oneshot::channel::<Result<Value>>();
            let unanswered_id = RequestId::Number(2);
            let (unanswered_tx, unanswered_rx) = oneshot::channel::<Result<Value>>();
            pending_requests.register(answered_id.clone(), answered_tx);
            pending_requests.register(unanswered_id.clone(), unanswered_tx);

            msg_tx
                .send(Ok(InboundMessage::Response(JsonRpcResponse {
                    jsonrpc: JsonRpcVersion,
                    id: answered_id,
                    outcome: JsonRpcOutcome::Result(serde_json::json!({ "ok": true })),
                })))
                .await
                .unwrap();
            command_tx.send(ClientCommand::Shutdown).await.unwrap();
            drop(command_tx);

            let inner_result = LspClient::message_loop_inner(
                &mut transport,
                &mut msg_rx,
                &mut command_rx,
                &pending_requests,
                None,
                &Redactions::default(),
                None,
            )
            .await;
            assert!(inner_result.is_ok(), "got {inner_result:?}");

            // Mirrors the drain `message_loop` runs after `message_loop_inner`
            // returns.
            LspClient::drain_and_fail_pending(&pending_requests, &StdMutex::default());

            let answered = answered_rx.await.unwrap();
            assert_eq!(answered.unwrap(), serde_json::json!({ "ok": true }));

            let unanswered = unanswered_rx.await.unwrap();
            assert_matches!(
                unanswered,
                Err(Error::ServerTerminated),
                "got {unanswered:?}"
            );
            assert!(pending_requests.no_waiting());
        }

        /// #458 S2: end-to-end proof that `message_loop`'s post-loop drain
        /// runs *after* `message_loop_inner` returns, driven through the
        /// real `message_loop` (via `fake_lsp_client`), not a hand-recreated
        /// sequence. Deterministic without depending on `select!`
        /// nondeterminism: the answered request is awaited to completion via
        /// the loop's ordinary response path *before* `shutdown` is ever
        /// sent, so nothing here relies on which branch `select!` happens to
        /// pick when both are ready -- that race is unit-tested separately in
        /// `test_message_loop_shutdown_resolves_answered_and_fails_unanswered_pending`.
        #[tokio::test]
        async fn test_message_loop_end_to_end_resolves_answered_then_fails_unanswered_on_shutdown()
        {
            let (client, mut server) = fake_lsp_client();
            let mut reader = BufReader::new(&mut server.write_stdout);

            let answered_client = client.clone();
            let answered_task = tokio::spawn(async move {
                answered_client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            let request = read_framed_message(&mut reader).await;
            let id = request["id"].clone();
            write_response(
                &mut server.read_half_stdin,
                &id,
                serde_json::json!({ "ok": true }),
            )
            .await;

            let answered = answered_task.await.unwrap().unwrap();
            assert_eq!(answered, serde_json::json!({ "ok": true }));

            let unanswered_client = client.clone();
            let unanswered_task = tokio::spawn(async move {
                unanswered_client
                    .request::<_, Value>(
                        "textDocument/definition",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });

            // Reading the framed bytes back confirms the request was fully
            // sent, which only happens after it is already registered in
            // `pending_requests` -- so shutdown below cannot race its insert.
            let _unanswered_request = read_framed_message(&mut reader).await;

            client.shutdown().await.unwrap();

            let unanswered = tokio::time::timeout(Duration::from_millis(200), unanswered_task)
                .await
                .unwrap_or_else(|_| {
                    panic!(
                        "unanswered request must fail immediately on shutdown, not hang until its own timeout"
                    )
                })
                .unwrap();
            assert_matches!(
                unanswered,
                Err(Error::ServerTerminated),
                "got {unanswered:?}"
            );
        }

        /// Drives dense, concurrent request/response traffic through the real
        /// `message_loop`/`spawn_reader_task` pair (via `fake_lsp_client`) and
        /// answers deliberately out of arrival order, so a bug that matched
        /// responses positionally instead of by id -- the failure mode a
        /// mid-frame desync would eventually cause -- would surface as a
        /// mismatched payload rather than a hang.
        #[tokio::test]
        async fn test_dense_concurrent_requests_all_resolve_to_matching_responses() {
            const REQUEST_COUNT: usize = 20;
            let (client, mut server) = fake_lsp_client();

            // A manual push loop, not `.map(..).collect()`: `tokio::spawn`
            // must run eagerly for every `i` right here, before
            // `server_task` starts answering below -- a lazily-iterated
            // combinator would spawn (and thus send) each request only as
            // its `JoinHandle` is later awaited, one at a time, defeating
            // the "dense concurrent" setup this test needs.
            let mut request_tasks = Vec::with_capacity(REQUEST_COUNT);
            for i in 0..REQUEST_COUNT {
                let client = client.clone();
                request_tasks.push(tokio::spawn(async move {
                    client
                        .request::<_, Value>(
                            "textDocument/hover",
                            serde_json::json!({ "n": i }),
                            Duration::from_secs(30),
                        )
                        .await
                }));
            }

            let server_task = tokio::spawn(async move {
                let mut reader = BufReader::new(&mut server.write_stdout);
                let mut requests = Vec::with_capacity(REQUEST_COUNT);
                for _ in 0..REQUEST_COUNT {
                    requests.push(read_framed_message(&mut reader).await);
                }
                for request in requests.into_iter().rev() {
                    let id = request["id"].clone();
                    let n = request["params"]["n"].clone();
                    write_response(
                        &mut server.read_half_stdin,
                        &id,
                        serde_json::json!({ "echo": n }),
                    )
                    .await;
                }
            });

            server_task.await.unwrap();

            for (i, task) in request_tasks.into_iter().enumerate() {
                let value = task
                    .await
                    .unwrap()
                    .unwrap_or_else(|e| panic!("request {i} failed: {e:?}"));
                assert_eq!(
                    value["echo"],
                    serde_json::json!(i),
                    "response for request {i} carried the wrong payload -- id/response mismatch"
                );
            }
        }

        /// Shutting down a clone stops the loop for every clone but cannot
        /// abort it, and the owner can still shut down afterwards.
        #[tokio::test]
        async fn test_shutdown_on_clone_stops_shared_loop_then_owner_shutdown_succeeds() {
            let (client, _server) = fake_lsp_client();

            client.clone().shutdown().await.unwrap();

            let request = timeout(
                Duration::from_secs(2),
                client.request::<_, Value>("x/y", serde_json::json!({}), Duration::from_secs(30)),
            )
            .await
            .unwrap_or_else(|_| panic!("request on a stopped loop must fail fast"));
            assert_matches!(request, Err(Error::ServerTerminated), "got {request:?}");

            client.shutdown().await.unwrap();
        }

        /// A deadline that has already passed still aborts the loop, reports
        /// `ShutdownTimeout`, and leaves the client in the `Shutdown` state.
        #[tokio::test]
        async fn test_shutdown_until_expired_deadline_reports_timeout() {
            let (mut client, _server) = fake_lsp_client();
            let probe = client.clone();

            let result = client
                .shutdown_until(Instant::now() - Duration::from_millis(50))
                .await;

            assert_matches!(result, Err(Error::ShutdownTimeout), "got {result:?}");
            assert_matches!(probe.state().await, crate::lsp::ServerState::Shutdown);
        }

        /// A message loop wedged writing to a server that never reads must not
        /// hang `shutdown_until`: it returns `ShutdownTimeout` at the deadline
        /// and fails the requests still in flight.
        #[tokio::test]
        async fn test_shutdown_until_aborts_wedged_loop_and_fails_pending() {
            let (mut client, mut server) = fake_lsp_client();
            let mut reader = BufReader::new(&mut server.write_stdout);

            let in_flight_client = client.clone();
            let in_flight = tokio::spawn(async move {
                in_flight_client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });
            let _ = read_framed_message(&mut reader).await;

            // Larger than the mock pipe's capacity, so the loop blocks in `send`.
            client
                .notify("x/wedge", serde_json::json!({ "p": "a".repeat(1 << 20) }))
                .await
                .unwrap();

            let deadline = Instant::now() + Duration::from_millis(200);
            let result = timeout(Duration::from_secs(5), client.shutdown_until(deadline))
                .await
                .unwrap_or_else(|_| panic!("shutdown_until must honor its deadline"));
            assert_matches!(result, Err(Error::ShutdownTimeout), "got {result:?}");

            let in_flight = timeout(Duration::from_secs(1), in_flight)
                .await
                .unwrap_or_else(|_| panic!("in-flight request must be failed by the drain"))
                .unwrap();
            assert_matches!(in_flight, Err(Error::ServerTerminated), "got {in_flight:?}");
        }

        /// A client marked restarted fails its stragglers with the retryable
        /// `ServerRestarted`, both from the explicit drain and from the
        /// message loop's exit drain.
        #[tokio::test]
        async fn test_marked_restarted_client_fails_pending_with_server_restarted() {
            let (mut client, mut server) = fake_lsp_client();
            let mut reader = BufReader::new(&mut server.write_stdout);

            let in_flight_client = client.clone();
            let in_flight = tokio::spawn(async move {
                in_flight_client
                    .request::<_, Value>(
                        "textDocument/hover",
                        serde_json::json!({}),
                        Duration::from_secs(30),
                    )
                    .await
            });
            let _ = read_framed_message(&mut reader).await;

            client.mark_restarted(ServerId::from_static("rust"));
            client
                .shutdown_until(Instant::now() + Duration::from_millis(200))
                .await
                .ok();

            let in_flight = timeout(Duration::from_secs(1), in_flight)
                .await
                .unwrap_or_else(|_| panic!("in-flight request must be failed by the drain"))
                .unwrap();
            assert!(
                matches!(&in_flight, Err(Error::ServerRestarted { server_id }) if server_id.as_str() == "rust"),
                "got {in_flight:?}"
            );
        }

        /// #458: a request issued after the client has already shut down
        /// must fail immediately via `register_and_send_request`'s
        /// `command_tx.send(..)` check, not hang until its own
        /// `request_timeout`. Wrapped in a short outer `timeout` so a
        /// regression back to the slow path fails this test instead of
        /// merely making it slow.
        #[tokio::test]
        async fn test_request_after_shutdown_fails_fast_instead_of_hanging() {
            let (client, _server) = fake_lsp_client();
            let post_shutdown_client = client.clone();

            client.shutdown().await.unwrap();

            let result = tokio::time::timeout(
                Duration::from_millis(200),
                post_shutdown_client.request::<_, Value>(
                    "textDocument/hover",
                    serde_json::json!({}),
                    Duration::from_secs(30),
                ),
            )
            .await
            .unwrap_or_else(|_| {
                panic!(
                    "request after shutdown must fail immediately, not hang until its own timeout"
                )
            });

            assert_matches!(result, Err(Error::ServerTerminated), "got {result:?}");
        }
    }
}