mcpls-core 0.6.0

Core library for MCP to LSP protocol translation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
//! Hover, go-to-definition/implementation/type-definition, and references
//! handlers.

use std::time::Duration;

use lsp_types::{
    HoverParams as LspHoverParams, PartialResultParams, ReferenceContext, ReferenceParams,
    TextDocumentIdentifier, TextDocumentPositionParams, WorkDoneProgressParams,
};
use tokio::time::Instant;

use super::Translator;
use super::dto::{
    DefinitionResult, HoverResult, Location, LocationsResult, Position, ReferencesResult,
};
use super::encoding_ctx::EncodingCtx;
use super::routing::{Capability, IndexingGate};
use crate::bridge::IndexingState;
use crate::bridge::indexing::{
    DEFAULT_INDEXING_READY_TIMEOUT_SECS, INDEXING_STALENESS_BOUND, PROGRESS_LATCH_IDLE,
    PROGRESS_SETTLE,
};
use crate::config::{ServerId, ToolKind};
use crate::error::{Error, Result};

/// Default maximum time [`Translator::wait_for_indexing_ready`] waits for a
/// routed LSP server to report it has finished its initial workspace load,
/// once a readiness signal has shown indexing is actually in progress.
/// Matches the timeout already used throughout the rust-analyzer integration
/// test suite's own (test-only) indexing-readiness helper.
///
/// This is only the built-in default (used by [`Translator::new`]) --
/// overridable per `Translator` via [`Translator::with_indexing_ready_timeout`],
/// wired from `workspace.indexing_ready_timeout_seconds` in `mcpls.toml`
/// (#424). The compile-time invariants below are checked against this
/// default; the same invariants are re-checked against a configured override
/// at `ServerConfig::validate` time, since a runtime value can't be asserted
/// at compile time.
pub(super) const INDEXING_READY_TIMEOUT: Duration =
    Duration::from_secs(DEFAULT_INDEXING_READY_TIMEOUT_SECS);

/// Poll interval used while waiting out [`INDEXING_READY_TIMEOUT`]. A single
/// mutex lock plus map lookup, not a network round trip, so a short
/// interval adds no meaningful overhead relative to the LSP request that
/// follows once the wait resolves.
const INDEXING_POLL_INTERVAL: Duration = Duration::from_millis(100);

/// `INDEXING_STALENESS_BOUND` must stay larger than `INDEXING_READY_TIMEOUT`,
/// or the read-time staleness self-heal could fire within a single caller's
/// own wait -- reintroducing the cross-caller self-heal race this bound
/// exists to prevent.
const _: () = assert!(
    INDEXING_STALENESS_BOUND.as_nanos() > INDEXING_READY_TIMEOUT.as_nanos(),
    "INDEXING_STALENESS_BOUND must be greater than INDEXING_READY_TIMEOUT"
);

/// `PROGRESS_SETTLE` (the read-path settle window) must stay shorter than
/// `PROGRESS_LATCH_IDLE` (the write-path latch threshold) -- see
/// `bridge::indexing::PROGRESS_LATCH_IDLE`'s doc for why collapsing the two
/// into a single threshold reintroduces a real regression (N1).
const _: () = assert!(
    PROGRESS_SETTLE.as_nanos() < PROGRESS_LATCH_IDLE.as_nanos(),
    "PROGRESS_SETTLE must be less than PROGRESS_LATCH_IDLE"
);

/// A settle window longer than the gate's own wait timeout would let
/// `wait_for_indexing_ready` time out while the entry is merely mid-settle,
/// not actually still loading.
const _: () = assert!(
    PROGRESS_SETTLE.as_nanos() < INDEXING_READY_TIMEOUT.as_nanos(),
    "PROGRESS_SETTLE must be less than INDEXING_READY_TIMEOUT"
);

/// Flattens a `Definition` (`Location` or `Location[]`) into an owned `Vec`.
fn definition_to_locations(definition: lsp_types::Definition) -> Vec<lsp_types::Location> {
    match definition {
        lsp_types::Definition::Location(loc) => vec![loc],
        lsp_types::Definition::LocationList(locs) => locs,
    }
}

/// Converts a `DefinitionLink` into a plain `Location` pointing at its target.
fn definition_link_to_location(link: lsp_types::DefinitionLink) -> lsp_types::Location {
    lsp_types::Location {
        uri: link.target_uri,
        range: link.target_selection_range,
    }
}

/// Hard cap on the number of `Location`s/symbols a single call normalizes
/// (`goto`, `references`, `workspace_symbol_search`). Without a limit, a
/// response naming an unbounded number of locations turns one MCP tool call
/// into an unbounded number of range conversions -- each one a potential
/// disk read on a cache miss -- letting a hostile or misbehaving LSP server
/// amplify one request into massive I/O (see #474). Applied before
/// normalization, not after, so it bounds the work actually done rather
/// than just the size of the returned list. Also used by
/// `Translator::handle_workspace_symbol` to clamp its caller-supplied
/// `limit`, which otherwise has no upper bound of its own.
pub(super) const MAX_NORMALIZED_LOCATIONS: usize = 10_000;

/// Converts raw LSP locations into MCP-facing `Location` values, normalizing
/// each range into the caller's 1-based coordinate space.
///
/// Truncates to [`MAX_NORMALIZED_LOCATIONS`] first -- see its doc. Logs a
/// single `warn!` when that truncation actually drops locations, so a
/// response silently capped below what the LSP server reported is at least
/// visible in logs (see #474).
///
/// Deliberately not filtered to workspace roots: unlike a write-bearing
/// `WorkspaceEdit` (see `edits.rs`), a goto-X/references location is
/// read-only, and legitimate results routinely point outside the workspace
/// (e.g. the standard library or a crates.io dependency) -- dropping those
/// would break ordinary navigation. Any subsequent attempt to open or read
/// the path this location names still goes through the inbound
/// `validate_path_against_roots` gate (`mcp/server.rs`), which fails closed,
/// so the untrusted-URI concern is already covered downstream.
async fn lsp_locations_to_mcp(
    mut locs: Vec<lsp_types::Location>,
    ctx: &EncodingCtx,
) -> NormalizedLocations {
    let truncated = locs.len() > MAX_NORMALIZED_LOCATIONS;
    if truncated {
        tracing::warn!(
            reported = locs.len(),
            cap = MAX_NORMALIZED_LOCATIONS,
            "LSP response location count exceeds MAX_NORMALIZED_LOCATIONS; truncating"
        );
    }
    locs.truncate(MAX_NORMALIZED_LOCATIONS);
    let mut locations = Vec::with_capacity(locs.len());
    for loc in locs {
        locations.push(Location {
            uri: loc.uri.to_string(),
            range: ctx.normalize_range(&loc.uri, loc.range).await,
            out_of_workspace: ctx.is_out_of_workspace(&loc.uri),
        });
    }
    NormalizedLocations {
        locations,
        truncated,
        positions_degraded: ctx.positions_degraded(),
    }
}

