codescout 0.14.0

High-performance coding agent toolkit MCP server
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
//! Async LSP client: spawns a language server subprocess and communicates
//! via JSON-RPC over stdio.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::sync::{Arc, Mutex as StdMutex};

use anyhow::{bail, Context, Result};
use serde_json::{json, Value};
use tokio::io::AsyncWrite;
use tokio::io::BufReader;
use tokio::process::Command;
use tokio::sync::{oneshot, Mutex};
use tokio::task::JoinHandle;

/// Pending outbound request map: request ID → response channel.
type PendingRequests = Arc<StdMutex<HashMap<i64, oneshot::Sender<Result<Value>>>>>;

use super::transport;
use crate::tools::RecoverableError;

/// Maximum number of stderr lines retained in the shared buffer.
///
/// Only error/exception/fatal lines are buffered (others are debug-logged and
/// dropped). The buffer is checked during `initialize()` to detect fatal
/// conditions (e.g. kotlin-lsp "Multiple editing sessions"). Older lines are
/// evicted once the cap is reached to prevent unbounded growth for long-lived
/// or unusually noisy server processes.
const MAX_STDERR_LINES: usize = 200;

use super::call_hierarchy::supports_call_hierarchy;

/// Convert an LSP URI to a filesystem path.
///
/// Delegates to [`crate::util::file_address::FileAddress::from_lsp_uri`] for the
/// canonical conversion. Falls back to `PathBuf::from(uri.path())` when neither
/// the URI parse nor the raw-path component yields a value (empty URI), to
/// preserve the original infallible signature.
fn uri_to_path(uri: &lsp_types::Uri) -> PathBuf {
    crate::util::file_address::FileAddress::from_lsp_uri(uri)
        .map(crate::util::file_address::FileAddress::into_path)
        .unwrap_or_else(|| PathBuf::from(uri.path().as_str()))
}

/// Convert a filesystem path to an LSP `file://` URI.
///
/// Delegates to [`crate::util::file_address::FileAddress::as_lsp_uri`].
fn path_to_uri(path: &Path) -> Result<lsp_types::Uri> {
    crate::util::file_address::FileAddress::from_path(path).as_lsp_uri()
}

/// Return true if the given LSP method is safe to retry after a
/// `-32800 RequestCancelled` response.
///
/// Idempotent methods only return information — retrying them may do extra
/// work server-side but does not double-apply any mutation. Methods like
/// `textDocument/rename` or `workspace/applyEdit` MAY have partially mutated
/// state before the cancellation, so retrying can double-apply edits.
fn is_idempotent_lsp_method(method: &str) -> bool {
    matches!(
        method,
        "textDocument/documentSymbol"
            | "textDocument/references"
            | "textDocument/hover"
            | "textDocument/definition"
            | "textDocument/declaration"
            | "textDocument/typeDefinition"
            | "textDocument/implementation"
            | "textDocument/completion"
            | "textDocument/signatureHelp"
            | "textDocument/codeAction"
            | "textDocument/codeLens"
            | "textDocument/foldingRange"
            | "textDocument/selectionRange"
            | "textDocument/prepareRename"
            | "textDocument/prepareCallHierarchy"
            | "callHierarchy/incomingCalls"
            | "callHierarchy/outgoingCalls"
            | "workspace/symbol"
            | "initialize"
    )
}

/// Transient LSP error codes that warrant an automatic retry.
///
/// - `-32800` `RequestCancelled` — server cancelled mid-request (typically
///   workspace lock contention or cold-start indexing).
/// - `-32801` `ContentModified` — server's analysis snapshot advanced
///   between request issue and response (typical during indexer warmup
///   right after `/mcp` reconnect; rust-analyzer publishes new diagnostics
///   and cancels any in-flight requests against the stale snapshot).
///
/// Both are explicitly "retry on the new snapshot" signals per the LSP
/// spec. We treat them identically — same backoff, same idempotency guard.
fn is_retryable_lsp_error(err: &anyhow::Error) -> bool {
    let s = err.to_string();
    s.contains("code -32800") || s.contains("code -32801")
}

/// Return true if cold-start's extended retry budget makes sense for `method`.
///
/// Most LSP queries that return `-32800 RequestCancelled` during cold start
/// become answerable per-file as the server parses each file, so retrying
/// for ~45s catches them. But `workspace/symbol` stays unanswerable until
/// the *whole* project is indexed (minutes for large Rust/Kotlin projects),
/// and a 45s retry budget + 30s per-attempt timeout blows through the MCP
/// 60s tool timeout. For that method we keep the short warm budget and let
/// callers (e.g. `symbols`) fail over to tree-sitter quickly.
fn uses_cold_start_retry_budget(method: &str) -> bool {
    !matches!(method, "workspace/symbol")
}

/// Cold-start retry count for LSP requests, scaled by host OS.
///
/// rust-analyzer and the Kotlin LSP cold-start are documented in the codescout
/// `gotchas` memory as 2–3× slower on Windows than Linux; macOS sits in between
/// under rosetta/ARM heterogeneity. The platform variance is largest at the
/// tail (slow startups), not the median, so scaling the retry **count** keeps
/// first-attempt latency identical on every platform — we only add more
/// attempts before giving up.
///
/// The retry delay (`RETRY_DELAY_COLD_MS`) and cold-start window
/// (`COLD_START_WINDOW`) deliberately stay platform-uniform; only the retry
/// count varies. `cfg!` is const-stable, so the body resolves at compile time
/// and the caller still treats the result as a plain `const usize`.
const fn cold_start_max_retries() -> usize {
    if cfg!(target_os = "windows") {
        20
    } else if cfg!(target_os = "macos") {
        15
    } else {
        10
    }
}

/// Scan a stderr line buffer for patterns that make LSP-side retries pointless.
///
/// Pure helper so it can be exercised in unit tests without spinning up a real
/// server. Add new patterns here when we encounter additional permanent-failure
/// modes (as opposed to transient ones that legitimately benefit from retry).
fn detect_fatal_stderr(lines: &[String]) -> Option<RecoverableError> {
    for line in lines {
        if line.contains("Multiple editing sessions") {
            return Some(RecoverableError::with_hint(
                "kotlin-lsp rejected this workspace: \
                 \"Multiple editing sessions for one workspace are not supported yet\"",
                "Another codescout instance or editor is already serving this \
                 project with kotlin-lsp. Only one Kotlin LSP session per \
                 workspace is allowed in the current kotlin-lsp release. \
                 Stop the other session and retry.",
            ));
        }
        if line.contains("Unknown binary 'rust-analyzer'") {
            return Some(RecoverableError::with_hint(
                "rust-analyzer is unreachable. The rustup shim is on PATH but the \
                 component is not installed: \
                 \"error: Unknown binary 'rust-analyzer' in official toolchain\"",
                "Run `rustup component add rust-analyzer` to install it for the active \
                 toolchain, or install rust-analyzer outside rustup \
                 (https://rust-analyzer.github.io). Rust LSP tools (edit_code, symbols, \
                 references, call_graph on .rs files) will keep returning this error \
                 until rust-analyzer launches successfully.",
            ));
        }
    }
    None
}

/// Convert hierarchical `DocumentSymbol[]` into our `SymbolInfo` tree.
fn convert_document_symbols(
    symbols: &[lsp_types::DocumentSymbol],
    file: &PathBuf,
    parent_path: &str,
) -> Vec<super::SymbolInfo> {
    symbols
        .iter()
        .map(|ds| {
            let name_path = if parent_path.is_empty() {
                ds.name.clone()
            } else {
                format!("{}/{}", parent_path, ds.name)
            };
            let children = ds
                .children
                .as_ref()
                .map(|c| convert_document_symbols(c, file, &name_path))
                .unwrap_or_default();
            super::SymbolInfo {
                name: ds.name.clone(),
                name_path: name_path.clone(),
                kind: ds.kind.into(),
                file: file.clone(),
                start_line: ds.selection_range.start.line,
                end_line: ds.range.end.line,
                start_col: ds.selection_range.start.character,
                range_start_line: Some(ds.range.start.line),
                children,
                detail: ds.detail.clone().filter(|s| !s.is_empty()),
            }
        })
        .collect()
}

/// Configuration for launching a language server.
#[derive(Debug, Clone)]
pub struct LspServerConfig {
    pub command: String,
    #[allow(dead_code)]
    pub args: Vec<String>,
    pub workspace_root: std::path::PathBuf,
    /// Timeout for the LSP `initialize` handshake. JVM-based servers need longer.
    /// Defaults to 30s if not set.
    pub init_timeout: Option<std::time::Duration>,
    /// If true, this language uses the LSP multiplexer for shared instances.
    pub mux: bool,
    /// Additional environment variables for the LSP server process.
    pub env: Vec<(String, String)>,
    /// Seconds the mux process waits with no connected clients before
    /// exiting. Only used when `mux == true`. `None` falls back to the
    /// mux default of 300s. Ignored on the direct-process path.
    pub idle_timeout_secs: Option<u64>,
}

/// How this LspClient is connected to its language server.
#[derive(Debug)]
#[allow(dead_code)] // Socket variant used in Task 3 (LspClient::connect)
pub(crate) enum LspTransport {
    /// Direct child process (normal LSP servers).
    Process { child_pid: Option<u32> },
    /// Connected to a mux socket (shared LSP servers like kotlin-lsp).
    Socket { socket_path: std::path::PathBuf },
}

