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
//! LSP server lifecycle management.
//!
//! This module handles the complete lifecycle of an LSP server:
//! 1. Spawn server process
//! 2. Initialize → initialized handshake
//! 3. Capability negotiation
//! 4. Active request handling
//! 5. Graceful shutdown sequence

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

use lsp_types::{
    ClientCapabilities, ClientInfo, DidChangeConfigurationNotification,
    DidChangeConfigurationParams, ExitNotification, GeneralClientCapabilities, InitializeParams,
    InitializeRequest, InitializeResult, InitializedNotification, InitializedParams,
    PositionEncodingKind, Request, ServerCapabilities, ShutdownRequest, StaleRequestSupportOptions,
    SymbolKind, WorkspaceFolder,
};
use tokio::process::Command;
use tokio::sync::mpsc;
use tokio::time::{Duration, Instant, timeout, timeout_at};
use tracing::{debug, info, warn};

use crate::bridge::{WorkspaceRoots, try_path_to_uri};
use crate::config::{LspServerConfig, LspSettings, PositionEncodings, ServerCommand};
use crate::error::{
    BackgroundTask, Error, InitFailureHint, InitPhase, Result, ServerSpawnFailure, StartupFailure,
    StdioStream, UntrustedRefusal,
};
use crate::lsp::client::{LspClient, SHUTDOWN_TIMEOUT};
#[cfg(unix)]
use crate::lsp::process::Binding;
use crate::lsp::process::{MarkOutcome, ServerProcess};
use crate::lsp::stderr::{EofWait, StderrCapture};
use crate::lsp::transport::LspTransport;
use crate::lsp::types::LspNotification;
use crate::lsp::vetting::UntrustedVetting;
use crate::lsp::{
    CONTENT_MODIFIED_RETRY_METHODS, ManagedEnvVar, NotificationInbox, NotificationSink, ParentEnv,
    process_env, tsserver_pin,
};
use crate::redaction::Redactions;

/// Environment variables passed through to a spawned LSP server even though
/// its environment is otherwise cleared.
///
/// `PATH` lets the server resolve its own toolchain (e.g. rustup shims, venv
/// binaries); `HOME`/`USERPROFILE` and `TMPDIR`/`TEMP`/`TMP` let it find user
/// config/cache and scratch directories.
///
/// This list is not exhaustive: session-specific values that cannot be
/// hardcoded into a static [`LspServerConfig::env`] table (e.g.
/// `SSH_AUTH_SOCK`, which changes every login session) have no way through
/// today. See [`LspServerConfig::env`] for the config-level override/addition
/// mechanism this list feeds into.
const ENV_PASSTHROUGH: &[&str] = &[
    ManagedEnvVar::Path.name(),
    ManagedEnvVar::Home.name(),
    ManagedEnvVar::UserProfile.name(),
    "TMPDIR",
    "TEMP",
    "TMP",
];

/// Upper bound [`LspServer::shutdown`] waits for the child process to exit on
/// its own after sending the LSP `exit` notification, before falling back to
/// killing its process tree. Only the leader is awaited here.
const CHILD_EXIT_GRACE: Duration = Duration::from_secs(3);

/// Least time the final process-tree sweep may take even when the shutdown
/// deadline is already spent, so a whole shutdown stays within
/// `SHUTDOWN_TIMEOUT` plus this.
const MIN_SWEEP_BUDGET: Duration = Duration::from_secs(3);

/// How long [`LspServer::terminate`] lets the leader process exit on its own
/// after the `shutdown` handshake, before the process tree is killed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitGrace {
    /// Up to the rest of the handshake budget, at most [`CHILD_EXIT_GRACE`]
    /// (normal shutdown).
    WithinBudget,
    /// A server that answered `shutdown` may take this long to exit, since a
    /// healthy server can be slow to flush; one that did not answer is killed
    /// at once.
    IfAnswered(Duration),
}

/// Whether the LSP `exit` notification reached the server on shutdown.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExitNotice {
    /// The `shutdown` handshake completed and `exit` was sent.
    Sent,
    /// The handshake failed or was cut short, or `exit` was withheld because
    /// escaping descendants could not be marked.
    NotSent,
}

impl ExitNotice {
    /// Judged from the handshake's own result, before it is merged with the
    /// message loop's stop.
    const fn of(handshake: &Result<MarkOutcome>) -> Self {
        match handshake {
            Ok(MarkOutcome::Confirmed) => Self::Sent,
            _ => Self::NotSent,
        }
    }
}

/// How long the leader process is given to exit on its own after the
/// handshake, with `remaining` of the shutdown budget left. `answered` is the
/// merged result of the handshake and the message loop's stop.
fn child_exit_wait(
    grace: ExitGrace,
    mark: MarkOutcome,
    answered: &Result<()>,
    remaining: Duration,
) -> Duration {
    match grace {
        _ if mark != MarkOutcome::Confirmed => Duration::ZERO,
        ExitGrace::WithinBudget => remaining.min(CHILD_EXIT_GRACE),
        ExitGrace::IfAnswered(grace) if answered.is_ok() => grace,
        ExitGrace::IfAnswered(_) => Duration::ZERO,
    }
}

/// How long a failed `initialize` waits for the child to be reaped before
/// concluding it is still running and keeping the original error.
const EARLY_EXIT_PROBE: Duration = Duration::from_millis(500);

/// Capacity of the diagnostics/log/showMessage notification channel (P3).
///
/// Raised from the pre-#422 value of 64: P1 makes mcpls advertise
/// `window.workDoneProgress`, so a server may now attach progress reporting
/// to ordinary request capabilities too, raising overall notification
/// volume generally even though progress itself moved to its own
/// [`LIFECYCLE_CHANNEL_CAPACITY`] lane.
const NOTIFICATION_CHANNEL_CAPACITY: usize = 256;

/// Capacity of the lifecycle channel (P3): `$/progress` `begin`/`end`
/// frames plus `Other` (rust-analyzer's `experimental/serverStatus`).
///
/// O(phases), not O(reports): a `$/progress` `report` frame is filtered out
/// before it ever reaches this channel (see
/// `lsp::client::LspClient::message_loop_inner`), so this only needs to hold
/// a handful of `begin`/`end` transitions even for a server with several
/// concurrent operations, not a `report`-per-package stream like gopls can
/// produce.
const LIFECYCLE_CHANNEL_CAPACITY: usize = 128;

/// Every symbol kind defined by LSP 3.17 and understood by mcpls, with the
/// lowercase name a `workspace/symbol` `kind_filter` accepts for it.
///
/// Single source of truth for both the `initialize` request's `value_set`
/// and the `kind_filter` validation in [`crate::bridge::translator::symbols`].
pub const SUPPORTED_SYMBOL_KINDS: [(SymbolKind, &str); 26] = [
    (SymbolKind::File, "file"),
    (SymbolKind::Module, "module"),
    (SymbolKind::Namespace, "namespace"),
    (SymbolKind::Package, "package"),
    (SymbolKind::Class, "class"),
    (SymbolKind::Method, "method"),
    (SymbolKind::Property, "property"),
    (SymbolKind::Field, "field"),
    (SymbolKind::Constructor, "constructor"),
    (SymbolKind::Enum, "enum"),
    (SymbolKind::Interface, "interface"),
    (SymbolKind::Function, "function"),
    (SymbolKind::Variable, "variable"),
    (SymbolKind::Constant, "constant"),
    (SymbolKind::String, "string"),
    (SymbolKind::Number, "number"),
    (SymbolKind::Boolean, "boolean"),
    (SymbolKind::Array, "array"),
    (SymbolKind::Object, "object"),
    (SymbolKind::Key, "key"),
    (SymbolKind::Null, "null"),
    (SymbolKind::EnumMember, "enummember"),
    (SymbolKind::Struct, "struct"),
    (SymbolKind::Event, "event"),
    (SymbolKind::Operator, "operator"),
    (SymbolKind::TypeParameter, "typeparameter"),
];

/// The kinds of [`SUPPORTED_SYMBOL_KINDS`] as the `initialize` request lists them.
fn advertised_symbol_kinds() -> Vec<SymbolKind> {
    SUPPORTED_SYMBOL_KINDS
        .iter()
        .map(|&(kind, _)| kind)
        .collect()
}

/// Windows-only additions to [`ENV_PASSTHROUGH`].
///
/// `SystemRoot`/`SystemDrive`/`windir` are required by the Windows process
/// loader itself; `APPDATA`/`LOCALAPPDATA` are read by the Node-based default
/// servers (pyright, typescript-language-server) for global config and
/// cache; the rest are conventionally expected by Windows child processes.
/// `NoDefaultCurrentDirectoryInExePath` passes through so a user who set it to
/// keep the current directory out of executable lookups is not overridden by
/// the environment clearing.
#[cfg(windows)]
const ENV_PASSTHROUGH_WINDOWS: &[&str] = &[
    ManagedEnvVar::NoDefaultCurrentDirectoryInExePath.name(),
    "SystemRoot",
    "SystemDrive",
    "windir",
    "APPDATA",
    "LOCALAPPDATA",
    "ProgramData",
    "ProgramFiles",
    "COMSPEC",
    "PATHEXT",
    "NUMBER_OF_PROCESSORS",
    "USERNAME",
];

/// State of an LSP server connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServerState {
    /// Server has not been initialized.
    Uninitialized,
    /// Server is currently initializing.
    Initializing,
    /// Server is ready to handle requests.
    Ready,
    /// Server is shutting down.
    ShuttingDown,
    /// Server has been shut down.
    Shutdown,
}

impl ServerState {
    /// Check if the server is ready to handle requests.
    #[must_use]
    pub const fn is_ready(&self) -> bool {
        matches!(self, Self::Ready)
    }
}

/// Where a spawned server's working directory is.
///
/// A closed type so a spawn never silently depends on the working directory
/// mcpls itself happens to have.
///
/// # Examples
///
/// ```
/// use std::path::PathBuf;
///
/// use mcpls_core::lsp::ChildWorkingDir;
///
/// assert_eq!(ChildWorkingDir::default(), ChildWorkingDir::Inherit);
/// let fixed = ChildWorkingDir::Fixed(PathBuf::from("project"));
/// assert_ne!(fixed, ChildWorkingDir::Inherit);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ChildWorkingDir {
    /// The server inherits mcpls's working directory.
    #[default]
    Inherit,
    /// The server starts in this directory.
    Fixed(PathBuf),
}

/// Whether a server belongs to an untrusted workspace, and if so what it was
/// vetted against.
#[derive(Debug, Clone)]
pub enum SpawnTrust {
    /// The server runs as configured.
    Trusted,
    /// The boundary the argument backstop and the tsserver pin are evaluated
    /// against again before every spawn, and the command as configured.
    Untrusted(UntrustedVetting),
}

impl SpawnTrust {
    /// What an untrusted server is vetted against; `None` for a trusted one.
    pub const fn vetting(&self) -> Option<&UntrustedVetting> {
        match self {
            Self::Trusted => None,
            Self::Untrusted(vetting) => Some(vetting),
        }
    }
}

/// A [`ServerInitConfig`] that [`ServerInitConfig::for_respawn`] vetted, so a
/// respawn spawns exactly what was checked. The spawn still re-runs the
/// argument backstop on purpose (#736): a workspace file can become
/// executable between vetting and spawn.
#[derive(Debug, Clone)]
pub struct VettedInitConfig(ServerInitConfig);

impl VettedInitConfig {
    /// The vetted config.
    pub(crate) fn into_inner(self) -> ServerInitConfig {
        self.0
    }
}

impl std::ops::Deref for VettedInitConfig {
    type Target = ServerInitConfig;

    fn deref(&self) -> &ServerInitConfig {
        &self.0
    }
}

/// Configuration for LSP server initialization.
///
/// Built by [`Self::new`]; the fields are private so the effective
/// `initialization_options` live in exactly one place, the
/// [`LspServerConfig`] this was built from.
#[derive(Debug, Clone)]
pub struct ServerInitConfig {
    server_config: LspServerConfig,
    workspace_roots: WorkspaceRoots,
    position_encodings: PositionEncodings,
    redactions: Arc<Redactions>,
    child_working_dir: ChildWorkingDir,
    /// The tsserver pin mcpls chose, as opposed to one the user configured, so
    /// a respawn can tell a pin that went stale (the install moved) from the
    /// user's own `tsserver.path`, which is never second-guessed.
    auto_pin: Option<PathBuf>,
    trust: SpawnTrust,
}

impl ServerInitConfig {
    /// Builds the config a server is spawned from.
    ///
    /// `server_config` must already carry the *effective* initialization
    /// options (for example with the tsserver pin applied): they are sent as
    /// they are and are the only copy.
    ///
    /// `position_encodings` is the preference order from
    /// [`crate::config::WorkspaceConfig::position_encodings`], sent as
    /// `capabilities.general.positionEncodings` during [`LspServer::spawn`]'s
    /// `initialize` handshake. `redactions` holds the secrets of every
    /// configured server, hidden in this server's output;
    /// [`LspServer::spawn`] adds the secrets of this server's own
    /// configuration and current environment, so an empty set still hides
    /// them, and `serve` fills it with the secrets of every configured server
    /// so a server that echoes another's secret has it hidden too.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use mcpls_core::bridge::WorkspaceRoots;
    /// use mcpls_core::config::{LspServerConfig, PositionEncodings};
    /// use mcpls_core::lsp::{ChildWorkingDir, ServerInitConfig};
    ///
    /// let config = ServerInitConfig::new(
    ///     LspServerConfig::rust_analyzer(),
    ///     WorkspaceRoots::default(),
    ///     PositionEncodings::DEFAULT,
    ///     Arc::default(),
    /// );
    /// assert_eq!(config.child_working_dir(), &ChildWorkingDir::Inherit);
    /// ```
    #[must_use]
    pub const fn new(
        server_config: LspServerConfig,
        workspace_roots: WorkspaceRoots,
        position_encodings: PositionEncodings,
        redactions: Arc<Redactions>,
    ) -> Self {
        Self {
            server_config,
            workspace_roots,
            position_encodings,
            redactions,
            child_working_dir: ChildWorkingDir::Inherit,
            auto_pin: None,
            trust: SpawnTrust::Trusted,
        }
    }

