deps-core 0.11.0

Core abstractions for deps-lsp: caching, errors, and traits
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
use tower_lsp_server::ls_types::{Hover, HoverContents, MarkupContent, MarkupKind, Position};

use crate::osv::{ADVISORY_DISPLAY_CAP, ScanOutcome};
use crate::{
    ParseResult, PublishTime, Registry, Version, VersionReq, format_relative_age,
    is_within_cooldown,
};

use super::{
    EcosystemFormatter, HOVER_RECENT_VERSIONS, VersionData, escape_markdown, markdown_code_span,
    position_in_range,
};

/// Formats the relative-age suffix for one "Recent versions" hover entry.
///
/// Returns an empty string when the registry doesn't expose a publish timestamp for
/// `version` (`published_at()` is `None`), so the entry renders exactly as it did
/// before this feature existed (graceful degradation, US-003).
///
/// `now` is taken as an explicit parameter rather than read internally so every entry
/// in the same "Recent versions" list is aged against one consistent instant.
fn version_age_suffix(version: &dyn Version, now: PublishTime) -> String {
    version
        .published_at()
        .map(|published| format!(" — {}", format_relative_age(published.age_secs_from(now))))
        .unwrap_or_default()
}

/// Bounds the `Registry::get_latest_matching` fallback (#373) hover fires when the
/// list-based `**Latest**` pick fails on a non-empty live list. Hover responses must
/// return quickly (`.claude/rules/rust-code.md`), and without this the fallback would
/// stack on top of `get_versions_with`'s own up-to-30s `reqwest` client timeout
/// (`HttpCache`), doubling worst-case hover latency to ~60s. `generate_hover` has no
/// `timeout_secs` config threaded in the way `lifecycle.rs`'s background fetch does, so
/// this is a fixed local bound rather than a configurable one — a few seconds is enough
/// slack for the already-rare "list-based pick failed" path without meaningfully
/// delaying the common case, which never reaches this fallback at all.
const HOVER_FALLBACK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