/// A running LSP client session connected to a language server process.
pub struct LspClient {
    writer: Arc<Mutex<Box<dyn AsyncWrite + Unpin + Send>>>,
    #[allow(dead_code)]
    next_id: AtomicI64,
    #[allow(dead_code)]
    pending: Arc<StdMutex<HashMap<i64, oneshot::Sender<Result<Value>>>>>,
    #[allow(dead_code)]
    alive: Arc<AtomicBool>,
    #[allow(dead_code)]
    reader_handle: StdMutex<Option<JoinHandle<()>>>,
    pub workspace_root: std::path::PathBuf,
    #[allow(dead_code)]
    pub(crate) capabilities: StdMutex<lsp_types::ServerCapabilities>,
    transport: LspTransport,
    /// Timeout for the LSP initialize handshake.
    init_timeout: std::time::Duration,
    /// Tracks files opened via textDocument/didOpen, mapped to their current document version.
    /// The LSP spec requires a monotonically increasing version on every didOpen/didChange.
    /// Keys are canonicalized paths to avoid symlink/relative-path aliases.
    /// The spec prohibits sending didOpen for an already-open file without an
    /// intervening didClose; some servers (e.g. kotlin-lsp) error on duplicates.
    open_files: StdMutex<HashMap<PathBuf, i32>>,
    /// Collects stderr lines from the server process. Checked during init retries
    /// to detect fatal errors (e.g. kotlin-lsp "Multiple editing sessions").
    stderr_lines: Arc<StdMutex<Vec<String>>>,
    /// Wall-clock instant when the LSP client was constructed. Used as a
    /// fallback anchor for the cold-start window if init hasn't completed yet.
    pub(crate) started_at: std::time::Instant,
    /// Set when the LSP `initialize` handshake completes successfully. The
    /// cold-start retry window is measured from this point, not from
    /// construction — otherwise a slow kotlin-lsp init (5+ min Gradle import)
    /// consumes the whole budget before the first user request.
    pub(crate) init_completed_at: std::sync::OnceLock<std::time::Instant>,
}

