deps-core 2.0.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
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
//! "What version does this dependency occurrence actually have" — shared by
//! `deps-lsp`'s registry-fetch/OSV-target pipeline and, for #394's S1 fix,
//! the yanked-diagnostic consistency check in [`super::diagnostics`].

use std::collections::HashMap;

use crate::lsp_helpers::{BoundedVersionReq, EcosystemFormatter, ResolvedPin};
use crate::{ConcreteVersion, Dependency, EcosystemId, PackageName};

/// How a *bare* (no explicit pin marker) version requirement should be treated when
/// deciding whether it denotes a single concrete version.
///
/// Replaces a plain boolean (critique B2 of #208's plan) because neither `true` nor
/// `false` is correct for GitHub Actions: `AlwaysRange`/`Concrete` alone cannot express
/// "a bare `v4` is a range, but a bare `v4.2.0` is a pin" — the two forms share no
/// syntactic marker to distinguish them by, only the number of components present.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BareRequirementPolicy {
    /// A bare requirement is always a range under this ecosystem's own default
    /// semantics (Cargo's implicit caret) — never treated as concrete without an
    /// explicit `=`/`==` pin marker.
    AlwaysRange,
    /// A bare requirement is concrete only when it has the shape of a full
    /// `major.minor.patch` version ([`is_full_semver_shape`]); a partial form (a bare
    /// major or major.minor, e.g. GitHub Actions' moving-major `v4` tag, or npm's
    /// bare `"4.17"`) is treated as a range instead, since it is one.
    ConcreteIfFullVersion,
    /// A bare requirement is already exact (no implicit range operator).
    Concrete,
}

/// Ecosystems whose *bare* (no explicit pin marker) version requirement is
/// unconditionally a range under that ecosystem's own default semantics —
/// Cargo's implicit caret. For these, [`concrete_pin_version`] requires an
/// explicit `=`/`==` (or an exact-bracket wrap) before treating a requirement
/// as concrete; a bare `"1.2.3"` alone is not enough evidence (critique C2).
/// Cargo is the sole member of this group: every other ecosystem with an
/// implicit-range default distinguishes a bare *full* version (a pin) from a
/// bare *partial* one (a range) instead, so it belongs under
/// [`BareRequirementPolicy::ConcreteIfFullVersion`] rather than here — and
/// NuGet, whose bare form is a range under its own registry-comparator
/// semantics too, is deliberately kept out of this group anyway; see
/// [`BareRequirementPolicy::Concrete`]'s doc for why.
///
/// GitHub Actions, GitLab CI, npm, Composer, and Deno all get
/// [`BareRequirementPolicy::ConcreteIfFullVersion`] instead — see that
/// variant's docs for the shared "full version is a pin, partial version is
/// a range" rule, and below for why each of the five qualifies:
///
/// - GitHub Actions: a bare `v4` (a moving-major tag) genuinely is a range,
///   so it must not be queried as if it were the concrete version `4`, but a
///   bare `v4.2.0` is a pin. A bare 40-character SHA also falls to the
///   `None` side of this gate ([`is_full_semver_shape`] rejects it), which is
///   the correct "honest unknown" outcome: resolving a SHA to its tag would
///   need registry access this pure function does not have.
/// - GitLab CI: a `component:` include's partial-semver pin (`1`, `1.2`) is a
///   range exactly like GitHub Actions' moving-major tag
///   ([`is_full_semver_shape`] correctly rejects it, since it requires all
///   three components), while a full `1.2.3`/`v1.2.3` tag or release-name pin
///   is concrete. A SHA pin (`project:`'s or `component:`'s) falls to the
///   same honest "unknown" `None` as GitHub Actions' bare SHA, and
///   `~latest`/a branch-shaped ref never look like a full version shape
///   either, so both also correctly fall through to `None`.
/// - npm and Composer (#664): unlike Cargo, a bare version is **not**
///   unconditionally a range under either ecosystem's own semver grammar. A
///   bare *full* `major.minor.patch` (e.g. npm's `"4.17.0"`,
///   `deps-npm::formatter`'s `node_semver::Range` compiles it to an exact
///   match; Composer's `version_satisfies_requirement` treats a full bare
///   version identically) is an exact pin. Only a bare *partial* version
///   (`"4.17"`, `"4"`) expands to an implicit range/prefix match — npm's
///   X-range semantics, Composer's `ver_parts.starts_with(&req_parts)`
///   prefix match in `deps-composer::formatter`. Before this fix both
///   ecosystems were grouped with Cargo under `AlwaysRange`, which silently
///   dropped `in_use_version` resolution (and therefore hover License/OSV
///   sections) for any bare-pinned npm/Composer manifest with no lock file.
/// - Deno (#667): `DenoFormatter::compile_bounded_requirement`
///   (`crates/deps-deno/src/formatter.rs`) compiles both its `jsr:` and
///   `npm:` specifiers through the identical `node_semver::Range` grammar
///   npm itself uses, so the same full-vs-partial distinction applies
///   unchanged. This matters more for Deno than for npm/Composer:
///   `deps-deno` has no lockfile support at all (`DenoEcosystem`'s
///   `LockFileProvider` is unimplemented), so `concrete_pin_version` is the
///   *only* possible source of an in-use version for any Deno dependency — a
///   `deno.json` `"npm:express@4.17.0"` import parses to the bare
///   requirement `"4.17.0"`, and grouping Deno with Cargo under
///   `AlwaysRange` meant that requirement could never resolve to a concrete
///   version, so no Deno dependency ever received an OSV scan under any
///   manifest, bare-pinned or not. Reclassifying it here does not change
///   `osv_package_name` returning `None` for `jsr:` specifiers
///   (`deps-deno/src/formatter.rs`, OSV has no JSR ecosystem) — that is an
///   independent, already-correct downstream filter.
///
/// Every remaining ecosystem (Pypi, Go, Bundler, Dart, Maven, Gradle, Swift,
/// NuGet) gets plain [`BareRequirementPolicy::Concrete`]. Gradle in
/// particular: a bare coordinate version (e.g. `"2.14.1"`) is an exact match
/// under `GradleFormatter`'s own `version_satisfies_requirement` unless it
/// uses the `+` dynamic-version suffix, which `looks_like_a_single_version`
/// rejects for every ecosystem whose `PlusSuffixMeaning` is `Dynamic`; Dart
/// (`0.8.13+1`) is the exception, where `+N` is part of a concrete version.
///
/// NuGet (#669) is the one member of this group that does *not* have "no
/// implicit-range default" in the strict sense: a bare `Version="1.0.0"`
/// under `PackageReference`/`PackageVersion` is actually a *minimum-only
/// floor* — `NuGetFormatter::version_satisfies_requirement`'s
/// `test_version_satisfies_bare_floor` shows `satisfies("2.5.0", "1.0.0")`
/// and `satisfies("9.9.9", "1.0.0")` are both `true`, which would put it
/// under `AlwaysRange` (Cargo's group) by the same reasoning that moved
/// npm/Composer/Deno to `ConcreteIfFullVersion`. It is deliberately kept
/// under `Concrete` anyway, as a documented approximation rather than an
/// oversight: `NuGetFormatter::is_bounded_requirement_up_to_date` (this crate's
/// sibling `deps-nuget`) already treats a bare floor as a pin for the
/// identical reason — restore resolves a direct `PackageReference` to
/// *exactly* its floor version unless something else forces a higher one,
/// so "the floor is the version in practice" is the right default answer for
/// "what version does this project actually have" even though it is not the
/// only version the requirement's own comparator would accept. Moving NuGet
/// to `AlwaysRange` (tried and reverted during #669's implementation) makes
/// `concrete_pin_version` return `None` for the dominant bare
/// `Version="12.0.1"` .csproj spelling with no lock file present — verified
/// live to silently drop OSV vulnerability scanning, hover
/// Security/Current/License sections, deps.dev trust signals, yanked
/// checks, and inlay hints for that dependency, since NuGet's
/// `packages.lock.json` is opt-in (`RestorePackagesWithLockFile`) and rarely
/// present to rescue it via the lockfile path instead. `Concrete` keeps all
/// of that working for the common case, at the cost of being wrong in two
/// narrower situations: the pinned floor version doesn't actually exist on
/// the feed, or a transitive dependency elsewhere in the graph raises the
/// effective floor above what this bare requirement alone states — both
/// already-known limitations of "lowest applicable version" as an
/// approximation, not new ones introduced by keeping this policy. An
/// explicit exact-bracket pin (`[1.0.0]`) is unaffected either way — it is
/// stripped and matched before `bare_requirement_policy` is ever consulted
/// (see [`concrete_pin_version`]).
///
/// Spelled out as explicit arms rather than a `_` catch-all (impl-critic
/// #664 review, finding M4): `EcosystemId` is deliberately exhaustive so a
/// 15th ecosystem forces every `match` on it to be updated at compile time
/// (`.claude/CLAUDE.md`'s bug-class-#118 rule) — a wildcard here would
/// silently default a new ecosystem to `Concrete`, the *least* conservative
/// policy, contradicting [`concrete_pin_version`]'s own doc that a false
/// positive is worse than a false negative.
const fn bare_requirement_policy(ecosystem: EcosystemId) -> BareRequirementPolicy {
    match ecosystem {
        EcosystemId::Cargo => BareRequirementPolicy::AlwaysRange,
        EcosystemId::GithubActions
        | EcosystemId::GitlabCi
        | EcosystemId::Npm
        | EcosystemId::Composer
        | EcosystemId::Deno => BareRequirementPolicy::ConcreteIfFullVersion,
        EcosystemId::Pypi
        | EcosystemId::Go
        | EcosystemId::Bundler
        | EcosystemId::Dart
        | EcosystemId::Maven
        | EcosystemId::Gradle
        | EcosystemId::Swift
        | EcosystemId::NuGet => BareRequirementPolicy::Concrete,
    }
}