pub async fn generate_hover<R: Registry + ?Sized>(
    parse_result: &dyn ParseResult,
    position: Position,
    versions: VersionData<'_>,
    registry: &R,
    formatter: &dyn EcosystemFormatter,
    freshness: crate::freshness::FreshnessSettings,
    now: PublishTime,
) -> Option<Hover> {
    use std::fmt::Write;

    let dep = parse_result.dependencies().into_iter().find(|d| {
        let on_name = position_in_range(position, d.name_range());
        let on_version = d
            .version_range()
            .is_some_and(|r| position_in_range(position, r));
        on_name || on_version
    })?;

    // A non-resolvable source (e.g. `CustomRegistry`, Git, Path) doesn't resolve
    // against `registry` at all — fetching by name here would silently check an
    // unrelated or coincidentally-named public-registry package (#248), so hover
    // must skip the registry lookup and every section built from it entirely.
    let resolvable = dep.source().is_version_resolvable();

    // `now` is a caller-supplied parameter (issue #227 M4) rather than computed
    // internally via `PublishTime::now()` — this is what lets tests pin an exact
    // cooldown-boundary instant deterministically, and guarantees every age rendered
    // in this single hover response (the `**Latest**` line and the "Recent versions"
    // list below) is aged against the same instant.
    let available_versions = if resolvable {
        Some(
            registry
                .get_versions_with(dep.name(), freshness)
                .await
                .ok()?,
        )
    } else {
        None
    };

    let url = formatter.package_url(dep.name());

    // Pre-allocate with estimated capacity to reduce allocations
    let mut markdown = String::with_capacity(512);
    write!(
        &mut markdown,
        "# [{}]({})\n\n",
        escape_markdown(dep.name().as_str()),
        url
    )
    .unwrap();

    let normalized_name = formatter.normalize_package_name(dep.name());

    let resolved: Option<&str> = if formatter.manifest_requirement_is_resolved_version(dep) {
        dep.version_requirement().map(VersionReq::as_str)
    } else {
        versions
            .resolved
            .get(normalized_name.as_str())
            .or_else(|| versions.resolved.get(dep.name()))
            .map(String::as_str)
    };
    if let Some(resolved_ver) = resolved {
        write!(
            &mut markdown,
            "**Current**: {}\n\n",
            markdown_code_span(resolved_ver)
        )
        .unwrap();
    } else if let Some(version_req) = dep.version_requirement() {
        write!(
            &mut markdown,
            "**Requirement**: {}\n\n",
            markdown_code_span(version_req.as_str())
        )
        .unwrap();
    }

    if let Some(marker_expr) = dep.markers() {
        write!(
            &mut markdown,
            "**Active when**: {}\n\n",
            markdown_code_span(marker_expr)
        )
        .unwrap();
    }

    // The `**Latest**` line prefers the just-fetched Ch2 list (`available_versions`) over
    // the Ch1 cache (`versions.cached`, populated by the lifecycle's background fetch)
    // whenever a live fetch is available. Ch1 alone would let this line render a version
    // older than the one the "Recent versions" list right below it shows as `*(latest)*` —
    // a self-contradictory response when a new version is published between the last
    // background fetch and this hover call, with the cooldown callout then decided off the
    // stale operand too (issue #227 F5). Falls back to Ch1 only when there is no live list
    // at all (non-resolvable source) — NOT merely when the live list has no stable entry:
    // a live list that's all pre-release still means a live fetch happened, and rendering
    // a stale Ch1 version that may not even appear in the live "Recent versions" list below
    // would be exactly the self-contradiction #227 F5 fixed, via a different path (#313).
    //
    // Exception (#373): when the list-based pick fails on a non-empty list, `latest_line`
    // can render a version sourced from `list_fallback_latest` — `Registry::get_latest_matching`
    // instead of the list — which the "Recent versions" list below is built from `available_versions`
    // alone and so may not contain (Go's `/@latest` can answer with a pseudo-version `/@v/list`
    // never enumerates). No entry is marked `*(latest)*` in that case, since `live_latest_idx`
    // is `None`. This is an accepted, narrower trade-off than the contradiction #227 F5/#313
    // guard against: rendering *a* correct latest version, even one absent from or unmarked in
    // the list below, beats rendering no `**Latest**` line at all.
    //
    // `live_latest_idx` (not raw index 0) picks the entry: `available_versions` is sorted
    // purely by version number, so a pre-release with the highest number can sort to index 0
    // even though it isn't the ecosystem's "latest stable" pick — mirroring this line to the
    // raw top entry would tag a pre-release as `(latest)` below. The pick is delegated to
    // `Registry::select_latest_matching` — the exact same call `lifecycle.rs`'s background
    // fetch uses to populate `versions.cached`'s `latest` and every cache-backed diagnostic —
    // rather than re-derived here with a generic `is_stable()` scan. The two must never
    // disagree about what "latest" is: an ecosystem whose `select_latest_matching` applies a
    // ranking preference beyond plain resolvability (e.g. npm's #338 NFR-002, which prefers a
    // non-deprecated version over a newer deprecated one) gets that same preference reflected
    // in this hover response instead of hover independently picking a different version and
    // silently dropping that version's `*(deprecated)*`/`*(yanked)*` label because it thinks
    // it's `(latest)` (#347/#348 S1). Recorded as an index rather than a version string so the
    // "Recent versions" marker below can match by position instead of string equality, which
    // could spuriously tag more than one entry if two ever shared a version string.
    let wildcard_req = VersionReq::new("*");
    let live_latest_idx = available_versions
        .as_ref()
        .and_then(|v| registry.select_latest_matching(v, &wildcard_req));
    // #373: `live_latest_idx` can be `None` even though a live fetch DID happen and the
    // list is non-empty — e.g. Go's `/@v/list` never enumerates pseudo-versions, so an
    // untagged module whose whole tagged history is pre-release fails the list-based pick
    // entirely. This must not fall straight to the Ch1 cache (see the comment on
    // `latest_line` below) — instead mirror the exact fallback `lifecycle.rs`'s background
    // fetch already uses for this same case: a second call to `Registry::get_latest_matching`,
    // which some registries (Go's `/@latest`) answer from a source more complete than the
    // list endpoint. Only attempted for a non-empty live list with no list-based pick; an
    // empty or absent live list keeps falling back to Ch1 untouched. Bounded by
    // `HOVER_FALLBACK_TIMEOUT` and logged like `lifecycle.rs`'s own fallback — a failure,
    // timeout, or `None` here degrades gracefully to no `**Latest**` line, same as today:
    // `available_versions` already succeeded, so this fallback's own error must not abort
    // the rest of the hover.
    let list_fallback_latest = if available_versions.as_ref().is_some_and(|v| !v.is_empty())
        && live_latest_idx.is_none()
    {
        match tokio::time::timeout(
            HOVER_FALLBACK_TIMEOUT,
            registry.get_latest_matching(dep.name(), &wildcard_req),
        )
        .await
        {
            Ok(Ok(found)) => {
                tracing::debug!(package = %dep.name(), found = found.is_some(), "hover latest fallback (get_latest_matching) resolved");
                found
            }
            Ok(Err(error)) => {
                tracing::warn!(package = %dep.name(), %error, "hover latest fallback (get_latest_matching) failed");
                None
            }
            Err(_) => {
                tracing::warn!(
                    package = %dep.name(),
                    timeout_secs = HOVER_FALLBACK_TIMEOUT.as_secs(),
                    "hover latest fallback (get_latest_matching) timed out"
                );
                None
            }
        }
    } else {
        None
    };
    let cached_latest = resolvable
        .then(|| {
            versions
                .cached
                .get(normalized_name.as_str())
                .or_else(|| versions.cached.get(dep.name()))
        })
        .flatten();
    // A non-empty live list with no stable entry is deliberately treated differently from
    // an empty (or absent) live list: the former tries `list_fallback_latest` (#373) first —
    // a second registry call for the rare "list-based pick failed but a live fetch happened"
    // case — before giving up, rather than falling back to the Ch1 cache, since the cache's
    // version wouldn't be part of what the live list just showed. Only once that fallback
    // also yields nothing does the line render nothing at all (no header, matching the empty
    // "Recent versions" list right beneath it). An empty live list carries no such
    // contradiction risk — it has nothing to contradict — so it keeps falling back to Ch1,
    // same as when there's no live fetch.
    let latest_line: Option<(&str, Option<PublishTime>)> = match &available_versions {
        Some(v) if !v.is_empty() => live_latest_idx
            .map(|idx| &v[idx])
            .map(|live| (live.version_string(), live.published_at()))
            .or_else(|| {
                list_fallback_latest
                    .as_deref()
                    .map(|live| (live.version_string(), live.published_at()))
            }),
        _ => cached_latest.map(|v| (v.latest.as_str(), v.published_at)),
    };
    if let Some((latest_ver, raw_published_at)) = latest_line {
        let published_at = freshness.enabled.then_some(raw_published_at).flatten();
        let age_secs = published_at.map(|p| p.age_secs_from(now));
        write!(
            &mut markdown,
            "**Latest**: {}",
            markdown_code_span(latest_ver)
        )
        .unwrap();
        if let Some(age_secs) = age_secs {
            write!(
                &mut markdown,
                " *(published {})*",
                format_relative_age(age_secs)
            )
            .unwrap();
        }
        markdown.push_str("\n\n");
        if age_secs.is_some_and(|age| is_within_cooldown(age, freshness.cooldown_secs)) {
            markdown.push_str(
                "> ⏳ **Recently published** — this release is still within the cooldown window.\n\
                 > It may still be yanked or superseded; consider verifying before upgrading.\n\n",
            );
        }
    }

    let vuln_outcome = versions.vulnerabilities.and_then(|m| {
        m.get(&normalized_name)
            .or_else(|| m.get(dep.name().as_str()))
    });
    push_vulnerability_hover_section(&mut markdown, vuln_outcome);

    if let Some(available_versions) = &available_versions {
        // Matched by position against `live_latest_idx` (the header's stable-latest pick)
        // rather than raw index 0 or string equality: `available_versions` is sorted purely
        // by version number, so index 0 can be a pre-release the header itself doesn't call
        // "latest" (issue #313), and matching by version string instead of index could tag
        // more than one entry if two ever shared a version string. No match in the rendered
        // top-N slice simply omits the marker.
        markdown.push_str("**Recent versions**:\n");
        for (i, version) in available_versions
            .iter()
            .take(HOVER_RECENT_VERSIONS)
            .enumerate()
        {
            let version_span = markdown_code_span(version.version_string());
            let age_suffix = if freshness.enabled {
                version_age_suffix(version.as_ref(), now)
            } else {
                String::new()
            };
            if Some(i) == live_latest_idx {
                if version.removal_status().is_flagged() {
                    // The resolved "latest" can itself be flagged (e.g. npm's ranking
                    // preference falls through to a deprecated version when no clean one
                    // exists) — the deprecation/yank warning must not silently vanish just
                    // because this entry also carries the `(latest)` marker (#347/#348 S1).
                    writeln!(
                        &mut markdown,
                        "- {version_span} *(latest)* {}{age_suffix}",
                        formatter.yanked_label()
                    )
                    .unwrap();
                } else {
                    writeln!(&mut markdown, "- {version_span} *(latest)*{age_suffix}").unwrap();
                }
            } else if version.removal_status().is_flagged() {
                writeln!(
                    &mut markdown,
                    "- {} {}{}",
                    version_span,
                    formatter.yanked_label(),
                    age_suffix
                )
                .unwrap();
            } else {
                writeln!(&mut markdown, "- {version_span}{age_suffix}").unwrap();
            }
        }
    }

    markdown.push_str("\n---\n⌨️ **Press `Cmd+.` to update version**");

    Some(Hover {
        contents: HoverContents::Markup(MarkupContent {
            kind: MarkupKind::Markdown,
            value: markdown,
        }),
        range: Some(dep.name_range()),
    })
}