impl LspClient {
    /// Dispatch a single incoming LSP message to the appropriate pending sender,
    /// or auto-respond null to server-to-client requests.
    ///
    /// Shared by the reader tasks in [`LspClient::start`] (process transport) and
    /// [`LspClient::connect`] (socket/mux transport). Both loops are structurally
    /// identical in the `Ok` branch; they differ only in error handling (process
    /// exit diagnostics vs. mux disconnection).
    ///
    /// `request_label` and `notification_label` control the tracing output so log
    /// lines identify the transport in use.
    async fn dispatch_lsp_message(
        msg: Value,
        pending: &PendingRequests,
        writer: &Arc<Mutex<Box<dyn AsyncWrite + Unpin + Send>>>,
        request_label: &str,
        notification_label: &str,
    ) {
        if let Some(id) = msg.get("id").and_then(|v| v.as_i64()) {
            if msg.get("method").is_some() {
                // Server-to-client request. Auto-respond null so the server doesn't stall.
                tracing::debug!(
                    "{} (id={}): {} — auto-responding null",
                    request_label,
                    id,
                    msg["method"]
                );
                let response = serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": id,
                    "result": null,
                });
                let mut w = writer.lock().await;
                let _ = transport::write_message(&mut *w, &response).await;
            } else {
                // Response to one of our outbound requests.
                if let Some(sender) = pending
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .remove(&id)
                {
                    if let Some(error) = msg.get("error") {
                        let err_msg = error["message"].as_str().unwrap_or("unknown LSP error");
                        let _ = sender.send(Err(anyhow::anyhow!(
                            "LSP error (code {}): {}",
                            error["code"],
                            err_msg
                        )));
                    } else {
                        let result = msg.get("result").cloned().unwrap_or(Value::Null);
                        let _ = sender.send(Ok(result));
                    }
                }
            }
        } else if let Some(method) = msg.get("method").and_then(|v| v.as_str()) {
            tracing::debug!("{}: {}", notification_label, method);
        }
    }

    /// Read messages from `reader` and dispatch them via `dispatch_lsp_message`
    /// until a transport error occurs. Returns the error so callers can run
    /// transport-specific cleanup before draining pending requests.
    async fn run_dispatch_loop<R>(
        mut reader: BufReader<R>,
        pending: PendingRequests,
        writer: Arc<Mutex<Box<dyn AsyncWrite + Unpin + Send>>>,
        request_label: &'static str,
        notif_label: &'static str,
    ) -> anyhow::Error
    where
        R: tokio::io::AsyncRead + Unpin + Send + 'static,
    {
        loop {
            match transport::read_message(&mut reader).await {
                Ok(msg) => {
                    Self::dispatch_lsp_message(msg, &pending, &writer, request_label, notif_label)
                        .await;
                }
                Err(e) => return e,
            }
        }
    }

    /// Drain all pending requests with a disconnect error message.
    fn drain_pending_disconnect(pending: &PendingRequests, msg: &'static str) {
        let mut map = pending.lock().unwrap_or_else(|e| e.into_inner());
        for (_, sender) in map.drain() {
            let _ = sender.send(Err(anyhow::anyhow!(msg)));
        }
    }

    /// Start a language server process and perform the LSP initialize handshake.
    /// Start a language server process and perform the LSP initialize handshake.
    pub async fn start(config: LspServerConfig) -> Result<Self> {
        tracing::info!("Starting LSP server: {} {:?}", config.command, config.args);

        let mut cmd = Command::new(&config.command);
        cmd.args(&config.args)
            .current_dir(&config.workspace_root)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .kill_on_drop(true);
        for (key, val) in &config.env {
            cmd.env(key, val);
        }
        let mut child = cmd
            .spawn()
            .with_context(|| format!("Failed to start LSP server: {}", config.command))?;

        // These `.take().expect()` calls are infallible: stdin, stdout, and stderr are
        // configured as `Stdio::piped()` in the Command builder immediately above, so
        // tokio guarantees they are `Some` after a successful spawn.
        let stdin = child.stdin.take().expect("stdin must be piped");
        let stdout = child.stdout.take().expect("stdout must be piped");
        let stderr = child.stderr.take().expect("stderr must be piped");
        let child_pid = child.id();
        tracing::debug!(
            pid = ?child_pid,
            binary = %config.command,
            "LSP server spawned"
        );

        let pending: PendingRequests = Arc::new(StdMutex::new(HashMap::new()));
        let alive = Arc::new(AtomicBool::new(true));

        // Wrap writer in Arc so the reader task can share it for auto-responses.
        let writer = Arc::new(Mutex::new(
            Box::new(stdin) as Box<dyn AsyncWrite + Unpin + Send>
        ));

        // Shared stderr buffer — checked by initialize() to detect fatal errors.
        let stderr_lines: Arc<StdMutex<Vec<String>>> = Arc::new(StdMutex::new(Vec::new()));
        let stderr_lines_clone = stderr_lines.clone();

        // Spawn stderr reader (logs server stderr, populates shared buffer)
        tokio::spawn(async move {
            let mut reader = BufReader::new(stderr);
            let mut line = String::new();
            loop {
                line.clear();
                match tokio::io::AsyncBufReadExt::read_line(&mut reader, &mut line).await {
                    Ok(0) => break,
                    Ok(_) => {
                        let trimmed = line.trim_end();
                        let lower = trimmed.to_lowercase();
                        if lower.contains("error")
                            || lower.contains("exception")
                            || lower.contains("fatal")
                        {
                            tracing::warn!(target: "lsp_stderr", "{}", trimmed);
                            let mut buf =
                                stderr_lines_clone.lock().unwrap_or_else(|e| e.into_inner());
                            if buf.len() >= MAX_STDERR_LINES {
                                buf.remove(0);
                            }
                            buf.push(trimmed.to_string());
                        } else {
                            tracing::debug!(target: "lsp_stderr", "{}", trimmed);
                        }
                    }
                    Err(_) => break,
                }
            }
        });

        // Spawn stdout reader task — dispatches responses to pending senders
        let pending_clone = pending.clone();
        let alive_clone = alive.clone();
        let writer_clone = writer.clone();
        let reader_handle = tokio::spawn(async move {
            let read_err = Self::run_dispatch_loop(
                BufReader::new(stdout),
                pending_clone.clone(),
                writer_clone,
                "LSP server request",
                "LSP notification",
            )
            .await;
            // EOF or read error — server crashed or exited
            if alive_clone.load(Ordering::SeqCst) {
                tracing::warn!("LSP reader error: {}", read_err);
            }
            // Try to get the exit status for diagnostics.
            // try_wait() returns Ok(None) if the child is still running (rare at EOF),
            // Ok(Some(status)) if it has exited, or Err if the call itself failed.
            match child.try_wait() {
                Ok(Some(status)) => {
                    tracing::warn!(exit_status = ?status, "LSP server exited")
                }
                Ok(None) => tracing::warn!("LSP reader EOF but child still running"),
                Err(wait_err) => {
                    tracing::warn!("could not get LSP exit status: {wait_err}")
                }
            }
            alive_clone.store(false, Ordering::SeqCst);
            Self::drain_pending_disconnect(&pending_clone, "LSP server disconnected");
            // Wait for child to exit (kill_on_drop will handle cleanup)
            let _ = child.wait().await;
        });
        let init_timeout = config
            .init_timeout
            .unwrap_or(std::time::Duration::from_secs(30));

        let client = Self {
            writer,
            next_id: AtomicI64::new(1),
            pending,
            alive,
            reader_handle: StdMutex::new(Some(reader_handle)),
            workspace_root: config.workspace_root.clone(),
            capabilities: StdMutex::new(lsp_types::ServerCapabilities::default()),
            transport: LspTransport::Process { child_pid },
            init_timeout,
            open_files: StdMutex::new(HashMap::new()),
            stderr_lines,
            started_at: std::time::Instant::now(),
            init_completed_at: std::sync::OnceLock::new(),
        };

        // Perform the LSP initialize handshake
        client.initialize().await?;

        Ok(client)
    }

    /// Connect to an existing mux socket instead of spawning a process.
    ///
    /// The mux sends a JSON init message immediately on connect containing
    /// the cached `InitializeResult`. This client does NOT perform the LSP
    /// initialize handshake.
    #[cfg(unix)]
    pub async fn connect(
        socket_path: &std::path::Path,
        workspace_root: std::path::PathBuf,
    ) -> Result<Self> {
        use tokio::net::UnixStream;

        let stream = UnixStream::connect(socket_path)
            .await
            .with_context(|| format!("Failed to connect to mux socket: {:?}", socket_path))?;

        let (read_half, write_half) = stream.into_split();

        let pending: PendingRequests = Arc::new(StdMutex::new(HashMap::new()));
        let alive = Arc::new(AtomicBool::new(true));
        let writer: Arc<Mutex<Box<dyn AsyncWrite + Unpin + Send>>> =
            Arc::new(Mutex::new(Box::new(write_half)));

        // Read init message from the mux — contains the cached InitializeResult
        // so we skip the full LSP handshake.
        let mut buf_reader = BufReader::new(read_half);
        let init_msg = transport::read_message(&mut buf_reader)
            .await
            .context("Failed to read mux init message")?;

        let capabilities = if let Some(result) = init_msg.get("result") {
            let init_result: lsp_types::InitializeResult =
                serde_json::from_value(result.clone())
                    .context("Failed to parse InitializeResult from mux")?;
            init_result.capabilities
        } else {
            tracing::warn!("Mux init message missing 'result' field, using default capabilities");
            lsp_types::ServerCapabilities::default()
        };

        // Spawn reader task — dispatches responses to pending senders.
        let pending_clone = pending.clone();
        let alive_clone = alive.clone();
        let writer_clone = writer.clone();
        let reader_handle = tokio::spawn(async move {
            let _read_err = Self::run_dispatch_loop(
                buf_reader,
                pending_clone.clone(),
                writer_clone,
                "mux forwarded server request",
                "LSP notification from mux",
            )
            .await;
            alive_clone.store(false, Ordering::SeqCst);
            Self::drain_pending_disconnect(&pending_clone, "Mux connection lost");
        });

        Ok(Self {
            writer,
            next_id: AtomicI64::new(1),
            pending,
            alive,
            reader_handle: StdMutex::new(Some(reader_handle)),
            workspace_root,
            capabilities: StdMutex::new(capabilities),
            transport: LspTransport::Socket {
                socket_path: socket_path.to_path_buf(),
            },
            init_timeout: std::time::Duration::from_secs(30),
            open_files: StdMutex::new(HashMap::new()),
            stderr_lines: Arc::new(StdMutex::new(Vec::new())),
            started_at: std::time::Instant::now(),
            init_completed_at: std::sync::OnceLock::new(),
        })
    }

    /// Send a JSON-RPC request and await the response.
    pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
        // During the cold-start indexing window (e.g. Gradle import for kotlin-lsp),
        // the server returns -32800 (RequestCancelled) for every query. We use a
        // patient retry window while fresh, and a short one once warm.
        //
        // Cold: cold_start_max_retries() retries × 3 s linear backoff.
        //       Linux ≈ 45 s max, macOS ≈ 67 s, Windows ≈ 90 s (per
        //       `cold_start_max_retries`).
        // Warm:  3 retries × 300 ms linear backoff ≈ 1.2 s max wait.
        const COLD_START_WINDOW: std::time::Duration = std::time::Duration::from_secs(5 * 60);
        const MAX_RETRIES_COLD: usize = cold_start_max_retries();
        const RETRY_DELAY_COLD_MS: u64 = 3_000;
        const MAX_RETRIES_WARM: usize = 3;
        const RETRY_DELAY_WARM_MS: u64 = 300;

        // Anchor cold-start budget at init completion if we have it; otherwise
        // fall back to construction time so in-flight init requests still
        // benefit from the patient window.
        let anchor = self.init_completed_at.get().unwrap_or(&self.started_at);
        let in_cold_start = anchor.elapsed() < COLD_START_WINDOW;
        let (max_retries, retry_delay_ms) = if in_cold_start && uses_cold_start_retry_budget(method)
        {
            (MAX_RETRIES_COLD, RETRY_DELAY_COLD_MS)
        } else {
            (MAX_RETRIES_WARM, RETRY_DELAY_WARM_MS)
        };

        // Only retry idempotent methods on transient LSP errors (-32800
        // RequestCancelled, -32801 ContentModified). Retrying a non-idempotent
        // method like textDocument/rename risks double-applying an edit if
        // the server cancelled AFTER performing the operation.
        let retry_on_cancel = is_idempotent_lsp_method(method);
        let effective_max_retries = if retry_on_cancel { max_retries } else { 0 };

        let mut last_err = None;
        for attempt in 0..=effective_max_retries {
            if attempt > 0 {
                let delay = std::time::Duration::from_millis(retry_delay_ms * attempt as u64);
                tokio::time::sleep(delay).await;
                tracing::debug!(
                    "LSP transient error, retrying {}/{}: {} (cold_start={})",
                    attempt,
                    effective_max_retries,
                    method,
                    in_cold_start,
                );
            }
            match self
                .request_with_timeout(method, params.clone(), std::time::Duration::from_secs(30))
                .await
            {
                Ok(result) => return Ok(result),
                Err(e) if is_retryable_lsp_error(&e) => {
                    if !retry_on_cancel {
                        // Surface as RecoverableError so sibling tool calls
                        // survive and the caller can retry at a higher level
                        // where the semantics are known.
                        return Err(RecoverableError::with_hint(
                            format!("LSP cancelled non-idempotent request: {method}"),
                            "The server cancelled mid-operation. Retry is unsafe here because \
                             the edit may have partially applied. Re-issue the request manually.",
                        )
                        .into());
                    }
                    last_err = Some(e);
                }
                Err(e) => return Err(e),
            }
        }
        Err(last_err.unwrap())
    }

    #[tracing::instrument(skip(self, params, timeout), fields(lsp_method = %method))]
    pub async fn request_with_timeout(
        &self,
        method: &str,
        params: Value,
        timeout: std::time::Duration,
    ) -> Result<Value> {
        if !self.alive.load(Ordering::SeqCst) {
            return Err(RecoverableError::with_hint(
                "LSP server is not running",
                "The language server exited or failed to start. Try re-activating the \
                 project or check logs for server startup errors.",
            )
            .into());
        }

        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
        let (tx, rx) = oneshot::channel();

        self.pending
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .insert(id, tx);

        let msg = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params,
        });

        {
            let mut writer = self.writer.lock().await;
            if let Err(e) = transport::write_message(&mut *writer, &msg).await {
                self.pending
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .remove(&id);
                return Err(e);
            }
        }

        // Await response with timeout
        match tokio::time::timeout(timeout, rx).await {
            Ok(Ok(result)) => {
                match &result {
                    Ok(v) => {
                        tracing::debug!(response_bytes = v.to_string().len(), "lsp response");
                    }
                    Err(e) => {
                        tracing::debug!(error = %e, "lsp response error");
                    }
                }
                result
            }
            Ok(Err(_)) => bail!("LSP response channel closed"),
            Err(_) => {
                self.pending
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .remove(&id);
                // Tell the server to stop working on this id — otherwise it
                // keeps computing (real CPU waste for slow kotlin-lsp /
                // rust-analyzer queries during Gradle or Cargo load).
                let _ = self.notify("$/cancelRequest", json!({ "id": id })).await;
                Err(RecoverableError::with_hint(
                    format!(
                        "LSP request timed out after {}s: {}",
                        timeout.as_secs(),
                        method
                    ),
                    "The server did not respond in time. This is common during cold \
                     start or heavy indexing; retry in a moment.",
                )
                .into())
            }
        }
    }

    /// Send a JSON-RPC notification (no response expected).
    pub async fn notify(&self, method: &str, params: Value) -> Result<()> {
        if !self.alive.load(Ordering::SeqCst) {
            return Err(RecoverableError::with_hint(
                "LSP server is not running",
                "The language server exited or failed to start.",
            )
            .into());
        }

        let msg = json!({
            "jsonrpc": "2.0",
            "method": method,
            "params": params,
        });

        let mut writer = self.writer.lock().await;
        transport::write_message(&mut *writer, &msg).await
    }

    /// Scan the buffered server stderr for patterns that make further
    /// retries pointless. Returns a `RecoverableError` with a user-facing
    /// hint if a known-fatal pattern is present.
    ///
    /// The caller is expected to surface the error to the tool layer; sibling
    /// tool calls should keep working. Add new patterns here as we encounter
    /// more permanent-failure modes.
    fn fatal_stderr_hint(&self) -> Option<RecoverableError> {
        let stderr = self.stderr_lines.lock().unwrap_or_else(|e| e.into_inner());
        detect_fatal_stderr(&stderr)
    }

    /// Perform the LSP initialize/initialized handshake.
    ///
    /// Retries on -32800 (RequestCancelled) because JVM-based servers like
    /// kotlin-lsp may return this during early JVM bootstrap before they're
    /// ready to handle the initialize request.
    async fn initialize(&self) -> Result<()> {
        let root_uri = path_to_uri(&self.workspace_root)?;

        let params = lsp_types::InitializeParams {
            process_id: Some(std::process::id()),
            capabilities: lsp_types::ClientCapabilities {
                text_document: Some(lsp_types::TextDocumentClientCapabilities {
                    document_symbol: Some(lsp_types::DocumentSymbolClientCapabilities {
                        hierarchical_document_symbol_support: Some(true),
                        ..Default::default()
                    }),
                    references: Some(lsp_types::DynamicRegistrationClientCapabilities {
                        dynamic_registration: Some(false),
                    }),
                    definition: Some(lsp_types::GotoCapability {
                        dynamic_registration: Some(false),
                        link_support: Some(false),
                    }),
                    rename: Some(lsp_types::RenameClientCapabilities {
                        prepare_support: Some(true),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            },
            workspace_folders: Some(vec![lsp_types::WorkspaceFolder {
                uri: root_uri,
                name: self
                    .workspace_root
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_default(),
            }]),
            ..Default::default()
        };

        // Retry on -32800 (RequestCancelled) during initialization.
        // JVM-based servers (kotlin-lsp) may cancel the init request while
        // still bootstrapping their platform subsystems.
        const MAX_INIT_RETRIES: usize = 5;
        const INIT_RETRY_DELAY_MS: u64 = 3000;

        let params_value = serde_json::to_value(params)?;
        let mut last_err = None;
        for attempt in 0..=MAX_INIT_RETRIES {
            if attempt > 0 {
                let delay = std::time::Duration::from_millis(INIT_RETRY_DELAY_MS * attempt as u64);
                tokio::time::sleep(delay).await;
                tracing::info!(
                    "LSP initialize cancelled, retrying {}/{}: {}",
                    attempt,
                    MAX_INIT_RETRIES,
                    self.workspace_root.display()
                );
            }
            // Pre-flight stderr check: a fatal error (e.g. kotlin-lsp
            // "Multiple editing sessions") may have been emitted between
            // attempts. Retrying would just spawn another doomed request.
            if let Some(fatal) = self.fatal_stderr_hint() {
                return Err(fatal.into());
            }
            match self
                .request_with_timeout("initialize", params_value.clone(), self.init_timeout)
                .await
            {
                Ok(result) => {
                    // Parse and store server capabilities
                    let init_result: lsp_types::InitializeResult = serde_json::from_value(result)?;
                    *self.capabilities.lock().unwrap_or_else(|e| e.into_inner()) =
                        init_result.capabilities;

                    // Send initialized notification
                    self.notify("initialized", json!({})).await?;

                    // Anchor the cold-start retry budget here, not at construction.
                    // A slow kotlin-lsp init (5+ min Gradle import) used to burn
                    // the whole window before the first user request.
                    let _ = self.init_completed_at.set(std::time::Instant::now());

                    tracing::info!("LSP server initialized successfully");
                    return Ok(());
                }
                Err(e) => {
                    // Any error path (-32800, timeout, disconnect, …): check
                    // stderr for fatal patterns before deciding whether to
                    // retry. The original code only checked on -32800, which
                    // missed the common case where kotlin-lsp crashes mid-init
                    // and the next attempt times out or hits a closed pipe
                    // rather than -32800.
                    if let Some(fatal) = self.fatal_stderr_hint() {
                        return Err(fatal.into());
                    }
                    if e.to_string().contains("code -32800") {
                        last_err = Some(e);
                    } else {
                        return Err(e);
                    }
                }
            }
        }
        Err(last_err.unwrap())
    }

    /// Check if the server process is still alive.
    pub fn is_alive(&self) -> bool {
        self.alive.load(Ordering::SeqCst)
    }

    /// Gracefully shut down the LSP server.
    pub async fn shutdown(&self) -> Result<()> {
        if !self.alive.load(Ordering::SeqCst) {
            return Ok(());
        }

        // Send shutdown request
        let _ = self.request("shutdown", Value::Null).await;

        // Send exit notification
        let _ = self.notify("exit", Value::Null).await;

        // Mark as dead
        self.alive.store(false, Ordering::SeqCst);

        // Wait for reader task to finish (with timeout)
        // Extract handle before awaiting to avoid holding MutexGuard across await
        let handle = self
            .reader_handle
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .take();
        if let Some(handle) = handle {
            let _ = tokio::time::timeout(std::time::Duration::from_secs(5), handle).await;
        }

        Ok(())
    }

    /// Request all symbols in the workspace matching a query string.
    ///
    /// Uses `workspace/symbol` — one round-trip for the whole project, vs
    /// `textDocument/documentSymbol` which requires one request per file.
    /// Returns a flat list (no hierarchy); `container_name` is preserved in
    /// `name_path` when available.
    pub async fn workspace_symbols(&self, query: &str) -> Result<Vec<super::SymbolInfo>> {
        let params = lsp_types::WorkspaceSymbolParams {
            query: query.to_string(),
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let result = self
            .request("workspace/symbol", serde_json::to_value(params)?)
            .await?;

        if result.is_null() {
            return Ok(vec![]);
        }

        let infos: Vec<lsp_types::SymbolInformation> =
            serde_json::from_value(result).context("failed to parse workspace/symbol response")?;

        Ok(infos
            .into_iter()
            .map(|si| {
                let file = uri_to_path(&si.location.uri);
                let name_path = match &si.container_name {
                    Some(container) if !container.is_empty() => {
                        format!("{}/{}", container, si.name)
                    }
                    _ => si.name.clone(),
                };
                super::SymbolInfo {
                    name: si.name,
                    name_path,
                    kind: si.kind.into(),
                    file,
                    start_line: si.location.range.start.line,
                    end_line: si.location.range.end.line,
                    start_col: si.location.range.start.character,
                    range_start_line: None,
                    children: vec![],
                    detail: None,
                }
            })
            .collect())
    }

    /// Send textDocument/didOpen notification for a file.
    pub async fn did_open(&self, path: &Path, language_id: &str) -> Result<()> {
        // For socket transport, the mux handles document state dedup — skip
        // local open_files tracking so every didOpen is forwarded to the mux.
        let is_socket = matches!(self.transport, LspTransport::Socket { .. });
        if !is_socket {
            // Canonicalize before tracking to avoid treating symlinks or relative paths
            // as different files — the LSP spec prohibits duplicate didOpen notifications.
            let canonical = std::fs::canonicalize(path)
                .with_context(|| format!("Failed to canonicalize path for didOpen: {:?}", path))?;
            {
                let mut open_files = self.open_files.lock().unwrap_or_else(|e| e.into_inner());
                if open_files.contains_key(&canonical) {
                    return Ok(());
                }
                // Version 1 is the conventional initial version per LSP spec.
                open_files.insert(canonical, 1);
            }
        }

        const MAX_DID_OPEN_SIZE: u64 = 10 * 1024 * 1024; // 10 MiB
        if let Ok(metadata) = std::fs::metadata(path) {
            if metadata.len() > MAX_DID_OPEN_SIZE {
                tracing::debug!(
                    "skipping didOpen for large file ({} bytes): {}",
                    metadata.len(),
                    path.display()
                );
                return Ok(());
            }
        }

        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read file for didOpen: {:?}", path))?;
        let uri = path_to_uri(path)?;

        self.notify(
            "textDocument/didOpen",
            serde_json::to_value(lsp_types::DidOpenTextDocumentParams {
                text_document: lsp_types::TextDocumentItem {
                    uri,
                    language_id: language_id.to_string(),
                    version: 1,
                    text: content,
                },
            })?,
        )
        .await
    }

    /// Request document symbols for a file.
    ///
    /// Returns the hierarchical `DocumentSymbol[]` response parsed into our
    /// `SymbolInfo` tree. Sends `didOpen` first if the file hasn't been opened.
    pub async fn document_symbols(
        &self,
        path: &Path,
        language_id: &str,
    ) -> Result<Vec<super::SymbolInfo>> {
        // Ensure the file is open in the server
        self.did_open(path, language_id).await?;

        let uri = path_to_uri(path)?;
        let params = lsp_types::DocumentSymbolParams {
            text_document: lsp_types::TextDocumentIdentifier { uri },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let result = self
            .request("textDocument/documentSymbol", serde_json::to_value(params)?)
            .await?;

        // LSP returns either DocumentSymbol[] (hierarchical) or SymbolInformation[] (flat)
        // We prefer hierarchical and convert both to SymbolInfo
        if result.is_null() {
            return Ok(vec![]);
        }

        let file_path = path.to_path_buf();

        // Try hierarchical first
        if let Ok(symbols) =
            serde_json::from_value::<Vec<lsp_types::DocumentSymbol>>(result.clone())
        {
            return Ok(convert_document_symbols(&symbols, &file_path, ""));
        }

        // Fall back to flat SymbolInformation[]
        if let Ok(infos) = serde_json::from_value::<Vec<lsp_types::SymbolInformation>>(result) {
            return Ok(infos
                .iter()
                .map(|si| {
                    let name_path = match &si.container_name {
                        Some(container) if !container.is_empty() => {
                            format!("{}/{}", container, si.name)
                        }
                        _ => si.name.clone(),
                    };
                    super::SymbolInfo {
                        name: si.name.clone(),
                        name_path,
                        kind: si.kind.into(),
                        file: file_path.clone(),
                        start_line: si.location.range.start.line,
                        end_line: si.location.range.end.line,
                        start_col: si.location.range.start.character,
                        range_start_line: None,
                        children: vec![],
                        detail: None,
                    }
                })
                .collect());
        }

        Ok(vec![])
    }

    /// Request references for a symbol at a given position.
    pub async fn references(
        &self,
        path: &Path,
        line: u32,
        col: u32,
        language_id: &str,
    ) -> Result<Vec<lsp_types::Location>> {
        self.did_open(path, language_id).await?;
        let uri = path_to_uri(path)?;
        let params = lsp_types::ReferenceParams {
            text_document_position: lsp_types::TextDocumentPositionParams {
                text_document: lsp_types::TextDocumentIdentifier { uri },
                position: lsp_types::Position {
                    line,
                    character: col,
                },
            },
            context: lsp_types::ReferenceContext {
                include_declaration: true,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let result = self
            .request("textDocument/references", serde_json::to_value(params)?)
            .await?;

        if result.is_null() {
            return Ok(vec![]);
        }

        Ok(serde_json::from_value(result)?)
    }

    /// Request definition location for a symbol at a given position.
    pub async fn goto_definition(
        &self,
        path: &Path,
        line: u32,
        col: u32,
        language_id: &str,
    ) -> Result<Vec<lsp_types::Location>> {
        self.did_open(path, language_id).await?;
        let uri = path_to_uri(path)?;
        let params = lsp_types::GotoDefinitionParams {
            text_document_position_params: lsp_types::TextDocumentPositionParams {
                text_document: lsp_types::TextDocumentIdentifier { uri },
                position: lsp_types::Position {
                    line,
                    character: col,
                },
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let result = self
            .request("textDocument/definition", serde_json::to_value(params)?)
            .await?;

        if result.is_null() {
            return Ok(vec![]);
        }

        // Can return Location | Location[] | LocationLink[]
        if let Ok(loc) = serde_json::from_value::<lsp_types::Location>(result.clone()) {
            return Ok(vec![loc]);
        }
        if let Ok(locs) = serde_json::from_value::<Vec<lsp_types::Location>>(result.clone()) {
            return Ok(locs);
        }
        if let Ok(links) = serde_json::from_value::<Vec<lsp_types::LocationLink>>(result) {
            return Ok(links
                .into_iter()
                .map(|l| lsp_types::Location {
                    uri: l.target_uri,
                    range: l.target_selection_range,
                })
                .collect());
        }

        Ok(vec![])
    }

    /// Send textDocument/hover and return the hover contents as a string.
    pub async fn hover(
        &self,
        path: &Path,
        line: u32,
        col: u32,
        language_id: &str,
    ) -> Result<Option<String>> {
        self.did_open(path, language_id).await?;
        let uri = path_to_uri(path)?;
        let params = lsp_types::HoverParams {
            text_document_position_params: lsp_types::TextDocumentPositionParams {
                text_document: lsp_types::TextDocumentIdentifier { uri },
                position: lsp_types::Position {
                    line,
                    character: col,
                },
            },
            work_done_progress_params: Default::default(),
        };

        let result = self
            .request("textDocument/hover", serde_json::to_value(params)?)
            .await?;

        if result.is_null() {
            return Ok(None);
        }

        let hover: lsp_types::Hover = serde_json::from_value(result)?;

        let text = match hover.contents {
            lsp_types::HoverContents::Scalar(ms) => match ms {
                lsp_types::MarkedString::String(s) => s,
                lsp_types::MarkedString::LanguageString(ls) => ls.value,
            },
            lsp_types::HoverContents::Array(arr) => arr
                .into_iter()
                .map(|ms| match ms {
                    lsp_types::MarkedString::String(s) => s,
                    lsp_types::MarkedString::LanguageString(ls) => ls.value,
                })
                .collect::<Vec<_>>()
                .join("\n\n"),
            lsp_types::HoverContents::Markup(mc) => mc.value,
        };

        Ok(Some(text))
    }

    /// Request a rename across the workspace.
    pub async fn rename(
        &self,
        path: &Path,
        line: u32,
        col: u32,
        new_name: &str,
        language_id: &str,
    ) -> Result<lsp_types::WorkspaceEdit> {
        self.did_open(path, language_id).await?;
        let uri = path_to_uri(path)?;
        let params = lsp_types::RenameParams {
            text_document_position: lsp_types::TextDocumentPositionParams {
                text_document: lsp_types::TextDocumentIdentifier { uri },
                position: lsp_types::Position {
                    line,
                    character: col,
                },
            },
            new_name: new_name.to_string(),
            work_done_progress_params: Default::default(),
        };

        let result = self
            .request("textDocument/rename", serde_json::to_value(params)?)
            .await?;

        Ok(serde_json::from_value(result)?)
    }

    /// Send textDocument/didClose notification for a file.
    pub async fn did_close(&self, path: &Path) -> Result<()> {
        // For socket transport, the mux tracks document state — skip local bookkeeping.
        if !matches!(self.transport, LspTransport::Socket { .. }) {
            let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
            self.open_files
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .remove(&canonical);
        }

        let uri = path_to_uri(path)?;

        self.notify(
            "textDocument/didClose",
            serde_json::to_value(lsp_types::DidCloseTextDocumentParams {
                text_document: lsp_types::TextDocumentIdentifier { uri },
            })?,
        )
        .await
    }

    /// Notify the LSP server that a file was modified on disk by an external tool.
    ///
    /// If the file is already open in this session, sends `textDocument/didChange`.
    /// If not (e.g. newly created by `create_file`), falls back to `textDocument/didOpen`
    /// so the LSP learns about the file immediately — BUG-028 fix.
    ///
    /// For socket transport, the mux tracks document versions — we always send
    /// didChange with version 0 and let the mux remap to the correct version.
    pub async fn did_change(&self, path: &Path) -> Result<()> {
        let is_socket = matches!(self.transport, LspTransport::Socket { .. });

        let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());

        // For socket transport, skip local version tracking — the mux owns versions.
        // Always send didChange and let the mux handle state.
        let version = if is_socket {
            // Use version 0 as a sentinel; the mux will remap to the real version.
            0
        } else {
            // Increment the per-file version counter. Fall back to did_open for files
            // that were never opened — the LSP spec only allows didChange for open documents,
            // but we transparently open new/unknown files so callers don't have to.
            //
            // The guard is scoped strictly to the inner block so it drops before any await
            // point — StdMutex guards are not Send and cannot be held across awaits.
            //
            // saturating_add: LSP spec requires strictly monotonic version per document
            // (rust-analyzer and kotlin-lsp have rejected non-monotonic versions in past
            // releases). Sessions never realistically reach i32::MAX edits; if they
            // somehow do, the counter pins at MAX instead of wrapping to a lower value
            // that would break the monotonicity contract. i32 matches
            // lsp_types::VersionedTextDocumentIdentifier.version.
            let maybe_version = {
                let mut open_files = self.open_files.lock().unwrap_or_else(|e| e.into_inner());
                open_files.get_mut(&canonical).map(|v| {
                    *v = v.saturating_add(1);
                    *v
                })
            }; // guard drops here
            match maybe_version {
                Some(v) => v,
                None => {
                    // File not yet open — use did_open to register it with the LSP.
                    if let Some(lang) = crate::ast::detect_language(path) {
                        if crate::lsp::servers::has_lsp_config(lang) {
                            let _ = self.did_open(path, lang).await;
                        }
                    }
                    return Ok(());
                }
            }
        };

        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read file for didChange: {:?}", path))?;
        let uri = path_to_uri(path)?;
        self.notify(
            "textDocument/didChange",
            serde_json::to_value(lsp_types::DidChangeTextDocumentParams {
                text_document: lsp_types::VersionedTextDocumentIdentifier { uri, version },
                content_changes: vec![lsp_types::TextDocumentContentChangeEvent {
                    range: None,
                    range_length: None,
                    text: content,
                }],
            })?,
        )
        .await
    }

    /// Prepare a call hierarchy item at the given position.
    ///
    /// Returns `Ok(None)` if the server does not support call hierarchy or if no
    /// item is found at the cursor position.
    pub async fn prepare_call_hierarchy(
        &self,
        path: &Path,
        line: u32,
        col: u32,
        language_id: &str,
    ) -> Result<Option<lsp_types::CallHierarchyItem>> {
        {
            let caps = self.capabilities.lock().unwrap_or_else(|e| e.into_inner());
            if !supports_call_hierarchy(&caps) {
                return Ok(None);
            }
        }
        self.did_open(path, language_id).await?;
        let uri = path_to_uri(path)?;
        let params = lsp_types::CallHierarchyPrepareParams {
            text_document_position_params: lsp_types::TextDocumentPositionParams {
                text_document: lsp_types::TextDocumentIdentifier { uri },
                position: lsp_types::Position {
                    line,
                    character: col,
                },
            },
            work_done_progress_params: Default::default(),
        };

        let result = self
            .request(
                "textDocument/prepareCallHierarchy",
                serde_json::to_value(params)?,
            )
            .await?;

        if result.is_null() {
            return Ok(None);
        }

        let items: Vec<lsp_types::CallHierarchyItem> = serde_json::from_value(result)?;
        Ok(items.into_iter().next())
    }

    /// Fetch incoming calls for a call hierarchy item.
    ///
    /// Returns an empty vec if the server does not support call hierarchy.
    pub async fn incoming_calls(
        &self,
        item: &lsp_types::CallHierarchyItem,
        _language_id: &str,
    ) -> Result<Vec<lsp_types::CallHierarchyIncomingCall>> {
        {
            let caps = self.capabilities.lock().unwrap_or_else(|e| e.into_inner());
            if !supports_call_hierarchy(&caps) {
                return Ok(vec![]);
            }
        }
        let params = lsp_types::CallHierarchyIncomingCallsParams {
            item: item.clone(),
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let result = self
            .request("callHierarchy/incomingCalls", serde_json::to_value(params)?)
            .await?;

        if result.is_null() {
            return Ok(vec![]);
        }

        let calls: Vec<lsp_types::CallHierarchyIncomingCall> = serde_json::from_value(result)?;
        Ok(calls)
    }

    /// Fetch outgoing calls for a call hierarchy item.
    ///
    /// Returns an empty vec if the server does not support call hierarchy.
    pub async fn outgoing_calls(
        &self,
        item: &lsp_types::CallHierarchyItem,
        _language_id: &str,
    ) -> Result<Vec<lsp_types::CallHierarchyOutgoingCall>> {
        {
            let caps = self.capabilities.lock().unwrap_or_else(|e| e.into_inner());
            if !supports_call_hierarchy(&caps) {
                return Ok(vec![]);
            }
        }
        let params = lsp_types::CallHierarchyOutgoingCallsParams {
            item: item.clone(),
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let result = self
            .request("callHierarchy/outgoingCalls", serde_json::to_value(params)?)
            .await?;

        if result.is_null() {
            return Ok(vec![]);
        }

        let calls: Vec<lsp_types::CallHierarchyOutgoingCall> = serde_json::from_value(result)?;
        Ok(calls)
    }
}

impl Drop for LspClient {
    fn drop(&mut self) {
        // Abort the reader task
        {
            let mut guard = self.reader_handle.lock().unwrap_or_else(|e| e.into_inner());
            if let Some(handle) = guard.take() {
                handle.abort();
            }
        }
        // Kill the child process as a safety net.
        // The graceful shutdown path (shutdown_all -> shutdown) sends LSP
        // shutdown/exit first.  This ensures the process dies even if the
        // graceful path was skipped (e.g., panic, abrupt exit).
        // For socket-connected clients there is no child to kill.
        if let LspTransport::Process {
            child_pid: Some(pid),
        } = &self.transport
        {
            // SAFETY: `pid` was captured from `child.id()` immediately after spawn and remains
            // valid for the lifetime of this `LspClient` (we hold the child handle). SIGTERM
            // (signal 15) is safe to send to a child process — it requests clean termination
            // without undefined behaviour. The `u32 as i32` cast is safe because Linux PIDs
            // are assigned from a range that fits in i32 (maximum 4,194,304 on 64-bit kernels).
            let _ = crate::platform::terminate_process(*pid);
        }
    }
}

#[async_trait::async_trait]
impl crate::lsp::ops::LspClientOps for LspClient {
    async fn document_symbols(
        &self,
        path: &std::path::Path,
        language_id: &str,
    ) -> anyhow::Result<Vec<crate::lsp::SymbolInfo>> {
        LspClient::document_symbols(self, path, language_id).await
    }

    async fn workspace_symbols(&self, query: &str) -> anyhow::Result<Vec<crate::lsp::SymbolInfo>> {
        LspClient::workspace_symbols(self, query).await
    }

    async fn references(
        &self,
        path: &std::path::Path,
        line: u32,
        col: u32,
        language_id: &str,
    ) -> anyhow::Result<Vec<lsp_types::Location>> {
        LspClient::references(self, path, line, col, language_id).await
    }

    async fn goto_definition(
        &self,
        path: &std::path::Path,
        line: u32,
        col: u32,
        language_id: &str,
    ) -> anyhow::Result<Vec<lsp_types::Location>> {
        LspClient::goto_definition(self, path, line, col, language_id).await
    }

    async fn hover(
        &self,
        path: &std::path::Path,
        line: u32,
        col: u32,
        language_id: &str,
    ) -> anyhow::Result<Option<String>> {
        LspClient::hover(self, path, line, col, language_id).await
    }

    async fn rename(
        &self,
        path: &std::path::Path,
        line: u32,
        col: u32,
        new_name: &str,
        language_id: &str,
    ) -> anyhow::Result<lsp_types::WorkspaceEdit> {
        LspClient::rename(self, path, line, col, new_name, language_id).await
    }

    async fn did_change(&self, path: &std::path::Path) -> anyhow::Result<()> {
        LspClient::did_change(self, path).await
    }

    async fn prepare_call_hierarchy(
        &self,
        path: &std::path::Path,
        line: u32,
        col: u32,
        language_id: &str,
    ) -> anyhow::Result<Option<lsp_types::CallHierarchyItem>> {
        LspClient::prepare_call_hierarchy(self, path, line, col, language_id).await
    }

    async fn incoming_calls(
        &self,
        item: &lsp_types::CallHierarchyItem,
        language_id: &str,
    ) -> anyhow::Result<Vec<lsp_types::CallHierarchyIncomingCall>> {
        LspClient::incoming_calls(self, item, language_id).await
    }

    async fn outgoing_calls(
        &self,
        item: &lsp_types::CallHierarchyItem,
        language_id: &str,
    ) -> anyhow::Result<Vec<lsp_types::CallHierarchyOutgoingCall>> {
        LspClient::outgoing_calls(self, item, language_id).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn workspace_symbol_skips_cold_start_retry_budget() {
        // Rationale: rust-analyzer answers -32800 for workspace/symbol until the
        // whole project is indexed (minutes). Cold-start budget (10×3s + 30s
        // per-attempt timeout) blows the 60s MCP tool timeout. symbols
        // falls back to tree-sitter when workspace/symbol errors, so fail fast.
        assert!(!uses_cold_start_retry_budget("workspace/symbol"));
        // Per-file ops become answerable as soon as the server parses the file,
        // so the patient cold-start retry still pays off there.
        assert!(uses_cold_start_retry_budget("textDocument/documentSymbol"));
        assert!(uses_cold_start_retry_budget("textDocument/references"));
        assert!(uses_cold_start_retry_budget("textDocument/hover"));
        // workspace/symbol must still be idempotent so warm-path retry works.
        assert!(is_idempotent_lsp_method("workspace/symbol"));
    }

    #[test]
    fn cold_start_max_retries_matches_host_platform() {
        // The helper is `const fn` with cfg! branching, so the result for the
        // currently-compiling host should be deterministic. This test asserts
        // that no future refactor accidentally inverts the platform ranking
        // (Windows must get the most headroom, Linux the least).
        let actual = cold_start_max_retries();
        let expected = if cfg!(target_os = "windows") {
            20
        } else if cfg!(target_os = "macos") {
            15
        } else {
            10
        };
        assert_eq!(actual, expected);

        // Sanity: cold-start budget must always exceed the warm-path retry
        // count (3, see `request`). A future tweak that drops cold below warm
        // means cold-start would retry *fewer* times than steady-state — almost
        // certainly a regression.
        assert!(actual >= 3, "cold-start retries must exceed warm budget");
    }

    #[test]
    fn is_retryable_lsp_error_matches_both_transient_codes() {
        // Both -32800 (RequestCancelled) and -32801 (ContentModified) are
        // explicit LSP "retry on new snapshot" signals. They share a retry
        // path here; this test pins both codes against the matcher.
        let cancelled = anyhow::anyhow!("LSP error (code -32800): cancelled");
        let modified = anyhow::anyhow!("LSP error (code -32801): content modified");
        let internal = anyhow::anyhow!("LSP error (code -32603): internal error");
        let timeout = anyhow::anyhow!("LSP request timed out after 30s");

        assert!(is_retryable_lsp_error(&cancelled), "-32800 must retry");
        assert!(is_retryable_lsp_error(&modified), "-32801 must retry");
        assert!(
            !is_retryable_lsp_error(&internal),
            "-32603 is a real fault — must NOT retry"
        );
        assert!(
            !is_retryable_lsp_error(&timeout),
            "timeouts are surfaced as RecoverableError separately — must NOT match"
        );
    }

    #[test]
    fn detect_fatal_stderr_flags_kotlin_multi_session() {
        // kotlin-lsp refuses to run when another editing session holds the
        // workspace. This is a permanent failure per release; retrying would
        // just spawn more zombie processes, so we must surface it fast.
        let lines = vec![
            "Exception in thread \"main\" com.jetbrains.lsp.implementation.\
             LspException: Multiple editing sessions for one workspace are not supported yet"
                .to_string(),
        ];
        let hint = detect_fatal_stderr(&lines).expect("should detect fatal pattern");
        let msg = hint.to_string();
        assert!(
            msg.contains("Multiple editing sessions"),
            "error message should surface the original pattern: {msg}"
        );
    }

    #[test]
    fn detect_fatal_stderr_flags_rustup_missing_component() {
        // rustup's shim for rust-analyzer prints this to stderr and exits 1
        // immediately if the component isn't installed for the active toolchain.
        // Pre-fix the LSP launch path swallowed it and reported the opaque
        // "LSP server disconnected" instead of pointing at the rustup fix.
        // See docs/issues/2026-05-20-lsp-launch-opaque-disconnected-error.md.
        let lines = vec![
            "error: Unknown binary 'rust-analyzer' in official toolchain \
                 'stable-x86_64-unknown-linux-gnu'."
                .to_string(),
        ];
        let hint = detect_fatal_stderr(&lines).expect("should detect rustup pattern");
        let msg = hint.to_string();
        assert!(
            msg.contains("rust-analyzer"),
            "error message should name rust-analyzer: {msg}"
        );
        assert!(
            msg.contains("rustup component add rust-analyzer"),
            "error message should include the rustup fix command: {msg}"
        );
    }

    #[test]
    fn detect_fatal_stderr_ignores_benign_lines() {
        // Noisy but non-fatal lines (warnings, informational) must not trip
        // the fast-fail path — those are normal cold-start chatter.
        let lines = vec![
            "WARN notify error: No path was found.".to_string(),
            "INFO LSP server starting".to_string(),
            "Gradle import in progress".to_string(),
        ];
        assert!(detect_fatal_stderr(&lines).is_none());
    }

    /// Create a minimal Cargo project for testing with rust-analyzer.
    fn create_test_cargo_project(dir: &Path) {
        std::fs::write(
            dir.join("Cargo.toml"),
            r#"[package]
name = "test-project"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(
            dir.join("src/main.rs"),
            r#"fn main() {
    println!("hello");
}

fn add(a: i32, b: i32) -> i32 {
    a + b
}

struct Point {
    x: f64,
    y: f64,
}
"#,
        )
        .unwrap();
    }

    fn rust_analyzer_available() -> bool {
        std::process::Command::new("rust-analyzer")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    #[tokio::test]
    async fn client_initializes_with_rust_analyzer() {
        if !rust_analyzer_available() {
            eprintln!("Skipping: rust-analyzer not installed");
            return;
        }

        let dir = tempdir().unwrap();
        create_test_cargo_project(dir.path());

        let config = LspServerConfig {
            command: "rust-analyzer".into(),
            args: vec![],
            workspace_root: dir.path().to_path_buf(),
            init_timeout: None,
            mux: false,
            env: vec![],
            idle_timeout_secs: None,
        };

        let client = LspClient::start(config).await.unwrap();
        assert!(client.is_alive());

        // Verify we got capabilities
        {
            let caps = client.capabilities.lock().unwrap();
            // rust-analyzer should support document symbols
            assert!(caps.document_symbol_provider.is_some());
        }

        client.shutdown().await.unwrap();
        assert!(!client.is_alive());
    }

    #[tokio::test]
    async fn client_detects_missing_server() {
        let dir = tempdir().unwrap();
        let config = LspServerConfig {
            command: "nonexistent-lsp-server-xyz".into(),
            args: vec![],
            workspace_root: dir.path().to_path_buf(),
            init_timeout: None,
            mux: false,
            env: vec![],
            idle_timeout_secs: None,
        };

        let result = LspClient::start(config).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn workspace_symbols_returns_project_symbols() {
        if !rust_analyzer_available() {
            eprintln!("Skipping: rust-analyzer not installed");
            return;
        }

        let dir = tempdir().unwrap();
        create_test_cargo_project(dir.path());

        let config = LspServerConfig {
            command: "rust-analyzer".into(),
            args: vec![],
            workspace_root: dir.path().to_path_buf(),
            init_timeout: None,
            mux: false,
            env: vec![],
            idle_timeout_secs: None,
        };

        let client = LspClient::start(config).await.unwrap();

        // Open a file to trigger rust-analyzer background indexing.
        client
            .did_open(&dir.path().join("src/main.rs"), "rust")
            .await
            .unwrap();

        // rust-analyzer indexes in the background after initialize; retry until
        // workspace/symbol returns results. Local Linux: typically < 2s, but GHA
        // runners (especially macOS + Windows) can be I/O-slower under load.
        // Budget 15s (30 × 500ms) on all platforms.
        let mut symbols = vec![];
        for _ in 0..30 {
            symbols = client.workspace_symbols("add").await.unwrap();
            if !symbols.is_empty() {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        }

        assert!(
            !symbols.is_empty(),
            "workspace/symbol 'add' should return results within the retry budget"
        );
        assert!(
            symbols.iter().any(|s| s.name == "add"),
            "should find the 'add' function, got: {:?}",
            symbols.iter().map(|s| &s.name).collect::<Vec<_>>()
        );

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

    #[tokio::test]
    async fn client_did_open_with_rust_analyzer() {
        if !rust_analyzer_available() {
            eprintln!("Skipping: rust-analyzer not installed");
            return;
        }

        let dir = tempdir().unwrap();
        create_test_cargo_project(dir.path());

        let config = LspServerConfig {
            command: "rust-analyzer".into(),
            args: vec![],
            workspace_root: dir.path().to_path_buf(),
            init_timeout: None,
            mux: false,
            env: vec![],
            idle_timeout_secs: None,
        };

        let client = LspClient::start(config).await.unwrap();
        // Open the main file
        client
            .did_open(&dir.path().join("src/main.rs"), "rust")
            .await
            .unwrap();

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

    #[test]
    fn convert_document_symbols_uses_selection_range() {
        use lsp_types::{DocumentSymbol, Position, Range, SymbolKind as LspSymbolKind};

        let symbols = vec![DocumentSymbol {
            name: "my_func".to_string(),
            detail: None,
            kind: LspSymbolKind::FUNCTION,
            tags: None,
            #[allow(deprecated)]
            deprecated: None,
            range: Range {
                start: Position {
                    line: 5,
                    character: 0,
                },
                end: Position {
                    line: 10,
                    character: 1,
                },
            },
            selection_range: Range {
                start: Position {
                    line: 8,
                    character: 4,
                },
                end: Position {
                    line: 8,
                    character: 11,
                },
            },
            children: None,
        }];

        let path = std::env::temp_dir().join("test.rs");
        let result = convert_document_symbols(&symbols, &path, "");

        assert_eq!(result.len(), 1);
        assert_eq!(
            result[0].start_line, 8,
            "start_line should use selection_range"
        );
        assert_eq!(
            result[0].start_col, 4,
            "start_col should use selection_range"
        );
        assert_eq!(
            result[0].end_line, 10,
            "end_line should use range for body extent"
        );
        assert_eq!(
            result[0].range_start_line,
            Some(5),
            "range_start_line should use range.start for full declaration (including attributes)"
        );
    }

    #[test]
    fn convert_document_symbols_captures_detail() {
        use lsp_types::{DocumentSymbol, Position, Range, SymbolKind as LspSymbolKind};

        let symbols = vec![DocumentSymbol {
            name: "my_func".to_string(),
            detail: Some("(x: i32) -> bool".to_string()),
            kind: LspSymbolKind::FUNCTION,
            tags: None,
            #[allow(deprecated)]
            deprecated: None,
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 5,
                    character: 1,
                },
            },
            selection_range: Range {
                start: Position {
                    line: 0,
                    character: 3,
                },
                end: Position {
                    line: 0,
                    character: 10,
                },
            },
            children: None,
        }];

        let path = std::env::temp_dir().join("test_detail_capture.rs");
        let result = convert_document_symbols(&symbols, &path, "");

        assert_eq!(result.len(), 1);
        assert_eq!(
            result[0].detail,
            Some("(x: i32) -> bool".to_string()),
            "detail should be captured from DocumentSymbol"
        );
    }

    #[test]
    fn convert_document_symbols_collapses_empty_detail() {
        use lsp_types::{DocumentSymbol, Position, Range, SymbolKind as LspSymbolKind};

        let symbols = vec![DocumentSymbol {
            name: "my_func".to_string(),
            detail: Some("".to_string()),
            kind: LspSymbolKind::FUNCTION,
            tags: None,
            #[allow(deprecated)]
            deprecated: None,
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 5,
                    character: 1,
                },
            },
            selection_range: Range {
                start: Position {
                    line: 0,
                    character: 3,
                },
                end: Position {
                    line: 0,
                    character: 10,
                },
            },
            children: None,
        }];

        let path = std::env::temp_dir().join("test_detail_empty.rs");
        let result = convert_document_symbols(&symbols, &path, "");

        assert_eq!(
            result[0].detail, None,
            "empty string detail should collapse to None"
        );
    }

    #[test]
    fn flat_symbol_information_builds_name_path_from_container() {
        use crate::lsp::SymbolInfo;
        use lsp_types::{
            Location, Position, Range, SymbolInformation, SymbolKind as LspSymbolKind, Uri,
        };

        let uri: Uri = if cfg!(windows) {
            "file:///C:/temp/test.rb".parse().unwrap()
        } else {
            "file:///tmp/test.rb".parse().unwrap()
        };
        let infos = [
            SymbolInformation {
                name: "MyClass".to_string(),
                kind: LspSymbolKind::CLASS,
                tags: None,
                #[allow(deprecated)]
                deprecated: None,
                location: Location {
                    uri: uri.clone(),
                    range: Range {
                        start: Position {
                            line: 0,
                            character: 0,
                        },
                        end: Position {
                            line: 20,
                            character: 3,
                        },
                    },
                },
                container_name: None,
            },
            SymbolInformation {
                name: "my_method".to_string(),
                kind: LspSymbolKind::METHOD,
                tags: None,
                #[allow(deprecated)]
                deprecated: None,
                location: Location {
                    uri: uri.clone(),
                    range: Range {
                        start: Position {
                            line: 5,
                            character: 2,
                        },
                        end: Position {
                            line: 10,
                            character: 5,
                        },
                    },
                },
                container_name: Some("MyClass".to_string()),
            },
        ];

        // Simulate what document_symbols does with flat format
        let file_path = std::env::temp_dir().join("test.rb");
        // Current code just does name_path: si.name.clone() — this test verifies the fix
        let result: Vec<SymbolInfo> = infos
            .iter()
            .map(|si| {
                let name_path = match &si.container_name {
                    Some(container) if !container.is_empty() => {
                        format!("{}/{}", container, si.name)
                    }
                    _ => si.name.clone(),
                };
                SymbolInfo {
                    name: si.name.clone(),
                    name_path,
                    kind: si.kind.into(),
                    file: file_path.clone(),
                    start_line: si.location.range.start.line,
                    end_line: si.location.range.end.line,
                    start_col: si.location.range.start.character,
                    range_start_line: None,
                    children: vec![],
                    detail: None,
                }
            })
            .collect();

        assert_eq!(result[0].name_path, "MyClass");
        assert_eq!(result[1].name_path, "MyClass/my_method");
    }

    #[test]
    fn path_to_uri_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.rs");
        std::fs::write(&file, "").unwrap();

        let uri = path_to_uri(&file).unwrap();
        let uri_str = uri.as_str();
        assert!(
            uri_str.starts_with("file:///"),
            "URI should start with file:///: {}",
            uri_str
        );

        let back = uri_to_path(&uri);
        assert_eq!(back, file, "roundtrip should preserve the path");
    }

    #[tokio::test]
    async fn drop_kills_child_process() {
        if !rust_analyzer_available() {
            eprintln!("Skipping: rust-analyzer not installed");
            return;
        }
        let dir = tempdir().unwrap();
        create_test_cargo_project(dir.path());
        let config = LspServerConfig {
            command: "rust-analyzer".into(),
            args: vec![],
            workspace_root: dir.path().to_path_buf(),
            init_timeout: None,
            mux: false,
            env: vec![],
            idle_timeout_secs: None,
        };
        let client = LspClient::start(config).await.unwrap();
        let pid = match &client.transport {
            LspTransport::Process { child_pid } => child_pid.unwrap(),
            _ => panic!("expected Process transport"),
        };

        // Verify child is alive
        assert!(
            crate::platform::process_alive(pid),
            "child should be alive before drop"
        );

        // Drop the client
        drop(client);

        // Give the process a moment to die
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;

        // Verify child is dead
        assert!(
            !crate::platform::process_alive(pid),
            "child should be dead after drop"
        );
    }

    /// Reproduce the stale-position bug: after editing a file on disk without sending
    /// didChange, the LSP returns positions from the old content. did_change fixes it.
    #[tokio::test]
    async fn did_change_refreshes_stale_symbol_positions() {
        if !rust_analyzer_available() {
            eprintln!("Skipping: rust-analyzer not installed");
            return;
        }

        let dir = tempdir().unwrap();
        create_test_cargo_project(dir.path());
        let main_rs = dir.path().join("src/main.rs");

        let config = LspServerConfig {
            command: "rust-analyzer".into(),
            args: vec![],
            workspace_root: dir.path().to_path_buf(),
            init_timeout: None,
            mux: false,
            env: vec![],
            idle_timeout_secs: None,
        };
        let client = LspClient::start(config).await.unwrap();

        // Step 1: query symbols — fn add is at line 4 (0-indexed) in the original file.
        let syms = client.document_symbols(&main_rs, "rust").await.unwrap();
        let add_before = syms
            .iter()
            .find(|s| s.name == "add")
            .expect("fn add not found");
        let original_line = add_before.start_line;

        // Step 2: prepend 3 blank lines on disk — shifts fn add to line 7.
        let original = std::fs::read_to_string(&main_rs).unwrap();
        std::fs::write(&main_rs, format!("\n\n\n{}", original)).unwrap();

        // Step 3: query again WITHOUT did_change — LSP returns stale positions.
        let syms_stale = client.document_symbols(&main_rs, "rust").await.unwrap();
        let add_stale = syms_stale
            .iter()
            .find(|s| s.name == "add")
            .expect("fn add not found");
        assert_eq!(
            add_stale.start_line, original_line,
            "without did_change, LSP should still return the old (stale) line number"
        );

        // Step 4: notify the LSP about the disk change.
        client.did_change(&main_rs).await.unwrap();

        // Step 5: query again — LSP should now return the shifted position.
        let syms_fresh = client.document_symbols(&main_rs, "rust").await.unwrap();
        let add_fresh = syms_fresh
            .iter()
            .find(|s| s.name == "add")
            .expect("fn add not found");
        assert_eq!(
            add_fresh.start_line,
            original_line + 3,
            "after did_change, LSP should return the updated line number (shifted by 3)"
        );

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

    /// BUG-028: did_change on a file not yet opened should fall back to did_open,
    /// so create_file on a new path registers the file with the LSP immediately.
    #[tokio::test]
    async fn did_change_opens_file_when_not_previously_open() {
        if !rust_analyzer_available() {
            eprintln!("Skipping: rust-analyzer not installed");
            return;
        }

        let dir = tempdir().unwrap();
        create_test_cargo_project(dir.path());

        let config = LspServerConfig {
            command: "rust-analyzer".into(),
            args: vec![],
            workspace_root: dir.path().to_path_buf(),
            init_timeout: None,
            mux: false,
            env: vec![],
            idle_timeout_secs: None,
        };
        let client = LspClient::start(config).await.unwrap();

        // Create a brand-new file that has never been opened in this LSP session.
        let new_rs = dir.path().join("src/helper.rs");
        std::fs::write(&new_rs, "pub fn helper_v1() -> i32 { 1 }\n").unwrap();

        // Call did_change on the never-opened file.
        // After the fix: falls back to did_open, registering the file with the LSP.
        client.did_change(&new_rs).await.unwrap();

        // Now mutate the file on disk without using did_change.
        std::fs::write(
            &new_rs,
            "pub fn helper_v1() -> i32 { 1 }\npub fn helper_v2() -> i32 { 2 }\n",
        )
        .unwrap();

        // Send did_change for the update — this only works if the file is already open
        // (in open_files). Before the fix, the first did_change was a no-op, so open_files
        // still doesn't have the file, making this second did_change also a no-op.
        client.did_change(&new_rs).await.unwrap();

        // Query symbols — must see helper_v2 (the updated content).
        // Before the fix: document_symbols would call did_open here, picking up the
        // current disk content anyway, so this assertion would pass regardless.
        // The real invariant tested: did_change on a never-opened file must NOT silently
        // no-op — it must open the file so future did_change notifications work correctly.
        let syms = client.document_symbols(&new_rs, "rust").await.unwrap();
        assert!(
            syms.iter().any(|s| s.name == "helper_v2"),
            "after two did_change calls (open fallback + update), helper_v2 must be visible"
        );

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

    /// Verify that prepare_call_hierarchy returns a CallHierarchyItem for a known function.
    ///
    /// This test requires a live rust-analyzer. It is skipped automatically when
    /// rust-analyzer is not installed so the normal `cargo test` suite stays green.
    ///
    /// Note: `prepareCallHierarchy` requires semantic analysis (not just parsing), so the
    /// server may return `None` if indexing hasn't completed. We treat that as a soft skip
    /// rather than a hard failure to avoid a flaky test. The assertion fires only when we
    /// do get an item back, ensuring the name and kind are correct.
    #[tokio::test]
    async fn call_hierarchy_prepare_returns_item() {
        if !rust_analyzer_available() {
            eprintln!("Skipping: rust-analyzer not installed");
            return;
        }

        let dir = tempdir().unwrap();
        create_test_cargo_project(dir.path());
        let main_rs = dir.path().join("src/main.rs");

        let config = LspServerConfig {
            command: "rust-analyzer".into(),
            args: vec![],
            workspace_root: dir.path().to_path_buf(),
            init_timeout: None,
            mux: false,
            env: vec![],
            idle_timeout_secs: None,
        };
        let client = LspClient::start(config).await.unwrap();

        // Warm up rust-analyzer by fetching document symbols first.
        // This ensures the file is parsed before we send the call hierarchy request.
        let syms = client.document_symbols(&main_rs, "rust").await.unwrap();
        let add_sym = syms.iter().find(|s| s.name == "add");
        let Some(add_sym) = add_sym else {
            eprintln!("Skipping: fn add not found in symbols (indexing lag)");
            client.shutdown().await.unwrap();
            return;
        };

        // start_line and start_col from selectionRange point directly at the name.
        // prepareCallHierarchy needs semantic analysis; it may return None if not
        // yet indexed — treated as a soft skip, not a test failure.
        let item = client
            .prepare_call_hierarchy(&main_rs, add_sym.start_line, add_sym.start_col, "rust")
            .await
            .expect("prepare_call_hierarchy should not error");

        match item {
            None => {
                eprintln!(
                    "Skipping: prepare_call_hierarchy returned None for fn add \
                     (line={}, col={}) — indexing not yet complete",
                    add_sym.start_line, add_sym.start_col
                );
            }
            Some(item) => {
                assert_eq!(
                    item.name, "add",
                    "expected item name 'add', got '{}'",
                    item.name
                );
            }
        }

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

    /// Verify that outgoing_calls returns calls made from a function.
    #[tokio::test]
    async fn call_hierarchy_outgoing_returns_calls() {
        if !rust_analyzer_available() {
            eprintln!("Skipping: rust-analyzer not installed");
            return;
        }

        // Extend the test project with a helper that calls `add`.
        let dir = tempdir().unwrap();
        create_test_cargo_project(dir.path());
        let main_rs = dir.path().join("src/main.rs");

        // Append a wrapper that calls `add` so outgoing_calls has something to find.
        let original = std::fs::read_to_string(&main_rs).unwrap();
        std::fs::write(
            &main_rs,
            format!("{original}\nfn add_twice(x: i32) -> i32 {{ add(x, x) }}\n"),
        )
        .unwrap();

        let config = LspServerConfig {
            command: "rust-analyzer".into(),
            args: vec![],
            workspace_root: dir.path().to_path_buf(),
            init_timeout: None,
            mux: false,
            env: vec![],
            idle_timeout_secs: None,
        };
        let client = LspClient::start(config).await.unwrap();

        // Warm up: fetch document symbols to ensure the file is parsed.
        let syms = client.document_symbols(&main_rs, "rust").await.unwrap();
        let add_twice = syms.iter().find(|s| s.name == "add_twice");
        let Some(sym) = add_twice else {
            eprintln!("Skipping: add_twice not found in symbols (indexing lag)");
            client.shutdown().await.unwrap();
            return;
        };
        // Use selectionRange coords directly — they point at the function name.
        let item = client
            .prepare_call_hierarchy(&main_rs, sym.start_line, sym.start_col, "rust")
            .await
            .expect("prepare_call_hierarchy should not error");

        if let Some(item) = item {
            let calls = client
                .outgoing_calls(&item, "rust")
                .await
                .expect("outgoing_calls should not error");
            // add_twice calls add — expect at least one outgoing call.
            assert!(
                !calls.is_empty(),
                "expected outgoing calls from add_twice, got none"
            );
        } else {
            eprintln!("Skipping: prepare_call_hierarchy returned None (indexing lag)");
        }

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

    /// Integration test: verify that `request()` retries on -32800 (RequestCancelled)
    /// and eventually succeeds. Uses a fake LSP server (Python script) that returns
    /// -32800 for the first 2 requests, then responds normally.
    ///
    /// Run manually: `cargo test retry_on_cancelled -- --ignored --nocapture`
    #[tokio::test]
    #[ignore] // requires Python 3; run manually
    async fn retry_on_cancelled_succeeds_after_transient_errors() {
        let dir = tempdir().unwrap();
        let fake_lsp = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/fake_lsp_cancelled.py");
        assert!(
            fake_lsp.exists(),
            "fake LSP script missing: {}",
            fake_lsp.display()
        );

        let config = LspServerConfig {
            command: "python3".into(),
            args: vec![fake_lsp.to_string_lossy().into_owned(), "2".into()],
            workspace_root: dir.path().to_path_buf(),
            init_timeout: Some(std::time::Duration::from_secs(5)),
            mux: false,
            env: vec![],
            idle_timeout_secs: None,
        };

        let client = LspClient::start(config)
            .await
            .expect("fake LSP should start");

        // This request goes through `request()` which has RETRY_ON_CANCELLED=true.
        // The fake server returns -32800 twice, then succeeds on the 3rd attempt.
        let result = client
            .request(
                "textDocument/documentSymbol",
                serde_json::json!({
                    "textDocument": { "uri": "file:///fake.kt" }
                }),
            )
            .await;

        assert!(
            result.is_ok(),
            "request should succeed after retries, got: {:?}",
            result.err()
        );

        let symbols = result.unwrap();
        assert!(symbols.is_array(), "expected array response");
        assert_eq!(
            symbols.as_array().unwrap().len(),
            1,
            "fake server returns exactly one symbol"
        );

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

    /// Integration test: verify that `request()` fails when the server returns
    /// -32800 on ALL retries (exhausts MAX_RETRIES).
    ///
    /// Run manually: `cargo test retry_exhausted -- --ignored --nocapture`
    #[tokio::test]
    #[ignore] // requires Python 3; run manually
    async fn retry_on_cancelled_fails_when_exhausted() {
        let dir = tempdir().unwrap();
        let fake_lsp = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/fake_lsp_cancelled.py");

        let config = LspServerConfig {
            command: "python3".into(),
            // Cancel 10 times — more than MAX_RETRIES (3), so all attempts fail
            args: vec![fake_lsp.to_string_lossy().into_owned(), "10".into()],
            workspace_root: dir.path().to_path_buf(),
            init_timeout: Some(std::time::Duration::from_secs(5)),
            mux: false,
            env: vec![],
            idle_timeout_secs: None,
        };

        let client = LspClient::start(config)
            .await
            .expect("fake LSP should start");

        let result = client
            .request(
                "textDocument/documentSymbol",
                serde_json::json!({
                    "textDocument": { "uri": "file:///fake.kt" }
                }),
            )
            .await;

        assert!(result.is_err(), "should fail after exhausting retries");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("code -32800"),
            "error should mention -32800, got: {}",
            err_msg
        );

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

    #[cfg(unix)]
    #[tokio::test]
    async fn lsp_client_connect_to_nonexistent_socket_returns_error() {
        let socket_path = std::env::temp_dir().join("codescout-test-nonexistent.sock");
        // Clean up in case a previous test run left a stale socket
        let _ = std::fs::remove_file(&socket_path);
        let result = LspClient::connect(&socket_path, std::env::temp_dir()).await;
        let err_msg = match result {
            Err(e) => e.to_string(),
            Ok(_) => panic!("connecting to nonexistent socket should fail"),
        };
        assert!(
            err_msg.contains("Failed to connect to mux socket"),
            "error should mention mux socket, got: {}",
            err_msg
        );
    }

    #[test]
    fn lsp_server_config_has_idle_timeout_field() {
        let cfg = LspServerConfig {
            command: "dummy".to_string(),
            args: vec![],
            workspace_root: std::path::PathBuf::from("/tmp"),
            init_timeout: None,
            mux: false,
            env: vec![],
            idle_timeout_secs: Some(42),
        };
        assert_eq!(cfg.idle_timeout_secs, Some(42));
    }
}