/// [`lsp_locations_to_mcp`]'s result: the normalized locations plus whether
/// [`MAX_NORMALIZED_LOCATIONS`] actually dropped any of the LSP server's
/// reported locations -- surfaced to the MCP caller via each result DTO's
/// `truncated` field, since `references`'/goto-X's tool descriptions
/// otherwise imply a complete result (see #474) -- and whether any position
/// among them could not be resolved for encoding conversion while
/// normalizing (disk-read budget exhaustion, an unresolvable path, a line
/// past EOF, or invalid UTF-8 -- see `ctx.positions_degraded()`), surfaced
/// via each result DTO's `positions_degraded` field (#497).
struct NormalizedLocations {
    locations: Vec<Location>,
    truncated: bool,
    positions_degraded: bool,
}

/// The two response shapes shared by `textDocument/definition`,
/// `textDocument/implementation`, and `textDocument/typeDefinition`: either a
/// single `Definition` (`Location` or `Location[]`), or a `DefinitionLink[]`
/// from clients that opted into `LinkSupport`.
enum GotoKind {
    /// A plain `Definition`, as returned to clients without `LinkSupport`.
    Definition(lsp_types::Definition),
    /// A `DefinitionLink[]`, as returned to clients with `LinkSupport`.
    DefinitionLinkList(Vec<lsp_types::DefinitionLink>),
}

/// Implemented once per go-to-X response enum so [`goto_response_to_locations`]
/// can normalize all three through one code path instead of three near-identical
/// match arms.
trait GotoResponse {
    /// Reduce the response enum down to the two variants shared by every
    /// go-to-X LSP response.
    fn into_kind(self) -> GotoKind;
}

impl GotoResponse for lsp_types::DefinitionResponse {
    fn into_kind(self) -> GotoKind {
        match self {
            Self::Definition(def) => GotoKind::Definition(def),
            Self::DefinitionLinkList(links) => GotoKind::DefinitionLinkList(links),
        }
    }
}

impl GotoResponse for lsp_types::ImplementationResponse {
    fn into_kind(self) -> GotoKind {
        match self {
            Self::Definition(def) => GotoKind::Definition(def),
            Self::DefinitionLinkList(links) => GotoKind::DefinitionLinkList(links),
        }
    }
}

impl GotoResponse for lsp_types::TypeDefinitionResponse {
    fn into_kind(self) -> GotoKind {
        match self {
            Self::Definition(def) => GotoKind::Definition(def),
            Self::DefinitionLinkList(links) => GotoKind::DefinitionLinkList(links),
        }
    }
}

/// Normalize a go-to-X response (`textDocument/definition`,
/// `textDocument/implementation`, or `textDocument/typeDefinition`) into a
/// flat list of MCP `Location` values.
async fn goto_response_to_locations<R: GotoResponse>(
    response: Option<R>,
    ctx: &EncodingCtx,
) -> NormalizedLocations {
    let lsp_locs = match response.map(GotoResponse::into_kind) {
        Some(GotoKind::Definition(def)) => definition_to_locations(def),
        Some(GotoKind::DefinitionLinkList(links)) => {
            links.into_iter().map(definition_link_to_location).collect()
        }
        None => vec![],
    };
    lsp_locations_to_mcp(lsp_locs, ctx).await
}

/// Implemented once per go-to-X request params type so [`Translator::handle_goto`]
/// can build request params generically instead of duplicating the
/// `TextDocumentPositionParams` wiring per handler.
trait GotoParams: Sized {
    /// Build the request params from the resolved document position, filling
    /// the remaining fields (work-done/partial-result progress) with defaults.
    fn from_position(text_document_position_params: TextDocumentPositionParams) -> Self;
}

impl GotoParams for lsp_types::DefinitionParams {
    fn from_position(text_document_position_params: TextDocumentPositionParams) -> Self {
        Self {
            text_document_position_params,
            work_done_progress_params: WorkDoneProgressParams::default(),
            partial_result_params: PartialResultParams::default(),
        }
    }
}

impl GotoParams for lsp_types::ImplementationParams {
    fn from_position(text_document_position_params: TextDocumentPositionParams) -> Self {
        Self {
            text_document_position_params,
            work_done_progress_params: WorkDoneProgressParams::default(),
            partial_result_params: PartialResultParams::default(),
        }
    }
}

impl GotoParams for lsp_types::TypeDefinitionParams {
    fn from_position(text_document_position_params: TextDocumentPositionParams) -> Self {
        Self {
            text_document_position_params,
            work_done_progress_params: WorkDoneProgressParams::default(),
            partial_result_params: PartialResultParams::default(),
        }
    }
}

/// Extracts hover contents as a plain string.
///
/// `MarkedString` is `#[deprecated]` in favor of `MarkupContent`, but LSP
/// 3.17 servers may still send it inside `Hover.contents` -- dropping
/// support would silently discard hover text from those servers, so this
/// (and `marked_string_to_string`) carry a narrow, scoped allow rather than
/// rewriting to `MarkupContent`-only.
#[allow(deprecated)]
fn extract_hover_contents(contents: lsp_types::Contents) -> String {
    match contents {
        lsp_types::Contents::MarkedString(marked_string) => marked_string_to_string(marked_string),
        lsp_types::Contents::MarkedStringList(marked_strings) => marked_strings
            .into_iter()
            .map(marked_string_to_string)
            .collect::<Vec<_>>()
            .join("\n\n"),
        lsp_types::Contents::MarkupContent(markup) => markup.value,
    }
}

/// Convert a marked string to a plain string.
#[allow(deprecated)]
fn marked_string_to_string(marked: lsp_types::MarkedString) -> String {
    match marked {
        lsp_types::MarkedString::String(s) => s,
        lsp_types::MarkedString::MarkedStringWithLanguage(ls) => {
            format!("```{}\n{}\n```", ls.language, ls.value)
        }
    }
}