/// Lowercase display label for a [`crate::osv::VulnSeverity`], used only in hover text.
const fn severity_label(severity: crate::osv::VulnSeverity) -> &'static str {
    match severity {
        crate::osv::VulnSeverity::Critical => "critical",
        crate::osv::VulnSeverity::High => "high",
        crate::osv::VulnSeverity::Medium => "medium",
        crate::osv::VulnSeverity::Low => "low",
        crate::osv::VulnSeverity::Unknown => "unknown severity",
    }
}

/// Appends the hover "Security advisories" section, gated strictly on the
/// scan outcome — never on map absence.
///
/// `Vulnerable` gets the advisories list, `Clean` may state the affirmative
/// "no known vulnerabilities", and `Skipped` (or no scan at all) says
/// **nothing**: saying "clean" about a dependency that was never queried is
/// worse than saying nothing at all (`architecture.md` §8 invariant 0).
fn push_vulnerability_hover_section(markdown: &mut String, outcome: Option<&ScanOutcome>) {
    use std::fmt::Write;

    match outcome {
        Some(ScanOutcome::Vulnerable(dv)) => {
            markdown.push_str("### Security advisories\n\n");

            let shown = dv.advisories.iter().take(ADVISORY_DISPLAY_CAP);
            for advisory in shown {
                writeln!(
                    markdown,
                    "- **[{}]({})** — {}",
                    escape_markdown(&advisory.id),
                    advisory.url,
                    severity_label(advisory.severity)
                )
                .unwrap();
                writeln!(
                    markdown,
                    "  {}",
                    escape_markdown(
                        advisory
                            .summary
                            .as_deref()
                            .unwrap_or("(no summary provided)")
                    )
                )
                .unwrap();

                let mut details = Vec::with_capacity(2);
                if let Some(fixed) = advisory.fixed_versions.last() {
                    details.push(format!("Fixed in: {}", markdown_code_span(fixed)));
                }
                if !advisory.aliases.is_empty() {
                    details.push(format!(
                        "Aliases: {}",
                        escape_markdown(&advisory.aliases.join(", "))
                    ));
                }
                if !details.is_empty() {
                    writeln!(markdown, "  {}", details.join(" \u{b7} ")).unwrap();
                }
            }

            let shown_count = dv.advisories.len().min(ADVISORY_DISPLAY_CAP);
            let remaining = dv.total_known.saturating_sub(shown_count);
            if remaining > 0 {
                writeln!(markdown, "- *(+{remaining} more advisories)*").unwrap();
            }

            if let crate::osv::UpgradeStatus::CandidateVulnerable { version, .. } =
                &dv.upgrade_status
            {
                writeln!(
                    markdown,
                    "\n\u{26a0}\u{fe0f} Latest version {} is also affected.",
                    markdown_code_span(version)
                )
                .unwrap();
            }

            markdown.push('\n');
        }
        Some(ScanOutcome::Clean) => {
            markdown.push_str("**No known vulnerabilities** (OSV.dev)\n\n");
        }
        Some(ScanOutcome::Skipped(_)) | None => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::RemovalStatus;
    use crate::lsp_helpers::test_support::*;
    use crate::lsp_helpers::*;

    use std::collections::HashMap;
    use std::sync::Arc;

    #[tokio::test]
    async fn test_generate_hover_recent_versions_shows_age_when_known() {
        use std::collections::HashMap;

        let registry = MockRegistryWithVersions {
            versions: vec![MockVersionWithAge {
                version: "1.2.3".to_string(),
                yanked: false,
                // 2 days ago — safely mid-bucket, immune to sub-second test flakiness.
                published_at: Some(PublishTime::from_unix_secs(
                    PublishTime::now().as_unix_secs() - 2 * 24 * 60 * 60,
                )),
            }],
        };
        let parse_result = freshness_test_parse_result("serde");

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content.value.contains("- `1.2.3` *(latest)* — 2 days ago"),
            "got: {}",
            content.value
        );
    }

    #[tokio::test]
    async fn test_generate_hover_recent_versions_omits_age_when_unknown() {
        use std::collections::HashMap;

        let registry = MockRegistryWithVersions {
            versions: vec![MockVersionWithAge {
                version: "1.2.3".to_string(),
                yanked: false,
                published_at: None,
            }],
        };
        let parse_result = freshness_test_parse_result("serde");

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        // Exactly the pre-feature line: no trailing age suffix.
        assert!(content.value.contains("- `1.2.3` *(latest)*\n"));
        assert!(!content.value.contains("ago"));
    }

    #[tokio::test]
    async fn test_generate_hover_latest_marker_skips_prerelease_at_raw_top() {
        use std::collections::HashMap;

        // Raw registry order (newest by version number first): a pre-release sorts above
        // the actual stable latest, mirroring NuGet's Newtonsoft.Json 13.0.5-beta1 vs
        // 13.0.4 (#313).
        let registry = MockRegistryWithVersions {
            versions: vec![
                MockVersionWithAge {
                    version: "13.0.5-beta1".to_string(),
                    yanked: false,
                    published_at: None,
                },
                MockVersionWithAge {
                    version: "13.0.4".to_string(),
                    yanked: false,
                    published_at: None,
                },
            ],
        };
        let parse_result = freshness_test_parse_result("Newtonsoft.Json");

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content.value.contains("**Latest**: `13.0.4`"),
            "got: {}",
            content.value
        );
        assert!(
            content.value.contains("- `13.0.4` *(latest)*"),
            "the stable version, not the raw-top pre-release, should carry the marker; got: {}",
            content.value
        );
        assert!(
            !content.value.contains("13.0.5-beta1` *(latest)*"),
            "the pre-release must not be tagged latest; got: {}",
            content.value
        );
    }

    #[tokio::test]
    async fn test_generate_hover_latest_marker_omitted_when_stable_outside_top_n() {
        use std::collections::HashMap;

        // Nine pre-releases followed by one stable version: the stable pick sits past
        // `HOVER_RECENT_VERSIONS`, so it never appears in the rendered list.
        let mut versions: Vec<MockVersionWithAge> = (0..=HOVER_RECENT_VERSIONS)
            .map(|i| MockVersionWithAge {
                version: format!("2.0.0-alpha{i}"),
                yanked: false,
                published_at: None,
            })
            .collect();
        versions.push(MockVersionWithAge {
            version: "1.9.0".to_string(),
            yanked: false,
            published_at: None,
        });
        let registry = MockRegistryWithVersions { versions };
        let parse_result = freshness_test_parse_result("example");

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content.value.contains("**Latest**: `1.9.0`"),
            "got: {}",
            content.value
        );
        assert!(
            !content.value.contains("*(latest)*"),
            "the stable latest isn't in the truncated top-N slice, so no entry should be marked; got: {}",
            content.value
        );
    }

    #[tokio::test]
    async fn test_generate_hover_latest_marker_all_prerelease_degrades_gracefully() {
        use std::collections::HashMap;

        // No stable version exists anywhere in the list: `find_latest_stable` returns
        // `None`, and there is no Ch1 cache to fall back to either (#313 edge case).
        let registry = MockRegistryWithVersions {
            versions: vec![
                MockVersionWithAge {
                    version: "2.0.0-beta2".to_string(),
                    yanked: false,
                    published_at: None,
                },
                MockVersionWithAge {
                    version: "2.0.0-beta1".to_string(),
                    yanked: false,
                    published_at: None,
                },
                MockVersionWithAge {
                    version: "1.9.0-alpha1".to_string(),
                    yanked: false,
                    published_at: None,
                },
            ],
        };
        let parse_result = freshness_test_parse_result("example");

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor, not panic");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            !content.value.contains("**Latest**:"),
            "no stable version exists, so the header should be omitted rather than picking a pre-release; got: {}",
            content.value
        );
        assert!(
            !content.value.contains("*(latest)*"),
            "no stable version exists, so no entry in the list should be marked latest; got: {}",
            content.value
        );
        assert!(
            content.value.contains("2.0.0-beta2"),
            "the raw version list should still render even without a latest marker; got: {}",
            content.value
        );
    }

    #[tokio::test]
    async fn test_generate_hover_latest_marker_all_prerelease_live_list_ignores_stale_cache() {
        use std::collections::HashMap;

        // A live fetch happened (so `available_versions` is `Some`), but every entry in it
        // is a pre-release: `live_latest_idx` is `None`. A stale Ch1 cache is also present,
        // recording a version that isn't part of the live list at all. Falling back to that
        // stale cached value here would render a `**Latest**` line that contradicts the live
        // "Recent versions" list right below it — exactly the self-contradiction #227 F5 was
        // fixed to prevent, just reached through this all-prerelease path instead (#313 S2).
        let registry = MockRegistryWithVersions {
            versions: vec![MockVersionWithAge {
                version: "2.0.0-beta2".to_string(),
                yanked: false,
                published_at: None,
            }],
        };
        let parse_result = freshness_test_parse_result("example");
        let mut cached_versions = HashMap::new();
        cached_versions.insert("example".into(), PackageVersions::latest_only("1.5.0"));

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &HashMap::new()),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor, not panic");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            !content.value.contains("**Latest**:"),
            "a live fetch with no stable entry must not fall back to a stale cached version \
             that isn't in the live list; got: {}",
            content.value
        );
        assert!(
            !content.value.contains("1.5.0"),
            "the stale cached version must not leak into the response at all; got: {}",
            content.value
        );
    }

    /// #373: Go's `/@v/list` never enumerates pseudo-versions, so an untagged module whose
    /// entire tagged history is pre-release fails `select_latest_matching`'s list-based pick
    /// even though the live fetch succeeded and returned a non-empty list. Hover must fall
    /// back to `Registry::get_latest_matching` (mirroring `lifecycle.rs`'s background-fetch
    /// fallback, which answers this from Go's `/@latest` endpoint) instead of rendering no
    /// `**Latest**` line at all.
    #[tokio::test]
    async fn test_generate_hover_latest_falls_back_to_get_latest_matching_when_list_pick_fails() {
        use std::collections::HashMap;

        let registry = MockRegistryListFailsLatestFallbackSucceeds {
            versions: vec![MockVersionWithAge {
                version: "v0.0.0-20230101000000-abcdef123456".to_string(),
                yanked: false,
                published_at: None,
            }],
            fallback_latest: MockVersionWithAge {
                version: "v1.2.3".to_string(),
                yanked: false,
                published_at: None,
            },
            list_pick_index: None,
            get_latest_matching_calls: std::sync::atomic::AtomicUsize::new(0),
        };
        let parse_result = freshness_test_parse_result("example.com/mod");

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content.value.contains("**Latest**: `v1.2.3`"),
            "the list-based pick failed, so hover must fall back to get_latest_matching's \
             result instead of omitting the Latest line; got: {}",
            content.value
        );
    }

    /// #373 M4: the fallback must not fire on the common "list-based pick already
    /// succeeded" path — asserted via a call counter on the mock, guarding against a
    /// future regression that would make every hover pay for a second registry round
    /// trip regardless of whether the list-based pick worked.
    #[tokio::test]
    async fn test_generate_hover_does_not_call_fallback_when_list_pick_succeeds() {
        use std::collections::HashMap;
        use std::sync::atomic::Ordering;

        let registry = MockRegistryListFailsLatestFallbackSucceeds {
            versions: vec![MockVersionWithAge {
                version: "v1.2.3".to_string(),
                yanked: false,
                published_at: None,
            }],
            fallback_latest: MockVersionWithAge {
                version: "v9.9.9".to_string(),
                yanked: false,
                published_at: None,
            },
            list_pick_index: Some(0),
            get_latest_matching_calls: std::sync::atomic::AtomicUsize::new(0),
        };
        let parse_result = freshness_test_parse_result("example.com/mod");

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content.value.contains("**Latest**: `v1.2.3`"),
            "expected the list-based pick's own version, not the fallback's; got: {}",
            content.value
        );
        assert_eq!(
            registry.get_latest_matching_calls.load(Ordering::Relaxed),
            0,
            "get_latest_matching must not be called when the list-based pick already succeeded"
        );
    }

    #[tokio::test]
    async fn test_generate_hover_go_prefers_manifest_requirement_over_stale_resolved_version() {
        use std::collections::HashMap;

        let parse_result = MockParseResult {
            deps: vec![MockDep {
                name: "example.com/mod".into(),
                version_req: "v0.8.1".into(),
                version_range: Range::new(Position::new(0, 10), Position::new(0, 20)),
                name_range: Range::new(Position::new(0, 0), Position::new(0, 16)),
            }],
            uri: crate::test_util::test_uri("/test/go.mod"),
        };

        // Stale go.sum entry left behind by a downgrade (#235): go.mod's `require`
        // line was downgraded back to v0.8.1, but the ledger-only go.sum still
        // records the higher v0.9.1 and sorts last, so it would win naive
        // last-occurrence-wins parsing if hover trusted `versions.resolved` here.
        let mut resolved_versions = HashMap::new();
        resolved_versions.insert("example.com/mod".into(), "v0.9.1".to_string());
        let cached_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &MockRegistry,
            &MockGoFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content.value.contains("**Current**: `v0.8.1`"),
            "expected hover to show go.mod's pinned version, got: {}",
            content.value
        );
        assert!(
            !content.value.contains("v0.9.1"),
            "hover must not surface the stale go.sum version: {}",
            content.value
        );
    }

    #[tokio::test]
    async fn test_generate_hover_non_go_formatter_uses_resolved_lockfile_version() {
        use std::collections::HashMap;

        let parse_result = MockParseResult {
            deps: vec![MockDep {
                name: "serde".into(),
                version_req: "1.0.0".into(),
                version_range: Range::new(Position::new(0, 10), Position::new(0, 20)),
                name_range: Range::new(Position::new(0, 0), Position::new(0, 5)),
            }],
            uri: crate::test_util::test_uri("/test/Cargo.toml"),
        };

        let mut resolved_versions = HashMap::new();
        resolved_versions.insert("serde".into(), "1.2.0".to_string());
        let cached_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        // Non-Go formatters must keep showing the lockfile-resolved version
        // ("1.2.0"), not the raw manifest requirement ("1.0.0") — confirms the Go
        // override does not leak into other ecosystems.
        assert!(
            content.value.contains("**Current**: `1.2.0`"),
            "expected hover to show the resolved lockfile version, got: {}",
            content.value
        );
        assert!(!content.value.contains("**Current**: `1.0.0`"));
    }

    #[tokio::test]
    async fn test_generate_hover_recent_versions_preserves_yanked_marker_with_age() {
        use std::collections::HashMap;

        let registry = MockRegistryWithVersions {
            versions: vec![
                MockVersionWithAge {
                    version: "1.2.3".to_string(),
                    yanked: false,
                    published_at: None,
                },
                MockVersionWithAge {
                    version: "1.2.1".to_string(),
                    yanked: true,
                    // ~5 months ago.
                    published_at: Some(PublishTime::from_unix_secs(
                        PublishTime::now().as_unix_secs() - 5 * 30 * 24 * 60 * 60,
                    )),
                },
            ],
        };
        let parse_result = freshness_test_parse_result("serde");

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content
                .value
                .contains("- `1.2.1` *(yanked)* — 5 months ago"),
            "got: {}",
            content.value
        );
    }

    #[tokio::test]
    async fn test_generate_hover_recent_versions_respects_freshness_disabled() {
        use std::collections::HashMap;

        let registry = MockRegistryWithVersions {
            versions: vec![MockVersionWithAge {
                version: "1.2.3".to_string(),
                yanked: false,
                published_at: Some(PublishTime::from_unix_secs(
                    PublishTime::now().as_unix_secs() - 2 * 24 * 60 * 60,
                )),
            }],
        };
        let parse_result = freshness_test_parse_result("serde");

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings {
                enabled: false,
                cooldown_secs: crate::freshness::DEFAULT_COOLDOWN_SECS,
            },
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(content.value.contains("- `1.2.3` *(latest)*\n"));
        assert!(!content.value.contains("ago"));
    }

    /// Issue #227 §4.2a: the `**Latest**` line gets a publish-age suffix and, within the
    /// cooldown window, the "Recently published" callout.
    #[tokio::test]
    async fn test_generate_hover_latest_line_shows_age_and_cooldown_callout_when_within_cooldown() {
        use std::collections::HashMap;

        let parse_result = freshness_test_parse_result("serde");
        let mut cached_versions = HashMap::new();
        cached_versions.insert(
            "serde".into(),
            PackageVersions {
                latest: "2.0.0".to_string(),
                available: Arc::from(vec!["2.0.0".to_string()]),
                yanked: Arc::from(Vec::new()),
                // 1 hour ago — well within the default 3-day cooldown.
                published_at: Some(PublishTime::from_unix_secs(
                    PublishTime::now().as_unix_secs() - 60 * 60,
                )),
            },
        );
        let resolved_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content
                .value
                .contains("**Latest**: `2.0.0` *(published 1 hour ago)*"),
            "got: {}",
            content.value
        );
        assert!(
            content.value.contains(
                "> ⏳ **Recently published** — this release is still within the cooldown window."
            ),
            "got: {}",
            content.value
        );
    }

    /// Same setup, but `latest` was published well outside the cooldown window — the age
    /// suffix still renders, but the callout must not.
    #[tokio::test]
    async fn test_generate_hover_latest_line_no_callout_when_outside_cooldown() {
        use std::collections::HashMap;

        let parse_result = freshness_test_parse_result("serde");
        let mut cached_versions = HashMap::new();
        cached_versions.insert(
            "serde".into(),
            PackageVersions {
                latest: "2.0.0".to_string(),
                available: Arc::from(vec!["2.0.0".to_string()]),
                yanked: Arc::from(Vec::new()),
                // 10 days ago — outside the default 3-day cooldown.
                published_at: Some(PublishTime::from_unix_secs(
                    PublishTime::now().as_unix_secs() - 10 * 24 * 60 * 60,
                )),
            },
        );
        let resolved_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content
                .value
                .contains("**Latest**: `2.0.0` *(published 1 week ago)*"),
            "got: {}",
            content.value
        );
        assert!(!content.value.contains("Recently published"));
    }

    /// A `latest` with no known publish time renders exactly the pre-feature line — no age
    /// suffix, no callout.
    #[tokio::test]
    async fn test_generate_hover_latest_line_omits_age_when_published_at_unknown() {
        use std::collections::HashMap;

        let parse_result = freshness_test_parse_result("serde");
        let mut cached_versions = HashMap::new();
        cached_versions.insert("serde".into(), PackageVersions::latest_only("2.0.0"));
        let resolved_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(content.value.contains("**Latest**: `2.0.0`\n\n"));
        assert!(!content.value.contains("published"));
        assert!(!content.value.contains("Recently published"));
    }

    /// `freshness.enabled: false` suppresses both the age suffix and the cooldown callout
    /// on the `**Latest**` line, even when the publish time would otherwise qualify.
    #[tokio::test]
    async fn test_generate_hover_latest_line_respects_freshness_disabled() {
        use std::collections::HashMap;

        let parse_result = freshness_test_parse_result("serde");
        let mut cached_versions = HashMap::new();
        cached_versions.insert(
            "serde".into(),
            PackageVersions {
                latest: "2.0.0".to_string(),
                available: Arc::from(vec!["2.0.0".to_string()]),
                yanked: Arc::from(Vec::new()),
                published_at: Some(PublishTime::from_unix_secs(
                    PublishTime::now().as_unix_secs() - 60 * 60,
                )),
            },
        );
        let resolved_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings {
                enabled: false,
                cooldown_secs: crate::freshness::DEFAULT_COOLDOWN_SECS,
            },
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(content.value.contains("**Latest**: `2.0.0`\n\n"));
        assert!(!content.value.contains("published"));
        assert!(!content.value.contains("Recently published"));
    }

    /// Deterministic boundary test (issue #227 M4): `now` is threaded in as a parameter
    /// rather than read internally, so `published_at`/`now`/`cooldown_secs` can be pinned
    /// to fixed absolute values with no wall-clock dependency. `age == cooldown_secs`
    /// exactly must NOT be within cooldown — the bound is exclusive (`age < cooldown`).
    #[tokio::test]
    async fn test_generate_hover_latest_line_cooldown_boundary_is_exclusive() {
        use std::collections::HashMap;

        const COOLDOWN_SECS: u64 = 100;
        let now = PublishTime::from_unix_secs(10_000);
        let published_at_at_boundary =
            PublishTime::from_unix_secs(10_000 - COOLDOWN_SECS.cast_signed());

        let parse_result = freshness_test_parse_result("serde");
        let mut cached_versions = HashMap::new();
        cached_versions.insert(
            "serde".into(),
            PackageVersions {
                latest: "2.0.0".to_string(),
                available: Arc::from(vec!["2.0.0".to_string()]),
                yanked: Arc::from(Vec::new()),
                published_at: Some(published_at_at_boundary),
            },
        );
        let resolved_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings {
                enabled: true,
                cooldown_secs: COOLDOWN_SECS,
            },
            now,
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            !content.value.contains("Recently published"),
            "age exactly equal to cooldown_secs must not be within cooldown, got: {}",
            content.value
        );
    }

    /// Same fixture, one second younger — must flip to within cooldown.
    #[tokio::test]
    async fn test_generate_hover_latest_line_cooldown_boundary_one_second_inside_shows_callout() {
        use std::collections::HashMap;

        const COOLDOWN_SECS: u64 = 100;
        let now = PublishTime::from_unix_secs(10_000);
        let published_at_just_inside =
            PublishTime::from_unix_secs(10_000 - (COOLDOWN_SECS.cast_signed() - 1));

        let parse_result = freshness_test_parse_result("serde");
        let mut cached_versions = HashMap::new();
        cached_versions.insert(
            "serde".into(),
            PackageVersions {
                latest: "2.0.0".to_string(),
                available: Arc::from(vec!["2.0.0".to_string()]),
                yanked: Arc::from(Vec::new()),
                published_at: Some(published_at_just_inside),
            },
        );
        let resolved_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings {
                enabled: true,
                cooldown_secs: COOLDOWN_SECS,
            },
            now,
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content.value.contains("Recently published"),
            "age == cooldown_secs - 1 must be within cooldown, got: {}",
            content.value
        );
    }

    /// Issue #227 F5: the Ch1 cache (`versions.cached`, populated by the lifecycle's
    /// background fetch) can go stale relative to the live Ch2 fetch this same hover call
    /// just made (`registry.get_versions_with`) — e.g. a new version published between the
    /// last background fetch and now. Before this fix, the `**Latest**` line and cooldown
    /// callout read Ch1 alone, so hover could render a self-contradictory response: an
    /// older `**Latest**` line sitting above a "Recent versions" list whose own `*(latest)*`
    /// entry is a newer version. The line must prefer the live entry instead.
    #[tokio::test]
    async fn test_generate_hover_latest_line_prefers_live_fetch_over_stale_ch1_cache() {
        use std::collections::HashMap;

        let now = PublishTime::now();
        let live_latest_published = PublishTime::from_unix_secs(now.as_unix_secs() - 60 * 60);
        let registry = MockRegistryWithVersions {
            versions: vec![
                MockVersionWithAge {
                    version: "1.0.214".to_string(),
                    yanked: false,
                    published_at: Some(live_latest_published),
                },
                MockVersionWithAge {
                    version: "1.0.213".to_string(),
                    yanked: false,
                    published_at: Some(PublishTime::from_unix_secs(
                        now.as_unix_secs() - 30 * 24 * 60 * 60,
                    )),
                },
            ],
        };

        let parse_result = freshness_test_parse_result("serde");
        let mut cached_versions = HashMap::new();
        // Stale Ch1 entry: an older version, with an even older publish time, standing in
        // for a background fetch that ran before 1.0.214 was published.
        cached_versions.insert(
            "serde".into(),
            PackageVersions {
                latest: "1.0.213".to_string(),
                available: Arc::from(vec!["1.0.213".to_string()]),
                yanked: Arc::from(Vec::new()),
                published_at: Some(PublishTime::from_unix_secs(
                    now.as_unix_secs() - 90 * 24 * 60 * 60,
                )),
            },
        );
        let resolved_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            now,
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content
                .value
                .contains("**Latest**: `1.0.214` *(published 1 hour ago)*"),
            "Latest line must reflect the live Ch2 fetch, not the stale Ch1 cache entry \
             `1.0.213`, got: {}",
            content.value
        );
        assert!(
            !content.value.contains("**Latest**: `1.0.213`"),
            "must not render the stale Ch1 version, got: {}",
            content.value
        );
        assert!(
            content
                .value
                .contains("- `1.0.214` *(latest)* — 1 hour ago"),
            "the Recent versions list's own *(latest)* entry must agree with the Latest \
             line above it, got: {}",
            content.value
        );
    }

    /// #347/#348 S1: npm-shaped package `[2.0.0 AdvisoryDeprecated, 1.9.0 Available]`.
    /// `is_stable()` accepts `AdvisoryDeprecated`, so a naive `is_stable()`-based scan for
    /// "latest" picks `2.0.0` — disagreeing with npm's own `select_latest_matching`, which
    /// deliberately ranks a non-deprecated version ahead of a deprecated one (#338 NFR-002)
    /// and would resolve `1.9.0` instead (this is exactly what `lifecycle.rs` caches and
    /// diagnostics read). Hover must delegate to the registry's `select_latest_matching`
    /// instead of re-deriving the pick, so it agrees with that cached value, and the
    /// resolved `2.0.0`-would-be-latest case below must still carry its deprecated label
    /// when a deprecated version *is* the resolved latest.
    #[tokio::test]
    async fn test_generate_hover_latest_agrees_with_npm_shaped_deprecated_ranking() {
        use std::collections::HashMap;

        let now = PublishTime::now();
        let registry = MockRegistryPreferringUnflagged {
            versions: vec![
                MockVersionWithStatus {
                    version: "2.0.0".to_string(),
                    status: RemovalStatus::AdvisoryDeprecated,
                },
                MockVersionWithStatus {
                    version: "1.9.0".to_string(),
                    status: RemovalStatus::Available,
                },
            ],
        };

        let parse_result = freshness_test_parse_result("pkg");
        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            now,
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content.value.contains("**Latest**: `1.9.0`"),
            "hover must agree with select_latest_matching's non-deprecated-preferred pick \
             (1.9.0), not a naive is_stable() scan that would pick the newer but deprecated \
             2.0.0, got: {}",
            content.value
        );
        assert!(
            content.value.contains("- `1.9.0` *(latest)*"),
            "the Recent versions list's own *(latest)* marker must agree with the Latest \
             line above it, got: {}",
            content.value
        );
        assert!(
            content.value.contains("- `2.0.0` *(yanked)*"),
            "2.0.0 must keep its flagged label even though it isn't the resolved latest, \
             got: {}",
            content.value
        );
    }

    /// #347/#348 S1: when every version is flagged, the registry's own ranking (rung 2 of
    /// `MockRegistryPreferringUnflagged`) can still resolve a flagged version as "latest" —
    /// hover must keep that entry's deprecated/yanked label instead of letting `*(latest)*`
    /// silently replace it (issue #227-F5/#313's self-contradiction class).
    #[tokio::test]
    async fn test_generate_hover_latest_keeps_flagged_label_when_resolved_version_is_flagged() {
        use std::collections::HashMap;

        let now = PublishTime::now();
        let registry = MockRegistryPreferringUnflagged {
            versions: vec![MockVersionWithStatus {
                version: "2.0.0".to_string(),
                status: RemovalStatus::AdvisoryDeprecated,
            }],
        };

        let parse_result = freshness_test_parse_result("pkg");
        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            now,
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content.value.contains("**Latest**: `2.0.0`"),
            "the only version resolves as latest even though it's flagged, got: {}",
            content.value
        );
        assert!(
            content.value.contains("- `2.0.0` *(latest)* *(yanked)*"),
            "the resolved latest must keep its flagged label instead of the warning \
             silently vanishing behind *(latest)*, got: {}",
            content.value
        );
    }

    /// #364 rung 3: an *all-yanked* package (Cargo/PyPI/Dart-shaped —
    /// `RemovalStatus::Yanked` blocks resolution, unlike npm's `AdvisoryDeprecated`) must
    /// still resolve a "latest" via [`crate::select_latest_for_existence`]'s unconditional
    /// last rung, instead of hover rendering no `**Latest**` line at all (the pre-#364
    /// `None` behavior that read as a false "Unknown package").
    #[tokio::test]
    async fn test_generate_hover_latest_resolves_when_all_versions_yanked() {
        use std::collections::HashMap;

        let now = PublishTime::now();
        let registry = MockRegistryPreferringUnflagged {
            versions: vec![
                MockVersionWithStatus {
                    version: "2.0.0".to_string(),
                    status: RemovalStatus::Yanked,
                },
                MockVersionWithStatus {
                    version: "1.9.0".to_string(),
                    status: RemovalStatus::Yanked,
                },
            ],
        };

        let parse_result = freshness_test_parse_result("pkg");
        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            now,
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content.value.contains("**Latest**: `2.0.0`"),
            "an all-yanked package still exists: hover must resolve the newest yanked \
             version as latest rather than showing no Latest line, got: {}",
            content.value
        );
        assert!(
            content.value.contains("- `2.0.0` *(latest)* *(yanked)*"),
            "the resolved latest must keep its yanked label, got: {}",
            content.value
        );
    }

    #[tokio::test]
    async fn test_generate_hover_surfaces_markers() {
        use std::collections::HashMap;
        use tower_lsp_server::ls_types::{Position, Range};

        let parse_result = MockMarkedParseResult {
            dep: MockMarkedDep {
                name: "numpy".into(),
                name_range: Range::new(Position::new(0, 0), Position::new(0, 5)),
                markers: Some("python_full_version >= '3.9'".to_string()),
            },
            uri: crate::test_util::test_uri("/test/pyproject.toml"),
        };

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content
                .value
                .contains("**Active when**: `python_full_version >= '3.9'`")
        );
    }

    #[tokio::test]
    async fn test_generate_hover_omits_active_when_without_markers() {
        use std::collections::HashMap;
        use tower_lsp_server::ls_types::{Position, Range};

        let parse_result = MockMarkedParseResult {
            dep: MockMarkedDep {
                name: "requests".into(),
                name_range: Range::new(Position::new(0, 0), Position::new(0, 8)),
                markers: None,
            },
            uri: crate::test_util::test_uri("/test/pyproject.toml"),
        };

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(!content.value.contains("Active when"));
    }

    #[tokio::test]
    async fn test_generate_hover_escapes_malicious_dependency_name() {
        use std::collections::HashMap;
        use tower_lsp_server::ls_types::{Position, Range};

        let malicious_name = "real-pkg](https://legit-looking-typosquat.example/download)[real-pkg";

        let parse_result = MockParseResult {
            deps: vec![MockDep {
                name: malicious_name.into(),
                version_req: "1.0.0".into(),
                version_range: Range::new(Position::new(0, 10), Position::new(0, 20)),
                name_range: Range::new(
                    Position::new(0, 0),
                    Position::new(0, malicious_name.len() as u32),
                ),
            }],
            uri: crate::test_util::test_uri("/test/Cargo.toml"),
        };

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };

        // The link label (between the H1's "# [" and the "](") must be the fully
        // escaped name, with no raw "](" sequence that could close the label early
        // and splice in an attacker-controlled markdown link.
        let header_line = content
            .value
            .lines()
            .next()
            .expect("hover markdown has a header line");
        let label = header_line
            .strip_prefix("# [")
            .expect("header starts with link label")
            .split("](")
            .next()
            .expect("header contains label/url separator");
        assert_eq!(
            label,
            r"real\-pkg\]\(https\:\/\/legit\-looking\-typosquat\.example\/download\)\[real\-pkg"
        );
    }

    #[tokio::test]
    async fn test_generate_hover_newline_in_name_cannot_forge_new_heading() {
        use std::collections::HashMap;
        use tower_lsp_server::ls_types::{Position, Range};

        // Combines S1 (newline breaks out of the ATX heading line) with an
        // autolink payload that needs no brackets/parens at all.
        let malicious_name = "react\n# [fake](https://evil.example) <https://evil.example>";

        let parse_result = MockParseResult {
            deps: vec![MockDep {
                name: malicious_name.into(),
                version_req: "1.0.0".into(),
                version_range: Range::new(Position::new(0, 10), Position::new(0, 20)),
                name_range: Range::new(
                    Position::new(0, 0),
                    Position::new(0, malicious_name.len() as u32),
                ),
            }],
            uri: crate::test_util::test_uri("/test/Cargo.toml"),
        };

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };

        // The link label must be the exact single-line escaped name: no raw
        // newline breaking the ATX heading, and the autolink's `<`/`>` escaped so
        // it cannot render as a live link independent of the `[]`/`()` escaping.
        let header_line = content
            .value
            .lines()
            .next()
            .expect("hover markdown has a header line");
        let label = header_line
            .strip_prefix("# [")
            .expect("header starts with link label")
            .split("](")
            .next()
            .expect("header contains label/url separator");
        assert_eq!(label, escape_markdown(malicious_name));
        assert!(!label.contains('\n'));
        assert!(label.contains(r"\<https"));
    }

    #[tokio::test]
    async fn test_generate_hover_marker_with_parens_renders_unescaped() {
        use std::collections::HashMap;
        use tower_lsp_server::ls_types::{Position, Range};

        // Regression guard (M4): a legitimate PEP 508 marker with parentheses must
        // render as-is inside its code span, not with visible `\(`/`\)` escapes —
        // backslash-escaping does not apply inside code spans.
        let marker = "python_version >= \"3.8\" and (sys_platform == \"linux\")";
        let parse_result = MockMarkedParseResult {
            dep: MockMarkedDep {
                name: "numpy".into(),
                name_range: Range::new(Position::new(0, 0), Position::new(0, 5)),
                markers: Some(marker.to_string()),
            },
            uri: crate::test_util::test_uri("/test/pyproject.toml"),
        };

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&HashMap::new(), &HashMap::new()),
            &MockRegistry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated for a dependency at the cursor");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(
            content
                .value
                .contains(&format!("**Active when**: `{marker}`"))
        );
    }

    #[tokio::test]
    async fn test_generate_hover_registry_sections_suppressed_for_non_registry_sources() {
        use crate::parser::DependencySource;

        let registry = MockRegistryWithVersions {
            versions: vec![MockVersionWithAge {
                version: "9.9.9".to_string(),
                yanked: false,
                published_at: None,
            }],
        };
        let cached_versions = {
            let mut m = HashMap::new();
            m.insert("dep".into(), PackageVersions::latest_only("9.9.9"));
            m
        };
        let resolved_versions = HashMap::new();
        let uri = crate::test_util::test_uri("/test/Cargo.toml");

        let parse_result = SingleDepParseResult {
            dep: NonRegistryDep(
                dep_at("dep"),
                DependencySource::CustomRegistry {
                    url: "my-corp".into(),
                },
            ),
            uri: uri.clone(),
        };

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should still be generated for a non-resolvable-source dependency");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(!content.value.contains("**Latest**"));
        assert!(!content.value.contains("**Recent versions**"));
        assert!(content.value.contains("**Requirement**"));

        // Control: the same fixture on a Registry-source dependency DOES show
        // both registry-derived sections, proving the fixture isn't vacuous.
        let registry_parse_result = SingleDepParseResult {
            dep: dep_at("dep"),
            uri,
        };
        let hover = generate_hover(
            &registry_parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &registry,
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated");
        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(content.value.contains("**Latest**"));
        assert!(content.value.contains("**Recent versions**"));
    }

    #[tokio::test]
    async fn test_generate_hover_clean_outcome_states_no_known_vulnerabilities() {
        use crate::osv::{ScanOutcome, VulnerabilityMap};

        let parse_result = MockParseResult {
            deps: vec![dep_at("clean-pkg")],
            uri: crate::test_util::test_uri("/test/Cargo.toml"),
        };
        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();

        let mut vulns: VulnerabilityMap = VulnerabilityMap::new();
        vulns.insert("clean-pkg".to_string(), ScanOutcome::Clean);

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions).with_vulnerabilities(&vulns),
            &MockRegistry,
            &MockFormatter,
            crate::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(content.value.contains("No known vulnerabilities"));
    }

    #[tokio::test]
    async fn test_generate_hover_skipped_outcome_says_nothing_about_vulnerabilities() {
        use crate::osv::{ScanOutcome, SkipReason, VulnerabilityMap};

        let parse_result = MockParseResult {
            deps: vec![dep_at("path-pkg")],
            uri: crate::test_util::test_uri("/test/Cargo.toml"),
        };
        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();

        let mut vulns: VulnerabilityMap = VulnerabilityMap::new();
        vulns.insert(
            "path-pkg".to_string(),
            ScanOutcome::Skipped(SkipReason::NonRegistrySource),
        );

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions).with_vulnerabilities(&vulns),
            &MockRegistry,
            &MockFormatter,
            crate::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(!content.value.contains("Security advisories"));
        assert!(!content.value.contains("No known vulnerabilities"));
    }

    #[tokio::test]
    async fn test_generate_hover_vulnerable_outcome_shows_advisories_and_more_count() {
        use crate::osv::{
            DependencyVulnerabilities, ScanOutcome, UpgradeStatus, VulnSeverity, VulnerabilityMap,
        };

        let parse_result = MockParseResult {
            deps: vec![dep_at("bad-pkg")],
            uri: crate::test_util::test_uri("/test/Cargo.toml"),
        };
        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();

        let mut vulns: VulnerabilityMap = VulnerabilityMap::new();
        vulns.insert(
            "bad-pkg".to_string(),
            ScanOutcome::Vulnerable(DependencyVulnerabilities {
                advisories: vec![sample_advisory("RUSTSEC-2020-0071", VulnSeverity::Critical)],
                total_known: 3,
                upgrade_status: UpgradeStatus::CandidateVulnerable {
                    version: "2.0.0".to_string(),
                    advisory_ids: vec!["RUSTSEC-2020-0071".to_string()],
                },
            }),
        );

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions).with_vulnerabilities(&vulns),
            &MockRegistry,
            &MockFormatter,
            crate::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await
        .expect("hover should be generated");

        let HoverContents::Markup(content) = hover.contents else {
            panic!("expected markup hover contents");
        };
        assert!(content.value.contains("Security advisories"));
        assert!(content.value.contains("RUSTSEC-2020-0071"));
        assert!(content.value.contains("Fixed in"));
        assert!(
            content.value.contains("1.5.0"),
            "must show highest fixed version"
        );
        assert!(content.value.contains("+2 more advisories"));
        assert!(content.value.contains("also affected"));
    }

    /// #366: a registry error classified as `PackageNotFound` (e.g. `deps-maven`'s
    /// `metadata_urls` rejecting a dot-segment coordinate like `com.example:..`, mirrored
    /// here by [`NotFoundRegistry`]) must make hover return `None` via this function's own
    /// `get_versions_with(...).await.ok()?` chain, exactly like it already does for a
    /// genuine 404 — not a broken hover section built from an empty version list.
    #[tokio::test]
    async fn test_generate_hover_none_when_registry_reports_not_found() {
        let parse_result = MockParseResult {
            deps: vec![dep_at("com.example:..")],
            uri: crate::test_util::test_uri("/test/pom.xml"),
        };
        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();

        let hover = generate_hover(
            &parse_result,
            Position::new(0, 2),
            VersionData::new(&cached_versions, &resolved_versions),
            &NotFoundRegistry,
            &MockFormatter,
            crate::FreshnessSettings::default(),
            PublishTime::now(),
        )
        .await;

        assert!(hover.is_none());
    }
}