    /// This config with the given trust; an untrusted server's arguments must
    /// keep clear of the boundary its vetting holds (see [`Self::vet_arguments`]).
    #[must_use]
    pub(crate) fn with_trust(mut self, trust: SpawnTrust) -> Self {
        self.trust = trust;
        self
    }

    /// Re-runs the untrusted argument backstop on the arguments the server
    /// would be spawned with; trusted configs are never vetted.
    ///
    /// A workspace file can become executable after the plan admitted the
    /// server, so every spawn (startup, respawn, restart) checks again.
    /// Walks the file system, so async callers use
    /// [`Self::vet_arguments_off_runtime`].
    ///
    /// # Errors
    ///
    /// [`Error::ServerFailedToStart`] with the untrusted-mode refusal when an
    /// argument now names an executable inside the workspace.
    pub(crate) fn vet_arguments(&self) -> Result<()> {
        let Some(vetting) = self.trust.vetting() else {
            return Ok(());
        };
        vetting
            .boundary()
            .refuse_arguments(
                &self.server_config.args,
                &self.child_working_dir,
                self.server_config.env.host(),
            )
            .map_err(|refusal| self.refusal(refusal))
    }

    /// [`Self::vet_arguments`] on the blocking pool, skipped for a trusted
    /// config.
    pub(crate) async fn vet_arguments_off_runtime(&self) -> Result<()> {
        if self.trust.vetting().is_none() {
            return Ok(());
        }
        self.on_planning_pool(Self::vet_arguments).await
    }

    /// Runs the blocking `plan` on a clone of this config on the blocking pool.
    async fn on_planning_pool<T: Send + 'static>(
        &self,
        plan: impl FnOnce(&Self) -> Result<T> + Send + 'static,
    ) -> Result<T> {
        let config = self.clone();
        crate::on_blocking_pool(move || plan(&config))
            .await
            .map_err(|source| Error::TaskFailed {
                task: crate::error::BackgroundTask::ServerPlanning,
                source,
            })?
    }

    /// This config with `tsserver` recorded as the pin mcpls chose.
    #[must_use]
    pub(crate) fn with_auto_pin(mut self, tsserver: PathBuf) -> Self {
        self.auto_pin = Some(tsserver);
        self
    }

    /// This config with the child started in `dir`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use std::sync::Arc;
    ///
    /// use mcpls_core::bridge::WorkspaceRoots;
    /// use mcpls_core::config::{LspServerConfig, PositionEncodings};
    /// use mcpls_core::lsp::{ChildWorkingDir, ServerInitConfig};
    ///
    /// let dir = ChildWorkingDir::Fixed(PathBuf::from("project"));
    /// let config = ServerInitConfig::new(
    ///     LspServerConfig::rust_analyzer(),
    ///     WorkspaceRoots::default(),
    ///     PositionEncodings::DEFAULT,
    ///     Arc::default(),
    /// )
    /// .with_child_working_dir(dir.clone());
    /// assert_eq!(config.child_working_dir(), &dir);
    /// ```
    #[must_use]
    pub fn with_child_working_dir(mut self, dir: ChildWorkingDir) -> Self {
        self.child_working_dir = dir;
        self
    }

    /// The server's configuration, carrying the effective initialization options.
    #[must_use]
    pub const fn server_config(&self) -> &LspServerConfig {
        &self.server_config
    }

    /// The workspace roots sent as `workspaceFolders`.
    #[must_use]
    pub const fn workspace_roots(&self) -> &WorkspaceRoots {
        &self.workspace_roots
    }

    /// The position encoding preference order offered to the server.
    #[must_use]
    pub const fn position_encodings(&self) -> &PositionEncodings {
        &self.position_encodings
    }

    /// The secrets hidden in this server's output.
    #[must_use]
    pub const fn redactions(&self) -> &Arc<Redactions> {
        &self.redactions
    }

    /// Where the child process starts.
    #[must_use]
    pub const fn child_working_dir(&self) -> &ChildWorkingDir {
        &self.child_working_dir
    }

    /// Mutable access to the server config, for tests that adjust a fixture.
    #[cfg(test)]
    pub(crate) const fn server_config_mut(&mut self) -> &mut LspServerConfig {
        &mut self.server_config
    }

    /// The tsserver this config pins through `initialization_options.tsserver.path`.
    #[must_use]
    pub fn pinned_tsserver(&self) -> Option<PathBuf> {
        tsserver_pin::configured_tsserver_path(self.server_config.initialization_options.as_ref())
    }

    /// The config a respawn of this server spawns from.
    ///
    /// Called by a restart before it stops the running server and by every
    /// other respawn right before it spawns; the filesystem work runs on the
    /// blocking pool and only for an auto-pinned or untrusted server. The
    /// result is what the respawn spawns; the spawn re-runs the argument
    /// backstop on purpose (#736).
    ///
    /// In untrusted mode the argument backstop runs again
    /// ([`Self::vet_arguments`]). A tsserver pin mcpls chose whose canonical
    /// path changed (the install was upgraded, moved or retargeted through a
    /// symlink) is resolved again and, in untrusted mode, checked against the
    /// boundary it was first vetted against. A pin the user configured is kept
    /// as is.
    ///
    /// # Errors
    ///
    /// [`Error::ServerFailedToStart`] with an untrusted-mode refusal when the
    /// tsserver now resolves inside the workspace, the server is now
    /// launched in a way no tsserver can be pinned for (the same two checks
    /// startup makes), or an argument now names an executable inside the
    /// workspace.
    pub(crate) async fn for_respawn(&self) -> Result<VettedInitConfig> {
        if self.auto_pin.is_none() && self.trust.vetting().is_none() {
            return Ok(VettedInitConfig(self.clone()));
        }
        self.on_planning_pool(Self::plan_respawn).await
    }

    /// The blocking half of [`Self::for_respawn`]: canonicalizes the pin and
    /// re-plans the tsserver, so it runs on the blocking pool.
    pub(crate) fn plan_respawn(&self) -> Result<VettedInitConfig> {
        self.vet_arguments()?;
        let pin_is_current = self
            .auto_pin
            .as_ref()
            .is_none_or(|pin| dunce::canonicalize(pin).ok().as_ref() == Some(pin));
        if pin_is_current {
            return Ok(VettedInitConfig(self.clone()));
        }
        let mut unpinned = self.server_config.clone();
        unpinned.initialization_options = None;
        let plan = tsserver_pin::plan_typescript(unpinned, process_env);
        if let Some(vetting) = self.trust.vetting() {
            plan.vet_untrusted(vetting)
                .map_err(|refusal| self.refusal(refusal))?;
        }
        let (server_config, auto_pin) = plan.apply(&self.workspace_roots);
        Ok(VettedInitConfig(Self {
            server_config,
            auto_pin,
            ..self.clone()
        }))
    }

    fn refusal(&self, refusal: UntrustedRefusal) -> Error {
        Error::ServerFailedToStart(Box::new(ServerSpawnFailure {
            server_id: self.server_config.id(),
            language_id: self.server_config.language_id.clone(),
            command: self.server_config.command.server_command().clone(),
            reason: StartupFailure::RefusedUntrustedWorkspace(refusal),
        }))
    }
}

/// The terminal outcome of starting one configured server.
///
/// A closed type so a settled server is either running or has a recorded
/// failure, never both and never neither.
#[derive(Debug)]
pub enum ServerStartOutcome {
    /// The server initialized and is ready to register.
    Started(Box<SpawnedServer>),
    /// The server failed to start.
    Failed(ServerSpawnFailure),
}

/// The two inbound notification lanes of a spawned server.
///
/// Handed out once, together with the server, by [`LspServer::spawn`]: a pump
/// owns them from then on, so a lane cannot be taken twice or left behind.
#[derive(Debug)]
pub struct ServerLanes {
    /// Diagnostics mailbox plus the log and `showMessage` frames
    /// ([`crate::lsp::ServerMessage`]). `textDocument/publishDiagnostics` is coalesced per
    /// file and a publish the mailbox cannot hold is reported as lost instead
    /// of being dropped (see [`crate::lsp::PublishReader`]).
    pub notifications: NotificationInbox,
    /// The lifecycle lane: `$/progress` `begin`/`end` frames and unrecognized
    /// notifications (which carry e.g. rust-analyzer's
    /// `experimental/serverStatus`), kept separate from the notification lane
    /// so a high-volume diagnostics publisher can never starve out a
    /// workspace-readiness signal, or vice versa.
    pub lifecycle: mpsc::Receiver<LspNotification>,
}

/// A freshly initialized server together with its inbound lanes.
#[derive(Debug)]
pub struct SpawnedServer {
    /// The running server.
    pub server: LspServer,
    /// Its notification lanes, to be drained by a pump.
    pub lanes: ServerLanes,
}

/// Managed LSP server instance with capabilities and encoding.
pub struct LspServer {
    client: LspClient,
    capabilities: ServerCapabilities,
    position_encoding: PositionEncodingKind,
    /// Child process handle. Kept alive for process lifetime management and
    /// queried by [`Self::has_exited`] to detect a crash. [`LspServer::shutdown`]
    /// waits for it to exit after sending `exit`; otherwise, or if that wait
    /// times out, dropping it terminates the process via SIGKILL
    /// (`kill_on_drop`). The process is also bound to the mcpls process
    /// lifetime (see [`ServerProcess`]), so it dies with mcpls on any exit.
    ///
    /// `None` only for test fixtures that never spawn a real server process
    /// (see `crate::test_lsp`, `Self::new_for_test_with_encoding`) --
    /// [`Self::spawn`] always populates this with `Some`.
    child: Option<ServerProcess>,
    /// Config this server was spawned from; the single source of its routing
    /// identity, respawn config and indexing policy.
    init_config: ServerInitConfig,
}

impl std::fmt::Debug for LspServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LspServer")
            .field("client", &self.client)
            .field("capabilities", &self.capabilities)
            .field("position_encoding", &self.position_encoding)
            .field("child", &"<process>")
            .field("id", &self.init_config.server_config.id())
            .finish()
    }
}

/// Resolve one environment variable as the spawned server would see it:
/// the server config's `env` override wins, otherwise the parent value.
///
/// `parent_env` is injected so callers and tests need not touch the real
/// process environment.
pub fn child_env_var(
    config: &LspServerConfig,
    key: &str,
    parent_env: impl ParentEnv,
) -> Option<std::ffi::OsString> {
    config
        .env
        .get(key)
        .map(std::ffi::OsString::from)
        .or_else(|| parent_env(key))
}

impl LspServer {
    /// The config this server was spawned from.
    pub(crate) const fn init_config(&self) -> &ServerInitConfig {
        &self.init_config
    }

    /// Replace the config a respawn of this server would use.
    #[cfg(test)]
    pub(crate) fn set_init_config(&mut self, config: ServerInitConfig) {
        self.init_config = config;
    }

    /// Spawn and initialize LSP server, returning it with its notification
    /// lanes.
    ///
    /// This performs the complete initialization sequence:
    /// 1. Spawns the LSP server as a child process
    /// 2. Sends initialize request with client capabilities
    /// 3. Receives server capabilities from initialize response
    /// 4. Sends initialized notification
    /// 5. Sends `workspace/didChangeConfiguration` with the configured
    ///    settings (null when unset), which servers that wait for a
    ///    configuration push (pyright) need before they answer requests
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Server process fails to spawn
    /// - Initialize request fails or times out
    /// - Server returns error during initialization
    /// - The `initialized` or `workspace/didChangeConfiguration` notification
    ///   cannot be written ([`Error::LspInitFailed`])
    pub async fn spawn(config: ServerInitConfig) -> Result<SpawnedServer> {
        // Repeated on purpose: a workspace file can become executable between plan and spawn (#736).
        config.vet_arguments_off_runtime().await?;
        let own = Redactions::for_server(config.server_config(), current_environment());
        let redactions = Arc::new(Redactions::union([config.redactions().as_ref(), &own]));
        Self::log_spawn(config.server_config(), &redactions);

        let command = Self::build_command(
            config.server_config(),
            config.child_working_dir(),
            process_env,
        );

        // Log allowlist presence and an override count only — never the
        // configured keys themselves, since `config.server_config.env` may
        // hold secret-bearing names (e.g. `AWS_SECRET_ACCESS_KEY`) whose
        // mere presence in a debug log would be its own disclosure.
        let passthrough_present = {
            let base = ENV_PASSTHROUGH
                .iter()
                .filter(|key| std::env::var_os(key).is_some())
                .count();
            #[cfg(windows)]
            let windows = ENV_PASSTHROUGH_WINDOWS
                .iter()
                .filter(|key| std::env::var_os(key).is_some())
                .count();
            #[cfg(not(windows))]
            let windows = 0;
            base.saturating_add(windows)
        };
        debug!(
            "Effective LSP server env: {passthrough_present} allowlisted key(s) present, \
             {} configured override(s) applied",
            config.server_config.env.len()
        );

        let mut child = ServerProcess::spawn(command)
            .map_err(|e| spawn_error(config.server_config.command.server_command().clone(), e))?;

        let stdin = child
            .take_stdin()
            .ok_or(Error::StdioCapture(StdioStream::Stdin))?;
        let stdout = child
            .take_stdout()
            .ok_or(Error::StdioCapture(StdioStream::Stdout))?;

        let stderr = child
            .take_stderr()
            .ok_or(Error::StdioCapture(StdioStream::Stderr))?;
        let stderr_capture = StderrCapture::start(stderr);

        let transport = LspTransport::with_redactions(stdin, stdout, Arc::clone(&redactions));
        let (notification_tx, notification_rx) = mpsc::channel(NOTIFICATION_CHANNEL_CAPACITY);
        let (notification_sink, publish_rx) = NotificationSink::new(notification_tx);
        let (lifecycle_tx, lifecycle_rx) = mpsc::channel(LIFECYCLE_CHANNEL_CAPACITY);
        let client = LspClient::from_transport_with_notifications(
            config.server_config.clone(),
            transport,
            notification_sink,
            lifecycle_tx,
            Arc::clone(&redactions),
        );
        #[cfg(unix)]
        let process_id = initialize_process_id(child.binding());
        #[cfg(windows)]
        let process_id = Some(mcpls_process_id());
        let (capabilities, position_encoding) =
            match Self::initialize_as(&client, &config, process_id).await {
                Ok(negotiated) => negotiated,
                Err(init_error) if is_connection_loss(&init_error) => {
                    return Err(Self::connection_loss_error(
                        &config,
                        &mut child,
                        stderr_capture,
                        &redactions,
                        init_error,
                    )
                    .await);
                }
                Err(Error::LspInitFailed { phase, cause, .. }) => {
                    // The server may be about to exit after printing its reason,
                    // so wait the (bounded) end-of-file grace whether or not it
                    // has exited yet.
                    let stderr = stderr_capture.finish(EofWait::Grace, &redactions).await;
                    let hint = Self::init_failure_hint(&config).await;
                    return Err(Error::LspInitFailed {
                        phase,
                        cause: Box::new(redactions.sanitize_error(*cause)),
                        hint,
                        stderr,
                    });
                }
                Err(init_error) => return Err(redactions.sanitize_error(init_error)),
            };

        info!("LSP server initialized successfully");

        Ok(SpawnedServer {
            server: Self {
                client,
                capabilities,
                position_encoding,
                child: Some(child),
                init_config: config,
            },
            lanes: ServerLanes {
                notifications: NotificationInbox::new(notification_rx, publish_rx),
                lifecycle: lifecycle_rx,
            },
        })
    }