/// What a `+` inside a version string means under an ecosystem's own grammar.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PlusSuffixMeaning {
    /// `+` marks a dynamic/range version (Gradle's `1.+`), never a concrete pin.
    Dynamic,
    /// `+` introduces a numeric build number that is part of a concrete version
    /// (Dart's `0.8.13+1`): exactly one `+`, text before it, all-digit text after.
    PartOfVersion,
}

impl PlusSuffixMeaning {
    /// Whether every `+` in `s` is placed consistently with this meaning.
    fn accepts(self, s: &str) -> bool {
        match self {
            Self::Dynamic => !s.contains('+'),
            Self::PartOfVersion => s.split_once('+').is_none_or(|(head, build)| {
                !head.is_empty() && !build.is_empty() && build.bytes().all(|b| b.is_ascii_digit())
            }),
        }
    }
}

/// Exhaustive on purpose: a new ecosystem must state what `+` means for it.
const fn plus_suffix_meaning(ecosystem: EcosystemId) -> PlusSuffixMeaning {
    match ecosystem {
        EcosystemId::Dart => PlusSuffixMeaning::PartOfVersion,
        EcosystemId::Cargo
        | EcosystemId::GithubActions
        | EcosystemId::GitlabCi
        | EcosystemId::Npm
        | EcosystemId::Composer
        | EcosystemId::Deno
        | EcosystemId::Pypi
        | EcosystemId::Go
        | EcosystemId::Bundler
        | EcosystemId::Maven
        | EcosystemId::Gradle
        | EcosystemId::Swift
        | EcosystemId::NuGet => PlusSuffixMeaning::Dynamic,
    }
}

/// Whether `s` has the shape of a full `major.minor.patch` version.
///
/// An optional leading `v`/`V`, three dot-separated all-digit components, and an
/// optional SemVer-style prerelease/build suffix introduced by `-` or `+` (accepted,
/// but not itself validated beyond "starts here").
///
/// Hand-rolled rather than pulled in via the `regex` crate: this is consulted from
/// `bare_requirement_policy` in `deps-core`, the workspace's most-depended-on crate,
/// which has no `regex` dependency today — equivalent to the pattern
/// `^v?\d+\.\d+\.\d+(?:[-+].*)?$`.
///
/// `deps-github-actions`'s SHA-comment-tag parsing rule used to share this predicate
/// verbatim, but issue #907 (review finding S1) found it rejected the dominant
/// real-world convention (a major-only `# v4` comment) while accepting free-text
/// content this predicate was never meant to police in the first place. It now uses
/// [`crate::lsp_helpers::is_partial_semver_shaped`] instead, which additionally rejects
/// a bare unprefixed integer (`1234`, `20240501`) that this function's *full*
/// three-component shape already excludes structurally — the two predicates
/// intentionally diverge now, each fit to its own domain.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::is_full_semver_shape;
///
/// assert!(is_full_semver_shape("v4.2.0"));
/// assert!(is_full_semver_shape("4.2.0-beta.1"));
/// assert!(!is_full_semver_shape("v4"));
/// assert!(!is_full_semver_shape("v4.2"));
/// assert!(!is_full_semver_shape("not-a-version"));
/// ```
#[expect(
    clippy::string_slice,
    reason = "idx comes from str::find(['-', '+']), both ASCII bytes, so it is always a char \
              boundary"
)]
#[must_use]
pub fn is_full_semver_shape(s: &str) -> bool {
    let s = crate::github::normalize_tag(s);
    let core = match s.find(['-', '+']) {
        Some(idx) => &s[..idx],
        None => s,
    };
    is_dotted_numeric::<3>(core)
}

/// Whether `core` is exactly `N` non-empty, all-digit, dot-separated components.
fn is_dotted_numeric<const N: usize>(core: &str) -> bool {
    let mut parts = core.split('.');
    let components: [Option<&str>; N] = std::array::from_fn(|_| parts.next());
    parts.next().is_none()
        && components
            .iter()
            .all(|p| p.is_some_and(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())))
}

/// Returns `true` if `s` (already stripped of any pin marker) has the shape
/// of a single concrete version: non-empty, no wildcard/range-operator
/// character, and starting with a digit (after an optional `v`/`V` prefix,
/// e.g. Go's `v1.9.1`).
///
/// Deliberately conservative — see [`concrete_pin_version`]'s doc for why a
/// false positive here is worse than a false negative.
fn looks_like_a_single_version(s: &str, ecosystem: EcosystemId) -> bool {
    if s.is_empty() {
        return false;
    }
    if s.contains([
        '^', '~', '*', '<', '>', ',', '|', '(', ')', '[', ']', ' ', '\t', ':',
    ]) {
        return false;
    }
    if !plus_suffix_meaning(ecosystem).accepts(s) {
        return false;
    }
    let core = crate::github::normalize_tag(s);
    core.chars().next().is_some_and(|c| c.is_ascii_digit()) && !has_wildcard_component(core)
}

/// Whether `version` carries an `x`/`X` wildcard: any `x`/`X` in the numeric core (before the
/// first `-`), or a later pre-release dot-component that is exactly `x`/`X`. A pre-release
/// word merely containing the letter (`experimental`, `dev.x1`) or a leading `-x` identifier
/// is not a wildcard.
fn has_wildcard_component(version: &str) -> bool {
    let (numeric, pre_release) = match version.split_once('-') {
        Some((numeric, pre)) => (numeric, Some(pre)),
        None => (version, None),
    };
    numeric.contains(['x', 'X'])
        || pre_release.is_some_and(|pre| pre.split('.').skip(1).any(|c| matches!(c, "x" | "X")))
}

/// Returns the concrete version text `requirement` denotes, or `None` if
/// `requirement` is not the shape of a single concrete version.
///
/// Any pin marker (`=`/`==`, or a single-value bracket wrap like NuGet's
/// `[1.0.0]`) is stripped off. The only shape safe to query OSV with
/// directly, and, for #233, the only shape safe to compare against a real
/// registry version string in the yanked-version probe. A wrong answer here
/// is invisible in testing (OSV silently returns `{}` for a fabricated
/// version; the yanked probe silently finds no match), so getting this
/// right matters more than covering every ecosystem's full range grammar.
///
/// An explicit pin marker is always accepted, and its marker is stripped
/// from the returned text — required because PyPI's parser retains the
/// pep440 comparator in `Dependency::version_requirement()` (an exact pin
/// parses to `"==4.9.0"`, not `"4.9.0"`; confirmed by
/// `deps-pypi`'s `test_basic_pinned`), so comparing the *unstripped* text
/// against a real registry version string (`"4.9.0"`) would never match. A
/// *bare* requirement (no marker) is returned verbatim, and is accepted only
/// for ecosystems where a bare version is not itself a range by default
/// (critique C2) — see `bare_requirement_policy`.
///
/// # Examples
///
/// ```
/// use deps_core::EcosystemId;
/// use deps_core::lsp_helpers::concrete_pin_version;
///
/// // An explicit pin marker is stripped, for any ecosystem.
/// assert_eq!(
///     concrete_pin_version("=1.2.3", EcosystemId::Cargo),
///     Some("1.2.3")
/// );
///
/// // Cargo's bare version is a caret range by default, not a pin.
/// assert_eq!(concrete_pin_version("1.2.3", EcosystemId::Cargo), None);
///
/// // Maven has no implicit range operator, so a bare version is exact.
/// assert_eq!(
///     concrete_pin_version("2.14.1", EcosystemId::Maven),
///     Some("2.14.1")
/// );
/// ```
pub fn concrete_pin_version(requirement: &str, ecosystem: EcosystemId) -> Option<&str> {
    let trimmed = requirement.trim();
    if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("latest") {
        return None;
    }

    let pinned = trimmed
        .strip_prefix("==")
        .or_else(|| trimmed.strip_prefix('='));
    let bracket_pinned = trimmed
        .strip_circumfix('[', ']')
        .filter(|inner| !inner.contains(','));

    match pinned.or(bracket_pinned) {
        Some(body) => looks_like_a_single_version(body, ecosystem).then_some(body),
        None => match bare_requirement_policy(ecosystem) {
            BareRequirementPolicy::AlwaysRange => None,
            BareRequirementPolicy::Concrete => {
                looks_like_a_single_version(trimmed, ecosystem).then_some(trimmed)
            }
            BareRequirementPolicy::ConcreteIfFullVersion => {
                is_full_semver_shape(trimmed).then_some(trimmed)
            }
        },
    }
}

/// Returns `true` if `requirement` denotes a single concrete version. See
/// [`concrete_pin_version`], whose boolean projection this is, for the
/// acceptance rules. Test-only: production code needs the stripped text
/// from `concrete_pin_version` itself, not just the boolean.
#[cfg(test)]
fn is_concrete_version(requirement: &str, ecosystem: EcosystemId) -> bool {
    concrete_pin_version(requirement, ecosystem).is_some()
}