impl Translator {
    /// Wait for the routed server `server_id` to finish its initial
    /// workspace-load/indexing phase before a whole-workspace query (hover,
    /// definition, implementation, type definition, references, rename,
    /// completions, code actions) reaches it. Called from
    /// [`Translator::prepare_gated_document`] for every call site declared
    /// [`IndexingGate::Required`].
    ///
    /// Returns immediately, without waiting, unless
    /// [`crate::bridge::NotificationCache::indexing_state`] currently
    /// reports [`IndexingState::Loading`] for `server_id` -- i.e. a
    /// recognized signal has positively indicated indexing is in progress.
    /// A server that has never reported any readiness signal
    /// ([`IndexingState::Unknown`]) is treated the same as
    /// [`IndexingState::Ready`]: without evidence indexing is happening,
    /// waiting would only add latency for servers and workspaces that have
    /// no indexing phase at all.
    ///
    /// # Errors
    ///
    /// Returns [`Error::WorkspaceIndexing`] if the server is still
    /// [`IndexingState::Loading`] after the translator's configured
    /// indexing-ready timeout (default [`INDEXING_READY_TIMEOUT`],
    /// overridable via [`Self::with_indexing_ready_timeout`]) elapses.
    pub(super) async fn wait_for_indexing_ready(&self, server_id: &ServerId) -> Result<()> {
        self.wait_for_indexing_ready_with(
            server_id,
            self.indexing_ready_timeout,
            INDEXING_POLL_INTERVAL,
        )
        .await
    }

    /// [`Self::wait_for_indexing_ready`] with an injectable timeout and poll
    /// interval, so tests can exercise the timeout path without waiting out
    /// the real default.
    ///
    /// On timeout this returns [`Error::WorkspaceIndexing`] to the caller
    /// *without* mutating any shared state -- self-healing for a stuck
    /// `Loading` signal (a dropped `quiescent: true` notification, or a
    /// server that stalls mid-index) is handled entirely by
    /// [`crate::bridge::NotificationCache::indexing_state`]'s own
    /// read-time staleness check, keyed to the signal's age rather than
    /// this call's. Earlier revisions reset the shared entry here on
    /// timeout, which let one caller's short timeout silently un-gate
    /// every other concurrent or later caller before its own deadline;
    /// never reintroduce a write here.
    async fn wait_for_indexing_ready_with(
        &self,
        server_id: &ServerId,
        timeout: Duration,
        poll_interval: Duration,
    ) -> Result<()> {
        let Some(cache) = self.notification_cache.as_ref() else {
            return Ok(());
        };

        let start = Instant::now();
        let deadline = start + timeout;
        loop {
            let state = cache.lock().await.indexing_state(server_id);
            if state != IndexingState::Loading {
                return Ok(());
            }
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Err(Error::WorkspaceIndexing {
                    server_id: server_id.clone(),
                    elapsed_secs: start.elapsed().as_secs(),
                });
            }
            tokio::time::sleep(poll_interval.min(remaining)).await;
        }
    }

    /// Handle hover request.
    ///
    /// # Errors
    ///
    /// Returns an error if the LSP request fails, the file cannot be opened,
    /// the routed server does not advertise `hoverProvider` support, or the
    /// server is still indexing the workspace after
    /// `INDEXING_READY_TIMEOUT`.
    pub async fn handle_hover(&self, file_path: String, position: Position) -> Result<HoverResult> {
        let Position { line, character } = position;
        let (server_id, client, uri) = self
            .prepare_gated_document(
                &file_path,
                ToolKind::Hover,
                Capability::Hover,
                IndexingGate::Required,
            )
            .await?;
        let ctx = self.encoding_ctx(&server_id);
        let lsp_position = ctx.to_lsp(&uri, line, character).await;
        let response_uri = uri.clone();

        let params = LspHoverParams {
            text_document_position_params: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier { uri },
                position: lsp_position,
            },
            work_done_progress_params: WorkDoneProgressParams::default(),
        };

        let response = client
            .request_typed::<lsp_types::HoverRequest>(params, client.request_timeout())
            .await?;

        let result = match response {
            Some(hover) => {
                let contents = extract_hover_contents(hover.contents);
                let range = match hover.range {
                    Some(r) => Some(ctx.normalize_range(&response_uri, r).await),
                    None => None,
                };
                HoverResult {
                    contents,
                    range,
                    positions_degraded: ctx.positions_degraded(),
                }
            }
            None => HoverResult {
                contents: "No hover information available".to_string(),
                range: None,
                positions_degraded: ctx.positions_degraded(),
            },
        };

        Ok(result)
    }

    /// Shared implementation of the go-to-X handlers (`textDocument/definition`,
    /// `textDocument/implementation`, `textDocument/typeDefinition`): gate on
    /// the request's capability and on indexing readiness, translate the MCP
    /// position into LSP coordinates, dispatch the LSP request, and flatten
    /// the response into MCP locations. Each public handler supplies its
    /// request type via `R` plus the capability key/predicate specific to
    /// it.
    ///
    /// # Errors
    ///
    /// Returns an error if the LSP request fails, the file cannot be opened,
    /// the routed server does not advertise `capability` support, or the
    /// server is still indexing the workspace after `INDEXING_READY_TIMEOUT`.
    async fn handle_goto<R, T>(
        &self,
        file_path: &str,
        position: Position,
        tool: ToolKind,
        capability: Capability,
    ) -> Result<NormalizedLocations>
    where
        R: lsp_types::Request<Result = Option<T>>,
        R::Params: GotoParams,
        T: GotoResponse,
    {
        let Position { line, character } = position;
        let (server_id, client, uri) = self
            .prepare_gated_document(file_path, tool, capability, IndexingGate::Required)
            .await?;
        let ctx = self.encoding_ctx(&server_id);
        let lsp_position = ctx.to_lsp(&uri, line, character).await;

        let params = R::Params::from_position(TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: lsp_position,
        });

        let response = client
            .request_typed::<R>(params, client.request_timeout())
            .await?;

        Ok(goto_response_to_locations(response, &ctx).await)
    }

    /// Handle definition request.
    ///
    /// # Errors
    ///
    /// Returns an error if the LSP request fails, the file cannot be opened,
    /// the routed server does not advertise `definitionProvider` support, or
    /// the server is still indexing the workspace after
    /// `INDEXING_READY_TIMEOUT`.
    pub async fn handle_definition(
        &self,
        file_path: String,
        position: Position,
    ) -> Result<DefinitionResult> {
        let NormalizedLocations {
            locations,
            truncated,
            positions_degraded,
        } = self
            .handle_goto::<lsp_types::DefinitionRequest, _>(
                &file_path,
                position,
                ToolKind::Definition,
                Capability::Definition,
            )
            .await?;

        Ok(DefinitionResult {
            locations,
            truncated,
            positions_degraded,
        })
    }

    /// Handle references request.
    ///
    /// # Errors
    ///
    /// Returns an error if the LSP request fails, the file cannot be opened,
    /// the routed server does not advertise `referencesProvider` support, or
    /// the server is still indexing the workspace after
    /// `INDEXING_READY_TIMEOUT`.
    pub async fn handle_references(
        &self,
        file_path: String,
        position: Position,
        include_declaration: bool,
    ) -> Result<ReferencesResult> {
        let Position { line, character } = position;
        let (server_id, client, uri) = self
            .prepare_gated_document(
                &file_path,
                ToolKind::References,
                Capability::References,
                IndexingGate::Required,
            )
            .await?;
        let ctx = self.encoding_ctx(&server_id);
        let lsp_position = ctx.to_lsp(&uri, line, character).await;

        let params = ReferenceParams {
            text_document_position_params: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier { uri },
                position: lsp_position,
            },
            work_done_progress_params: WorkDoneProgressParams::default(),
            partial_result_params: PartialResultParams::default(),
            context: ReferenceContext {
                include_declaration,
            },
        };

        let response = client
            .request_typed::<lsp_types::ReferencesRequest>(params, client.request_timeout())
            .await?;

        let locations = response.unwrap_or_default();
        let NormalizedLocations {
            locations,
            truncated,
            positions_degraded,
        } = lsp_locations_to_mcp(locations, &ctx).await;

        Ok(ReferencesResult {
            locations,
            truncated,
            positions_degraded,
        })
    }

    /// Handle go-to-implementation request (`textDocument/implementation`).
    ///
    /// Returns the locations of trait method or interface member implementations.
    ///
    /// # Errors
    ///
    /// Returns an error if the LSP request fails, the file cannot be opened,
    /// the routed server does not advertise `implementationProvider`
    /// support, or the server is still indexing the workspace after
    /// `INDEXING_READY_TIMEOUT`.
    pub async fn handle_implementation(
        &self,
        file_path: String,
        position: Position,
    ) -> Result<LocationsResult> {
        let NormalizedLocations {
            locations,
            truncated,
            positions_degraded,
        } = self
            .handle_goto::<lsp_types::ImplementationRequest, _>(
                &file_path,
                position,
                ToolKind::Implementation,
                Capability::Implementation,
            )
            .await?;

        Ok(LocationsResult {
            locations,
            truncated,
            positions_degraded,
        })
    }

    /// Handle go-to-type-definition request (`textDocument/typeDefinition`).
    ///
    /// Returns the type definition location of the expression at position. Distinct
    /// from go-to-definition for variable bindings where definition and type differ.
    ///
    /// # Errors
    ///
    /// Returns an error if the LSP request fails, the file cannot be opened,
    /// the routed server does not advertise `typeDefinitionProvider`
    /// support, or the server is still indexing the workspace after
    /// `INDEXING_READY_TIMEOUT`.
    pub async fn handle_type_definition(
        &self,
        file_path: String,
        position: Position,
    ) -> Result<LocationsResult> {
        let NormalizedLocations {
            locations,
            truncated,
            positions_degraded,
        } = self
            .handle_goto::<lsp_types::TypeDefinitionRequest, _>(
                &file_path,
                position,
                ToolKind::TypeDefinition,
                Capability::TypeDefinition,
            )
            .await?;

        Ok(LocationsResult {
            locations,
            truncated,
            positions_degraded,
        })
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, deprecated)]
mod tests {
    use std::fs;
    use std::sync::Arc;
    use std::time::Duration;