    /// The error for an `initialize` that ended in a lost connection: the
    /// server exited (with its exit status) or the pipe closed first.
    async fn connection_loss_error(
        config: &ServerInitConfig,
        child: &mut ServerProcess,
        stderr_capture: StderrCapture,
        redactions: &Redactions,
        init_error: Error,
    ) -> Error {
        let exit_status = early_exit_status(child).await;
        let eof_wait = if exit_status.is_some() {
            EofWait::Grace
        } else {
            EofWait::Skip
        };
        let stderr = stderr_capture.finish(eof_wait, redactions).await;
        let hint = Self::init_failure_hint(config).await;
        match exit_status {
            Some(status) => Error::ServerExitedDuringInit {
                command: config.server_config.command.server_command().clone(),
                exit_code: status.code(),
                hint,
                stderr,
            },
            None => Error::LspInitFailed {
                phase: InitPhase::Initialize,
                cause: Box::new(redactions.sanitize_error(init_error)),
                hint,
                stderr,
            },
        }
    }

    /// The guidance for a failed `initialize` of `config`, if its cause is known.
    ///
    /// Runs on the failure path only. It walks `PATH` and reads package
    /// manifests, so it runs on the blocking pool; the hint is dropped when the
    /// pool is shutting down.
    async fn init_failure_hint(config: &ServerInitConfig) -> Option<InitFailureHint> {
        let config = config.clone();
        let hint = crate::on_blocking_pool(move || {
            tsserver_pin::init_failure_hint(
                config.server_config(),
                config.workspace_roots(),
                process_env,
            )
        })
        .await;
        hint.unwrap_or_else(|error| {
            debug!("Dropped the init failure hint: {error}");
            None
        })
    }

    /// Logs the command and argument count at `info`, and the argument values
    /// (redacted) only at `debug`.
    fn log_spawn(server_config: &LspServerConfig, redactions: &Redactions) {
        info!(
            "Spawning LSP server: {} ({} arg(s))",
            server_config.command,
            server_config.args.len()
        );
        debug!(
            "LSP server args: {:?}",
            server_config
                .args
                .iter()
                .map(|arg| redactions.apply(arg))
                .collect::<Vec<_>>()
        );
    }

    /// Build the child `Command` for a spawned LSP server, without spawning it.
    ///
    /// The child's environment is cleared, then [`ENV_PASSTHROUGH`] (plus
    /// [`ENV_PASSTHROUGH_WINDOWS`] under `cfg(windows)`) is copied in from
    /// `parent_env` for whichever of those keys it returns `Some` for, then
    /// `config.env` is applied last so it can override any passthrough
    /// value. `parent_env` is injected (production passes
    /// `std::env::var_os`) so tests can supply a fixed environment without
    /// racing on real process-global state.
    fn build_command(
        config: &LspServerConfig,
        working_dir: &ChildWorkingDir,
        parent_env: impl ParentEnv,
    ) -> Command {
        let mut command = Command::new(&config.command);
        command.args(&config.args).env_clear();
        if let ChildWorkingDir::Fixed(dir) = working_dir {
            command.current_dir(dir);
        }

        for key in ENV_PASSTHROUGH {
            if let Some(value) = child_env_var(config, key, &parent_env) {
                command.env(key, value);
            }
        }
        #[cfg(windows)]
        for key in ENV_PASSTHROUGH_WINDOWS {
            if let Some(value) = child_env_var(config, key, &parent_env) {
                command.env(key, value);
            }
        }

        command
            .envs(config.env.iter())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        command
    }

    /// Folding ranges with columns (`lineFoldingOnly: false`), the three
    /// standard kinds, and collapsed text.
    fn folding_range_capabilities() -> lsp_types::FoldingRangeClientCapabilities {
        lsp_types::FoldingRangeClientCapabilities {
            dynamic_registration: Some(false),
            line_folding_only: Some(false),
            folding_range_kind: Some(lsp_types::ClientFoldingRangeKindOptions {
                value_set: Some(vec![
                    lsp_types::FoldingRangeKind::Comment,
                    lsp_types::FoldingRangeKind::Imports,
                    lsp_types::FoldingRangeKind::Region,
                ]),
            }),
            folding_range: Some(lsp_types::ClientFoldingRangeOptions {
                collapsed_text: Some(true),
            }),
            ..Default::default()
        }
    }