/// Picks the lock-file-resolved candidate that best matches one dependency occurrence's own
/// version requirement (FR-001/FR-002), among a name's multiple retained lock-file entries.
///
/// Filters `candidates` down to those [`crate::lsp_helpers::RequirementResolution::version_satisfies_bounded_requirement`]
/// accepts, then returns the highest-semver entry among that satisfying subset — falling back
/// to [`crate::lockfile`]'s lexicographic tiebreak for non-parseable versions
/// ([`crate::lockfile::compare_lockfile_versions`]), the same ordering a single-candidate
/// collapse already uses, so this never diverges from it. Returns `None` when nothing
/// satisfies the requirement (FR-003) — the caller must not then substitute an arbitrary
/// non-matching entry.
/// Prefers [`crate::lsp_helpers::RequirementResolution::compile_bounded_requirement`]'s precise, ecosystem-native
/// comparator (e.g. `deps-cargo`'s real `semver::VersionReq` range semantics) over
/// [`crate::lsp_helpers::RequirementResolution::version_satisfies_bounded_requirement`]'s looser heuristic — critical
/// here specifically because that heuristic's plain/partial-requirement branch requires
/// *minor-version equality* (`is_same_major_minor`), so a caret-range requirement like
/// Cargo's `"2.4"` (meaning `>=2.4.0, <3.0.0`) would wrongly reject a `2.9.4` candidate,
/// turning a real match into a false FR-003 skip. `compile_bounded_requirement` is only used when
/// it succeeds; an ecosystem that returns `None` (requirement fails to parse under its own
/// comparator) falls back to the heuristic exactly as it did before this existed.
fn version_matches_requirement(
    formatter: &dyn EcosystemFormatter,
    version: &ConcreteVersion,
    requirement: BoundedVersionReq<'_>,
) -> bool {
    if let Some(matcher) = formatter.compile_bounded_requirement(requirement) {
        matcher.matches(version) == Some(true)
    } else {
        formatter.version_satisfies_bounded_requirement(version, requirement)
    }
}

fn best_candidate_for_requirement<'a>(
    candidates: &'a [ConcreteVersion],
    requirement: &crate::VersionReq,
    formatter: &dyn EcosystemFormatter,
) -> Option<&'a ConcreteVersion> {
    // #1472: an oversized requirement's parse cost would multiply by `candidates.len()`.
    let requirement = BoundedVersionReq::new(requirement)?;
    candidates
        .iter()
        .filter(|v| version_matches_requirement(formatter, v, requirement))
        .max_by(|a, b| crate::lockfile::compare_lockfile_versions(a.as_str(), b.as_str()))
}

/// Resolves one dependency occurrence's lock-file version, disambiguating by its own
/// `version_requirement()` when the resolved name has more than one retained lock-file entry
/// (issue #649).
///
/// `resolved_version_candidates` holds every retained lock-file entry per name (built from
/// [`crate::lockfile::ResolvedPackages::iter_all`]) but, per NFR-003, is expected to carry an
/// entry **only** for names with more than one occurrence — the common single-occurrence case
/// falls straight through to `resolved_versions` (the fast `HashMap` lookup, unchanged from
/// before this function existed, FR-005) without ever consulting the candidates map. The same
/// fallback applies when `dep.version_requirement()` is `None` (edge case: a renamed
/// occurrence with no version to disambiguate against) or when no candidate satisfies the
/// requirement (FR-003) — that last case intentionally does not substitute the collapsed
/// value, since it would be an arbitrary, possibly wrong, non-matching entry.
///
/// Shared by [`resolve_in_use_version`] and the resolved-version lookups in
/// [`super::hover::generate_hover`] and [`super::inlay_hints::generate_inlay_hints`] so all
/// three surfaces (hover, inlay hints, OSV target selection) apply the identical
/// per-occurrence disambiguation policy (US-001/US-002).
pub(crate) fn resolve_occurrence_version<'a>(
    dep: &dyn Dependency,
    normalized_name: &str,
    resolved_versions: &'a HashMap<PackageName, ConcreteVersion>,
    resolved_version_candidates: Option<&'a HashMap<PackageName, Vec<ConcreteVersion>>>,
    formatter: &dyn EcosystemFormatter,
) -> Option<&'a ConcreteVersion> {
    let candidates = resolved_version_candidates.and_then(|candidates| {
        candidates
            .get(normalized_name)
            .or_else(|| candidates.get(dep.name()))
    });

    match (candidates, dep.version_requirement()) {
        (Some(candidates), Some(req)) if candidates.len() > 1 => {
            best_candidate_for_requirement(candidates, req, formatter)
        }
        _ => resolved_versions
            .get(normalized_name)
            .or_else(|| resolved_versions.get(dep.name())),
    }
}

/// The version of `dep` this project treats as actually in use.
///
/// The lock-file-resolved version, else the declared requirement when it is
/// already concrete ([`concrete_pin_version`]). `None` when neither applies.
///
/// A dependency whose manifest requirement is itself the resolved version
/// ([`crate::lsp_helpers::RequirementResolution::manifest_requirement_is_resolved_version`] — a Go
/// `require`-directive dependency) skips the lockfile step entirely, going
/// straight to the declared requirement (go.sum is unreliable there — a
/// checksum ledger that `go get`/`go build` only ever append to, so its
/// last-occurrence-wins parse can surface a version still recorded in the
/// file but no longer selected by Go's MVS). Shared by `deps-lsp`'s OSV
/// target selection, its yanked-version check, and the yanked-diagnostic
/// consistency check in [`super::diagnostics::generate_diagnostics_from_cache`]
/// (#394 S1) — all three need "what version does the user actually have"
/// for the same reason: querying a fabricated version produces a silent
/// false negative.
///
/// `resolved_version_candidates` disambiguates a name with more than one lock-file entry by
/// the occurrence's own `version_requirement()` (issue #649) — see this module's
/// `resolve_occurrence_version` for the exact policy. `None` (most callers with no such map
/// to give) behaves exactly as before this parameter existed.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{
///     DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
///     RequirementResolution, SourcePolicy, resolve_in_use_version,
/// };
/// use deps_core::{ConcreteVersion, Dependency, EcosystemId, PackageName, VersionReq};
/// use std::any::Any;
/// use std::collections::HashMap;
/// use deps_core::position::Range;
///
/// struct SimpleDep {
///     name: PackageName,
///     version_req: Option<VersionReq>,
/// }
///
/// impl Dependency for SimpleDep {
///     fn name(&self) -> &PackageName {
///         &self.name
///     }
///     fn name_range(&self) -> Range {
///         Range::default()
///     }
///     fn version_requirement(&self) -> Option<&VersionReq> {
///         self.version_req.as_ref()
///     }
///     fn version_range(&self) -> Option<Range> {
///         None
///     }
///     fn source(&self) -> deps_core::parser::DependencySource {
///         deps_core::parser::DependencySource::Registry
///     }
///     fn as_any(&self) -> &dyn Any {
///         self
///     }
/// }
///
/// struct SimpleFormatter;
/// impl PackageNaming for SimpleFormatter {}
/// impl PackageRendering for SimpleFormatter {
///     fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
///         version.to_string()
///     }
///     fn package_url(&self, name: &PackageName) -> String {
///         name.as_str().to_string()
///     }
/// }
/// impl RequirementResolution for SimpleFormatter {}
/// impl DiagnosticMessages for SimpleFormatter {}
/// impl DiagnosticPolicy for SimpleFormatter {}
/// impl SourcePolicy for SimpleFormatter {}
/// impl OsvNaming for SimpleFormatter {}
///
/// let dep = SimpleDep {
///     name: PackageName::new("time"),
///     version_req: Some(VersionReq::new("=0.1.43")),
/// };
/// let resolved_versions: HashMap<PackageName, ConcreteVersion> = HashMap::new();
///
/// // No lock file, but the requirement is already an exact pin — falls
/// // back to it, stripped of its `=` marker.
/// assert_eq!(
///     resolve_in_use_version(&dep, "time", &resolved_versions, None, &SimpleFormatter, EcosystemId::Cargo),
///     Some(ConcreteVersion::new("0.1.43"))
/// );
/// ```
pub fn resolve_in_use_version(
    dep: &dyn Dependency,
    normalized_name: &str,
    resolved_versions: &HashMap<PackageName, ConcreteVersion>,
    resolved_version_candidates: Option<&HashMap<PackageName, Vec<ConcreteVersion>>>,
    formatter: &dyn EcosystemFormatter,
    ecosystem: EcosystemId,
) -> Option<ConcreteVersion> {
    resolve_in_use_versions(
        dep,
        normalized_name,
        resolved_versions,
        resolved_version_candidates,
        formatter,
        ecosystem,
    )
    .map(InUseVersions::into_primary)
}

/// Every version of one dependency occurrence that is in use: the primary plus any sibling
/// release tags naming the same commit.
///
/// Siblings come only from a formatter-resolved tag pin (GitHub Actions SHA and exact-tag
/// pins), each admitted through the same queryability gate as the primary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InUseVersions {
    primary: ConcreteVersion,
    siblings: Vec<ConcreteVersion>,
}

impl InUseVersions {
    fn without_siblings(primary: ConcreteVersion) -> Self {
        Self {
            primary,
            siblings: Vec::new(),
        }
    }

    /// Builds a value without a formatter, for tests of consumers in other crates.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub const fn for_test(primary: ConcreteVersion, siblings: Vec<ConcreteVersion>) -> Self {
        Self { primary, siblings }
    }

    /// The version [`resolve_in_use_version`] reports.
    #[must_use]
    pub const fn primary(&self) -> &ConcreteVersion {
        &self.primary
    }

    /// Other queryable release tags on the primary's commit, lowest version first.
    #[must_use]
    pub fn siblings(&self) -> &[ConcreteVersion] {
        &self.siblings
    }

    /// Discards the siblings, keeping the primary.
    #[must_use]
    pub fn into_primary(self) -> ConcreteVersion {
        self.primary
    }
}