    use tempfile::TempDir;
    use tokio::io::BufReader;
    use tokio::sync::Mutex;
    use tokio::time::timeout;
    use url::Url;

    use super::*;
    use crate::bridge::encoding::PositionEncoding;
    use crate::bridge::translator::testing::*;
    use crate::bridge::{NotificationCache, lock_std, path_to_uri};
    use crate::config::ServerId;

    // -----------------------------------------------------------------
    // Indexing readiness gate (`Translator::wait_for_indexing_ready`)
    // -----------------------------------------------------------------

    #[tokio::test]
    async fn test_wait_for_indexing_ready_without_cache_is_noop() {
        // No wired cache (most fixtures) must never block -- see `Translator::notification_cache`'s field doc.
        let translator = Translator::new();
        let server_id = ServerId::from("rust");

        translator
            .wait_for_indexing_ready(&server_id)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_wait_for_indexing_ready_unknown_state_is_noop() {
        let translator = Translator::new()
            .with_notification_cache(Arc::new(Mutex::new(NotificationCache::new())));
        let server_id = ServerId::from("rust");

        translator
            .wait_for_indexing_ready(&server_id)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_wait_for_indexing_ready_ready_state_is_noop() {
        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        let server_id = ServerId::from("rust");
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": true})),
        );
        let translator = Translator::new().with_notification_cache(cache);

        translator
            .wait_for_indexing_ready(&server_id)
            .await
            .unwrap();
    }

    /// #424: `with_indexing_ready_timeout` must actually change the bound
    /// `wait_for_indexing_ready` (the public entry point, not the
    /// timeout-injectable `_with` test helper) waits before giving up --
    /// pins the config wiring end-to-end rather than only the constructor
    /// storing the value.
    #[tokio::test(start_paused = true)]
    async fn test_wait_for_indexing_ready_uses_configured_timeout_override() {
        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        let server_id = ServerId::from("rust");
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        let translator = Translator::new()
            .with_notification_cache(cache)
            .with_indexing_ready_timeout(Duration::from_secs(5));

        let start = Instant::now();
        let err = translator
            .wait_for_indexing_ready(&server_id)
            .await
            .unwrap_err();

        assert!(matches!(err, Error::WorkspaceIndexing { elapsed_secs, .. } if elapsed_secs == 5));
        assert_eq!(start.elapsed(), Duration::from_secs(5));
    }

    #[tokio::test]
    async fn test_wait_for_indexing_ready_loading_times_out() {
        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        let server_id = ServerId::from("rust");
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        let translator = Translator::new().with_notification_cache(cache);

        let err = translator
            .wait_for_indexing_ready_with(
                &server_id,
                Duration::from_millis(50),
                Duration::from_millis(10),
            )
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            Error::WorkspaceIndexing { server_id: id, .. } if id == ServerId::from("rust")
        ));
    }

    #[tokio::test]
    async fn test_wait_for_indexing_ready_returns_ok_once_signaled_ready() {
        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        let server_id = ServerId::from("rust");
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        let translator = Translator::new().with_notification_cache(Arc::clone(&cache));

        let waiter = {
            let server_id = server_id.clone();
            tokio::spawn(async move {
                translator
                    .wait_for_indexing_ready_with(
                        &server_id,
                        Duration::from_secs(5),
                        Duration::from_millis(10),
                    )
                    .await
            })
        };

        tokio::time::sleep(Duration::from_millis(30)).await;
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": true})),
        );

        timeout(Duration::from_secs(1), waiter)
            .await
            .expect("waiter task timed out")
            .expect("waiter task panicked")
            .expect("expected Ok once quiescent");
    }

    /// End-to-end: a real handler (`handle_hover`) must surface
    /// `Error::WorkspaceIndexing` -- not an empty/`null` result -- when the
    /// routed server is still `Loading`, without ever reaching the fake LSP
    /// server. Runs under paused virtual time so it does not actually wait
    /// out the real `INDEXING_READY_TIMEOUT`.
    #[tokio::test(start_paused = true)]
    async fn test_handle_hover_returns_workspace_indexing_error_when_loading() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            hover_provider: Some(lsp_types::HoverProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, _server) = translator_with_capabilities(&dir, &server_id, caps);

        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        let translator = translator.with_notification_cache(cache);

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

        let err = translator
            .handle_hover(path.to_string_lossy().to_string(), pos(1, 1))
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            Error::WorkspaceIndexing { server_id: id, elapsed_secs: 30 } if id == server_id
        ));
    }

    /// Companion to the timeout test above: when the cache reports `Ready`,
    /// `handle_hover` must dispatch normally with no added delay.
    #[tokio::test]
    async fn test_handle_hover_dispatches_when_indexing_ready() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            hover_provider: Some(lsp_types::HoverProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, mut server) = translator_with_capabilities(&dir, &server_id, caps);

        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": true})),
        );
        let translator = Arc::new(translator.with_notification_cache(cache));

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

        let handle = {
            let translator = Arc::clone(&translator);
            let path = path.to_string_lossy().to_string();
            tokio::spawn(async move { translator.handle_hover(path, pos(1, 1)).await })
        };

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

        write_response(
            &mut server.read_half_stdin,
            &request["id"],
            serde_json::json!({
                "contents": {"kind": "markdown", "value": "hover text"}
            }),
        )
        .await;

        let result = handle.await.unwrap().unwrap();
        assert_eq!(result.contents, "hover text");
    }

    /// End-to-end: `handle_definition` must surface `Error::WorkspaceIndexing`
    /// while the routed server is still `Loading`, without reaching the fake
    /// LSP server.
    #[tokio::test(start_paused = true)]
    async fn test_handle_definition_returns_workspace_indexing_error_when_loading() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            definition_provider: Some(lsp_types::DefinitionProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, _server) = translator_with_capabilities(&dir, &server_id, caps);

        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        let translator = translator.with_notification_cache(cache);

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

        let err = translator
            .handle_definition(path.to_string_lossy().to_string(), pos(1, 1))
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            Error::WorkspaceIndexing { server_id: id, .. } if id == server_id
        ));
    }

    /// Companion: when the cache reports `Ready`, `handle_definition` must
    /// dispatch normally.
    #[tokio::test]
    async fn test_handle_definition_dispatches_when_indexing_ready() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            definition_provider: Some(lsp_types::DefinitionProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, mut server) = translator_with_capabilities(&dir, &server_id, caps);

        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": true})),
        );
        let translator = Arc::new(translator.with_notification_cache(cache));

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

        let handle = {
            let translator = Arc::clone(&translator);
            let path = path.to_string_lossy().to_string();
            tokio::spawn(async move { translator.handle_definition(path, pos(1, 1)).await })
        };

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

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

        let result = handle.await.unwrap().unwrap();
        assert!(result.locations.is_empty());
    }

    /// End-to-end: `handle_references` must surface `Error::WorkspaceIndexing`
    /// while the routed server is still `Loading`, without reaching the fake
    /// LSP server.
    #[tokio::test(start_paused = true)]
    async fn test_handle_references_returns_workspace_indexing_error_when_loading() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            references_provider: Some(lsp_types::ReferencesProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, _server) = translator_with_capabilities(&dir, &server_id, caps);

        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        let translator = translator.with_notification_cache(cache);

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

        let err = translator
            .handle_references(path.to_string_lossy().to_string(), pos(1, 1), true)
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            Error::WorkspaceIndexing { server_id: id, .. } if id == server_id
        ));
    }

    /// Companion: when the cache reports `Ready`, `handle_references` must
    /// dispatch normally.
    #[tokio::test]
    async fn test_handle_references_dispatches_when_indexing_ready() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            references_provider: Some(lsp_types::ReferencesProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, mut server) = translator_with_capabilities(&dir, &server_id, caps);

        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": true})),
        );
        let translator = Arc::new(translator.with_notification_cache(cache));

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

        let handle = {
            let translator = Arc::clone(&translator);
            let path = path.to_string_lossy().to_string();
            tokio::spawn(async move { translator.handle_references(path, pos(1, 1), true).await })
        };

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

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

        let result = handle.await.unwrap().unwrap();
        assert!(result.locations.is_empty());
    }

    /// S3 fix: `handle_implementation` shares `handle_goto` with
    /// `handle_definition` and must now be gated the same way --
    /// `textDocument/implementation` needs the whole-crate trait-impl index,
    /// which is at least as index-dependent as `definition`.
    #[tokio::test(start_paused = true)]
    async fn test_handle_implementation_returns_workspace_indexing_error_when_loading() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            implementation_provider: Some(lsp_types::ImplementationProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, _server) = translator_with_capabilities(&dir, &server_id, caps);

        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        let translator = translator.with_notification_cache(cache);

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

        let err = translator
            .handle_implementation(path.to_string_lossy().to_string(), pos(1, 1))
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            Error::WorkspaceIndexing { server_id: id, .. } if id == server_id
        ));
    }

    /// S3 fix, companion for `handle_type_definition`.
    #[tokio::test(start_paused = true)]
    async fn test_handle_type_definition_returns_workspace_indexing_error_when_loading() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            type_definition_provider: Some(lsp_types::TypeDefinitionProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, _server) = translator_with_capabilities(&dir, &server_id, caps);

        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        let translator = translator.with_notification_cache(cache);

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

        let err = translator
            .handle_type_definition(path.to_string_lossy().to_string(), pos(1, 1))
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            Error::WorkspaceIndexing { server_id: id, .. } if id == server_id
        ));
    }

    /// A timed-out wait must return `Error::WorkspaceIndexing` to its own
    /// caller without mutating the shared cache entry -- a fixed-in-review
    /// regression had the timeout handler reset the entry to `Unknown`,
    /// which released every other concurrent/later caller early (see
    /// `test_wait_for_indexing_ready_one_callers_timeout_does_not_release_another`
    /// for the direct reproduction). Self-healing for a genuinely stuck
    /// signal now lives entirely in
    /// `NotificationCache::indexing_state`'s own staleness check.
    #[tokio::test]
    async fn test_wait_for_indexing_ready_timeout_does_not_mutate_shared_state() {
        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        let server_id = ServerId::from("rust");
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        let translator = Translator::new().with_notification_cache(Arc::clone(&cache));

        translator
            .wait_for_indexing_ready_with(
                &server_id,
                Duration::from_millis(30),
                Duration::from_millis(10),
            )
            .await
            .unwrap_err();

        assert_eq!(
            cache.lock().await.indexing_state(&server_id),
            IndexingState::Loading,
            "a timed-out wait must not touch the shared entry -- it is still fresh, so it must \
             still read as Loading for any other caller"
        );
    }

    /// Direct reproduction of the self-heal race: a short-timeout waiter's
    /// own timeout must never resolve a concurrent long-timeout waiter's
    /// independent wait early. Before the fix, both waiters observed the
    /// same shared `IndexingState`, and the short waiter's timeout handler
    /// reset it to `Unknown` as a side effect -- silently un-gating the
    /// long waiter tens of seconds before its own deadline.
    #[tokio::test]
    async fn test_wait_for_indexing_ready_one_callers_timeout_does_not_release_another() {
        let cache = Arc::new(Mutex::new(NotificationCache::new()));
        let server_id = ServerId::from("rust");
        cache.lock().await.observe_indexing_signal(
            &server_id,
            "experimental/serverStatus",
            Some(&serde_json::json!({"quiescent": false})),
        );
        let translator = Arc::new(Translator::new().with_notification_cache(Arc::clone(&cache)));

        let short = {
            let translator = Arc::clone(&translator);
            let server_id = server_id.clone();
            tokio::spawn(async move {
                translator
                    .wait_for_indexing_ready_with(
                        &server_id,
                        Duration::from_millis(80),
                        Duration::from_millis(10),
                    )
                    .await
            })
        };
        let long = {
            let translator = Arc::clone(&translator);
            let server_id = server_id.clone();
            tokio::spawn(async move {
                translator
                    .wait_for_indexing_ready_with(
                        &server_id,
                        Duration::from_secs(30),
                        Duration::from_millis(10),
                    )
                    .await
            })
        };

        let short_result = short.await.unwrap();
        assert!(
            matches!(short_result, Err(Error::WorkspaceIndexing { .. })),
            "the short-timeout waiter must time out on its own schedule, got {short_result:?}"
        );

        // Well past the short waiter's 80ms deadline, nowhere near the long
        // waiter's 30s one.
        tokio::time::sleep(Duration::from_millis(150)).await;
        assert!(
            !long.is_finished(),
            "a concurrent caller's short timeout must never resolve another caller's \
             independent wait early"
        );
        long.abort();
    }

    #[test]
    fn test_extract_hover_contents_string() {
        let marked_string = lsp_types::MarkedString::String("Test hover".to_string());
        let contents = lsp_types::Contents::MarkedString(marked_string);
        let result = extract_hover_contents(contents);
        assert_eq!(result, "Test hover");
    }

    #[test]
    fn test_extract_hover_contents_language_string() {
        let marked_string = lsp_types::MarkedString::MarkedStringWithLanguage(
            lsp_types::MarkedStringWithLanguage {
                language: "rust".to_string(),
                value: "fn main() {}".to_string(),
            },
        );
        let contents = lsp_types::Contents::MarkedString(marked_string);
        let result = extract_hover_contents(contents);
        assert_eq!(result, "```rust\nfn main() {}\n```");
    }

    #[test]
    fn test_extract_hover_contents_markup() {
        let markup = lsp_types::MarkupContent {
            kind: lsp_types::MarkupKind::Markdown,
            value: "# Documentation".to_string(),
        };
        let contents = lsp_types::Contents::MarkupContent(markup);
        let result = extract_hover_contents(contents);
        assert_eq!(result, "# Documentation");
    }

    /// Success-path coverage for `handle_definition` through the
    /// `Definition::Location` -> `GotoKind::Definition` arm, pinning the
    /// `GotoResponse` impl for `DefinitionResponse`.
    #[tokio::test]
    async fn test_handle_definition_flattens_single_location() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            definition_provider: Some(lsp_types::DefinitionProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, mut server) = translator_with_capabilities(&dir, &server_id, caps);

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

        let translator = Arc::new(translator);
        let handle = {
            let translator = Arc::clone(&translator);
            let path = path.to_string_lossy().to_string();
            tokio::spawn(async move {
                translator
                    .handle_definition(
                        path,
                        Position {
                            line: 1,
                            character: 1,
                        },
                    )
                    .await
            })
        };

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

        write_response(
            &mut server.read_half_stdin,
            &request["id"],
            serde_json::json!({
                "uri": target_uri,
                "range": {
                    "start": {"line": 0, "character": 0},
                    "end": {"line": 0, "character": 6}
                }
            }),
        )
        .await;

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

        assert_eq!(result.locations.len(), 1);
        assert_eq!(result.locations[0].uri, target_uri);
        assert!(
            !result.locations[0].out_of_workspace,
            "a definition location inside the workspace root must not be marked out_of_workspace"
        );
    }

    /// #415 (revised per critic C1): a definition location whose URI falls
    /// outside every configured workspace root must still be returned --
    /// goto-definition into the standard library or a crates.io dependency
    /// is normal, expected navigation, not an attack. The untrusted-URI
    /// concern is instead covered downstream, by the inbound
    /// `validate_path_against_roots` gate any subsequent open/read of the
    /// path would hit.
    #[tokio::test]
    async fn test_handle_definition_does_not_filter_out_of_workspace_location() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            definition_provider: Some(lsp_types::DefinitionProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, mut server) = translator_with_capabilities(&dir, &server_id, caps);

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();
        let outside_uri = "file:///outside/workspace/stdlib.rs";

        let translator = Arc::new(translator);
        let handle = {
            let translator = Arc::clone(&translator);
            let path = path.to_string_lossy().to_string();
            tokio::spawn(async move {
                translator
                    .handle_definition(
                        path,
                        Position {
                            line: 1,
                            character: 1,
                        },
                    )
                    .await
            })
        };

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

        write_response(
            &mut server.read_half_stdin,
            &request["id"],
            serde_json::json!({
                "uri": outside_uri,
                "range": {
                    "start": {"line": 0, "character": 0},
                    "end": {"line": 0, "character": 6}
                }
            }),
        )
        .await;

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

        assert_eq!(
            result.locations.len(),
            1,
            "an out-of-workspace definition location (e.g. stdlib/a dependency) must be \
             returned, not dropped"
        );
        assert_eq!(result.locations[0].uri, outside_uri);
        assert!(
            result.locations[0].out_of_workspace,
            "a definition location outside every workspace root must be marked out_of_workspace"
        );
    }

    /// #415 (revised per critic C1) companion for `handle_references`: an
    /// out-of-workspace location must pass through unfiltered, same as an
    /// in-workspace one -- see `test_handle_definition_does_not_filter_out_of_workspace_location`.
    #[tokio::test]
    async fn test_handle_references_does_not_filter_out_of_workspace_location() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            references_provider: Some(lsp_types::ReferencesProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, mut server) = translator_with_capabilities(&dir, &server_id, caps);

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();
        let inside_path = dir.path().join("inside.rs");
        fs::write(&inside_path, "fn used() {}").unwrap();
        let inside_uri = Url::from_file_path(&inside_path).unwrap().to_string();
        let outside_uri = "file:///outside/workspace/stdlib.rs";

        let translator = Arc::new(translator);
        let handle = {
            let translator = Arc::clone(&translator);
            let path = path.to_string_lossy().to_string();
            tokio::spawn(async move { translator.handle_references(path, pos(1, 1), true).await })
        };

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

        write_response(
            &mut server.read_half_stdin,
            &request["id"],
            serde_json::json!([
                {
                    "uri": inside_uri,
                    "range": {
                        "start": {"line": 0, "character": 0},
                        "end": {"line": 0, "character": 4}
                    }
                },
                {
                    "uri": outside_uri,
                    "range": {
                        "start": {"line": 0, "character": 0},
                        "end": {"line": 0, "character": 4}
                    }
                }
            ]),
        )
        .await;

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

        assert_eq!(
            result.locations.len(),
            2,
            "both the in-workspace and out-of-workspace locations must survive"
        );
        assert!(result.locations.iter().any(|l| l.uri == inside_uri));
        assert!(result.locations.iter().any(|l| l.uri == outside_uri));
        assert!(
            !result
                .locations
                .iter()
                .find(|l| l.uri == inside_uri)
                .unwrap()
                .out_of_workspace,
            "an in-workspace reference location must not be marked out_of_workspace"
        );
        assert!(
            result
                .locations
                .iter()
                .find(|l| l.uri == outside_uri)
                .unwrap()
                .out_of_workspace,
            "an out-of-workspace reference location must be marked out_of_workspace"
        );
    }

    /// Regression for #474/M4: `get_references`' tool description no longer
    /// promises "all" references, since a response past
    /// `MAX_NORMALIZED_LOCATIONS` is capped -- the client must be able to
    /// detect that via `ReferencesResult::truncated` rather than silently
    /// receiving a partial result that looks complete.
    #[tokio::test]
    async fn test_handle_references_sets_truncated_flag_past_cap() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            references_provider: Some(lsp_types::ReferencesProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, mut server) = translator_with_capabilities(&dir, &server_id, caps);

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

        let translator = Arc::new(translator);
        let handle = {
            let translator = Arc::clone(&translator);
            let path = path.to_string_lossy().to_string();
            tokio::spawn(async move { translator.handle_references(path, pos(1, 1), true).await })
        };

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

        let locations: Vec<serde_json::Value> = (0..MAX_NORMALIZED_LOCATIONS + 500)
            .map(|_| {
                serde_json::json!({
                    "uri": uri,
                    "range": {
                        "start": {"line": 0, "character": 0},
                        "end": {"line": 0, "character": 4}
                    }
                })
            })
            .collect();
        write_response(
            &mut server.read_half_stdin,
            &request["id"],
            serde_json::json!(locations),
        )
        .await;

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

        assert_eq!(result.locations.len(), MAX_NORMALIZED_LOCATIONS);
        assert!(
            result.truncated,
            "a references response past MAX_NORMALIZED_LOCATIONS must set truncated: true"
        );
    }

    /// Success-path coverage for `handle_implementation` through the
    /// `Definition::LocationList` -> `GotoKind::Definition` arm, pinning the
    /// `GotoResponse` impl for `ImplementationResponse`.
    #[tokio::test]
    async fn test_handle_implementation_flattens_location_list() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            implementation_provider: Some(lsp_types::ImplementationProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, mut server) = translator_with_capabilities(&dir, &server_id, caps);

        let path = dir.path().join("main.rs");
        fs::write(&path, "fn main() {}").unwrap();
        let first_impl_path = dir.path().join("impl_a.rs");
        fs::write(&first_impl_path, "struct A;").unwrap();
        let first_impl_uri = Url::from_file_path(&first_impl_path).unwrap().to_string();
        let second_impl_path = dir.path().join("impl_b.rs");
        fs::write(&second_impl_path, "struct B;").unwrap();
        let second_impl_uri = Url::from_file_path(&second_impl_path).unwrap().to_string();

        let translator = Arc::new(translator);
        let handle = {
            let translator = Arc::clone(&translator);
            let path = path.to_string_lossy().to_string();
            tokio::spawn(async move {
                translator
                    .handle_implementation(
                        path,
                        Position {
                            line: 1,
                            character: 1,
                        },
                    )
                    .await
            })
        };

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

        write_response(
            &mut server.read_half_stdin,
            &request["id"],
            serde_json::json!([
                {
                    "uri": first_impl_uri,
                    "range": {
                        "start": {"line": 0, "character": 0},
                        "end": {"line": 0, "character": 9}
                    }
                },
                {
                    "uri": second_impl_uri,
                    "range": {
                        "start": {"line": 0, "character": 0},
                        "end": {"line": 0, "character": 9}
                    }
                }
            ]),
        )
        .await;

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

        assert_eq!(result.locations.len(), 2);
        assert_eq!(result.locations[0].uri, first_impl_uri);
        assert_eq!(result.locations[1].uri, second_impl_uri);
    }

    /// Success-path coverage for `handle_type_definition` through the
    /// `DefinitionLinkList` -> `GotoKind::DefinitionLinkList` arm, pinning
    /// the `GotoResponse` impl for `TypeDefinitionResponse` and the
    /// `definition_link_to_location` mapping (`target_selection_range`, not
    /// `target_range`).
    #[tokio::test]
    async fn test_handle_type_definition_flattens_definition_link_list() {
        let dir = TempDir::new().unwrap();
        let server_id = ServerId::from("rust");
        let caps = lsp_types::ServerCapabilities {
            type_definition_provider: Some(lsp_types::TypeDefinitionProvider::Bool(true)),
            ..Default::default()
        };
        let (translator, mut server) = translator_with_capabilities(&dir, &server_id, caps);

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

        let translator = Arc::new(translator);
        let handle = {
            let translator = Arc::clone(&translator);
            let path = path.to_string_lossy().to_string();
            tokio::spawn(async move {
                translator
                    .handle_type_definition(
                        path,
                        Position {
                            line: 1,
                            character: 1,
                        },
                    )
                    .await
            })
        };

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

        write_response(
            &mut server.read_half_stdin,
            &request["id"],
            serde_json::json!([{
                "targetUri": target_uri,
                "targetRange": {
                    "start": {"line": 0, "character": 0},
                    "end": {"line": 0, "character": 18}
                },
                "targetSelectionRange": {
                    "start": {"line": 0, "character": 7},
                    "end": {"line": 0, "character": 17}
                }
            }]),
        )
        .await;

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

        assert_eq!(result.locations.len(), 1);
        assert_eq!(result.locations[0].uri, target_uri);
        assert_eq!(result.locations[0].range.start.character, 8);
    }

    // -----------------------------------------------------------------
    // Resource-amplification defenses (#474)
    // -----------------------------------------------------------------

    /// Regression for #474's exact attack scenario: many `Location`s
    /// clustered onto a handful of distinct `(file, line)` pairs must cost
    /// one disk read per distinct pair, not one per location. Proven through
    /// the real `lsp_locations_to_mcp` entry point shared by `handle_goto`
    /// and `handle_references` -- not by calling the cache-backed helper
    /// directly -- and via the cache's own size, which is a direct count of
    /// how many times the disk-read fallback actually ran.
    #[tokio::test]
    async fn test_lsp_locations_to_mcp_reads_disk_once_per_distinct_file_line() {
        let dir = TempDir::new().unwrap();
        let mut uris = Vec::new();
        for i in 0..3 {
            let path = dir.path().join(format!("file{i}.rs"));
            fs::write(&path, "hello").unwrap();
            uris.push(path_to_uri(&path).unwrap());
        }

        let ctx = test_ctx_with(PositionEncoding::Utf8);
        // 300 locations, but only 3 distinct (file, line) pairs.
        let locs: Vec<lsp_types::Location> = (0..300)
            .map(|i| lsp_types::Location {
                uri: uris[i % 3].clone(),
                range: lsp_types::Range {
                    start: lsp_types::Position {
                        line: 0,
                        character: 0,
                    },
                    end: lsp_types::Position {
                        line: 0,
                        character: 3,
                    },
                },
            })
            .collect();

        let result = lsp_locations_to_mcp(locs, &ctx).await;

        assert_eq!(result.locations.len(), 300);
        assert!(!result.truncated);
        assert!(
            result.locations.iter().all(|l| l.range.end.character == 4),
            "MCP columns are 1-based, so LSP byte offset 3 in all-ASCII \"hello\" must convert \
             to 4"
        );
        assert_eq!(
            lock_std(&ctx.line_cache).entries.len(),
            3,
            "300 locations across 3 distinct files must populate the cache with exactly 3 \
             entries (one disk read per distinct file/line), not one per location"
        );
    }

    /// Regression for #474: without a cap, a response naming an unbounded
    /// number of locations would drive an unbounded number of range
    /// conversions. `Utf16` needs no disk read at all (see `test_ctx`), so
    /// this isolates the truncation itself from I/O cost -- a response well
    /// past `MAX_NORMALIZED_LOCATIONS` must be truncated to it, not hang,
    /// OOM, or panic.
    #[tokio::test]
    async fn test_lsp_locations_to_mcp_truncates_to_max_normalized_locations() {
        let ctx = test_ctx();
        let uri = test_uri();
        let locs: Vec<lsp_types::Location> = (0..MAX_NORMALIZED_LOCATIONS + 500)
            .map(|_| lsp_types::Location {
                uri: uri.clone(),
                range: lsp_types::Range {
                    start: lsp_types::Position {
                        line: 0,
                        character: 0,
                    },
                    end: lsp_types::Position {
                        line: 0,
                        character: 1,
                    },
                },
            })
            .collect();

        let result = lsp_locations_to_mcp(locs, &ctx).await;

        assert_eq!(result.locations.len(), MAX_NORMALIZED_LOCATIONS);
        assert!(
            result.truncated,
            "a response naming more than MAX_NORMALIZED_LOCATIONS must report truncated: true"
        );
    }
}