    /// Build the `capabilities` mcpls advertises in the `initialize`
    /// request, given the configured position-encoding preference order.
    ///
    /// Extracted from [`Self::initialize`] (S2) so a unit test can assert
    /// directly on the returned value -- in particular that
    /// `window.work_done_progress == Some(true)` (P1), without which no
    /// spec-compliant LSP server may ever initiate `$/progress` at all (see
    /// the matching `window/workDoneProgress/create` allowlist entry in
    /// [`crate::lsp::client::LspClient::server_request_result`]). Before
    /// this existed, deleting those capability lines would silently no-op
    /// the whole feature with an otherwise-green test suite.
    ///
    /// `workspace.configuration` is advertised only when `settings` are
    /// configured: without them mcpls has nothing to answer with.
    fn client_capabilities(
        position_encodings: &PositionEncodings,
        settings: Option<&LspSettings>,
    ) -> ClientCapabilities {
        ClientCapabilities {
            general: Some(GeneralClientCapabilities {
                position_encodings: Some(
                    position_encodings
                        .as_slice()
                        .iter()
                        .map(|encoding| encoding.to_kind())
                        .collect(),
                ),
                stale_request_support: Some(StaleRequestSupportOptions {
                    // mcpls does not implement active in-flight request
                    // cancellation.
                    cancel: false,
                    retry_on_content_modified: CONTENT_MODIFIED_RETRY_METHODS
                        .iter()
                        .map(ToString::to_string)
                        .collect(),
                }),
                ..Default::default()
            }),
            text_document: Some(lsp_types::TextDocumentClientCapabilities {
                synchronization: Some(lsp_types::TextDocumentSyncClientCapabilities {
                    dynamic_registration: Some(false),
                    did_save: Some(true),
                    ..Default::default()
                }),
                document_symbol: Some(lsp_types::DocumentSymbolClientCapabilities {
                    dynamic_registration: Some(false),
                    symbol_kind: Some(lsp_types::ClientSymbolKindOptions {
                        value_set: Some(advertised_symbol_kinds()),
                    }),
                    hierarchical_document_symbol_support: Some(true),
                    ..Default::default()
                }),
                hover: Some(lsp_types::HoverClientCapabilities {
                    dynamic_registration: Some(false),
                    content_format: Some(vec![
                        lsp_types::MarkupKind::Markdown,
                        lsp_types::MarkupKind::PlainText,
                    ]),
                }),
                definition: Some(lsp_types::DefinitionClientCapabilities {
                    dynamic_registration: Some(false),
                    link_support: Some(true),
                }),
                declaration: Some(lsp_types::DeclarationClientCapabilities {
                    dynamic_registration: Some(false),
                    link_support: Some(true),
                }),
                references: Some(lsp_types::ReferenceClientCapabilities {
                    dynamic_registration: Some(false),
                }),
                // clangd and typescript-language-server answer `prepareProvider` only
                // when the client advertises `prepareSupport`.
                rename: Some(lsp_types::RenameClientCapabilities {
                    dynamic_registration: Some(false),
                    prepare_support: Some(true),
                    prepare_support_default_behavior: Some(
                        lsp_types::PrepareSupportDefaultBehavior::Identifier,
                    ),
                    ..Default::default()
                }),
                folding_range: Some(Self::folding_range_capabilities()),
                // typescript-language-server publishes nothing unless this object is present;
                // only `versionSupport`, the one field the diagnostics cache retains.
                publish_diagnostics: Some(lsp_types::PublishDiagnosticsClientCapabilities {
                    version_support: Some(true),
                    ..Default::default()
                }),
                selection_range: Some(lsp_types::SelectionRangeClientCapabilities {
                    dynamic_registration: Some(false),
                }),
                code_action: Some(lsp_types::CodeActionClientCapabilities {
                    dynamic_registration: Some(false),
                    data_support: Some(true),
                    resolve_support: Some(lsp_types::ClientCodeActionResolveOptions {
                        properties: vec!["edit".to_string()],
                    }),
                    // Declare supported action kinds so the server returns
                    // CodeAction objects (not just legacy Command objects).
                    code_action_literal_support: Some(lsp_types::ClientCodeActionLiteralOptions {
                        code_action_kind: lsp_types::ClientCodeActionKindOptions {
                            value_set: std::iter::once(lsp_types::CodeActionKind::Empty)
                                .chain(
                                    crate::bridge::CodeActionKindFilter::ALL
                                        .map(lsp_types::CodeActionKind::from),
                                )
                                .collect(),
                        },
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            workspace: Some(lsp_types::WorkspaceClientCapabilities {
                workspace_folders: Some(true),
                configuration: settings.map(|_| true),
                ..Default::default()
            }),
            // Required per LSP 3.17 before a server may send $/progress at all -- see this fn's doc.
            window: Some(lsp_types::WindowClientCapabilities {
                work_done_progress: Some(true),
                ..Default::default()
            }),
            // Required for rust-analyzer to ever emit experimental/serverStatus; other servers ignore this unrecognized key.
            experimental: Some(serde_json::json!({ "serverStatusNotification": true })),
            ..Default::default()
        }
    }

    /// Perform LSP initialization handshake.
    ///
    /// Sends initialize request and waits for response, then sends the
    /// initialized and `workspace/didChangeConfiguration` notifications.
    ///
    /// The pushed settings are the configured per-server settings. Without
    /// any they are null rather than `{}`: some servers rebuild their
    /// preferences from an empty settings map and so drop their
    /// `initialization_options`, while a non-map value is ignored. Because
    /// configured settings are never empty (see [`LspSettings`]), servers
    /// such as jdtls may replace their `initialization_options`-derived
    /// preferences with them.
    #[cfg(test)]
    async fn initialize(
        client: &LspClient,
        config: &ServerInitConfig,
    ) -> Result<(ServerCapabilities, PositionEncodingKind)> {
        Self::initialize_as(client, config, Some(mcpls_process_id())).await
    }

    /// As [`Self::initialize`], reporting `process_id` as the parent process
    /// the server may watch (`None` is allowed by LSP and sent while a
    /// lifeline watchdog is bound: a server that exits when mcpls vanishes
    /// would otherwise race the watchdog's freeze of its descendants).
    async fn initialize_as(
        client: &LspClient,
        config: &ServerInitConfig,
        process_id: Option<i32>,
    ) -> Result<(ServerCapabilities, PositionEncodingKind)> {
        debug!("Sending initialize request");
        if config.server_config().initialization_options.is_some()
            && config.server_config().settings.is_some()
        {
            warn!(
                "server `{}` has both initialization_options and settings: servers that pull \
                 workspace/configuration (rust-analyzer, jdtls) may replace the options with \
                 the settings",
                config.server_config.command
            );
        }

        let workspace_folders: Vec<WorkspaceFolder> = config
            .workspace_roots()
            .canonical()
            .iter()
            .map(|root| workspace_folder(root))
            .collect::<Result<Vec<_>>>()?;

        let params = InitializeParams {
            process_id,
            #[allow(
                deprecated,
                reason = "`root_uri` is deprecated but the struct literal must still set it"
            )]
            root_uri: None,
            initialization_options: config.server_config().initialization_options.clone(),
            capabilities: Self::client_capabilities(
                &config.position_encodings,
                config.server_config.settings.as_ref(),
            ),
            client_info: Some(ClientInfo {
                name: "mcpls".to_string(),
                version: Some(env!("CARGO_PKG_VERSION").to_string()),
            }),
            workspace_folders_initialize_params: lsp_types::WorkspaceFoldersInitializeParams {
                workspace_folders: Some(lsp_types::WorkspaceFolders::WorkspaceFolderList(
                    workspace_folders,
                )),
            },
            ..Default::default()
        };

        // Use the server's configured timeout for the initialize handshake too,
        // not a hardcoded 30s: large solutions (e.g. a 130-project Unity .sln via
        // OmniSharp) take minutes to respond to `initialize`.
        let result: InitializeResult = client
            .request_typed::<InitializeRequest>(
                params,
                config.server_config.timeout_seconds.as_duration(),
            )
            .await
            .map_err(|e| {
                if is_connection_loss(&e) {
                    e
                } else {
                    Error::LspInitFailed {
                        phase: InitPhase::Initialize,
                        cause: Box::new(e),
                        hint: None,
                        stderr: None,
                    }
                }
            })?;

        let position_encoding = result
            .capabilities
            .position_encoding
            .clone()
            .unwrap_or(PositionEncodingKind::UTF16);

        debug!(
            "Server capabilities received, encoding: {:?}",
            position_encoding
        );

        notify_handshake::<InitializedNotification>(
            client,
            InitPhase::Initialized,
            InitializedParams {},
        )
        .await?;
        notify_handshake::<DidChangeConfigurationNotification>(
            client,
            InitPhase::DidChangeConfiguration,
            DidChangeConfigurationParams {
                settings: config
                    .server_config
                    .settings
                    .as_ref()
                    .map_or(serde_json::Value::Null, LspSettings::to_value),
            },
        )
        .await?;

        Ok((result.capabilities, position_encoding))
    }

    /// Get server capabilities.
    #[must_use]
    pub const fn capabilities(&self) -> &ServerCapabilities {
        &self.capabilities
    }

    /// Get negotiated position encoding.
    #[must_use]
    pub fn position_encoding(&self) -> PositionEncodingKind {
        self.position_encoding.clone()
    }

    /// Get client for making requests.
    #[must_use]
    pub const fn client(&self) -> &LspClient {
        &self.client
    }

    /// Non-blocking check for whether the child process has already exited.
    ///
    /// Uses [`tokio::process::Child::try_wait`] on the leader process, which never blocks waiting
    /// for the process: `true` means it is gone (crashed, killed, or exited
    /// on its own), and any [`LspClient`] obtained from [`Self::client`] is
    /// now permanently disconnected -- new requests through it fail with
    /// [`crate::error::Error::ServerTerminated`]. Callers that want to
    /// recover substitute a freshly [`Self::spawn`]ed replacement.
    ///
    /// Always returns `Ok(false)` for a test fixture with no real backing
    /// process (`self.child` is `None`) -- there is nothing to have exited.
    /// [`Self::spawn`] always populates `child`, so production code never
    /// observes this case.
    ///
    /// # Errors
    ///
    /// Returns an error if the OS fails to report the process's status.
    pub fn has_exited(&mut self) -> Result<bool> {
        match &mut self.child {
            Some(child) => Ok(child.try_wait()?.is_some()),
            None => Ok(false),
        }
    }

    /// Whether this server can no longer serve requests: its child process
    /// has exited, or its message loop has stopped (e.g. it panicked) while
    /// the child is still running.
    ///
    /// Unlike [`Self::has_exited`], this catches a live child whose connection
    /// is already dead, which nothing else would ever respawn. Test fixtures
    /// with no child process are never reported dead.
    ///
    /// # Errors
    ///
    /// Returns an error if the OS fails to report the process's status.
    pub(crate) fn is_dead(&mut self) -> Result<bool> {
        if self.has_exited()? {
            return Ok(true);
        }
        Ok(self.child.is_some() && self.client.is_message_loop_finished())
    }

    /// Shutdown server gracefully, with an overall deadline of [`SHUTDOWN_TIMEOUT`].
    ///
    /// Sends the LSP `shutdown` request, waits for the response, has the
    /// lifeline watchdog freeze and record descendants that escaped the
    /// server's process group (Unix), sends the `exit` notification, stops the
    /// message loop, then waits up to a grace period (never past the overall
    /// deadline) for the leader process to exit on its own. Whatever is left,
    /// including escapees that left the group through `setsid`/`setpgid` and
    /// shared daemons such as Gradle or Bloop, is then killed and waited for,
    /// up to [`crate::lsp::LIFELINE_SWEEP_BUDGET`] beyond the deadline, so
    /// when this returns the server's whole tree is gone. If the escapee mark
    /// fails the `exit` notification is skipped and the tree is killed right
    /// away. A test fixture with no real backing process skips the process
    /// steps.
    ///
    /// # Errors
    ///
    /// Returns the first error of the handshake or the message-loop stop,
    /// including [`Error::ShutdownTimeout`] when the deadline elapsed. The
    /// process tree is still torn down regardless of whether this returns
    /// `Ok` or `Err`.
    pub async fn shutdown(mut self) -> Result<()> {
        self.terminate(SHUTDOWN_TIMEOUT, ExitGrace::WithinBudget)
            .await
    }

    /// Stop the server and its whole process tree, leaving `self` usable as a
    /// dead server (`is_dead()` is `true` for a real process).
    ///
    /// Sends the LSP `shutdown` request, waits for the response, sends the
    /// `exit` notification and stops the message loop, all within `budget`.
    /// It then lets the leader process exit on its own for as long as `grace`
    /// allows, which is the only path that lets the server reap its own
    /// children. Whatever is left in the server's process group is then killed
    /// (on Unix this includes shared daemons such as Gradle or Bloop started
    /// by the server). A test fixture with no real backing process (`child`
    /// is `None`) skips the process steps.
    ///
    /// # Errors
    ///
    /// Returns the first error of the handshake or the message-loop stop,
    /// including [`Error::ShutdownTimeout`] when `budget` elapsed. The
    /// process tree is still torn down regardless of whether this returns
    /// `Ok` or `Err`.
    #[allow(
        clippy::arithmetic_side_effects,
        reason = "SHUTDOWN_TIMEOUT and CHILD_EXIT_GRACE are small constants"
    )]
    pub(crate) async fn terminate(&mut self, budget: Duration, grace: ExitGrace) -> Result<()> {
        debug!("Shutting down LSP server");

        let deadline = Instant::now() + budget;
        let client = &mut self.client;
        let shutdown_request_timeout = Duration::from_secs(5).min(budget);

        let handshake: Result<MarkOutcome> = timeout_at(deadline, async {
            client.suppress_cancels();
            let _: serde_json::Value = client
                .request(
                    ShutdownRequest::METHOD.as_str(),
                    (),
                    shutdown_request_timeout,
                )
                .await?;
            #[cfg(unix)]
            let mark = match self.child.as_mut() {
                Some(child) => child.mark_escapees().await,
                None => MarkOutcome::Confirmed,
            };
            #[cfg(windows)]
            let mark = MarkOutcome::Confirmed;
            if mark == MarkOutcome::Confirmed {
                client.notify_typed::<ExitNotification>(()).await?;
            }
            Ok(mark)
        })
        .await
        .unwrap_or(Err(Error::ShutdownTimeout));
        let mark = handshake
            .as_ref()
            .map_or(MarkOutcome::Confirmed, |mark| *mark);
        let notice = ExitNotice::of(&handshake);
        let handshake = handshake.map(drop);
        let handshake = match client.shutdown_until(deadline).await {
            Ok(()) => handshake,
            Err(e) => handshake.and(Err(e)),
        };

        if let Some(child) = &mut self.child {
            let wait = child_exit_wait(
                grace,
                mark,
                &handshake,
                deadline.saturating_duration_since(Instant::now()),
            );
            match timeout(wait, child.wait()).await {
                Ok(Ok(status)) => match notice {
                    ExitNotice::Sent => {
                        debug!(
                            ?status,
                            "LSP server process exited after `exit` notification"
                        );
                    }
                    ExitNotice::NotSent => {
                        debug!(
                            ?status,
                            "LSP server process exited without an `exit` notification"
                        );
                    }
                },
                Ok(Err(e)) => warn!(error = %e, "failed to wait for LSP server process exit"),
                Err(_) => match notice {
                    ExitNotice::Sent => warn!(
                        waited = ?wait,
                        exit = ?notice,
                        "LSP server process did not exit within the wait after `exit` \
                         notification, killing it"
                    ),
                    ExitNotice::NotSent => warn!(
                        waited = ?wait,
                        exit = ?notice,
                        "LSP server process killed without an `exit` notification"
                    ),
                },
            }
            let sweep_budget = deadline
                .saturating_duration_since(Instant::now())
                .clamp(MIN_SWEEP_BUDGET, crate::lsp::LIFELINE_SWEEP_BUDGET);
            child.terminate_tree(sweep_budget).await;
        }

        handshake?;
        info!("LSP server shut down successfully");
        Ok(())
    }

    /// Spawns and initializes one server, turning an error or a panic into
    /// that server's [`ServerStartOutcome::Failed`] so it can never affect a
    /// sibling. Logs the outcome with the id and elapsed time.
    ///
    /// Runs on the caller's task: dropping the future drops the child
    /// process it owns.
    pub(crate) async fn start_contained(config: &ServerInitConfig) -> ServerStartOutcome {
        Box::pin(contain(config, Self::spawn(config.clone()))).await
    }
}

/// Drives `start` (one server's spawn and handshake) and classifies how it
/// ended; see [`LspServer::start_contained`].
async fn contain(
    config: &ServerInitConfig,
    start: impl std::future::Future<Output = Result<SpawnedServer>>,
) -> ServerStartOutcome {
    let server_id = config.server_config.id();
    let language_id = config.server_config.language_id.clone();
    let command = config.server_config.command.server_command().clone();
    let started = Instant::now();

    let reason = match crate::util::catch_panic(start).await {
        Ok(Ok(spawned)) => {
            info!(
                "Successfully spawned LSP server: {} ({}) in {:?}",
                server_id,
                command,
                started.elapsed()
            );
            return ServerStartOutcome::Started(Box::new(spawned));
        }
        Ok(Err(e)) => {
            tracing::error!(
                "Failed to spawn LSP server: {} ({}) after {:?}: {}",
                server_id,
                command,
                started.elapsed(),
                e
            );
            StartupFailure::Spawn(Arc::new(e))
        }
        Err(panicked) => {
            tracing::error!(
                "Starting LSP server {} ({}) panicked after {:?}: {}",
                server_id,
                command,
                started.elapsed(),
                panicked.message()
            );
            StartupFailure::InitTaskPanicked
        }
    };
    ServerStartOutcome::Failed(ServerSpawnFailure {
        server_id,
        language_id,
        command,
        reason,
    })
}

fn mcpls_process_id() -> i32 {
    i32::try_from(std::process::id()).unwrap_or(i32::MAX)
}

/// The `processId` to send: none while a lifeline watchdog is bound, the real
/// mcpls pid otherwise.
#[cfg(unix)]
fn initialize_process_id(binding: Binding) -> Option<i32> {
    match binding {
        Binding::Bound => None,
        Binding::Unbound => Some(mcpls_process_id()),
    }
}

/// Sends one handshake notification, mapping a failed write to
/// [`Error::LspInitFailed`] naming the notification's method.
async fn notify_handshake<N>(client: &LspClient, phase: InitPhase, params: N::Params) -> Result<()>
where
    N: lsp_types::Notification,
{
    client
        .notify_typed::<N>(params)
        .await
        .map_err(|e| Error::LspInitFailed {
            phase,
            cause: Box::new(e),
            hint: None,
            stderr: None,
        })
}

/// Whether `error` means the connection to the server is gone, as opposed to
/// the server answering with a failure of its own.
const fn is_connection_loss(error: &Error) -> bool {
    matches!(
        error,
        Error::ServerTerminated
            | Error::TaskFailed {
                task: BackgroundTask::LspReceiver,
                ..
            }
    )
}

/// Exit status of `child` if it has exited (or does so within
/// [`EARLY_EXIT_PROBE`]), `None` if it is still running.
async fn early_exit_status(child: &mut ServerProcess) -> Option<std::process::ExitStatus> {
    timeout(EARLY_EXIT_PROBE, child.wait()).await.ok()?.ok()
}

/// Classify a spawn failure: a missing executable gets its own variant so the
/// message can carry PATH and install guidance.
fn spawn_error(command: ServerCommand, source: std::io::Error) -> Error {
    if source.kind() == std::io::ErrorKind::NotFound {
        Error::ServerNotFound {
            command,
            io: source,
        }
    } else {
        Error::ServerSpawnFailed { command, source }
    }
}

/// The process environment as `(name, value)` pairs, skipping non-UTF-8 entries.
pub fn current_environment() -> Vec<(String, String)> {
    std::env::vars_os()
        .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
        .collect()
}

/// Build the `workspace/workspaceFolders` entry for one configured root.
///
/// Reserved characters have to be percent-encoded here: an unencoded `#`
/// would truncate the path into a URI fragment, and `[` / `]` are rejected
/// outright by `Uri`.
fn workspace_folder(root: &Path) -> Result<WorkspaceFolder> {
    let uri = try_path_to_uri(root).ok_or_else(|| Error::PathToUri(root.to_path_buf()))?;
    Ok(WorkspaceFolder {
        uri,
        name: root
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("workspace")
            .to_string(),
    })
}

/// Builds an `LspServer` that can be registered without a real language
/// server: an inert, in-memory transport (see `crate::test_lsp`) and no
/// backing child process (`child: None`) -- neither is ever read from or
/// written to.
///
/// `pub` rather than private to this module's own `tests` (`lifecycle` is a
/// private module, so this stays crate-scoped in practice, per the
/// `redundant_pub_crate` clippy lint): it constructs `LspServer` via a
/// struct literal, which only code inside this module can do (all its
/// fields are private), so this is the one place other modules'
/// shutdown-path tests (`bridge::translator`, `lib.rs`) can get a real,
/// registerable `LspServer` from.
#[cfg(test)]
pub fn fake_lsp_server() -> LspServer {
    fake_lsp_server_with_config(LspServerConfig::pyright())
}

/// As [`fake_lsp_server`], with a caller-chosen config, which is also what
/// the returned server reports as its `init_config`.
#[cfg(test)]
pub fn fake_lsp_server_with_config(server_config: LspServerConfig) -> LspServer {
    let transport = crate::test_lsp::inert_transport();
    let client = LspClient::from_transport(server_config.clone(), transport);
    LspServer {
        client,
        capabilities: lsp_types::ServerCapabilities::default(),
        position_encoding: PositionEncodingKind::UTF8,
        child: None,
        init_config: crate::test_lsp::init_config_for(server_config),
    }
}

/// [`fake_lsp_server_with_config`] with inert lanes, as [`LspServer::spawn`]
/// returns it.
#[cfg(test)]
pub fn fake_spawned_server_with_config(server_config: LspServerConfig) -> SpawnedServer {
    let (_, messages) = mpsc::channel(1);
    let (_, lifecycle) = mpsc::channel(1);
    SpawnedServer {
        server: fake_lsp_server_with_config(server_config),
        lanes: ServerLanes {
            notifications: NotificationInbox::new(messages, crate::lsp::PublishReader::closed()),
            lifecycle,
        },
    }
}

/// A server whose child process (`sleep`) is alive but whose message loop
/// dies at once on its inert transport -- the shape of a panicked loop.
#[cfg(test)]
#[cfg(unix)]
pub fn fake_lsp_server_with_dead_loop_and_live_child() -> LspServer {
    let child = tokio::process::Command::new("sleep")
        .arg("30")
        .kill_on_drop(true)
        .spawn()
        .unwrap_or_else(|e| panic!("failed to spawn sleep: {e}"));
    let mut server = fake_lsp_server();
    server.child = Some(ServerProcess::from_unbound(child));
    server
}

#[cfg(test)]
impl LspServer {
    /// Construct an `LspServer` fixture carrying the given capabilities, for
    /// tests elsewhere in the crate that need to drive capability-gated
    /// dispatch paths in `Translator` without spawning a real language server.
    ///
    /// The underlying client and child process (`child: None`) are inert
    /// placeholders — only `capabilities()` is meaningful on the returned
    /// value.
    ///
    /// Uses `LspClient::new` (uninitialized, no background task) rather than
    /// `LspClient::from_transport`, so this does not depend on the Tokio
    /// message loop or a real process at all.
    pub(crate) fn new_for_test(capabilities: ServerCapabilities) -> Self {
        Self::new_for_test_with_encoding(capabilities, PositionEncodingKind::UTF16)
    }

    /// As [`Self::new_for_test`], but with a caller-chosen negotiated
    /// encoding -- for tests exercising a non-UTF-16 conversion path (e.g.
    /// `EncodingCtx`-driven range conversion) without spawning a real
    /// process.
    pub(crate) fn new_for_test_with_encoding(
        capabilities: ServerCapabilities,
        position_encoding: PositionEncodingKind,
    ) -> Self {
        Self::new_for_test_with_client(
            capabilities,
            position_encoding,
            LspClient::new(LspServerConfig::rust_analyzer()),
        )
    }

    /// As [`Self::new_for_test_with_encoding`], but around a caller-built
    /// client -- for tests that drive the client over a scripted transport
    /// (see `crate::test_lsp`).
    pub(crate) fn new_for_test_with_client(
        capabilities: ServerCapabilities,
        position_encoding: PositionEncodingKind,
        client: LspClient,
    ) -> Self {
        Self {
            client,
            capabilities,
            position_encoding,
            child: None,
            init_config: crate::test_lsp::init_config_for(LspServerConfig::rust_analyzer()),
        }
    }
}

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

    use super::*;
    use crate::bridge::PositionEncoding;
    use crate::config::{FilePattern, HostOs, LanguageId, TimeoutSecs, ToolSet};
    use crate::lsp::JsonRpcError;

    #[test]
    fn test_child_exit_wait_follows_the_grace_policy() {
        let remaining = Duration::from_secs(10);
        let grace = Duration::from_secs(7);
        let answered = Ok(());
        let unanswered = Err(Error::ShutdownTimeout);
        let wait = |policy, mark, answered: &Result<()>| {
            child_exit_wait(policy, mark, answered, remaining)
        };

        assert_eq!(
            wait(ExitGrace::WithinBudget, MarkOutcome::Confirmed, &answered),
            CHILD_EXIT_GRACE
        );
        assert_eq!(
            child_exit_wait(
                ExitGrace::WithinBudget,
                MarkOutcome::Confirmed,
                &answered,
                Duration::from_secs(1)
            ),
            Duration::from_secs(1)
        );
        assert_eq!(
            wait(
                ExitGrace::IfAnswered(grace),
                MarkOutcome::Confirmed,
                &answered
            ),
            grace
        );
        assert_eq!(
            wait(
                ExitGrace::IfAnswered(grace),
                MarkOutcome::Confirmed,
                &unanswered
            ),
            Duration::ZERO
        );
    }

    #[test]
    fn test_exit_notice_is_sent_only_after_a_confirmed_handshake() {
        assert_eq!(
            ExitNotice::of(&Ok(MarkOutcome::Confirmed)),
            ExitNotice::Sent
        );
        assert_eq!(
            ExitNotice::of(&Err(Error::ShutdownTimeout)),
            ExitNotice::NotSent
        );
        #[cfg(unix)]
        assert_eq!(
            ExitNotice::of(&Ok(MarkOutcome::Failed(
                crate::lsp::process::MarkFailure::NoConfirmation
            ))),
            ExitNotice::NotSent,
            "a withheld `exit` is not a sent one"
        );
    }

    #[test]
    fn test_client_capabilities_offer_configured_encodings_in_order() {
        let encodings =
            PositionEncodings::new(vec![PositionEncoding::Utf32, PositionEncoding::Utf8]).unwrap();
        let general = LspServer::client_capabilities(&encodings, None)
            .general
            .unwrap();
        assert_eq!(
            general.position_encodings,
            Some(vec![
                PositionEncodingKind::UTF32,
                PositionEncodingKind::UTF8
            ])
        );
    }

    /// P1/S2: without `window.work_done_progress == Some(true)`, no
    /// spec-compliant LSP server may ever initiate `$/progress` at all.
    /// Regression guard: deleting the capability lines in
    /// `client_capabilities` must fail this test, not silently no-op the
    /// whole feature with an otherwise-green suite.
    #[test]
    fn test_client_capabilities_advertises_work_done_progress() {
        let capabilities = LspServer::client_capabilities(&PositionEncodings::DEFAULT, None);

        assert_eq!(
            capabilities.window.and_then(|w| w.work_done_progress),
            Some(true)
        );
    }

    /// Without `prepareSupport`, clangd and typescript-language-server never
    /// advertise `prepareProvider`, which would make `prepare_rename`
    /// unreachable on them.
    #[test]
    fn test_client_capabilities_advertises_prepare_rename_support() {
        let rename = LspServer::client_capabilities(&PositionEncodings::DEFAULT, None)
            .text_document
            .and_then(|t| t.rename)
            .unwrap();

        assert_eq!(rename.prepare_support, Some(true));
        assert_eq!(
            rename.prepare_support_default_behavior,
            Some(lsp_types::PrepareSupportDefaultBehavior::Identifier)
        );
    }

    #[test]
    fn test_client_capabilities_advertises_folding_range_with_columns_and_collapsed_text() {
        let folding = LspServer::client_capabilities(&PositionEncodings::DEFAULT, None)
            .text_document
            .and_then(|t| t.folding_range)
            .unwrap();

        assert_eq!(folding.line_folding_only, Some(false));
        assert_eq!(
            folding
                .folding_range
                .and_then(|options| options.collapsed_text),
            Some(true)
        );
    }

    #[test]
    fn test_client_capabilities_advertises_selection_range() {
        let capabilities = LspServer::client_capabilities(&PositionEncodings::DEFAULT, None)
            .text_document
            .and_then(|t| t.selection_range)
            .unwrap();

        assert_eq!(capabilities.dynamic_registration, Some(false));
    }

    #[test]
    fn test_client_capabilities_advertise_did_save_without_dynamic_registration() {
        let synchronization = LspServer::client_capabilities(&PositionEncodings::DEFAULT, None)
            .text_document
            .and_then(|t| t.synchronization)
            .unwrap();

        assert_eq!(
            synchronization,
            lsp_types::TextDocumentSyncClientCapabilities {
                dynamic_registration: Some(false),
                did_save: Some(true),
                ..Default::default()
            }
        );
    }

    #[test]
    fn test_client_capabilities_advertises_publish_diagnostics_with_version_support_only() {
        let capabilities = LspServer::client_capabilities(&PositionEncodings::DEFAULT, None)
            .text_document
            .and_then(|t| t.publish_diagnostics)
            .unwrap();

        assert_eq!(
            capabilities,
            lsp_types::PublishDiagnosticsClientCapabilities {
                version_support: Some(true),
                ..Default::default()
            }
        );
    }

    #[test]
    fn test_client_capabilities_do_not_advertise_pull_diagnostics() {
        let text_document = LspServer::client_capabilities(&PositionEncodings::DEFAULT, None)
            .text_document
            .unwrap();

        assert!(text_document.diagnostic.is_none());
    }

    #[test]
    fn test_server_state_ready() {
        assert!(ServerState::Ready.is_ready());
    }

    #[test]
    fn test_server_state_uninitialized() {
        assert!(!ServerState::Uninitialized.is_ready());
    }

    #[test]
    fn test_server_state_initializing() {
        assert!(!ServerState::Initializing.is_ready());
    }

    #[test]
    fn test_workspace_folder_encodes_fragment_char() {
        // An unencoded `#` parses as a fragment, silently handing the server
        // the parent directory as its root.
        #[cfg(windows)]
        let (root, expected) = (
            Path::new(r"C:\home\me\dev\#work"),
            "file:///C:/home/me/dev/%23work",
        );
        #[cfg(not(windows))]
        let (root, expected) = (
            Path::new("/home/me/dev/#work"),
            "file:///home/me/dev/%23work",
        );

        let folder = workspace_folder(root).unwrap();

        assert_eq!(folder.uri.as_ref(), expected);
        assert_eq!(folder.name, "#work");
    }

    #[test]
    fn test_workspace_folder_encodes_bracket_chars() {
        #[cfg(windows)]
        let (root, expected) = (
            Path::new(r"C:\home\me\dev\[env]"),
            "file:///C:/home/me/dev/%5Benv%5D",
        );
        #[cfg(not(windows))]
        let (root, expected) = (
            Path::new("/home/me/dev/[env]"),
            "file:///home/me/dev/%5Benv%5D",
        );

        let folder = workspace_folder(root).unwrap();

        assert_eq!(folder.uri.as_ref(), expected);
        assert_eq!(folder.name, "[env]");
    }

    #[test]
    fn test_workspace_folder_rejects_relative_root() {
        let err = workspace_folder(Path::new("relative/root")).unwrap_err();
        assert_matches!(err, Error::PathToUri(_), "got {err:?}");
    }

    #[test]
    fn test_server_state_shutting_down() {
        assert!(!ServerState::ShuttingDown.is_ready());
    }

    #[test]
    fn test_server_state_shutdown() {
        assert!(!ServerState::Shutdown.is_ready());
    }

    #[test]
    fn test_server_state_equality() {
        assert_eq!(ServerState::Ready, ServerState::Ready);
        assert_ne!(ServerState::Ready, ServerState::Uninitialized);
        assert_eq!(ServerState::Shutdown, ServerState::Shutdown);
    }

    #[test]
    fn test_server_state_clone() {
        let state = ServerState::Ready;
        let cloned = state;
        assert_eq!(state, cloned);
    }

    #[test]
    fn test_server_state_debug() {
        let state = ServerState::Ready;
        let debug_str = format!("{state:?}");
        assert!(debug_str.contains("Ready"));
    }

    #[test]
    fn test_server_init_config_clone() {
        let config = ServerInitConfig::new(
            {
                let mut c = LspServerConfig::rust_analyzer();
                c.initialization_options = Some(serde_json::json!({"key": "value"}));
                c
            },
            WorkspaceRoots::for_test(vec![PathBuf::from("/tmp/workspace")], vec![]),
            PositionEncodings::DEFAULT,
            std::sync::Arc::default(),
        );

        #[allow(clippy::redundant_clone, reason = "the test exercises `Clone` itself")]
        let cloned = config.clone();
        assert_eq!(cloned.server_config().language_id, "rust");
        assert_eq!(cloned.workspace_roots().canonical().len(), 1);
    }

    #[test]
    fn test_server_init_config_debug() {
        let config = ServerInitConfig::new(
            LspServerConfig::pyright(),
            WorkspaceRoots::default(),
            PositionEncodings::DEFAULT,
            std::sync::Arc::default(),
        );

        let debug_str = format!("{config:?}");
        assert!(debug_str.contains("python"));
        assert!(debug_str.contains("pyright"));
    }

    #[test]
    fn test_server_init_config_with_options() {
        let init_opts = serde_json::json!({
            "settings": {
                "python": {
                    "analysis": {
                        "typeCheckingMode": "strict"
                    }
                }
            }
        });

        let mut env = crate::config::ServerEnv::default();
        env.insert(
            crate::config::EnvKey::from_static("PYTHONPATH"),
            crate::config::EnvValue::from_static("/usr/lib"),
        )
        .unwrap();

        let config = ServerInitConfig::new(
            LspServerConfig {
                language_id: LanguageId::from_static("python"),
                command: ServerCommand::from_static("pyright-langserver").into(),
                args: crate::config::ServerArgs::try_from(vec!["--stdio".to_string()]).unwrap(),
                env,
                file_patterns: vec![FilePattern::from_static("**/*.py")],
                initialization_options: Some(init_opts),
                settings: None,
                timeout_seconds: TimeoutSecs::new(10).unwrap(),
                request_timeout_seconds: TimeoutSecs::new(10).unwrap(),
                heuristics: None,
                name: None,
                handles: None,
                indexing: crate::bridge::IndexingPolicy::Auto,
            },
            WorkspaceRoots::for_test(vec![PathBuf::from("/workspace")], vec![]),
            PositionEncodings::DEFAULT,
            std::sync::Arc::default(),
        );

        assert!(config.server_config().initialization_options.is_some());
        assert_eq!(config.workspace_roots().canonical().len(), 1);
    }

    #[test]
    fn test_server_init_config_empty_workspace() {
        let config = ServerInitConfig::new(
            LspServerConfig::typescript(),
            WorkspaceRoots::default(),
            PositionEncodings::DEFAULT,
            std::sync::Arc::default(),
        );

        assert_eq!(config.workspace_roots().canonical().len(), 0);
    }

    #[test]
    fn test_server_init_config_multiple_workspaces() {
        let config = ServerInitConfig::new(
            LspServerConfig::rust_analyzer(),
            WorkspaceRoots::for_test(
                vec![
                    PathBuf::from("/workspace1"),
                    PathBuf::from("/workspace2"),
                    PathBuf::from("/workspace3"),
                ],
                vec![],
            ),
            PositionEncodings::DEFAULT,
            std::sync::Arc::default(),
        );

        assert_eq!(config.workspace_roots().canonical().len(), 3);
    }

    /// #249: `has_exited` must distinguish a live child from one that has
    /// already exited, since this is the signal the respawn path relies on
    /// to detect a crashed LSP server.
    ///
    /// Unix-only: spawns a real `sleep` subprocess, which is unavailable on
    /// the Windows CI runner.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_has_exited_reflects_child_process_state() {
        use lsp_types::ServerCapabilities;

        let mut mock_child = tokio::process::Command::new("sleep")
            .arg("2")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .unwrap();

        let mock_stdin = mock_child.stdin.take().unwrap();
        let mock_stdout = mock_child.stdout.take().unwrap();

        let transport = LspTransport::new(mock_stdin, mock_stdout);
        let client = LspClient::from_transport(LspServerConfig::rust_analyzer(), transport);

        let mut server = LspServer {
            client,
            capabilities: ServerCapabilities::default(),
            position_encoding: PositionEncodingKind::UTF8,
            child: Some(ServerProcess::from_unbound(mock_child)),
            init_config: crate::test_lsp::init_config_for(LspServerConfig::rust_analyzer()),
        };

        assert!(
            !server.has_exited().unwrap(),
            "freshly spawned `sleep 2` should still be running"
        );

        server.child.as_mut().unwrap().kill().await.unwrap();
        // `kill().await` waits for the process to actually exit, so the
        // very next `try_wait` reliably observes it as gone.
        assert!(
            server.has_exited().unwrap(),
            "killed child must report as exited"
        );
    }