/// Like [`resolve_in_use_version`], but also reports the sibling release tags sharing the
/// primary's commit (see [`InUseVersions`]).
///
/// Siblings only come from an ecosystem's tag-pin resolution (GitHub Actions); every other
/// source yields an empty list.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{
///     DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
///     RequirementResolution, SourcePolicy, resolve_in_use_versions,
/// };
/// use deps_core::position::Range;
/// use deps_core::{ConcreteVersion, Dependency, EcosystemId, PackageName, VersionReq};
/// use std::any::Any;
/// use std::collections::HashMap;
///
/// struct SimpleDep {
///     name: PackageName,
///     version_req: Option<VersionReq>,
/// }
///
/// impl Dependency for SimpleDep {
///     fn name(&self) -> &PackageName {
///         &self.name
///     }
///     fn name_range(&self) -> Range {
///         Range::default()
///     }
///     fn version_requirement(&self) -> Option<&VersionReq> {
///         self.version_req.as_ref()
///     }
///     fn version_range(&self) -> Option<Range> {
///         None
///     }
///     fn source(&self) -> deps_core::parser::DependencySource {
///         deps_core::parser::DependencySource::Registry
///     }
///     fn as_any(&self) -> &dyn Any {
///         self
///     }
/// }
///
/// struct SimpleFormatter;
/// impl PackageNaming for SimpleFormatter {}
/// impl PackageRendering for SimpleFormatter {
///     fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
///         version.to_string()
///     }
///     fn package_url(&self, name: &PackageName) -> String {
///         name.as_str().to_string()
///     }
/// }
/// impl RequirementResolution for SimpleFormatter {}
/// impl DiagnosticMessages for SimpleFormatter {}
/// impl DiagnosticPolicy for SimpleFormatter {}
/// impl SourcePolicy for SimpleFormatter {}
/// impl OsvNaming for SimpleFormatter {}
///
/// let dep = SimpleDep {
///     name: PackageName::new("time"),
///     version_req: Some(VersionReq::new("=0.1.43")),
/// };
/// let versions = resolve_in_use_versions(
///     &dep,
///     "time",
///     &HashMap::new(),
///     None,
///     &SimpleFormatter,
///     EcosystemId::Cargo,
/// )
/// .unwrap();
/// assert_eq!(versions.primary().as_str(), "0.1.43");
/// assert!(versions.siblings().is_empty());
/// ```
pub fn resolve_in_use_versions(
    dep: &dyn Dependency,
    normalized_name: &str,
    resolved_versions: &HashMap<PackageName, ConcreteVersion>,
    resolved_version_candidates: Option<&HashMap<PackageName, Vec<ConcreteVersion>>>,
    formatter: &dyn EcosystemFormatter,
    ecosystem: EcosystemId,
) -> Option<InUseVersions> {
    if formatter.manifest_requirement_is_resolved_version(dep) {
        return dep
            .version_requirement()
            .and_then(|req| concrete_pin_version(req.as_str(), ecosystem))
            .map(|v| InUseVersions::without_siblings(ConcreteVersion::from(v)));
    }

    if let Some(version) = resolve_occurrence_version(
        dep,
        normalized_name,
        resolved_versions,
        resolved_version_candidates,
        formatter,
    ) {
        return Some(InUseVersions::without_siblings(version.clone()));
    }

    // #1556: an ecosystem's own out-of-band resolution (e.g. GitHub Actions' `TagIndex`)
    // wins over the manifest-text fallback below — but never over a lock-file-resolved
    // version above (impl-critic M2: a stronger existing resolution source must not be
    // silently superseded) — and still must pass a shape gate, since `TagIndex` can resolve a
    // SHA to a moving alias (`v1`, `v2` next to `v2.9`) that is not a queryable version (#503).
    if let Some(pin) = formatter.resolved_pin_version(dep)
        && let Some(primary) = queryable_pin_version(&pin, ecosystem)
    {
        let siblings = pin
            .siblings()
            .iter()
            .filter_map(|tag| {
                queryable_pin_version(&ResolvedPin::most_specific(tag.clone()), ecosystem)
            })
            .collect();
        return Some(InUseVersions { primary, siblings });
    }

    dep.version_requirement()
        .and_then(|req| concrete_pin_version(req.as_str(), ecosystem))
        .map(|v| InUseVersions::without_siblings(ConcreteVersion::from(v)))
}

/// The version a [`ResolvedPin`] may be queried with: a full `major.minor.patch` tag, or a
/// two-component tag that is the most specific name published for the pinned commit (#1668).
fn queryable_pin_version(pin: &ResolvedPin, ecosystem: EcosystemId) -> Option<ConcreteVersion> {
    let version = pin.version();
    match pin {
        ResolvedPin::MostSpecific { .. } if is_major_minor_shape(version.as_str()) => {
            Some(version.clone())
        }
        ResolvedPin::MostSpecific { .. } | ResolvedPin::Alias { .. } => {
            concrete_pin_version(version.as_str(), ecosystem).map(ConcreteVersion::from)
        }
    }
}

/// Whether `s` is exactly `major.minor` (optional `v`/`V` prefix), all-digit, no suffix.
fn is_major_minor_shape(s: &str) -> bool {
    is_dotted_numeric::<2>(crate::github::normalize_tag(s))
}