    /// A live child whose message loop has stopped must be reported dead.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_is_dead_when_message_loop_finished_but_child_alive() {
        let mut server = fake_lsp_server_with_dead_loop_and_live_child();

        tokio::time::timeout(Duration::from_secs(2), async {
            while !server.client.is_message_loop_finished() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .unwrap();

        assert!(!server.has_exited().unwrap());
        assert!(server.is_dead().unwrap());
    }

    /// A server that never answers `shutdown` fails the handshake with the
    /// request timeout, well inside `SHUTDOWN_TIMEOUT`, and still stops its
    /// message loop.
    #[tokio::test(start_paused = true)]
    async fn test_shutdown_reports_handshake_timeout_within_deadline() {
        let (client, _fake_server) = crate::test_lsp::fake_lsp_client();
        let probe = client.clone();
        let server = LspServer {
            client,
            capabilities: lsp_types::ServerCapabilities::default(),
            position_encoding: PositionEncodingKind::UTF8,
            child: None,
            init_config: crate::test_lsp::init_config_for(LspServerConfig::rust_analyzer()),
        };

        let started = Instant::now();
        let result = server.shutdown().await;

        assert_matches!(result, Err(Error::Timeout(_)), "got {result:?}");
        assert!(started.elapsed() <= SHUTDOWN_TIMEOUT);
        assert_matches!(probe.state().await, ServerState::Shutdown);
    }

    #[tokio::test]
    async fn test_is_dead_false_for_childless_fixture() {
        let mut server = fake_lsp_server();
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(!server.is_dead().unwrap());
    }

    #[tokio::test]
    async fn test_lsp_server_getters() {
        use lsp_types::ServerCapabilities;

        let transport = crate::test_lsp::inert_transport();
        let client = LspClient::from_transport(LspServerConfig::rust_analyzer(), transport);

        let server = LspServer {
            client,
            capabilities: ServerCapabilities::default(),
            position_encoding: PositionEncodingKind::UTF8,
            child: None,
            init_config: crate::test_lsp::init_config_for(LspServerConfig::rust_analyzer()),
        };

        assert_eq!(server.position_encoding(), PositionEncodingKind::UTF8);
        assert!(server.capabilities().text_document_sync.is_none());

        let debug_str = format!("{server:?}");
        assert!(debug_str.contains("LspServer"));
        assert!(debug_str.contains("<process>"));
    }

    #[test]
    fn test_spawn_error_classifies_not_found() {
        use std::io::{Error as IoError, ErrorKind};

        let missing = spawn_error(
            ServerCommand::from_static("x"),
            IoError::from(ErrorKind::NotFound),
        );
        assert_matches!(missing, Error::ServerNotFound { .. });
        let denied = spawn_error(
            ServerCommand::from_static("x"),
            IoError::from(ErrorKind::PermissionDenied),
        );
        assert_matches!(denied, Error::ServerSpawnFailed { .. });
    }

    #[tokio::test]
    async fn test_spawn_nonexistent_command_is_server_not_found() {
        let mut server_config = LspServerConfig::rust_analyzer();
        server_config.command = ServerCommand::from_static("nonexistent-lsp-cmd-xyz").into();
        let config = ServerInitConfig::new(
            server_config,
            WorkspaceRoots::default(),
            PositionEncodings::DEFAULT,
            std::sync::Arc::default(),
        );
        let err = LspServer::spawn(config).await.unwrap_err();
        assert_matches!(err, Error::ServerNotFound { .. }, "got {err:?}");
    }

    #[tokio::test]
    async fn test_is_connection_loss_excludes_server_replies() {
        let join_error = tokio::spawn(async { panic!("receiver died") })
            .await
            .unwrap_err();
        assert!(is_connection_loss(&Error::ServerTerminated));
        assert!(is_connection_loss(&Error::TaskFailed {
            task: BackgroundTask::LspReceiver,
            source: join_error,
        }));
        assert!(!is_connection_loss(&Error::StdioCapture(
            StdioStream::Stdin
        )));
        assert!(!is_connection_loss(&Error::LspServerError(JsonRpcError {
            code: -32603,
            message: "bad".to_string(),
            data: None,
        })));
    }

    /// A server that answers `initialize` with an error and then exits keeps
    /// its own error instead of being reported as an early exit.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_keeps_servers_own_initialize_error_when_it_exits_afterwards() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = crate::test_lsp::sh_script_init_config(
            dir.path(),
            &crate::test_lsp::with_read_preamble(
                r#"body='{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"rejected by server"}}'
printf 'Content-Length: %d\r\n\r\n%s' ${#body} "$body"
"#,
            ),
        );

        let err = LspServer::spawn(config).await.unwrap_err();

        assert_matches!(
            &err,
            Error::LspInitFailed { phase: InitPhase::Initialize, cause, .. }
                if matches!(**cause, Error::LspServerError(JsonRpcError { code: -32603, .. })),
            "got {err:?}"
        );
        assert!(err.to_string().contains("rejected by server"), "{err}");
    }

    /// Connection lost while the child is still running: the error keeps the
    /// "initialize failed" context rather than a bare transport error.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_connection_loss_with_live_child_is_lsp_init_failed() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = crate::test_lsp::sh_script_init_config(dir.path(), "exec 1>&-\nsleep 5\n");

        let err = LspServer::spawn(config).await.unwrap_err();

        assert_matches!(
            &err,
            Error::LspInitFailed {
                phase: InitPhase::Initialize,
                ..
            },
            "got {err:?}"
        );
        assert!(
            err.to_string().contains("Initialize request failed"),
            "{err}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_exiting_before_initialize_reply_is_server_exited_during_init() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = crate::test_lsp::sh_script_init_config(dir.path(), "exit 1\n");

        let err = LspServer::spawn(config).await.unwrap_err();

        assert_matches!(
            err,
            Error::ServerExitedDuringInit {
                exit_code: Some(1),
                ..
            },
            "got {err:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_unbound_server_gets_the_real_process_id() {
        assert_eq!(
            initialize_process_id(Binding::Unbound),
            Some(i32::try_from(std::process::id()).unwrap())
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_bound_server_gets_no_process_id() {
        assert_eq!(initialize_process_id(Binding::Bound), None);
    }

    /// A server guarded by a lifeline watchdog must not be handed the mcpls
    /// pid to watch: it could exit before the watchdog has frozen its tree.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_sends_null_process_id_while_a_lifeline_is_bound() {
        let dir = tempfile::TempDir::new().unwrap();
        let dump = dir.path().join("request");
        let script = format!(
            "read -r header\nread -r _\nhead -c \"$(printf %s \"$header\" | tr -dc 0-9)\" > '{}'\nexit 1\n",
            dump.display()
        );
        let config = crate::test_lsp::sh_script_init_config(dir.path(), &script);

        LspServer::spawn(config).await.unwrap_err();

        let request = std::fs::read_to_string(&dump).unwrap();
        assert!(request.contains(r#""processId":null"#), "got {request}");
    }

    /// #534: what the server printed before exiting reaches the error.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_exit_during_init_carries_stderr() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = crate::test_lsp::sh_script_init_config(
            dir.path(),
            "echo 'fatal: bad toolchain' >&2\nexit 1\n",
        );

        let err = LspServer::spawn(config).await.unwrap_err();

        let Error::ServerExitedDuringInit {
            stderr: Some(stderr),
            ..
        } = &err
        else {
            panic!("got {err:?}");
        };
        assert_eq!(stderr.head(), "fatal: bad toolchain");
        assert!(err.to_string().contains("stderr: fatal: bad toolchain"));
    }

    /// A server that rejects `initialize` and prints its reason just before
    /// exiting must not lose that last line.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_rejection_keeps_stderr_written_just_before_exit() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = crate::test_lsp::sh_script_init_config(
            dir.path(),
            &crate::test_lsp::with_read_preamble(
                r#"body='{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"rejected by server"}}'
printf 'Content-Length: %d\r\n\r\n%s' ${#body} "$body"
# Shell-only pause: an external `sleep` can take longer than the 100 ms EOF grace just to start on a loaded macOS runner.
i=0; while [ $i -lt 300 ]; do i=$((i+1)); done
echo 'fatal: bad toolchain' >&2
"#,
            ),
        );

        let err = LspServer::spawn(config).await.unwrap_err();

        let Error::LspInitFailed {
            stderr: Some(stderr),
            ..
        } = &err
        else {
            panic!("got {err:?}");
        };
        assert_eq!(stderr.head(), "fatal: bad toolchain");
    }

    /// #534: a server that hangs after writing to stderr times out with its
    /// output attached.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_initialize_timeout_carries_stderr() {
        let dir = tempfile::TempDir::new().unwrap();
        let mut config = crate::test_lsp::sh_script_init_config(
            dir.path(),
            "echo 'indexing forever' >&2\nsleep 5\n",
        );
        config.server_config.timeout_seconds = TimeoutSecs::new(1).unwrap();

        let err = LspServer::spawn(config).await.unwrap_err();

        let Error::LspInitFailed {
            stderr: Some(stderr),
            ..
        } = &err
        else {
            panic!("got {err:?}");
        };
        assert_eq!(stderr.head(), "indexing forever");
    }

    /// #612: a secret of another configured server, handed in through the
    /// init config, is hidden from this server's output although its own
    /// configuration does not name it.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_hides_another_servers_secret_from_stderr() {
        let dir = tempfile::TempDir::new().unwrap();
        let mut config = crate::test_lsp::sh_script_init_config(
            dir.path(),
            "echo \"seen=$OTHER_VALUE own=$API_TOKEN\" >&2\nexit 1\n",
        );
        config
            .server_config
            .env
            .insert(
                crate::config::EnvKey::from_static("OTHER_VALUE"),
                crate::config::EnvValue::from_static("bravo-secret-222"),
            )
            .unwrap();
        config
            .server_config
            .env
            .insert(
                crate::config::EnvKey::from_static("API_TOKEN"),
                crate::config::EnvValue::from_static("s3cr3t-value"),
            )
            .unwrap();
        config.redactions = std::sync::Arc::new(Redactions::new([(
            "B_TOKEN".to_owned(),
            "bravo-secret-222".to_owned(),
        )]));

        let err = LspServer::spawn(config).await.unwrap_err();