/// Whether `dep` resolved to a tag too imprecise to query with (a moving alias or a
/// non-version name).
///
/// "Resolved" means [`RequirementResolution::resolved_pin_version`](crate::lsp_helpers::RequirementResolution::resolved_pin_version)
/// returned `Some`.
///
/// Lets a caller that got `None` from [`resolve_in_use_version`] tell "a tag was resolved but
/// is not a full version" apart from "nothing was resolved at all" (#1668).
#[must_use]
pub fn has_unqueryable_resolved_pin(
    dep: &dyn Dependency,
    formatter: &dyn EcosystemFormatter,
    ecosystem: EcosystemId,
) -> bool {
    formatter
        .resolved_pin_version(dep)
        .is_some_and(|pin| queryable_pin_version(&pin, ecosystem).is_none())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::position::Range;

    /// Minimal formatter with a real `compile_bounded_requirement` (Cargo-style `semver::VersionReq`
    /// semantics), for tests that must distinguish `best_candidate_for_requirement`'s
    /// precise `compile_bounded_requirement` path from `MOCK_FORMATTER`'s heuristic-only fallback
    /// (issue #649 critic finding C1).
    struct CaretFormatter;

    impl crate::lsp_helpers::PackageNaming for CaretFormatter {}
    impl crate::lsp_helpers::PackageRendering for CaretFormatter {
        fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
            version.to_string()
        }
        fn package_url(&self, name: &PackageName) -> String {
            name.as_str().to_string()
        }
    }
    impl crate::lsp_helpers::RequirementResolution for CaretFormatter {
        fn compile_bounded_requirement(
            &self,
            requirement: BoundedVersionReq<'_>,
        ) -> Option<Box<dyn crate::lsp_helpers::RequirementMatcher>> {
            let requirement = requirement.get();
            // Flips strict_prerelease_exclusion() from this module's old local matcher's
            // `false` to `true` — inert here, since nothing in this test module reads that flag.
            crate::lsp_helpers::compile_semver_requirement(requirement)
        }
    }
    impl crate::lsp_helpers::DiagnosticMessages for CaretFormatter {}
    impl crate::lsp_helpers::DiagnosticPolicy for CaretFormatter {}
    impl crate::lsp_helpers::SourcePolicy for CaretFormatter {}
    impl crate::lsp_helpers::OsvNaming for CaretFormatter {}

    /// A formatter whose `resolved_pin_version` always returns a fixed value regardless of
    /// `dep` — exercises `resolve_in_use_version`'s own full-semver-shape gate on the hook's
    /// output (#1556 critic S1), independent of any ecosystem's own `TagIndex` plumbing.
    struct FixedResolvedPinFormatter(ResolvedPin);

    impl FixedResolvedPinFormatter {
        fn most_specific(tag: &str) -> Self {
            Self(ResolvedPin::most_specific(ConcreteVersion::new(tag)))
        }

        fn alias(tag: &str) -> Self {
            Self(ResolvedPin::alias(ConcreteVersion::new(tag)))
        }

        fn from_index(tags: &[&str]) -> Self {
            let sha = crate::lsp_helpers::CommitSha::parse(&"a".repeat(40)).unwrap();
            let index = crate::lsp_helpers::TagIndex::from_tags(tags.iter().map(|t| (*t, &sha)));
            Self(index.resolved_pin(sha.as_str()).unwrap())
        }
    }

    impl crate::lsp_helpers::PackageNaming for FixedResolvedPinFormatter {}
    impl crate::lsp_helpers::PackageRendering for FixedResolvedPinFormatter {
        fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
            version.to_string()
        }
        fn package_url(&self, name: &PackageName) -> String {
            name.as_str().to_string()
        }
    }
    impl crate::lsp_helpers::RequirementResolution for FixedResolvedPinFormatter {
        fn resolved_pin_version(&self, _dep: &dyn Dependency) -> Option<ResolvedPin> {
            Some(self.0.clone())
        }
    }
    impl crate::lsp_helpers::DiagnosticMessages for FixedResolvedPinFormatter {}
    impl crate::lsp_helpers::DiagnosticPolicy for FixedResolvedPinFormatter {}
    impl crate::lsp_helpers::SourcePolicy for FixedResolvedPinFormatter {}
    impl crate::lsp_helpers::OsvNaming for FixedResolvedPinFormatter {}

    /// #1556 impl-critic S1: `resolved_pin_version`'s raw output (e.g. GitHub Actions'
    /// `TagIndex`-resolved tag) must not bypass the same full-semver-shape check manifest
    /// text goes through — a moving-major/partial tag name (`v1`, `2.9`) is not a real
    /// queryable version, and treating it as one regresses the #503 invariant this
    /// resolution hook must not query OSV.dev with a fabricated version.
    #[test]
    fn resolve_in_use_version_rejects_hook_output_that_is_not_full_semver_shape() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("actions/checkout"),
            version_req: VersionReq::new("deadbeef"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let unqueryable = [
            FixedResolvedPinFormatter::most_specific("v1"),
            FixedResolvedPinFormatter::most_specific("cargo-deny"),
            FixedResolvedPinFormatter::alias("v1"),
            FixedResolvedPinFormatter::alias("2.9"),
        ];
        for formatter in &unqueryable {
            let result = resolve_in_use_version(
                &dep,
                "actions/checkout",
                &HashMap::new(),
                None,
                formatter,
                EcosystemId::GithubActions,
            );
            assert_eq!(
                result, None,
                "{:?} must not resolve as concrete",
                formatter.0
            );
            assert!(has_unqueryable_resolved_pin(
                &dep,
                formatter,
                EcosystemId::GithubActions
            ));
        }
    }

    /// #1668: a two-component tag that no other tag on the commit extends is the most
    /// specific release name published, so it is queryable; the same text as a moving alias
    /// is not.
    #[test]
    fn resolve_in_use_version_accepts_most_specific_two_component_tag() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("obi1kenobi/cargo-semver-checks-action"),
            version_req: VersionReq::new("deadbeef"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        for (formatter, expected) in [
            (
                FixedResolvedPinFormatter::most_specific("v2.9"),
                Some(ConcreteVersion::from("v2.9")),
            ),
            (FixedResolvedPinFormatter::alias("v2.9"), None),
        ] {
            let result = resolve_in_use_version(
                &dep,
                "obi1kenobi/cargo-semver-checks-action",
                &HashMap::new(),
                None,
                &formatter,
                EcosystemId::GithubActions,
            );
            assert_eq!(result, expected, "{:?}", formatter.0);
        }
    }

    /// #1556 impl-critic M2: a lock-file-resolved version, when one exists, must win over
    /// `resolved_pin_version` — the hook only fills a gap the lock file leaves open, it must
    /// never silently supersede a stronger existing resolution source.
    #[test]
    fn resolve_in_use_version_lockfile_wins_over_resolved_pin_version_hook() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("actions/checkout"),
            version_req: VersionReq::new("deadbeef"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let mut resolved_versions = HashMap::new();
        resolved_versions.insert(
            PackageName::new("actions/checkout"),
            ConcreteVersion::from("v9.9.9"),
        );

        let result = resolve_in_use_version(
            &dep,
            "actions/checkout",
            &resolved_versions,
            None,
            &FixedResolvedPinFormatter::most_specific("v1.3.0"),
            EcosystemId::GithubActions,
        );
        assert_eq!(
            result,
            Some(ConcreteVersion::from("v9.9.9")),
            "the lock-file-resolved version must win over resolved_pin_version's hook output"
        );
    }

    /// The actually-intended case (#1556's original bug): a `resolved_pin_version` hook
    /// output that IS a full `major.minor.patch` tag must still win outright over the
    /// manifest-text ladder, exactly as before this gate was added.
    #[test]
    fn resolve_in_use_version_accepts_hook_output_that_is_full_semver_shape() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("actions/checkout"),
            version_req: VersionReq::new("deadbeef"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let result = resolve_in_use_version(
            &dep,
            "actions/checkout",
            &HashMap::new(),
            None,
            &FixedResolvedPinFormatter::most_specific("v1.3.0"),
            EcosystemId::GithubActions,
        );
        assert_eq!(result, Some(ConcreteVersion::from("v1.3.0")));
    }

    #[test]
    fn is_major_minor_shape_accepts_only_bare_two_component_versions() {
        for accepted in ["v2.9", "V2.9", "2.9", "v10.0"] {
            assert!(is_major_minor_shape(accepted), "{accepted:?}");
        }
        for rejected in ["v2.9-rc1", "v2.", "v.9", "v2.9.0", "v2", "", "v2.x", "main"] {
            assert!(!is_major_minor_shape(rejected), "{rejected:?}");
        }
    }

    /// #1668: the hook-resolved tag is unqueryable exactly when `queryable_pin_version`
    /// rejects it; no hook output at all is not "unqueryable".
    #[test]
    fn has_unqueryable_resolved_pin_distinguishes_partial_tag_from_no_resolution() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("actions/checkout"),
            version_req: VersionReq::new("deadbeef"),
            version_range: Range::default(),
            name_range: Range::default(),
        };
        for (formatter, expected) in [
            (FixedResolvedPinFormatter::most_specific("v2.9-rc1"), true),
            (FixedResolvedPinFormatter::most_specific("v2"), true),
            (FixedResolvedPinFormatter::alias("v2.9"), true),
            (FixedResolvedPinFormatter::most_specific("v2.9"), false),
            (FixedResolvedPinFormatter::most_specific("v1.3.0"), false),
        ] {
            assert_eq!(
                has_unqueryable_resolved_pin(&dep, &formatter, EcosystemId::GithubActions),
                expected,
                "{:?}",
                formatter.0
            );
        }
        assert!(!has_unqueryable_resolved_pin(
            &dep,
            &CaretFormatter,
            EcosystemId::GithubActions
        ));
    }

    #[test]
    fn is_concrete_version_accepts_explicit_pins_in_any_ecosystem() {
        for eco in [EcosystemId::Cargo, EcosystemId::Npm, EcosystemId::Go] {
            assert!(is_concrete_version("=1.2.3", eco), "{eco:?}");
        }
        // Go is not in the range-default set, so go.mod's bare `v1.9.1` style is accepted
        // without needing an explicit `=`.
        assert!(is_concrete_version("v1.9.1", EcosystemId::Go));
    }

    #[test]
    fn is_concrete_version_pep440_double_equals_is_a_pin() {
        // Critique C2: `strip_prefix('=')` alone turns PEP 440 `"==2.28.0"`
        // into `"=2.28.0"`, whose first char then fails the digit check.
        assert!(is_concrete_version("==2.28.0", EcosystemId::Pypi));
    }

    #[test]
    fn is_concrete_version_bare_digit_accepted_for_non_range_default_ecosystems() {
        // Maven/Go/Bundler/Dart/Gradle/NuGet: a bare version is already exact (or, for
        // NuGet's PackageReference floor, resolves to exactly that version in practice).
        // Gradle's only range shape is the `+` dynamic-version suffix, rejected separately
        // by `looks_like_a_single_version`.
        for eco in [
            EcosystemId::Maven,
            EcosystemId::Go,
            EcosystemId::Bundler,
            EcosystemId::Dart,
            EcosystemId::Gradle,
            EcosystemId::NuGet,
        ] {
            assert!(is_concrete_version("2.14.1", eco), "{eco:?}");
        }
    }

    #[test]
    fn is_concrete_version_dart_plus_build_number_is_a_pin() {
        assert_eq!(
            concrete_pin_version("0.8.13+1", EcosystemId::Dart),
            Some("0.8.13+1")
        );
        assert_eq!(
            concrete_pin_version("1.0.0-beta.2+3", EcosystemId::Dart),
            Some("1.0.0-beta.2+3")
        );
    }

    #[test]
    fn is_concrete_version_dart_malformed_plus_is_rejected() {
        for req in [
            "1.+",
            "4.+",
            "1+",
            "1.0.0+",
            "1.0.0+1+2",
            "1.0+local",
            "1.2.3+build",
        ] {
            assert!(!is_concrete_version(req, EcosystemId::Dart), "{req}");
        }
    }

    #[test]
    fn is_concrete_version_dart_plus_ranges_stay_non_exact() {
        for req in ["^0.8.13+1", ">=1.0.0+2", ">=1.0.0+2 <2.0.0", "any"] {
            assert!(!is_concrete_version(req, EcosystemId::Dart), "{req}");
        }
    }

    #[test]
    fn is_concrete_version_plus_still_dynamic_for_gradle_and_others() {
        for req in ["1.+", "4.+", "1.2.3+1"] {
            assert!(!is_concrete_version(req, EcosystemId::Gradle), "{req}");
        }
        for &eco in EcosystemId::ALL.iter().filter(|&&e| e != EcosystemId::Dart) {
            assert!(!is_concrete_version("==0.8.13+1", eco), "{eco:?}");
        }
    }

    #[test]
    fn is_concrete_version_nuget_bare_version_is_a_deliberate_pin_approximation() {
        // #669: a bare NuGet `Version="1.0.0"` is really a minimum-only floor, but treated
        // as concrete anyway (mirrors `NuGetFormatter::is_bounded_requirement_up_to_date`) —
        // reclassifying to always-range was tried and reverted since it dropped OSV/hover/
        // license resolution for the dominant bare-version spelling. See `Concrete`'s doc.
        assert!(is_concrete_version("1.0.0", EcosystemId::NuGet));
        // An explicit exact-bracket pin is stripped and matched before this policy applies.
        assert!(is_concrete_version("[1.0.0]", EcosystemId::NuGet));
    }

    #[test]
    fn is_concrete_version_bare_digit_rejected_for_range_default_ecosystems() {
        // Critique C2: Cargo's bare "1.2.3" is a caret range, not a pin — Cargo is the sole
        // remaining `AlwaysRange` ecosystem (npm/Composer #664 and Deno #667 moved to
        // `ConcreteIfFullVersion`, since a bare *full* version is their own exact pin).
        assert!(!is_concrete_version("1.2.3", EcosystemId::Cargo));
        // ...but an explicit pin is still accepted.
        assert!(is_concrete_version("=1.2.3", EcosystemId::Cargo));
    }

    #[test]
    fn is_concrete_version_rejects_partials_and_wildcards() {
        // Critique C2: npm/Composer "1.x"/"1.2.x" and bare partials like "1.2" are ranges
        // (rejected by the wildcard-component check and `ConcreteIfFullVersion`'s
        // `is_full_semver_shape` gate respectively, #664), and Gradle's "1.+" is dynamic.
        for eco in [EcosystemId::Npm, EcosystemId::Composer] {
            assert!(!is_concrete_version("1.x", eco), "{eco:?}");
            assert!(!is_concrete_version("1.2.x", eco), "{eco:?}");
            assert!(!is_concrete_version("1.2", eco), "{eco:?}");
        }
        assert!(!is_concrete_version("1.+", EcosystemId::Gradle));
    }

    #[test]
    fn is_concrete_version_accepts_pins_containing_the_letter_x() {
        for eco in [EcosystemId::Go, EcosystemId::Dart, EcosystemId::Npm] {
            for pin in [
                "0.1.0-experimental",
                "2.0.0-dev.x1",
                "1.0.0-next",
                "1.2.3-x",
                "1.2.3-x.1",
                "1.0.0-max",
                "1.0.0-xx",
            ] {
                assert!(is_concrete_version(pin, eco), "{pin} {eco:?}");
            }
        }
    }

    #[test]
    fn is_concrete_version_rejects_wildcard_components() {
        for eco in [EcosystemId::Go, EcosystemId::Dart] {
            for wildcard in [
                "1.x",
                "1.2.X",
                "1.*",
                "x",
                "X",
                "x.1",
                "v1.x",
                "1..x",
                "1.x.0",
                "1.2.xx",
                "1.x0",
                "1.2.x-SNAPSHOT",
                "1.2.x-beta",
                "1.x-beta",
                "2.x-dev",
                "1.2.3-alpha.x",
                "1.0.0-rc.x",
            ] {
                assert!(!is_concrete_version(wildcard, eco), "{wildcard} {eco:?}");
            }
        }
    }

    #[test]
    fn is_concrete_version_rejects_ranges_and_wildcards() {
        for eco in [EcosystemId::Maven, EcosystemId::Go] {
            assert!(!is_concrete_version("^1.0", eco));
            assert!(!is_concrete_version("~1.2", eco));
            assert!(!is_concrete_version("*", eco));
            assert!(!is_concrete_version(">=1.0", eco));
            assert!(!is_concrete_version(">=1.0 <2.0", eco));
            assert!(!is_concrete_version("1.0.*", eco));
            assert!(!is_concrete_version("", eco));
        }
    }

    #[test]
    fn is_concrete_version_rejects_non_version_schemes() {
        let eco = EcosystemId::Go;
        assert!(!is_concrete_version("latest", eco));
        assert!(!is_concrete_version("github:user/repo", eco));
        assert!(!is_concrete_version("file:../x", eco));
        assert!(!is_concrete_version("main", eco));
    }

    #[test]
    fn concrete_pin_version_strips_pep440_double_equals_comparator() {
        // Regression guard: PyPI's parser retains the pep440 comparator in
        // `version_requirement().as_str()` (`"==4.9.0"`, not `"4.9.0"`) — the verbatim
        // string was unusable against real registry versions in the yanked probe.
        assert_eq!(
            concrete_pin_version("==4.9.0", EcosystemId::Pypi),
            Some("4.9.0")
        );
    }

    #[test]
    fn concrete_pin_version_strips_single_equals_and_bracket_pins() {
        assert_eq!(
            concrete_pin_version("=1.2.3", EcosystemId::Cargo),
            Some("1.2.3")
        );
        assert_eq!(
            concrete_pin_version("[1.0.0]", EcosystemId::NuGet),
            Some("1.0.0")
        );
    }

    #[test]
    fn concrete_pin_version_bare_version_returned_verbatim() {
        // No operator to strip: Maven/Go/Bundler/Dart/Gradle/NuGet treat
        // a bare version as already exact.
        assert_eq!(
            concrete_pin_version("2.14.1", EcosystemId::Maven),
            Some("2.14.1")
        );
    }

    #[test]
    fn concrete_pin_version_rejects_ranges_and_partials() {
        assert_eq!(concrete_pin_version("^1.0", EcosystemId::Cargo), None);
        assert_eq!(concrete_pin_version("1.2.3", EcosystemId::Cargo), None);
        assert_eq!(concrete_pin_version(">=1.0,<2.0", EcosystemId::Pypi), None);
    }

    // --- is_full_semver_shape ---

    #[test]
    fn is_full_semver_shape_accepts_full_versions_with_and_without_v_prefix() {
        assert!(is_full_semver_shape("4.2.0"));
        assert!(is_full_semver_shape("v4.2.0"));
        assert!(is_full_semver_shape("V4.2.0"));
    }

    #[test]
    fn is_full_semver_shape_accepts_prerelease_and_build_suffixes() {
        assert!(is_full_semver_shape("v4.2.0-beta.1"));
        assert!(is_full_semver_shape("4.2.0+build.5"));
    }

    #[test]
    fn is_full_semver_shape_rejects_partial_versions() {
        assert!(!is_full_semver_shape("v4"));
        assert!(!is_full_semver_shape("v4.2"));
    }

    #[test]
    fn is_full_semver_shape_rejects_non_version_and_sha_shapes() {
        assert!(!is_full_semver_shape("main"));
        assert!(!is_full_semver_shape(
            "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"
        ));
        assert!(!is_full_semver_shape(""));
        assert!(!is_full_semver_shape("4.2.0.1"));
        assert!(!is_full_semver_shape("4..0"));
    }

    // --- concrete_pin_version: BareRequirementPolicy::ConcreteIfFullVersion (GitHub Actions) ---

    #[test]
    fn concrete_pin_version_github_actions_full_bare_tag_is_concrete() {
        assert_eq!(
            concrete_pin_version("v4.2.0", EcosystemId::GithubActions),
            Some("v4.2.0")
        );
    }

    #[test]
    fn concrete_pin_version_github_actions_moving_major_tag_is_a_range() {
        // `v4` genuinely is a range (a moving major tag) — must not be queried as if
        // it were the concrete version `4` (critique B2).
        assert_eq!(concrete_pin_version("v4", EcosystemId::GithubActions), None);
        assert_eq!(
            concrete_pin_version("v4.2", EcosystemId::GithubActions),
            None
        );
    }

    #[test]
    fn concrete_pin_version_github_actions_bare_sha_is_not_concrete() {
        // A bare SHA has no dots, so it fails `is_full_semver_shape` and falls to the
        // honest "unknown" `None` rather than being queried as a fabricated version.
        assert_eq!(
            concrete_pin_version(
                "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
                EcosystemId::GithubActions
            ),
            None
        );
    }

    // --- concrete_pin_version: BareRequirementPolicy::ConcreteIfFullVersion (GitLab CI) ---

    #[test]
    fn concrete_pin_version_gitlab_ci_full_tag_is_concrete() {
        assert_eq!(
            concrete_pin_version("1.2.3", EcosystemId::GitlabCi),
            Some("1.2.3")
        );
        assert_eq!(
            concrete_pin_version("v1.2.3", EcosystemId::GitlabCi),
            Some("v1.2.3")
        );
    }

    #[test]
    fn concrete_pin_version_gitlab_ci_partial_pin_is_a_range() {
        // H2 regression (#466 review): a `component:` partial-semver pin (`1`, `1.2`)
        // is a range under GitLab's own documented `~{raw}` semantics, not a single
        // version — must not be queried as if it were the concrete version `1.2`.
        assert_eq!(concrete_pin_version("1.2", EcosystemId::GitlabCi), None);
        assert_eq!(concrete_pin_version("1", EcosystemId::GitlabCi), None);
    }

    #[test]
    fn concrete_pin_version_gitlab_ci_digit_leading_sha_is_not_concrete() {
        // A 40-hex SHA that happens to start with a digit must still fall to the
        // honest "unknown" `None` rather than being misread as a version — it has no
        // dots, so it fails `is_full_semver_shape` regardless of its leading
        // character.
        assert_eq!(
            concrete_pin_version(
                "1234567890abcdef1234567890abcdef12345678",
                EcosystemId::GitlabCi
            ),
            None
        );
    }

    // --- concrete_pin_version: BareRequirementPolicy::ConcreteIfFullVersion (npm/Composer, #664) ---

    #[test]
    fn concrete_pin_version_npm_full_bare_version_is_concrete() {
        assert_eq!(
            concrete_pin_version("4.17.0", EcosystemId::Npm),
            Some("4.17.0")
        );
    }

    #[test]
    fn concrete_pin_version_npm_partial_bare_version_is_a_range() {
        // node-semver's implicit X-range: a bare partial version expands to
        // `>=4.17.0 <4.18.0` (or wider), not a single version.
        assert_eq!(concrete_pin_version("4.17", EcosystemId::Npm), None);
        assert_eq!(concrete_pin_version("4", EcosystemId::Npm), None);
    }

    #[test]
    fn concrete_pin_version_npm_explicit_pin_still_concrete() {
        assert_eq!(
            concrete_pin_version("=4.17.0", EcosystemId::Npm),
            Some("4.17.0")
        );
    }

    #[test]
    fn concrete_pin_version_composer_full_bare_version_is_concrete() {
        assert_eq!(
            concrete_pin_version("2.0.0", EcosystemId::Composer),
            Some("2.0.0")
        );
    }

    #[test]
    fn concrete_pin_version_composer_partial_bare_version_is_a_range() {
        // Composer's prefix-match semantics: a bare partial version matches
        // any version sharing that prefix, not a single version.
        assert_eq!(concrete_pin_version("2.0", EcosystemId::Composer), None);
        assert_eq!(concrete_pin_version("2", EcosystemId::Composer), None);
    }

    #[test]
    fn concrete_pin_version_composer_explicit_pin_still_concrete() {
        assert_eq!(
            concrete_pin_version("=2.0.0", EcosystemId::Composer),
            Some("2.0.0")
        );
    }

    // --- concrete_pin_version: BareRequirementPolicy::ConcreteIfFullVersion (Deno, #667) ---

    #[test]
    fn concrete_pin_version_deno_full_bare_version_is_concrete() {
        assert_eq!(
            concrete_pin_version("4.17.0", EcosystemId::Deno),
            Some("4.17.0")
        );
    }

    #[test]
    fn concrete_pin_version_deno_partial_bare_version_is_a_range() {
        // `DenoFormatter::compile_bounded_requirement` compiles `jsr:`/`npm:` requirements
        // through the same `node_semver::Range` npm uses, so a bare partial version
        // expands to an implicit X-range, not a single version.
        assert_eq!(concrete_pin_version("4.17", EcosystemId::Deno), None);
        assert_eq!(concrete_pin_version("4", EcosystemId::Deno), None);
    }

    #[test]
    fn concrete_pin_version_deno_explicit_pin_still_concrete() {
        assert_eq!(
            concrete_pin_version("=1.0.0", EcosystemId::Deno),
            Some("1.0.0")
        );
    }

    /// Regression guard for issue #649 (deps-cargo `package = "..."` rename, follow-up to
    /// #648): two manifest occurrences of the same crate — one plain, one renamed via
    /// `package = "..."` to select an older major — both resolve `Dependency::name()` to
    /// the same registry name. Before this fix, both collided on `resolved_versions`'s
    /// single collapsed highest-semver entry (asserted by a since-superseded version of
    /// this test — see the critic handoff `.local/handoff/2026-09-05T23-48-31-critic.md`,
    /// finding S1, for the original failure-mode analysis). With
    /// `resolved_version_candidates` populated, each occurrence now resolves to the
    /// lock-file entry that actually satisfies its own `version_requirement()`
    /// (US-001/US-002, FR-001/FR-002).
    #[test]
    fn in_use_version_renamed_occurrence_resolves_its_own_major() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let renamed_old_major = MockDep {
            name: PackageName::new("serde"),
            version_req: VersionReq::new("0.9"),
            version_range: Range::default(),
            name_range: Range::default(),
        };
        let plain_current_major = MockDep {
            name: PackageName::new("serde"),
            version_req: VersionReq::new("1.0"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let mut resolved_versions = HashMap::new();
        resolved_versions.insert(PackageName::new("serde"), ConcreteVersion::from("1.0.219"));
        let mut candidates = HashMap::new();
        candidates.insert(
            PackageName::new("serde"),
            vec![
                ConcreteVersion::from("0.9.15"),
                ConcreteVersion::from("1.0.219"),
            ],
        );

        let renamed_result = resolve_in_use_version(
            &renamed_old_major,
            "serde",
            &resolved_versions,
            Some(&candidates),
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Cargo,
        );
        let plain_result = resolve_in_use_version(
            &plain_current_major,
            "serde",
            &resolved_versions,
            Some(&candidates),
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Cargo,
        );

        assert_eq!(renamed_result, Some(ConcreteVersion::from("0.9.15")));
        assert_eq!(plain_result, Some(ConcreteVersion::from("1.0.219")));
    }

    /// FR-003: when no lock-file candidate satisfies the occurrence's own requirement, the
    /// result is the honest "no concrete version" skip — never an arbitrary non-matching
    /// entry.
    #[test]
    fn in_use_version_no_candidate_satisfies_requirement_returns_none() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("serde"),
            version_req: VersionReq::new("0.9"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let resolved_versions = HashMap::new();
        let mut candidates = HashMap::new();
        candidates.insert(
            PackageName::new("serde"),
            vec![
                ConcreteVersion::from("1.0.219"),
                ConcreteVersion::from("1.1.0"),
            ],
        );

        let result = resolve_in_use_version(
            &dep,
            "serde",
            &resolved_versions,
            Some(&candidates),
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Cargo,
        );

        assert_eq!(result, None);
    }

    /// Edge case (spec section 6): a renamed occurrence with no `version_requirement()` to
    /// disambiguate against falls back to the collapsed highest-semver value, same as
    /// before this fix — no new skip-reason variant.
    #[test]
    fn in_use_version_no_requirement_falls_back_to_collapsed_value() {
        use crate::lsp_helpers::test_support::MockMarkedDep;

        let dep = MockMarkedDep {
            name: PackageName::new("serde"),
            name_range: Range::default(),
            markers: None,
        };

        let mut resolved_versions = HashMap::new();
        resolved_versions.insert(PackageName::new("serde"), ConcreteVersion::from("1.0.219"));
        let mut candidates = HashMap::new();
        candidates.insert(
            PackageName::new("serde"),
            vec![
                ConcreteVersion::from("0.9.15"),
                ConcreteVersion::from("1.0.219"),
            ],
        );

        let result = resolve_in_use_version(
            &dep,
            "serde",
            &resolved_versions,
            Some(&candidates),
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Cargo,
        );

        assert_eq!(result, Some(ConcreteVersion::from("1.0.219")));
    }

    /// FR-005/NFR-001: a single-candidate name (the dominant case, no rename involved)
    /// behaves identically whether or not a candidates map is supplied — the fast path
    /// never routes through the per-occurrence filter.
    #[test]
    fn in_use_version_single_candidate_matches_collapsed_fast_path() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("serde"),
            version_req: VersionReq::new("1.0"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let mut resolved_versions = HashMap::new();
        resolved_versions.insert(PackageName::new("serde"), ConcreteVersion::from("1.0.219"));
        let mut candidates = HashMap::new();
        candidates.insert(
            PackageName::new("serde"),
            vec![ConcreteVersion::from("1.0.219")],
        );

        let with_candidates = resolve_in_use_version(
            &dep,
            "serde",
            &resolved_versions,
            Some(&candidates),
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Cargo,
        );
        let without_candidates = resolve_in_use_version(
            &dep,
            "serde",
            &resolved_versions,
            None,
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Cargo,
        );

        assert_eq!(with_candidates, Some(ConcreteVersion::from("1.0.219")));
        assert_eq!(with_candidates, without_candidates);
    }

    /// Edge case (spec section 6): non-semver-parseable versions among the candidates fall
    /// back to `compare_lockfile_versions`'s lexicographic tiebreak, not a second, divergent
    /// comparison policy.
    #[test]
    fn best_candidate_for_requirement_non_semver_uses_lexicographic_tiebreak() {
        // Testing gap 2 fix: both candidates must satisfy the requirement and both must fail
        // semver parsing, so `max_by` falls all the way to `compare_lockfile_versions`'s
        // `(Err, Err) => a.cmp(b)` branch — a single-match case never calls the comparator.
        // Requirement `"1"` is a partial-version bare requirement; both `"1-rc1"`/`"1-rc2"`
        // satisfy it via the `starts_with` fallback branch.
        let candidates = vec![
            ConcreteVersion::from("1-rc1"),
            ConcreteVersion::from("1-rc2"),
        ];

        let result = best_candidate_for_requirement(
            &candidates,
            &crate::VersionReq::new("1"),
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
        );

        assert_eq!(result, Some(&ConcreteVersion::from("1-rc2")));
    }

    /// C1 fix regression guard: `best_candidate_for_requirement` must prefer
    /// `compile_bounded_requirement`'s precise comparator over `version_satisfies_requirement`'s
    /// heuristic. The heuristic's partial-requirement branch requires *minor-version
    /// equality*, so a Cargo-style caret requirement `"2.4"` (meaning `>=2.4.0, <3.0.0`)
    /// would wrongly reject `2.9.4` under the heuristic alone — this is the exact
    /// false-negative the critic's C1 finding identified (a real dependency silently
    /// dropped from in-use-version resolution, and therefore from the OSV scan).
    #[test]
    fn best_candidate_for_requirement_uses_compile_requirement_when_available() {
        use crate::VersionReq;

        let candidates = vec![
            ConcreteVersion::from("1.3.2"),
            ConcreteVersion::from("2.9.4"),
        ];

        // Bare "2.4" under Cargo's real semver semantics is a caret range matching
        // 2.9.4, not 1.3.2 — but the heuristic's minor-equality check would reject both
        // (neither candidate has minor "4"), producing a false FR-003 skip.
        let result =
            best_candidate_for_requirement(&candidates, &VersionReq::new("2.4"), &CaretFormatter);

        assert_eq!(result, Some(&ConcreteVersion::from("2.9.4")));
    }

    /// FR-002: when more than one lock-file entry satisfies an occurrence's requirement,
    /// the tiebreak must pick the highest-semver *among the satisfying subset*, not the
    /// highest overall — `2.0.0` here is the highest candidate but does not satisfy `^1.0`,
    /// so it must never be picked.
    #[test]
    fn best_candidate_for_requirement_picks_highest_of_satisfying_subset() {
        use crate::VersionReq;

        let candidates = vec![
            ConcreteVersion::from("1.0.1"),
            ConcreteVersion::from("1.0.5"),
            ConcreteVersion::from("2.0.0"),
        ];

        let result =
            best_candidate_for_requirement(&candidates, &VersionReq::new("^1.0"), &CaretFormatter);

        assert_eq!(result, Some(&ConcreteVersion::from("1.0.5")));
    }

    /// #1472 defense-in-depth: an oversized requirement must short-circuit to `None` before
    /// ever calling into `compile_bounded_requirement`/`version_satisfies_requirement` per candidate —
    /// not just fail to match. The candidate here is built to trivially satisfy the heuristic's
    /// exact-equality branch if the gate were bypassed, proving the gate itself is what decides.
    #[test]
    fn best_candidate_for_requirement_oversized_requirement_returns_none() {
        use crate::VersionReq;

        let oversized = "1".repeat(300);
        let candidates = vec![ConcreteVersion::from(oversized.as_str())];

        let result = best_candidate_for_requirement(
            &candidates,
            &VersionReq::new(oversized),
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
        );

        assert_eq!(result, None);
    }

    /// FR-002 end-to-end through `in_use_version`/`resolve_occurrence_version`, not just the
    /// isolated `best_candidate_for_requirement` helper.
    #[test]
    fn in_use_version_tiebreaks_among_multiple_satisfying_candidates() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("pkg"),
            version_req: VersionReq::new("^1.0"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let resolved_versions = HashMap::new();
        let mut candidates = HashMap::new();
        candidates.insert(
            PackageName::new("pkg"),
            vec![
                ConcreteVersion::from("1.0.1"),
                ConcreteVersion::from("1.0.5"),
                ConcreteVersion::from("2.0.0"),
            ],
        );

        let result = resolve_in_use_version(
            &dep,
            "pkg",
            &resolved_versions,
            Some(&candidates),
            &CaretFormatter,
            EcosystemId::Cargo,
        );

        assert_eq!(result, Some(ConcreteVersion::from("1.0.5")));
    }

    // --- in_use_version end-to-end: #664's exact repro (no lock file, bare full version) ---

    /// #664's exact repro: `"express": "4.17.0"` in `package.json` with no
    /// `package-lock.json` — `resolve_occurrence_version` has nothing to resolve from
    /// (empty `resolved_versions`, no candidates), so the fix must be observable through
    /// the fallback to `concrete_pin_version`, not just in that helper in isolation.
    #[test]
    fn in_use_version_npm_bare_full_version_no_lockfile_resolves_664_repro() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("express"),
            version_req: VersionReq::new("4.17.0"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let result = resolve_in_use_version(
            &dep,
            "express",
            &HashMap::new(),
            None,
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Npm,
        );

        assert_eq!(result, Some(ConcreteVersion::from("4.17.0")));
    }

    /// Composer counterpart of the #664 repro: `"monolog/monolog": "2.0.0"` in
    /// `composer.json` with no `composer.lock`.
    #[test]
    fn in_use_version_composer_bare_full_version_no_lockfile_resolves_664_repro() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("monolog/monolog"),
            version_req: VersionReq::new("2.0.0"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let result = resolve_in_use_version(
            &dep,
            "monolog/monolog",
            &HashMap::new(),
            None,
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Composer,
        );

        assert_eq!(result, Some(ConcreteVersion::from("2.0.0")));
    }

    /// Regression guard: Cargo's identically-shaped bare full version must still resolve
    /// to no concrete pin end-to-end (not just via `concrete_pin_version` in isolation) —
    /// #664 only reclassified npm/Composer, not Cargo's real implicit-caret default.
    #[test]
    fn in_use_version_cargo_bare_full_version_no_lockfile_still_none() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("serde"),
            version_req: VersionReq::new("1.0.219"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let result = resolve_in_use_version(
            &dep,
            "serde",
            &HashMap::new(),
            None,
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Cargo,
        );

        assert_eq!(result, None);
    }

    /// #667's exact repro: a `deno.json` `"npm:express@4.17.0"` import with no lock
    /// file — `deps-deno` has no `LockFileProvider` implementation at all, so this is
    /// the *only* path through which a Deno dependency can ever resolve an in-use
    /// version. Before this fix, Deno was grouped with Cargo under `AlwaysRange`, so
    /// this bare full-version pin resolved to `None` and never received an OSV scan.
    #[test]
    fn in_use_version_deno_bare_full_version_no_lockfile_resolves_667_repro() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("express"),
            version_req: VersionReq::new("4.17.0"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let result = resolve_in_use_version(
            &dep,
            "express",
            &HashMap::new(),
            None,
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Deno,
        );

        assert_eq!(result, Some(ConcreteVersion::from("4.17.0")));
    }

    /// #669's exact scenario: a `.csproj` `<PackageReference Include="Newtonsoft.Json"
    /// Version="1.0.0" />` with no lock file present. `NuGetFormatter::
    /// version_satisfies_requirement` would accept `"2.5.0"`/`"9.9.9"` too (the bare
    /// requirement is really an unbounded minimum floor), but `in_use_version` still
    /// resolves this to the pin-approximation `Some("1.0.0")` — restore resolves a
    /// direct `PackageReference` to exactly its floor version in practice, so this is
    /// the right default answer for "what version does the project actually have"
    /// even though it is not the only version the requirement's own comparator would
    /// accept. Reclassifying NuGet to always-range instead (tried and reverted during
    /// #669's implementation) made this `None`, which silently dropped OSV scanning
    /// and hover Security/License sections for the dominant bare `Version="X"`
    /// spelling — see this module's `Concrete` doc for the full rationale.
    #[test]
    fn in_use_version_nuget_bare_floor_resolves_as_pin_approximation() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("Newtonsoft.Json"),
            version_req: VersionReq::new("1.0.0"),
            version_range: Range::default(),
            name_range: Range::default(),
        };

        let result = resolve_in_use_version(
            &dep,
            "newtonsoft.json",
            &HashMap::new(),
            None,
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::NuGet,
        );

        assert_eq!(result, Some(ConcreteVersion::from("1.0.0")));
    }

    fn sha_pinned_dep() -> crate::lsp_helpers::test_support::MockDep {
        crate::lsp_helpers::test_support::MockDep {
            name: PackageName::new("actions/checkout"),
            version_req: crate::VersionReq::new("deadbeef"),
            version_range: Range::default(),
            name_range: Range::default(),
        }
    }

    /// #1709: a pin's sibling release tags are reported next to the primary.
    #[test]
    fn resolve_in_use_versions_reports_pin_siblings_through_the_queryable_gate() {
        let formatter = FixedResolvedPinFormatter::from_index(&[
            "v4.9.0",
            "v4.8.0",
            "v4.10.0",
            "v4.11.0-rc1",
            "v4",
        ]);
        let versions = resolve_in_use_versions(
            &sha_pinned_dep(),
            "actions/checkout",
            &HashMap::new(),
            None,
            &formatter,
            EcosystemId::GithubActions,
        )
        .unwrap();
        assert_eq!(versions.primary().as_str(), "v4.8.0");
        let siblings: Vec<&str> = versions.siblings().iter().map(|s| s.as_str()).collect();
        assert_eq!(siblings, ["v4.9.0", "v4.10.0"]);
    }

    /// #1709 (G7): a most-specific two-component primary keeps its two-component siblings.
    #[test]
    fn resolve_in_use_versions_two_component_primary_keeps_two_component_siblings() {
        let formatter = FixedResolvedPinFormatter::from_index(&["v2.9", "v2.10"]);
        let versions = resolve_in_use_versions(
            &sha_pinned_dep(),
            "actions/checkout",
            &HashMap::new(),
            None,
            &formatter,
            EcosystemId::GithubActions,
        )
        .unwrap();
        assert_eq!(versions.primary().as_str(), "v2.9");
        assert_eq!(versions.siblings().len(), 1);
    }

    /// #1709: a lock-file version wins and carries no siblings.
    #[test]
    fn resolve_in_use_versions_lockfile_version_has_no_siblings() {
        let formatter = FixedResolvedPinFormatter::from_index(&["v4.8.0", "v4.9.0"]);
        let resolved = HashMap::from([(
            PackageName::new("actions/checkout"),
            ConcreteVersion::new("4.7.0"),
        )]);
        let versions = resolve_in_use_versions(
            &sha_pinned_dep(),
            "actions/checkout",
            &resolved,
            None,
            &formatter,
            EcosystemId::GithubActions,
        )
        .unwrap();
        assert_eq!(versions.primary().as_str(), "4.7.0");
        assert!(versions.siblings().is_empty());
    }

    /// #1709: `resolve_in_use_version` stays the primary of `resolve_in_use_versions`.
    #[test]
    fn resolve_in_use_version_returns_the_primary_of_a_sibling_pin() {
        let formatter = FixedResolvedPinFormatter::from_index(&["v4.8.0", "v4.9.0"]);
        assert_eq!(
            resolve_in_use_version(
                &sha_pinned_dep(),
                "actions/checkout",
                &HashMap::new(),
                None,
                &formatter,
                EcosystemId::GithubActions,
            ),
            Some(ConcreteVersion::new("v4.8.0"))
        );
    }

    /// #1602: `bare_requirement_policy` (in-use-version resolution) and `bare_meaning`
    /// (rewrite safety, `lsp_helpers::formatter`) answer different questions and are allowed to
    /// diverge for most ecosystems (see `bare_meaning`'s own doc for why Maven/Gradle are
    /// exactly such a divergence) — but the one thing they must never disagree on is
    /// "does a bare version auto-follow future releases at all": an ecosystem is
    /// `BareRequirementPolicy::AlwaysRange` here if and only if it is `BareMeaning::Caret`
    /// there. A future ecosystem wired to one of these functions but not the other, or wired
    /// inconsistently, fails this loop instead of silently shipping a mismatched pair.
    #[test]
    fn bare_meaning_agrees_with_bare_requirement_policy_on_always_range() {
        use crate::lsp_helpers::{BareMeaning, bare_meaning};

        for &eco in EcosystemId::ALL {
            let policy = bare_requirement_policy(eco);
            let meaning = bare_meaning(eco);
            match policy {
                BareRequirementPolicy::AlwaysRange => assert_eq!(
                    meaning,
                    BareMeaning::Caret,
                    "{eco:?}: AlwaysRange (bare is an auto-following range for in-use-version \
                     resolution) must also be BareMeaning::Caret for rewrite-safety purposes"
                ),
                BareRequirementPolicy::ConcreteIfFullVersion | BareRequirementPolicy::Concrete => {
                    assert_ne!(
                        meaning,
                        BareMeaning::Caret,
                        "{eco:?}: a bare version usable as an in-use-version pin ({policy:?}) \
                         cannot also carry BareMeaning::Caret rewrite semantics — an ecosystem \
                         whose bare form doesn't auto-follow future releases cannot widen when a \
                         bounded range collapses to bare either"
                    );
                }
            }
        }
    }
}