        let text = err.to_string();
        assert!(text.contains("seen=[redacted:B_TOKEN]"), "{text}");
        assert!(text.contains("own=[redacted:API_TOKEN]"), "{text}");
    }

    /// Values configured in `env` never reach the error text.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_stderr_redacts_configured_env_values() {
        let dir = tempfile::TempDir::new().unwrap();
        let mut config = crate::test_lsp::sh_script_init_config(
            dir.path(),
            "echo \"token=$API_TOKEN toolchain=$RUSTUP_TOOLCHAIN\" >&2\nexit 1\n",
        );
        config
            .server_config
            .env
            .insert(
                crate::config::EnvKey::from_static("RUSTUP_TOOLCHAIN"),
                crate::config::EnvValue::from_static("nightly-2024-01-01"),
            )
            .unwrap();
        config
            .server_config
            .env
            .insert(
                crate::config::EnvKey::from_static("API_TOKEN"),
                crate::config::EnvValue::from_static("s3cr3t-value"),
            )
            .unwrap();

        let err = LspServer::spawn(config).await.unwrap_err();

        let text = err.to_string();
        assert!(text.contains("token=[redacted:API_TOKEN]"), "{text}");
        assert!(text.contains("toolchain=nightly-2024-01-01"), "{text}");
        assert!(!text.contains("s3cr3t-value"), "{text}");
    }

    #[test]
    fn test_log_spawn_hides_argument_values() {
        use tracing_subscriber::prelude::*;

        use crate::test_lsp::CapturedLogs;

        let mut config = LspServerConfig::rust_analyzer();
        config.args = crate::config::ServerArgs::new(["--api-key=SuperSecretArg456"]).unwrap();
        let redactions = Redactions::for_server(&config, std::iter::empty());
        let logs = CapturedLogs::default();
        let info_only = tracing_subscriber::registry()
            .with(tracing_subscriber::filter::LevelFilter::INFO)
            .with(logs.clone());

        tracing::subscriber::with_default(info_only, || {
            LspServer::log_spawn(&config, &redactions);
        });

        let output = logs.messages().join("\n");
        assert!(output.contains("(1 arg(s))"), "{output}");
        assert!(!output.contains("SuperSecretArg456"), "{output}");
    }

    /// FR-012: a panic while starting one server is that server's failure.
    #[tokio::test]
    async fn contain_attributes_a_panic_to_its_own_server() {
        let config = crate::test_lsp::init_config_for(LspServerConfig::rust_analyzer());

        let outcome = contain(&config, async { panic!("start boom") }).await;

        assert_matches!(
            outcome,
            ServerStartOutcome::Failed(failure)
                if failure.server_id == config.server_config.id()
                    && matches!(failure.reason, StartupFailure::InitTaskPanicked)
        );
    }

    #[tokio::test]
    async fn contain_reports_a_spawn_error_as_that_servers_failure() {
        let config = crate::test_lsp::init_config_for(LspServerConfig::rust_analyzer());

        let outcome = contain(&config, async { Err(Error::ServerTerminated) }).await;

        assert_matches!(
            outcome,
            ServerStartOutcome::Failed(failure) if matches!(failure.reason, StartupFailure::Spawn(_))
        );
    }

    /// `window/logMessage` and `window/showMessage` text echoing configured
    /// secrets is redacted before it reaches the notification lane (#554).
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_redacts_secrets_in_server_log_and_show_messages() {
        let dir = tempfile::TempDir::new().unwrap();
        let script = r#"body='{"jsonrpc":"2.0","id":1,"result":{"capabilities":{}}}'
printf 'Content-Length: %d\r\n\r\n%s' ${#body} "$body"
body="{\"jsonrpc\":\"2.0\",\"method\":\"window/logMessage\",\"params\":{\"type\":3,\"message\":\"env=$API_TOKEN arg=$1\"}}"
printf 'Content-Length: %d\r\n\r\n%s' ${#body} "$body"
body="{\"jsonrpc\":\"2.0\",\"method\":\"window/showMessage\",\"params\":{\"type\":3,\"message\":\"env=$API_TOKEN\"}}"
printf 'Content-Length: %d\r\n\r\n%s' ${#body} "$body"
sleep 5
"#;
        let mut config = crate::test_lsp::sh_script_init_config(
            dir.path(),
            &crate::test_lsp::with_read_preamble(script),
        );
        config.server_config.args = crate::config::ServerArgs::new(
            config
                .server_config
                .args
                .iter()
                .cloned()
                .chain(["--api-key=SuperSecretArg456".to_string()]),
        )
        .unwrap();
        config
            .server_config
            .env
            .insert(
                crate::config::EnvKey::from_static("API_TOKEN"),
                crate::config::EnvValue::from_static("SuperSecretValue123"),
            )
            .unwrap();

        let SpawnedServer {
            server: _server,
            lanes,
        } = LspServer::spawn(config).await.unwrap();
        let mut rx = lanes.notifications.messages;
        let mut texts = Vec::new();
        for _ in 0..2 {
            let notification = tokio::time::timeout(Duration::from_secs(5), rx.recv())
                .await
                .unwrap()
                .unwrap();
            texts.push(format!("{notification:?}"));
        }

        let joined = texts.join("\n");
        assert!(!joined.contains("SuperSecretValue123"), "{joined}");
        assert!(!joined.contains("SuperSecretArg456"), "{joined}");
        assert!(joined.contains("[redacted:API_TOKEN]"), "{joined}");
        assert!(joined.contains("[redacted:api-key]"), "{joined}");
    }

    /// A secret echoed into a mistyped `initialize` result reaches the serde
    /// error text, which is redacted too (#554).
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_redacts_secrets_in_initialize_decode_error() {
        let dir = tempfile::TempDir::new().unwrap();
        let script = r#"body='{"jsonrpc":"2.0","id":1,"result":{"capabilities":"SuperSecretValue123"}}'
printf 'Content-Length: %d\r\n\r\n%s' ${#body} "$body"
sleep 5
"#;
        let mut config = crate::test_lsp::sh_script_init_config(
            dir.path(),
            &crate::test_lsp::with_read_preamble(script),
        );
        config
            .server_config
            .env
            .insert(
                crate::config::EnvKey::from_static("API_TOKEN"),
                crate::config::EnvValue::from_static("SuperSecretValue123"),
            )
            .unwrap();

        let err = LspServer::spawn(config).await.unwrap_err();

        let text = err.to_string();
        assert!(!text.contains("SuperSecretValue123"), "{text}");
    }

    /// The server's own `initialize` error text is redacted (#554).
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_redacts_secrets_in_initialize_error_message() {
        let dir = tempfile::TempDir::new().unwrap();
        let script = r#"body="{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32603,\"message\":\"bad token $API_TOKEN\"}}"
printf 'Content-Length: %d\r\n\r\n%s' ${#body} "$body"
sleep 5
"#;
        let mut config = crate::test_lsp::sh_script_init_config(
            dir.path(),
            &crate::test_lsp::with_read_preamble(script),
        );
        config
            .server_config
            .env
            .insert(
                crate::config::EnvKey::from_static("API_TOKEN"),
                crate::config::EnvValue::from_static("SuperSecretValue123"),
            )
            .unwrap();

        let err = LspServer::spawn(config).await.unwrap_err();

        let text = err.to_string();
        assert!(text.contains("[redacted:API_TOKEN]"), "{text}");
        assert!(!text.contains("SuperSecretValue123"), "{text}");
    }

    /// Regression guard for the drain: a server flooding stderr both before
    /// and after it answers `initialize` must never block or lose its pipe
    /// (`EPIPE`/`SIGPIPE`) once `spawn` has returned.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_spawn_keeps_draining_stderr_after_initialize() {
        let dir = tempfile::TempDir::new().unwrap();
        let marker = dir.path().join("flooded");
        let script = format!(
            r#"head -c 200000 /dev/zero | tr '\0' 'e' >&2
body='{{"jsonrpc":"2.0","id":1,"result":{{"capabilities":{{}}}}}}'
printf 'Content-Length: %d\r\n\r\n%s' ${{#body}} "$body"
sleep 0.3
head -c 200000 /dev/zero | tr '\0' 'e' >&2 && echo done > '{}'
sleep 5
"#,
            marker.display()
        );
        let config = crate::test_lsp::sh_script_init_config(
            dir.path(),
            &crate::test_lsp::with_read_preamble(&script),
        );

        let mut server = LspServer::spawn(config).await.unwrap().server;

        let flooded = tokio::time::timeout(Duration::from_secs(5), async {
            while !marker.exists() {
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        })
        .await;
        assert!(
            flooded.is_ok(),
            "server's post-initialize stderr flood did not complete"
        );
        assert!(!server.has_exited().unwrap());
    }

    /// Wire-level regressions for the `initialize` request. The tests
    /// capture the real bytes `LspServer::initialize` writes over an
    /// in-memory duplex pipe standing in for the LSP server. Mirrors the
    /// `fake_lsp_client`/`FakeServer` pattern in
    /// `client.rs::tests::retry_behavior`.
    mod initialize_wire {

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

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

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

            let config = ServerInitConfig::new(
                LspServerConfig::rust_analyzer(),
                WorkspaceRoots::default(),
                PositionEncodings::new(vec![PositionEncoding::Utf32, PositionEncoding::Utf8])
                    .unwrap(),
                std::sync::Arc::default(),
            );

            let init_task =
                tokio::spawn(async move { LspServer::initialize(&client, &config).await });

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

            assert_eq!(request["method"], "initialize");
            assert_eq!(
                request["params"]["capabilities"]["general"]["positionEncodings"],
                serde_json::json!(["utf-32", "utf-8"]),
                "initialize request must carry the configured encoding order, not the \
                 hardcoded [UTF8, UTF16] default"
            );

            write_success_response(
                &mut server.read_half_stdin,
                &request["id"].clone(),
                serde_json::json!({ "capabilities": {} }),
            )
            .await;

            // The response written above must let `initialize` complete successfully.
            init_task.await.unwrap().unwrap();
        }

        /// The three client frames of a handshake: `initialize`, `initialized`
        /// and `workspace/didChangeConfiguration`.
        struct Handshake {
            initialize: serde_json::Value,
            initialized: serde_json::Value,
            configuration: serde_json::Value,
        }

        async fn handshake_with_settings(settings_json: Option<&str>) -> Handshake {
            let (client, mut server) = fake_lsp_client();
            let mut server_config = LspServerConfig::rust_analyzer();
            server_config.settings = settings_json.map(|json| serde_json::from_str(json).unwrap());
            let config = crate::test_lsp::init_config_for(server_config);
            let init_task =
                tokio::spawn(async move { LspServer::initialize(&client, &config).await });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let initialize = read_framed_message(&mut reader).await;
            assert_eq!(initialize["method"], "initialize");
            write_success_response(
                &mut server.read_half_stdin,
                &initialize["id"].clone(),
                serde_json::json!({ "capabilities": {} }),
            )
            .await;
            let initialized = read_framed_message(&mut reader).await;
            let configuration = read_framed_message(&mut reader).await;
            init_task.await.unwrap().unwrap();
            Handshake {
                initialize,
                initialized,
                configuration,
            }
        }

        #[tokio::test]
        async fn test_initialize_pushes_null_settings_right_after_initialized() {
            let wire = handshake_with_settings(None).await;

            assert_eq!(wire.initialized["method"], "initialized");
            assert_eq!(
                wire.configuration["method"],
                "workspace/didChangeConfiguration"
            );
            assert_eq!(
                wire.configuration["params"],
                serde_json::json!({ "settings": null })
            );
        }

        #[tokio::test]
        async fn test_initialize_pushes_configured_settings_and_advertises_configuration() {
            let wire =
                handshake_with_settings(Some(r#"{"python.analysis.typeCheckingMode": "strict"}"#))
                    .await;

            assert_eq!(
                wire.initialize["params"]["capabilities"]["workspace"]["configuration"],
                serde_json::json!(true)
            );
            assert_eq!(
                wire.configuration["params"],
                serde_json::json!({
                    "settings": { "python": { "analysis": { "typeCheckingMode": "strict" } } }
                })
            );
        }

        #[tokio::test]
        async fn test_initialize_pushes_gopls_flat_and_yaml_url_keys_on_the_wire() {
            let wire = handshake_with_settings(Some(
                r#"{"gopls":{"ui.semanticTokens":true},
                    "yaml.schemas":{"https://json.schemastore.org/x.json":"*.yml"}}"#,
            ))
            .await;

            let settings =
                serde_json::to_string(&wire.configuration["params"]["settings"]).unwrap();
            assert!(
                settings.contains(r#""gopls":{"ui.semanticTokens":true}"#),
                "{settings}"
            );
            assert!(
                settings.contains(
                    r#""yaml":{"schemas":{"https://json.schemastore.org/x.json":"*.yml"}}"#
                ),
                "{settings}"
            );
        }

        #[test]
        fn test_workspace_configuration_not_advertised_without_settings() {
            let workspace = LspServer::client_capabilities(&PositionEncodings::DEFAULT, None)
                .workspace
                .unwrap();
            assert_eq!(workspace.configuration, None);
        }

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

            let config = ServerInitConfig::new(
                LspServerConfig::rust_analyzer(),
                WorkspaceRoots::default(),
                PositionEncodings::DEFAULT,
                std::sync::Arc::default(),
            );

            let init_task =
                tokio::spawn(async move { LspServer::initialize(&client, &config).await });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let request = read_framed_message(&mut reader).await;
            let params: InitializeParams =
                serde_json::from_value(request["params"].clone()).unwrap();
            let stale_request_support = params
                .capabilities
                .general
                .unwrap()
                .stale_request_support
                .unwrap();

            assert_eq!(request["method"], "initialize");
            assert!(
                !stale_request_support.cancel,
                "mcpls does not implement active in-flight request cancellation"
            );
            assert_eq!(
                stale_request_support.retry_on_content_modified,
                CONTENT_MODIFIED_RETRY_METHODS
                    .iter()
                    .map(ToString::to_string)
                    .collect::<Vec<_>>(),
                "the wire-advertised capability must match the methods LspClient::request \
                 actually retries -32801 for, not drift from it"
            );

            write_success_response(
                &mut server.read_half_stdin,
                &request["id"].clone(),
                serde_json::json!({ "capabilities": {} }),
            )
            .await;

            init_task.await.unwrap().unwrap();
        }

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

            let config = ServerInitConfig::new(
                LspServerConfig::rust_analyzer(),
                WorkspaceRoots::default(),
                PositionEncodings::DEFAULT,
                std::sync::Arc::default(),
            );

            let init_task =
                tokio::spawn(async move { LspServer::initialize(&client, &config).await });

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

            assert_eq!(request["method"], "initialize");
            assert_eq!(
                request["params"]["capabilities"]["experimental"]["serverStatusNotification"],
                serde_json::json!(true),
                "without this, rust-analyzer never emits experimental/serverStatus and the \
                 indexing-readiness gate in Translator::wait_for_indexing_ready is a \
                 permanent no-op"
            );

            write_success_response(
                &mut server.read_half_stdin,
                &request["id"].clone(),
                serde_json::json!({ "capabilities": {} }),
            )
            .await;

            init_task.await.unwrap().unwrap();
        }

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

            let config = ServerInitConfig::new(
                LspServerConfig::rust_analyzer(),
                WorkspaceRoots::default(),
                PositionEncodings::DEFAULT,
                std::sync::Arc::default(),
            );

            let init_task =
                tokio::spawn(async move { LspServer::initialize(&client, &config).await });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let request = read_framed_message(&mut reader).await;
            let params: InitializeParams =
                serde_json::from_value(request["params"].clone()).unwrap();
            let document_symbol = params
                .capabilities
                .text_document
                .unwrap()
                .document_symbol
                .unwrap();

            assert_eq!(request["method"], "initialize");
            assert_eq!(document_symbol.dynamic_registration, Some(false));
            assert_eq!(
                document_symbol.hierarchical_document_symbol_support,
                Some(true)
            );
            assert_eq!(
                document_symbol.symbol_kind.unwrap().value_set,
                Some(advertised_symbol_kinds())
            );

            write_success_response(
                &mut server.read_half_stdin,
                &request["id"].clone(),
                serde_json::json!({ "capabilities": {} }),
            )
            .await;

            init_task.await.unwrap().unwrap();
        }

        #[tokio::test]
        async fn test_initialize_accepts_resolved_dot_workspace_root() {
            let temp_dir = TempDir::new().unwrap();
            let base = dunce::canonicalize(temp_dir.path()).unwrap();
            let workspace_roots =
                crate::bridge::WorkspaceRoots::from_paths_with(&[PathBuf::from(".")], || {
                    Ok(crate::bridge::ProcessCwd::new(base.clone(), None))
                })
                .unwrap()
                .canonical()
                .to_vec();
            assert_eq!(workspace_roots, vec![base.clone()]);

            let (client, mut server) = fake_lsp_client();
            let config = ServerInitConfig::new(
                LspServerConfig::rust_analyzer(),
                WorkspaceRoots::for_test(workspace_roots, vec![]),
                PositionEncodings::DEFAULT,
                std::sync::Arc::default(),
            );

            let init_task =
                tokio::spawn(async move { LspServer::initialize(&client, &config).await });

            let mut reader = BufReader::new(&mut server.write_stdout);
            let request = read_framed_message(&mut reader).await;
            let expected_uri = try_path_to_uri(&base).unwrap();
            assert_eq!(
                request["params"]["workspaceFolders"][0]["uri"],
                expected_uri.as_ref()
            );

            write_success_response(
                &mut server.read_half_stdin,
                &request["id"].clone(),
                serde_json::json!({ "capabilities": {} }),
            )
            .await;

            init_task.await.unwrap().unwrap();
        }
    }

    /// #691: an override spelled `Path` is the `PATH` the child sees on Windows,
    /// so resolution must read it too; elsewhere it is another variable.
    #[test]
    fn child_env_var_compares_names_as_the_host_does() {
        let parent = |_: &str| Some(std::ffi::OsString::from("/parent"));
        let on = |host| {
            let mut config = bare_server_config(HashMap::new());
            config.env = crate::config::ServerEnv::from_entries(
                [(
                    crate::config::EnvKey::from_static("Path"),
                    crate::config::EnvValue::from_static("/over"),
                )],
                host,
            )
            .unwrap();
            child_env_var(&config, "PATH", parent)
        };

        assert_eq!(on(HostOs::Windows), Some(std::ffi::OsString::from("/over")));
        assert_eq!(on(HostOs::Other), Some(std::ffi::OsString::from("/parent")));
    }

    /// Minimal [`LspServerConfig`] for `build_command` tests, where only
    /// `command`/`args`/`env` matter.
    fn bare_server_config(
        env: HashMap<crate::config::EnvKey, crate::config::EnvValue>,
    ) -> LspServerConfig {
        LspServerConfig {
            language_id: LanguageId::from_static("test"),
            command: ServerCommand::from_static("irrelevant-for-build-command").into(),
            args: crate::config::ServerArgs::default(),
            env: crate::config::ServerEnv::from_entries(env, HostOs::CURRENT).unwrap(),
            file_patterns: vec![],
            initialization_options: None,
            settings: None,
            timeout_seconds: TimeoutSecs::new(5).unwrap(),
            request_timeout_seconds: TimeoutSecs::new(5).unwrap(),
            heuristics: None,
            name: None,
            handles: None,
            indexing: crate::bridge::IndexingPolicy::Auto,
        }
    }

    /// Collects the env vars a `Command` would set, resolving `env_clear`
    /// removals (`None` values from `get_envs`) away so the map reflects
    /// what the child process would actually see.
    fn effective_envs(command: &Command) -> HashMap<String, String> {
        command
            .as_std()
            .get_envs()
            .filter_map(|(k, v)| {
                v.map(|v| {
                    (
                        k.to_string_lossy().into_owned(),
                        v.to_string_lossy().into_owned(),
                    )
                })
            })
            .collect()
    }

    /// Regression test for #236/#246: a spawned LSP server used to inherit
    /// mcpls's entire environment. `build_command` must only pass through
    /// `ENV_PASSTHROUGH` keys from `parent_env`, not arbitrary ones.
    #[test]
    fn test_build_command_excludes_non_allowlisted_parent_env_vars() {
        let config = bare_server_config(HashMap::new());
        let command =
            LspServer::build_command(&config, &ChildWorkingDir::Inherit, |key| match key {
                "PATH" => Some("/parent/bin".into()),
                "MCPLS_TEST_LEAK_CANARY" => Some("should-not-reach-child".into()),
                _ => None,
            });

        let envs = effective_envs(&command);

        assert!(
            !envs.contains_key("MCPLS_TEST_LEAK_CANARY"),
            "non-allowlisted parent env var leaked into child command: {envs:?}"
        );

        // The assertion above is provably vacuous on its own:
        // `Command::get_envs()` only reports explicit `.env()`/`.envs()`
        // modifications and is blind to whether `.env_clear()` was called,
        // and `build_command`'s passthrough loop never even queries
        // `parent_env` for a key outside `ENV_PASSTHROUGH`, so it would
        // pass unchanged even if `.env_clear()` were deleted from
        // `build_command` entirely. `std::process::Command`'s `Debug` impl
        // does encode clearing, prefixing the formatted command with
        // `env -i ` on Unix once `.env_clear()` has run; assert on that to
        // actually guard against the clear being removed.
        #[cfg(unix)]
        assert!(
            format!("{:?}", command.as_std()).starts_with("env -i "),
            "build_command must call .env_clear() so the child doesn't inherit the full parent environment"
        );
    }

    /// Regression test for #236/#246: allowlisted vars present in the parent
    /// (e.g. `PATH`) must still reach the child.
    #[test]
    fn test_build_command_passes_through_allowlisted_env_vars() {
        let config = bare_server_config(HashMap::new());
        let command = LspServer::build_command(&config, &ChildWorkingDir::Inherit, |key| {
            (key == "PATH").then(|| "/parent/bin".into())
        });

        let envs = effective_envs(&command);

        assert_eq!(envs.get("PATH"), Some(&"/parent/bin".to_string()));
    }

    #[test]
    fn test_build_command_inherits_working_dir_unless_fixed() {
        let config = bare_server_config(HashMap::new());
        let inherited = LspServer::build_command(&config, &ChildWorkingDir::Inherit, |_| None);
        assert_eq!(inherited.as_std().get_current_dir(), None);

        let dir = PathBuf::from("/fixed/dir");
        let fixed =
            LspServer::build_command(&config, &ChildWorkingDir::Fixed(dir.clone()), |_| None);
        assert_eq!(fixed.as_std().get_current_dir(), Some(dir.as_path()));
    }

    #[test]
    fn test_server_init_config_defaults_to_inherited_working_dir() {
        let config = ServerInitConfig::new(
            LspServerConfig::rust_analyzer(),
            WorkspaceRoots::default(),
            PositionEncodings::DEFAULT,
            std::sync::Arc::default(),
        );
        assert_eq!(config.child_working_dir(), &ChildWorkingDir::Inherit);
        let fixed = config.with_child_working_dir(ChildWorkingDir::Fixed(PathBuf::from("/x")));
        assert_eq!(
            fixed.child_working_dir(),
            &ChildWorkingDir::Fixed(PathBuf::from("/x"))
        );
    }

    #[tokio::test]
    async fn test_for_respawn_keeps_the_config_and_pinned_tsserver() {
        let mut server_config = LspServerConfig::typescript();
        server_config.initialization_options =
            Some(serde_json::json!({"tsserver": {"path": "/pin/tsserver.js"}}));
        let config = ServerInitConfig::new(
            server_config,
            WorkspaceRoots::default(),
            PositionEncodings::DEFAULT,
            std::sync::Arc::default(),
        );
        assert_eq!(
            config.pinned_tsserver(),
            Some(PathBuf::from("/pin/tsserver.js"))
        );

        let respawn = config.for_respawn().await.unwrap();
        assert_eq!(
            respawn.server_config().initialization_options,
            config.server_config().initialization_options
        );
        assert_eq!(respawn.pinned_tsserver(), config.pinned_tsserver());
    }

    /// An auto-pinned server is re-planned on the blocking pool and the result
    /// keeps the entry's identity; a pin that no longer resolves is dropped.
    #[tokio::test]
    async fn test_for_respawn_replans_an_auto_pinned_server_off_the_runtime() {
        let mut server_config = LspServerConfig::typescript();
        server_config.initialization_options =
            Some(serde_json::json!({"tsserver": {"path": "/mcpls-test/stale/tsserver.js"}}));
        let config = ServerInitConfig::new(
            server_config,
            WorkspaceRoots::default(),
            PositionEncodings::DEFAULT,
            std::sync::Arc::default(),
        )
        .with_auto_pin(PathBuf::from("/mcpls-test/stale/tsserver.js"));

        let respawn = config.for_respawn().await.unwrap();

        assert_eq!(respawn.server_config().id(), config.server_config().id());
        assert_ne!(respawn.pinned_tsserver(), config.pinned_tsserver());
    }

    /// An untrusted server with `tool`, a file inside its boundary that is not
    /// executable yet, as its only argument.
    fn untrusted_init_naming_a_tool_argument() -> (tempfile::TempDir, PathBuf, ServerInitConfig) {
        let dir = tempfile::TempDir::new().unwrap();
        let workspace = dunce::canonicalize(dir.path()).unwrap();
        let tool = workspace.join("tool");
        std::fs::write(&tool, "").unwrap();
        let roots = WorkspaceRoots::from_paths(std::slice::from_ref(&workspace)).unwrap();
        let mut server_config = LspServerConfig::rust_analyzer();
        server_config.command = ServerCommand::from_static("mcpls-test-no-such-server").into();
        server_config.args =
            crate::config::ServerArgs::new([tool.to_string_lossy().into_owned()]).unwrap();
        let command = server_config.command.server_command().clone();
        let init = ServerInitConfig::new(
            server_config,
            roots.clone(),
            PositionEncodings::DEFAULT,
            std::sync::Arc::default(),
        )
        .with_trust(SpawnTrust::Untrusted(UntrustedVetting::new(roots, command)));
        (dir, tool, init)
    }

    /// Makes the file `tool` something the host would start.
    fn become_executable(tool: &Path) {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            std::fs::set_permissions(tool, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        #[cfg(windows)]
        std::fs::write(tool.with_added_extension("exe"), "").unwrap();
    }

    fn refused_argument(error: &Error) -> bool {
        matches!(
            error,
            Error::ServerFailedToStart(failure) if matches!(
                failure.reason,
                StartupFailure::RefusedUntrustedWorkspace(
                    UntrustedRefusal::WorkspaceExecutableArgument { index: 0, .. }
                )
            )
        )
    }

    /// Regression test for #736: the backstop runs again at spawn time.
    #[tokio::test]
    async fn test_spawn_refuses_an_argument_that_became_executable_after_planning() {
        let (_dir, tool, init) = untrusted_init_naming_a_tool_argument();
        init.vet_arguments().unwrap();

        become_executable(&tool);

        let Err(error) = LspServer::spawn(init).await else {
            panic!("the spawn must be refused");
        };
        assert!(refused_argument(&error), "{error:?}");
    }

    /// Regression test for #736: a respawn plan is a complete dry run.
    #[tokio::test]
    async fn test_for_respawn_refuses_an_argument_that_became_executable_after_planning() {
        let (_dir, tool, init) = untrusted_init_naming_a_tool_argument();
        let unchanged = init.for_respawn().await.unwrap();
        assert_eq!(unchanged.server_config().args, init.server_config().args);

        become_executable(&tool);

        let Err(error) = init.for_respawn().await else {
            panic!("the respawn plan must be refused");
        };
        assert!(refused_argument(&error), "{error:?}");
    }

    #[tokio::test]
    async fn test_a_trusted_config_is_never_vetted_at_spawn_time() {
        let (_dir, tool, init) = untrusted_init_naming_a_tool_argument();
        let trusted = ServerInitConfig::new(
            init.server_config().clone(),
            init.workspace_roots().clone(),
            PositionEncodings::DEFAULT,
            std::sync::Arc::default(),
        );
        become_executable(&tool);

        trusted.vet_arguments().unwrap();
        trusted.vet_arguments_off_runtime().await.unwrap();
        trusted.for_respawn().await.unwrap();
    }

    /// The `shutdown` result is `null` by the specification; a server that
    /// answers with another value still gets the `exit` that follows.
    #[tokio::test(start_paused = true)]
    async fn test_terminate_sends_exit_after_a_shutdown_answer_that_is_not_null() {
        use tokio::io::BufReader;

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

        let (client, mut fake) = fake_lsp_client();
        let mut server = LspServer {
            client,
            capabilities: lsp_types::ServerCapabilities::default(),
            position_encoding: PositionEncodingKind::UTF8,
            child: None,
            init_config: crate::test_lsp::init_config_for(LspServerConfig::rust_analyzer()),
        };
        let terminating = tokio::spawn(async move {
            server
                .terminate(SHUTDOWN_TIMEOUT, ExitGrace::WithinBudget)
                .await
        });
        let mut wire = BufReader::new(&mut fake.write_stdout);

        let request = read_framed_message(&mut wire).await;
        assert_eq!(request["method"], "shutdown");
        write_response(
            &mut fake.read_half_stdin,
            &request["id"],
            serde_json::json!({}),
        )
        .await;
        let exit = read_framed_message(&mut wire).await;

        assert_eq!(exit["method"], "exit");
        assert_matches!(terminating.await.unwrap(), Ok(()));
    }

    /// Regression test for #247: `LspServerConfig::env` entries must reach
    /// the spawned child (previously dead configuration).
    #[test]
    fn test_build_command_includes_configured_env_vars() {
        let mut env = HashMap::new();
        env.insert(
            crate::config::EnvKey::from_static("MCPLS_TEST_CONFIGURED"),
            crate::config::EnvValue::from_static("from-server-config"),
        );
        let config = bare_server_config(env);
        let command = LspServer::build_command(&config, &ChildWorkingDir::Inherit, |_| None);

        let envs = effective_envs(&command);

        assert_eq!(
            envs.get("MCPLS_TEST_CONFIGURED"),
            Some(&"from-server-config".to_string())
        );
    }

    /// Regression test for #247: a `LspServerConfig::env` entry must be able
    /// to override an allowlisted passthrough value, since `config.env` is
    /// applied after the passthrough loop in `build_command`.
    #[test]
    fn test_build_command_configured_env_overrides_allowlisted_var() {
        let mut env = HashMap::new();
        env.insert(
            crate::config::EnvKey::from_static("PATH"),
            crate::config::EnvValue::from_static("/configured/override/path"),
        );
        let config = bare_server_config(env);
        let command = LspServer::build_command(&config, &ChildWorkingDir::Inherit, |key| {
            (key == "PATH").then(|| "/parent/bin".into())
        });

        let envs = effective_envs(&command);

        assert_eq!(
            envs.get("PATH"),
            Some(&"/configured/override/path".to_string())
        );
    }

    /// #174 section 8 regression: the diagnostics route must be read from the
    /// router as re-derived after the explicit diagnostics server failed, not
    /// from the configured one. A narrow "diagnostics-only" server
    /// (`pyright-diag`) fails to start, leaving only a catch-all (`pylsp`);
    /// resolving `Diagnostics` against the configured router would name the
    /// dead `pyright-diag` and silence diagnostics for `python`.
    #[tokio::test]
    async fn test_settling_dead_diagnostics_server_hands_the_route_to_the_catch_all() {
        use crate::bridge::Translator;
        use crate::config::{ServerId, ToolKind, ToolRouter};

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

        translator.settle_failed(&ServerSpawnFailure {
            server_id: ServerId::from_static("pyright-diag"),
            language_id: LanguageId::from_static("python"),
            command: ServerCommand::from_static("pyright-langserver"),
            reason: StartupFailure::InitTaskPanicked,
        });
        translator.settle_started(fake_lsp_server_with_config(configs[1].clone()));

        assert!(
            translator.is_diagnostics_route(&LanguageId::from_static("python"), &pylsp_id),
            "pylsp must inherit the diagnostics route once pyright-diag is known dead"
        );
    }
}