deps-core 5.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
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
//! "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 std::sync::Arc;

use crate::lockfile::compare_parsed_versions;
use crate::lsp_helpers::{
    BoundedVersionReq, CandidateSet, DependencyFormatter, EcosystemFormatter, OwnerPreference,
    PinResolution, ResolvedCandidatesMap, ResolvedPin,
};
use crate::osv::{AlternativeCoverage, MAX_LOCK_ALTERNATIVES, SiblingCoverage};
use crate::{ConcreteVersion, Dependency, EcosystemId, NormalizedName, PackageKey};

/// 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. The candidates map cannot say which
/// entry the package manager installed for this dependency, so every other satisfying entry is
/// reported as a lock alternative ([`InUseVersions::lock_alternatives`]) and scanned too (#1981).
/// 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.
///
/// The requirement is compiled once for the whole candidate list, not once per candidate, and
/// `set` (the list parsed once, see [`CachedList`]) answers without reparsing any candidate.
/// Returns one flag per candidate, in order; an oversized requirement satisfies none.
fn satisfying_mask(
    candidates: &[ConcreteVersion],
    requirement: &crate::VersionReq,
    formatter: &dyn EcosystemFormatter,
    set: Option<&dyn CandidateSet>,
) -> Vec<bool> {
    // #1472: an oversized requirement's parse cost would multiply by `candidates.len()`.
    let Some(requirement) = BoundedVersionReq::new(requirement) else {
        return vec![false; candidates.len()];
    };
    if let Some(mask) = set.and_then(|set| set.satisfying(requirement)) {
        return mask;
    }
    let matcher = formatter.compile_bounded_requirement(requirement);
    candidates
        .iter()
        .map(|version| match &matcher {
            Some(matcher) => matcher.matches(version) == Some(true),
            None => formatter.version_satisfies_bounded_requirement(version, requirement),
        })
        .collect()
}

/// A candidate list's versions parsed as semver, one slot per candidate, shared across every
/// requirement selected from that list in one pass.
type ParsedVersions = Arc<[Option<semver::Version>]>;

/// What one pass keeps per candidate list: its semver parse for ordering, and the ecosystem's
/// own parse of it for requirement matching (`None` for a formatter without a candidate set).
#[derive(Clone)]
pub(crate) struct CachedList {
    parsed: ParsedVersions,
    set: Option<Arc<dyn CandidateSet>>,
}

impl CachedList {
    pub(crate) fn new(entries: &[ConcreteVersion], formatter: &dyn EcosystemFormatter) -> Self {
        Self {
            parsed: parse_all(entries),
            set: formatter.candidate_set(entries).map(Arc::from),
        }
    }
}

impl std::fmt::Debug for CachedList {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CachedList")
            .field("candidates", &self.parsed.len())
            .field("has_set", &self.set.is_some())
            .finish()
    }
}

fn parse_all(candidates: &[ConcreteVersion]) -> ParsedVersions {
    candidates
        .iter()
        .map(|v| semver::Version::parse(v.as_str()).ok())
        .collect()
}

/// One candidate with its parsed form, ordered like [`crate::lockfile::compare_lockfile_versions`].
#[derive(Clone, Copy)]
struct Entry<'v, 'p> {
    version: &'v ConcreteVersion,
    parsed: &'p Option<semver::Version>,
}

fn compare_entries(a: &Entry<'_, '_>, b: &Entry<'_, '_>) -> std::cmp::Ordering {
    compare_parsed_versions(
        (a.parsed.as_ref(), a.version.as_str()),
        (b.parsed.as_ref(), b.version.as_str()),
    )
}

/// The flagged candidates with their parsed forms.
fn flagged_entries<'v, 'p>(
    candidates: &'v [ConcreteVersion],
    parsed: &'p [Option<semver::Version>],
    mask: &'p [bool],
) -> impl Iterator<Item = Entry<'v, 'p>> {
    candidates
        .iter()
        .zip(parsed)
        .zip(mask)
        .filter(|(_, flagged)| **flagged)
        .map(|((version, parsed), _)| Entry { version, parsed })
}

/// The lock entries an occurrence could be using, with the parse cache of their list.
struct Candidates<'a> {
    entries: &'a [ConcreteVersion],
    parsed: ParsedVersions,
    possible: Vec<bool>,
    preference: &'a OwnerPreference,
}

impl<'a> Candidates<'a> {
    fn highest(&self) -> Option<&'a ConcreteVersion> {
        flagged_entries(self.entries, &self.parsed, &self.possible)
            .max_by(compare_entries)
            .map(|entry| entry.version)
    }

    /// The possible entry the requesting manifest is using: the highest possible one it owns,
    /// else the highest possible one overall (#1993). A yarn lock file records which declared
    /// requirement each entry resolves, so an entry listing `requirement` verbatim is its own.
    fn preferred(&self, requirement: Option<&crate::VersionReq>) -> Option<&'a ConcreteVersion> {
        let owned: Vec<bool> = match (self.preference, requirement) {
            (OwnerPreference::Unscoped, _) | (OwnerPreference::Descriptors(_), None) => {
                return self.highest();
            }
            (OwnerPreference::Owned(flags), _) => flags.to_vec(),
            (OwnerPreference::Descriptors(per_version), Some(requirement)) => per_version
                .iter()
                .map(|declared| declared.iter().any(|d| d.as_str() == requirement.as_str()))
                .collect(),
        };
        let preferred = Self {
            entries: self.entries,
            parsed: Arc::clone(&self.parsed),
            possible: self
                .possible
                .iter()
                .zip(owned)
                .map(|(p, o)| *p && o)
                .collect(),
            preference: self.preference,
        };
        preferred.highest().or_else(|| self.highest())
    }

    /// The distinct possible versions other than `primary`: all of them when at most
    /// `MAX_LOCK_ALTERNATIVES` exist, else the `MAX_LOCK_ALTERNATIVES` nearest to `primary` in
    /// sorted order (ties go to the higher side), ascending. A newer vulnerable copy is the one
    /// worth scanning, so the nearest are kept rather than the lowest (#1997). The cost is linear
    /// in the list plus a sort of at most `MAX_LOCK_ALTERNATIVES` entries.
    fn nearest_others(
        &self,
        primary: &ConcreteVersion,
    ) -> (Vec<ConcreteVersion>, AlternativeCoverage) {
        let primary_parsed = semver::Version::parse(primary.as_str()).ok();
        let primary_entry = Entry {
            version: primary,
            parsed: &primary_parsed,
        };
        let mut seen = std::collections::HashSet::new();
        let (mut below, mut above): (Vec<Entry<'_, '_>>, Vec<Entry<'_, '_>>) =
            flagged_entries(self.entries, &self.parsed, &self.possible)
                .filter(|entry| entry.version != primary && seen.insert(entry.version.as_str()))
                .partition(|entry| compare_entries(entry, &primary_entry).is_lt());
        let coverage = if below.len() + above.len() > MAX_LOCK_ALTERNATIVES {
            AlternativeCoverage::Truncated
        } else {
            AlternativeCoverage::Complete
        };
        let take_above = above.len().min(MAX_LOCK_ALTERNATIVES.div_ceil(2));
        let take_below = below.len().min(MAX_LOCK_ALTERNATIVES - take_above);
        let take_above = above.len().min(MAX_LOCK_ALTERNATIVES - take_below);
        keep_largest(&mut below, take_below);
        keep_smallest(&mut above, take_above);
        let alternatives = below
            .iter()
            .chain(&above)
            .map(|entry| entry.version.clone())
            .collect();
        (alternatives, coverage)
    }
}

/// Keeps the `n` largest entries of `entries`, ascending.
fn keep_largest(entries: &mut Vec<Entry<'_, '_>>, n: usize) {
    if let Some(drop) = entries.len().checked_sub(n).filter(|drop| *drop > 0) {
        if n == 0 {
            entries.clear();
        } else {
            entries.select_nth_unstable_by(drop, compare_entries);
            entries.drain(..drop);
        }
    }
    entries.sort_by(compare_entries);
}

/// Keeps the `n` smallest entries of `entries`, ascending.
fn keep_smallest(entries: &mut Vec<Entry<'_, '_>>, n: usize) {
    if entries.len() > n {
        if n == 0 {
            entries.clear();
        } else {
            entries.select_nth_unstable_by(n, compare_entries);
            entries.truncate(n);
        }
    }
    entries.sort_by(compare_entries);
}

/// Selections already computed within one pass, per `(name, requirement)` pair.
///
/// A manifest can repeat one dependency (target-specific sections, markers) against a lock
/// file holding thousands of entries for it; selecting once per distinct pair keeps a pass
/// linear in the lock entries instead of in occurrences times entries. Lookups borrow the name
/// and requirement, so a hit allocates nothing for the key.
#[derive(Debug, Default)]
pub struct LockSelectionMemo {
    by_name: HashMap<NormalizedName, RequirementMemo>,
}

/// One name's memoized outcomes: for a bare occurrence, and per declared requirement.
#[derive(Debug, Default)]
struct RequirementMemo {
    bare: Option<Outcome>,
    by_requirement: HashMap<crate::VersionReq, Outcome>,
}

impl RequirementMemo {
    fn get(&self, requirement: Option<&crate::VersionReq>) -> Option<&Outcome> {
        match requirement {
            Some(requirement) => self.by_requirement.get(requirement),
            None => self.bare.as_ref(),
        }
    }

    fn insert(&mut self, requirement: Option<&crate::VersionReq>, outcome: Outcome) {
        match requirement {
            Some(requirement) => {
                self.by_requirement.insert(requirement.clone(), outcome);
            }
            None => self.bare = Some(outcome),
        }
    }
}

/// A memoized selection result; `NoMatch` is a cached FR-003 miss.
#[derive(Debug, Clone)]
enum Outcome {
    Selected(Selection),
    NoMatch,
}

impl Outcome {
    fn of(selection: Option<Selection>) -> Self {
        selection.map_or(Self::NoMatch, Self::Selected)
    }

    fn selection(&self) -> Option<Selection> {
        match self {
            Self::Selected(selection) => Some(selection.clone()),
            Self::NoMatch => None,
        }
    }
}

/// A primary version and its lock alternatives.
#[derive(Debug, Clone)]
struct Selection {
    primary: ConcreteVersion,
    alternatives: Vec<ConcreteVersion>,
    alternative_coverage: AlternativeCoverage,
}

/// Whether a lock selection also lists the alternatives to the primary, which costs a sort of
/// the satisfying entries that a primary-only caller never needs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AlternativeScope {
    PrimaryOnly,
    WithAlternatives,
}

/// The occurrence's primary version and the lock entries that could equally be in use.
struct Picked<'a> {
    primary: &'a ConcreteVersion,
    /// `None` when the primary is the collapsed entry and no other candidate competes.
    candidates: Option<Candidates<'a>>,
}

/// The single selection policy behind hover, inlay hints and OSV targeting (#649, #1981).
///
/// With several lock candidates and a requirement, the primary is the highest candidate that
/// satisfies it, and none satisfying (FR-003) is `None` rather than an arbitrary entry. Without
/// a requirement, or with at most one candidate, the primary is the collapsed
/// `resolved_versions` entry; a bare name with several candidates keeps all of them as possible.
/// The candidate list's parse is cached on its `LockCandidates`, so repeated selections share it.
fn pick<'a>(
    dep: &dyn Dependency,
    key: &PackageKey,
    resolved_versions: &'a HashMap<NormalizedName, ConcreteVersion>,
    resolved_version_candidates: Option<&'a ResolvedCandidatesMap>,
    formatter: &dyn EcosystemFormatter,
) -> Option<Picked<'a>> {
    let collapsed = resolved_versions.get(key.normalized());
    let Some(lock) = resolved_version_candidates
        .and_then(|candidates| candidates.get(key.normalized()))
        .filter(|candidates| candidates.len() > 1)
    else {
        return Some(Picked {
            primary: collapsed?,
            candidates: None,
        });
    };
    let entries = lock.versions();
    let list = lock.cached_list(formatter);
    let (primary, possible) = match dep.version_requirement() {
        Some(req) => (
            None,
            satisfying_mask(entries, req, formatter, list.set.as_deref()),
        ),
        None => (collapsed, vec![true; entries.len()]),
    };
    let candidates = Candidates {
        entries,
        parsed: Arc::clone(&list.parsed),
        possible,
        preference: lock.preference(),
    };
    Some(Picked {
        primary: match primary {
            Some(primary) => primary,
            None => candidates.preferred(dep.version_requirement())?,
        },
        candidates: Some(candidates),
    })
}

/// The occurrence's primary version and its lock alternatives (the nearest, ascending, capped).
fn select_occurrence(
    dep: &dyn Dependency,
    key: &PackageKey,
    resolved_versions: &HashMap<NormalizedName, ConcreteVersion>,
    resolved_version_candidates: Option<&ResolvedCandidatesMap>,
    formatter: &dyn EcosystemFormatter,
    scope: AlternativeScope,
    memo: Option<&mut LockSelectionMemo>,
) -> Option<Selection> {
    let select = || {
        let Picked {
            primary,
            candidates,
        } = pick(
            dep,
            key,
            resolved_versions,
            resolved_version_candidates,
            formatter,
        )?;
        let (alternatives, alternative_coverage) = match (scope, candidates) {
            (AlternativeScope::WithAlternatives, Some(candidates)) => {
                candidates.nearest_others(primary)
            }
            (AlternativeScope::PrimaryOnly, _) | (AlternativeScope::WithAlternatives, None) => {
                (Vec::new(), AlternativeCoverage::Complete)
            }
        };
        Some(Selection {
            primary: primary.clone(),
            alternatives,
            alternative_coverage,
        })
    };
    let multiple_candidates = resolved_version_candidates
        .and_then(|candidates| candidates.get(key.normalized()))
        .is_some_and(|candidates| candidates.len() > 1);
    let Some(memo) =
        memo.filter(|_| multiple_candidates && scope == AlternativeScope::WithAlternatives)
    else {
        return select();
    };
    let requirement = dep.version_requirement();
    if let Some(outcome) = memo
        .by_name
        .get(key.normalized())
        .and_then(|memoized| memoized.get(requirement))
    {
        return outcome.selection();
    }
    let selection = select();
    memo.by_name
        .entry(key.normalized().clone())
        .or_default()
        .insert(requirement, Outcome::of(selection.clone()));
    selection
}

/// 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).
#[cfg(feature = "lsp-responses")]
pub(crate) fn resolve_occurrence_version<'a>(
    dep: &dyn Dependency,
    key: &PackageKey,
    resolved_versions: &'a HashMap<NormalizedName, ConcreteVersion>,
    resolved_version_candidates: Option<&'a ResolvedCandidatesMap>,
    formatter: &dyn EcosystemFormatter,
) -> Option<&'a ConcreteVersion> {
    pick(
        dep,
        key,
        resolved_versions,
        resolved_version_candidates,
        formatter,
    )
    .map(|picked| picked.primary)
}

/// 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::DependencyFormatter::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::{
///     DependencyFormatter, DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
///     RequirementResolution, SourcePolicy, resolve_in_use_version,
/// };
/// use deps_core::{ConcreteVersion, Dependency, EcosystemId, NormalizedName, PackageKey, PackageName, VersionReq};
/// use std::any::Any;
/// use std::collections::HashMap;
/// use deps_core::position::Range;
///
/// struct SimpleDep {
///     name: PackageName,
///     version_req: Option<VersionReq>,
/// }
///
/// # deps_core::impl_unprobed_dependency!(SimpleDep);
/// 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
///     }
/// }
///
/// 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 {}
/// impl DependencyFormatter for SimpleFormatter {
///     type Dep = SimpleDep;
/// }
///
/// let dep = SimpleDep {
///     name: PackageName::new("time"),
///     version_req: Some(VersionReq::new("=0.1.43")),
/// };
/// let resolved_versions: HashMap<NormalizedName, 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,
///         &PackageKey::new(dep.name(), &SimpleFormatter),
///         &resolved_versions,
///         None,
///         &SimpleFormatter,
///         EcosystemId::Cargo,
///     ),
///     Some(ConcreteVersion::new("0.1.43"))
/// );
/// ```
pub fn resolve_in_use_version<F: DependencyFormatter>(
    dep: &F::Dep,
    key: &PackageKey,
    resolved_versions: &HashMap<NormalizedName, ConcreteVersion>,
    resolved_version_candidates: Option<&ResolvedCandidatesMap>,
    formatter: &F,
    ecosystem: EcosystemId,
) -> Option<ConcreteVersion> {
    resolve_in_use_versions_scoped(
        dep,
        key,
        resolved_versions,
        resolved_version_candidates,
        formatter,
        ecosystem,
        AlternativeScope::PrimaryOnly,
        None,
    )
    .map(InUseVersions::into_primary)
}

/// Every version of one dependency occurrence that is in use: the primary, any sibling
/// release tags naming the same commit, and any other lock entries satisfying the requirement.
///
/// 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. Every value states
/// whether its sibling list is complete ([`Self::sibling_coverage`]): a primary read from
/// manifest text for a pin that a truncated tag list does not reach has unknown siblings.
/// Lock alternatives come only from the lock-file candidate branch, so the two lists are
/// disjoint by construction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InUseVersions {
    primary: ConcreteVersion,
    siblings: Vec<ConcreteVersion>,
    lock_alternatives: Vec<ConcreteVersion>,
    alternative_coverage: AlternativeCoverage,
    sibling_coverage: SiblingCoverage,
}

impl InUseVersions {
    /// A primary that is not derived from a tag index (lock file, concrete requirement), so
    /// there are no sibling tags to miss.
    fn untagged(primary: ConcreteVersion) -> Self {
        Self {
            primary,
            siblings: Vec::new(),
            lock_alternatives: Vec::new(),
            alternative_coverage: AlternativeCoverage::Complete,
            sibling_coverage: SiblingCoverage::Complete,
        }
    }

    /// A primary read from manifest text for a tag pin that a truncated tag list does not
    /// list, so its sibling tags are unknown.
    fn siblings_unknown(primary: ConcreteVersion) -> Self {
        Self {
            primary,
            siblings: Vec::new(),
            lock_alternatives: Vec::new(),
            alternative_coverage: AlternativeCoverage::Complete,
            sibling_coverage: SiblingCoverage::Truncated,
        }
    }

    /// A primary read from manifest text for a tag pin whose repository tag list has not been
    /// fetched yet (or failed to fetch), so its sibling tags are unknown.
    fn not_yet_indexed(primary: ConcreteVersion) -> Self {
        Self {
            primary,
            siblings: Vec::new(),
            lock_alternatives: Vec::new(),
            alternative_coverage: AlternativeCoverage::Complete,
            sibling_coverage: SiblingCoverage::NotYetIndexed,
        }
    }

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

    /// Like [`Self::for_test`], with an explicit sibling coverage.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub const fn for_test_with_coverage(
        primary: ConcreteVersion,
        siblings: Vec<ConcreteVersion>,
        sibling_coverage: SiblingCoverage,
    ) -> Self {
        Self {
            primary,
            siblings,
            lock_alternatives: Vec::new(),
            alternative_coverage: AlternativeCoverage::Complete,
            sibling_coverage,
        }
    }

    /// Like [`Self::for_test`], with lock alternatives.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub fn for_test_with_lock_alternatives(
        primary: ConcreteVersion,
        lock_alternatives: Vec<ConcreteVersion>,
    ) -> Self {
        Self::for_test_with_alternative_coverage(
            primary,
            lock_alternatives,
            AlternativeCoverage::Complete,
        )
    }

    /// Like [`Self::for_test_with_lock_alternatives`], with an explicit alternative coverage.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub fn for_test_with_alternative_coverage(
        primary: ConcreteVersion,
        lock_alternatives: Vec<ConcreteVersion>,
        alternative_coverage: AlternativeCoverage,
    ) -> Self {
        Self {
            lock_alternatives,
            alternative_coverage,
            ..Self::untagged(primary)
        }
    }

    /// Whether [`Self::siblings`] was read from a complete tag list.
    ///
    /// Anything but [`SiblingCoverage::Complete`] means a sibling tag naming the primary's
    /// commit may be missing, so a clean OSV answer for the primary and the listed siblings is
    /// not authoritative.
    #[must_use]
    pub const fn sibling_coverage(&self) -> SiblingCoverage {
        self.sibling_coverage
    }

    /// 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
    }

    /// Other lock-file entries that also satisfy the requirement, distinct and ascending: all of
    /// them, or the `MAX_LOCK_ALTERNATIVES` nearest the primary when
    /// [`Self::alternative_coverage`] is truncated.
    ///
    /// The lock file cannot say which of them the package manager installed for this
    /// dependency, so each is scanned for advisories alongside the primary (#1981).
    #[must_use]
    pub fn lock_alternatives(&self) -> &[ConcreteVersion] {
        &self.lock_alternatives
    }

    /// Whether [`Self::lock_alternatives`] lists every other satisfying lock entry.
    #[must_use]
    pub const fn alternative_coverage(&self) -> AlternativeCoverage {
        self.alternative_coverage
    }

    /// Discards the siblings and lock alternatives, 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. Lock alternatives only come from a name with several
/// satisfying lock-file candidates.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{
///     DependencyFormatter, DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
///     RequirementResolution, SourcePolicy, resolve_in_use_versions,
/// };
/// use deps_core::position::Range;
/// use deps_core::{ConcreteVersion, Dependency, EcosystemId, NormalizedName, PackageKey, PackageName, VersionReq};
/// use std::any::Any;
/// use std::collections::HashMap;
///
/// struct SimpleDep {
///     name: PackageName,
///     version_req: Option<VersionReq>,
/// }
///
/// # deps_core::impl_unprobed_dependency!(SimpleDep);
/// 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
///     }
/// }
///
/// 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 {}
/// impl DependencyFormatter for SimpleFormatter {
///     type Dep = SimpleDep;
/// }
///
/// let dep = SimpleDep {
///     name: PackageName::new("time"),
///     version_req: Some(VersionReq::new("=0.1.43")),
/// };
/// let versions = resolve_in_use_versions(
///     &dep,
///     &PackageKey::new(dep.name(), &SimpleFormatter),
///     &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<F: DependencyFormatter>(
    dep: &F::Dep,
    key: &PackageKey,
    resolved_versions: &HashMap<NormalizedName, ConcreteVersion>,
    resolved_version_candidates: Option<&ResolvedCandidatesMap>,
    formatter: &F,
    ecosystem: EcosystemId,
) -> Option<InUseVersions> {
    resolve_in_use_versions_scoped(
        dep,
        key,
        resolved_versions,
        resolved_version_candidates,
        formatter,
        ecosystem,
        AlternativeScope::WithAlternatives,
        None,
    )
}

/// [`resolve_in_use_versions`] reusing `memo` for repeated `(name, requirement)` lock selections.
///
/// Use one fresh [`LockSelectionMemo`] per pass over a manifest, against one fixed pair of
/// resolved-version maps: the memo is keyed by name and requirement only, so it must not
/// outlive a change to the maps. The result is identical to [`resolve_in_use_versions`].
pub fn resolve_in_use_versions_memoized<F: DependencyFormatter>(
    dep: &F::Dep,
    key: &PackageKey,
    resolved_versions: &HashMap<NormalizedName, ConcreteVersion>,
    resolved_version_candidates: Option<&ResolvedCandidatesMap>,
    formatter: &F,
    ecosystem: EcosystemId,
    memo: &mut LockSelectionMemo,
) -> Option<InUseVersions> {
    resolve_in_use_versions_scoped(
        dep,
        key,
        resolved_versions,
        resolved_version_candidates,
        formatter,
        ecosystem,
        AlternativeScope::WithAlternatives,
        Some(memo),
    )
}

#[expect(
    clippy::too_many_arguments,
    reason = "the three public entry points differ only in `scope` and `memo`"
)]
fn resolve_in_use_versions_scoped<F: DependencyFormatter>(
    dep: &F::Dep,
    key: &PackageKey,
    resolved_versions: &HashMap<NormalizedName, ConcreteVersion>,
    resolved_version_candidates: Option<&ResolvedCandidatesMap>,
    formatter: &F,
    ecosystem: EcosystemId,
    scope: AlternativeScope,
    memo: Option<&mut LockSelectionMemo>,
) -> 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::untagged(ConcreteVersion::from(v)));
    }

    if let Some(Selection {
        primary,
        alternatives,
        alternative_coverage,
    }) = select_occurrence(
        dep,
        key,
        resolved_versions,
        resolved_version_candidates,
        formatter,
        scope,
        memo,
    ) {
        return Some(InUseVersions {
            lock_alternatives: alternatives,
            alternative_coverage,
            ..InUseVersions::untagged(primary)
        });
    }

    // #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).
    match formatter.resolved_pin_version(dep) {
        PinResolution::Resolved {
            pin,
            sibling_coverage,
        } => {
            let primary = queryable_pin_version(&pin, ecosystem)?;
            let siblings = queryable_siblings(&pin, ecosystem);
            Some(InUseVersions {
                primary,
                siblings,
                lock_alternatives: Vec::new(),
                alternative_coverage: AlternativeCoverage::Complete,
                sibling_coverage: sibling_coverage.into(),
            })
        }
        PinResolution::Untagged
        | PinResolution::CommentContradicted
        | PinResolution::Unpublished => None,
        PinResolution::Unresolved => dep
            .version_requirement()
            .and_then(|req| concrete_pin_version(req.as_str(), ecosystem))
            .map(|v| InUseVersions::untagged(ConcreteVersion::from(v))),
        PinResolution::Unlisted => dep
            .version_requirement()
            .and_then(|req| concrete_pin_version(req.as_str(), ecosystem))
            .map(|v| InUseVersions::siblings_unknown(ConcreteVersion::from(v))),
        PinResolution::NotYetIndexed => dep
            .version_requirement()
            .and_then(|req| concrete_pin_version(req.as_str(), ecosystem))
            .map(|v| InUseVersions::not_yet_indexed(ConcreteVersion::from(v))),
    }
}

/// The siblings of `pin` that pass the same queryability gate as its primary.
pub(super) fn queryable_siblings(
    pin: &ResolvedPin,
    ecosystem: EcosystemId,
) -> Vec<ConcreteVersion> {
    pin.siblings()
        .iter()
        .filter_map(|tag| {
            queryable_pin_version(&ResolvedPin::most_specific(tag.clone()), ecosystem)
        })
        .collect()
}

/// 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 [`crate::lsp_helpers::DependencyFormatter::resolved_pin_version`]
/// returned [`PinResolution::Resolved`].
///
/// 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<F: DependencyFormatter>(
    dep: &F::Dep,
    formatter: &F,
    ecosystem: EcosystemId,
) -> bool {
    matches!(
        formatter.resolved_pin_version(dep),
        PinResolution::Resolved { pin, .. } if queryable_pin_version(&pin, ecosystem).is_none()
    )
}

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

    use super::*;
    use crate::PackageName;
    use crate::lsp_helpers::LockCandidates;
    use crate::pagination::ListCoverage;
    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 {}
    impl DependencyFormatter for CaretFormatter {
        type Dep = crate::lsp_helpers::test_support::MockDep;
    }

    /// [`SemverGrammar`](crate::lsp_helpers::SemverGrammar) that counts the candidates it parses.
    #[derive(Clone, Default)]
    struct CountingSemver {
        parses: Arc<std::sync::atomic::AtomicUsize>,
    }

    impl crate::lsp_helpers::VersionGrammar for CountingSemver {
        type Version = semver::Version;
        type Compiled = semver::VersionReq;

        fn parse_version(&self, version: &ConcreteVersion) -> Option<semver::Version> {
            self.parses
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            crate::lsp_helpers::SemverGrammar.parse_version(version)
        }

        fn compile(&self, requirement: BoundedVersionReq<'_>) -> Option<semver::VersionReq> {
            crate::lsp_helpers::SemverGrammar.compile(requirement)
        }

        fn satisfies(&self, compiled: &semver::VersionReq, version: &semver::Version) -> bool {
            crate::lsp_helpers::SemverGrammar.satisfies(compiled, version)
        }

        fn strict_prerelease_exclusion(&self, compiled: &semver::VersionReq) -> bool {
            crate::lsp_helpers::SemverGrammar.strict_prerelease_exclusion(compiled)
        }
    }

    /// [`CaretFormatter`] with a candidate set built from [`CountingSemver`].
    struct CountingSetFormatter(CountingSemver);

    impl crate::lsp_helpers::PackageNaming for CountingSetFormatter {}
    impl crate::lsp_helpers::PackageRendering for CountingSetFormatter {
        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 CountingSetFormatter {
        fn compile_bounded_requirement(
            &self,
            requirement: BoundedVersionReq<'_>,
        ) -> Option<Box<dyn crate::lsp_helpers::RequirementMatcher>> {
            crate::lsp_helpers::grammar_matcher(self.0.clone(), requirement)
        }

        fn candidate_set(&self, candidates: &[ConcreteVersion]) -> Option<Box<dyn CandidateSet>> {
            Some(crate::lsp_helpers::grammar_candidates(
                self.0.clone(),
                candidates,
            ))
        }
    }
    impl crate::lsp_helpers::DiagnosticMessages for CountingSetFormatter {}
    impl crate::lsp_helpers::DiagnosticPolicy for CountingSetFormatter {}
    impl crate::lsp_helpers::SourcePolicy for CountingSetFormatter {}
    impl crate::lsp_helpers::OsvNaming for CountingSetFormatter {}
    impl DependencyFormatter for CountingSetFormatter {
        type Dep = crate::lsp_helpers::test_support::MockDep;
    }

    /// 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(PinResolution);

    impl FixedResolvedPinFormatter {
        fn most_specific(tag: &str) -> Self {
            Self(PinResolution::Resolved {
                pin: ResolvedPin::most_specific(ConcreteVersion::new(tag)),
                sibling_coverage: ListCoverage::Complete,
            })
        }

        fn alias(tag: &str) -> Self {
            Self(PinResolution::Resolved {
                pin: ResolvedPin::alias(ConcreteVersion::new(tag)),
                sibling_coverage: ListCoverage::Complete,
            })
        }

        fn with_resolution(resolution: PinResolution) -> Self {
            Self(resolution)
        }

        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.pin_resolution(&sha, None))
        }
    }

    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 {}
    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 {}
    impl DependencyFormatter for FixedResolvedPinFormatter {
        type Dep = crate::lsp_helpers::test_support::MockDep;

        fn resolved_pin_version(
            &self,
            _dep: &crate::lsp_helpers::test_support::MockDep,
        ) -> PinResolution {
            self.0.clone()
        }
    }

    /// #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,
                &crate::test_util::package_key("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,
                &crate::test_util::package_key("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(
            NormalizedName::for_test("actions/checkout"),
            ConcreteVersion::from("v9.9.9"),
        );

        let result = resolve_in_use_version(
            &dep,
            &crate::test_util::package_key("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,
            &crate::test_util::package_key("actions/checkout"),
            &HashMap::new(),
            None,
            &FixedResolvedPinFormatter::most_specific("v1.3.0"),
            EcosystemId::GithubActions,
        );
        assert_eq!(result, Some(ConcreteVersion::from("v1.3.0")));
    }

    /// #1735: the commit's trailing comment (`version_req`) must not stand in for the version
    /// when the index proves the commit is untagged, nor when the resolved tag is an
    /// unqueryable alias; it still does when the index has no evidence either way.
    #[test]
    fn resolve_in_use_version_comment_text_only_stands_in_when_unresolved() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("actions/checkout"),
            version_req: VersionReq::new("v4.2.0"),
            version_range: Range::default(),
            name_range: Range::default(),
        };
        let resolve = |formatter: &FixedResolvedPinFormatter| {
            resolve_in_use_version(
                &dep,
                &crate::test_util::package_key("actions/checkout"),
                &HashMap::new(),
                None,
                formatter,
                EcosystemId::GithubActions,
            )
        };

        assert_eq!(
            resolve(&FixedResolvedPinFormatter::with_resolution(
                PinResolution::Untagged
            )),
            None
        );
        assert_eq!(
            resolve(&FixedResolvedPinFormatter::with_resolution(
                PinResolution::CommentContradicted
            )),
            None
        );
        assert_eq!(resolve(&FixedResolvedPinFormatter::alias("v1")), None);
        assert!(!has_unqueryable_resolved_pin(
            &dep,
            &FixedResolvedPinFormatter::with_resolution(PinResolution::Untagged),
            EcosystemId::GithubActions
        ));
        assert_eq!(
            resolve(&FixedResolvedPinFormatter::with_resolution(
                PinResolution::Unresolved
            )),
            Some(ConcreteVersion::from("v4.2.0"))
        );
    }

    /// #1769: the sibling coverage follows where the primary came from.
    #[test]
    fn resolve_in_use_versions_states_sibling_coverage_per_source() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("actions/checkout"),
            version_req: VersionReq::new("v4.2.0"),
            version_range: Range::default(),
            name_range: Range::default(),
        };
        let coverage = |formatter: &FixedResolvedPinFormatter| {
            resolve_in_use_versions(
                &dep,
                &crate::test_util::package_key("actions/checkout"),
                &HashMap::new(),
                None,
                formatter,
                EcosystemId::GithubActions,
            )
            .map(|versions| versions.sibling_coverage())
        };
        let resolved = |sibling_coverage| {
            FixedResolvedPinFormatter::with_resolution(PinResolution::Resolved {
                pin: ResolvedPin::most_specific(ConcreteVersion::new("v4.2.0")),
                sibling_coverage,
            })
        };

        assert_eq!(
            coverage(&resolved(ListCoverage::Truncated)),
            Some(SiblingCoverage::Truncated)
        );
        assert_eq!(
            coverage(&resolved(ListCoverage::Complete)),
            Some(SiblingCoverage::Complete)
        );
        assert_eq!(
            coverage(&FixedResolvedPinFormatter::with_resolution(
                PinResolution::Unresolved
            )),
            Some(SiblingCoverage::Complete)
        );
        assert_eq!(
            coverage(&FixedResolvedPinFormatter::with_resolution(
                PinResolution::Unlisted
            )),
            Some(SiblingCoverage::Truncated),
            "manifest text stands in for an unlisted pin, with its siblings unknown"
        );
        assert_eq!(
            coverage(&FixedResolvedPinFormatter::with_resolution(
                PinResolution::NotYetIndexed
            )),
            Some(SiblingCoverage::NotYetIndexed),
            "manifest text stands in for a cold-cache pin, with its siblings unknown"
        );
    }

    #[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(
            NormalizedName::for_test("serde"),
            ConcreteVersion::from("1.0.219"),
        );
        let mut candidates = HashMap::new();
        candidates.insert(
            NormalizedName::for_test("serde"),
            LockCandidates::from(vec![
                ConcreteVersion::from("0.9.15"),
                ConcreteVersion::from("1.0.219"),
            ]),
        );

        let renamed_result = resolve_in_use_version(
            &renamed_old_major,
            &crate::test_util::package_key("serde"),
            &resolved_versions,
            Some(&candidates),
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Cargo,
        );
        let plain_result = resolve_in_use_version(
            &plain_current_major,
            &crate::test_util::package_key("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(
            NormalizedName::for_test("serde"),
            LockCandidates::from(vec![
                ConcreteVersion::from("1.0.219"),
                ConcreteVersion::from("1.1.0"),
            ]),
        );

        let result = resolve_in_use_version(
            &dep,
            &crate::test_util::package_key("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(
            NormalizedName::for_test("serde"),
            ConcreteVersion::from("1.0.219"),
        );
        let mut candidates = HashMap::new();
        candidates.insert(
            NormalizedName::for_test("serde"),
            LockCandidates::from(vec![
                ConcreteVersion::from("0.9.15"),
                ConcreteVersion::from("1.0.219"),
            ]),
        );

        let result = resolve_in_use_version(
            &dep,
            &crate::test_util::package_key("serde"),
            &resolved_versions,
            Some(&candidates),
            &crate::lsp_helpers::test_support::MOCK_FORMATTER.for_dependency(),
            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(
            NormalizedName::for_test("serde"),
            ConcreteVersion::from("1.0.219"),
        );
        let mut candidates = HashMap::new();
        candidates.insert(
            NormalizedName::for_test("serde"),
            LockCandidates::from(vec![ConcreteVersion::from("1.0.219")]),
        );

        let with_candidates = resolve_in_use_version(
            &dep,
            &crate::test_util::package_key("serde"),
            &resolved_versions,
            Some(&candidates),
            &crate::lsp_helpers::test_support::MOCK_FORMATTER,
            EcosystemId::Cargo,
        );
        let without_candidates = resolve_in_use_version(
            &dep,
            &crate::test_util::package_key("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 picks the highest-semver *among the satisfying subset* — `2.0.0` 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: the highest satisfying entry is the primary, and the other
    /// satisfying entry is the lock alternative (#1981); `2.0.0` is neither.
    #[test]
    fn in_use_version_picks_highest_satisfying_and_reports_the_rest_as_alternatives() {
        let versions = resolve_caret_pkg("^1.0", &["1.0.5", "2.0.0", "1.0.1"]).unwrap();

        assert_eq!(versions.primary(), &ConcreteVersion::from("1.0.5"));
        assert_eq!(
            versions.lock_alternatives(),
            &[ConcreteVersion::from("1.0.1")]
        );
        assert!(versions.siblings().is_empty());
    }

    #[test]
    fn lock_alternatives_are_distinct_and_lowest_first() {
        let versions =
            resolve_caret_pkg("^1.0", &["1.0.9", "1.0.3", "1.0.3", "1.0.5", "1.0.9"]).unwrap();

        assert_eq!(versions.primary(), &ConcreteVersion::from("1.0.9"));
        assert_eq!(
            versions.lock_alternatives(),
            &[
                ConcreteVersion::from("1.0.3"),
                ConcreteVersion::from("1.0.5")
            ]
        );
    }

    #[test]
    fn lock_alternatives_empty_for_a_single_satisfying_candidate() {
        let versions = resolve_caret_pkg("^1.0", &["1.0.5", "2.0.0"]).unwrap();

        assert_eq!(versions.primary(), &ConcreteVersion::from("1.0.5"));
        assert!(versions.lock_alternatives().is_empty());
    }

    #[test]
    fn lock_alternatives_empty_for_a_single_candidate() {
        let versions = resolve_caret_pkg("^1.0", &["1.0.5"]).unwrap();

        assert!(versions.lock_alternatives().is_empty());
    }

    /// A bare name has no requirement to narrow the lock entries, so every other entry is an
    /// alternative and the primary stays the highest.
    #[test]
    fn lock_alternatives_include_every_other_entry_for_a_bare_name() {
        use crate::lsp_helpers::test_support::MockMarkedDep;

        let dep = MockMarkedDep {
            name: PackageName::new("pkg"),
            name_range: Range::default(),
            markers: None,
        };
        let candidates = HashMap::from([(
            NormalizedName::for_test("pkg"),
            ["2.1.0", "1.26.4", "1.0.0"]
                .map(ConcreteVersion::from)
                .to_vec()
                .into(),
        )]);
        let collapsed = HashMap::from([(
            NormalizedName::for_test("pkg"),
            ConcreteVersion::from("2.1.0"),
        )]);

        let versions = resolve_in_use_versions(
            &dep,
            &crate::test_util::package_key("pkg"),
            &collapsed,
            Some(&candidates),
            &crate::lsp_helpers::test_support::MOCK_FORMATTER.for_dependency(),
            EcosystemId::Cargo,
        )
        .unwrap();

        assert_eq!(versions.primary(), &ConcreteVersion::from("2.1.0"));
        assert_eq!(
            versions.lock_alternatives(),
            [
                ConcreteVersion::from("1.0.0"),
                ConcreteVersion::from("1.26.4")
            ]
        );
    }

    /// #1995: a pass of many distinct requirements over one lock list parses each candidate once
    /// through the formatter's candidate set, and selects exactly what the per-requirement
    /// matcher selects.
    #[test]
    fn memo_parses_each_candidate_once_through_the_candidate_set() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        const ENTRIES: usize = 500;
        const REQUIREMENTS: usize = 40;
        let name = NormalizedName::for_test("pkg");
        let candidates = HashMap::from([(
            name.clone(),
            (0..ENTRIES)
                .map(|n| ConcreteVersion::from(format!("1.0.{n}")))
                .collect::<Vec<_>>()
                .into(),
        )]);
        let resolved =
            HashMap::from([(name, ConcreteVersion::from(format!("1.0.{}", ENTRIES - 1)))]);
        let counting = CountingSetFormatter(CountingSemver::default());
        let mut memo = LockSelectionMemo::default();
        let key = crate::test_util::package_key("pkg");

        for n in 0..REQUIREMENTS {
            let dep = MockDep {
                name: PackageName::new("pkg"),
                version_req: VersionReq::new(format!(">=1.0.{n}")),
                version_range: Range::default(),
                name_range: Range::default(),
            };
            let with_set = resolve_in_use_versions_memoized(
                &dep,
                &key,
                &resolved,
                Some(&candidates),
                &counting,
                EcosystemId::Cargo,
                &mut memo,
            );
            let per_requirement = resolve_in_use_versions(
                &dep,
                &key,
                &resolved,
                Some(&candidates),
                &CaretFormatter,
                EcosystemId::Cargo,
            );
            assert_eq!(
                with_set.as_ref().map(InUseVersions::primary),
                per_requirement.as_ref().map(InUseVersions::primary)
            );
            assert_eq!(
                with_set.as_ref().map(InUseVersions::lock_alternatives),
                per_requirement
                    .as_ref()
                    .map(InUseVersions::lock_alternatives)
            );
        }

        assert_eq!(
            counting.0.parses.load(std::sync::atomic::Ordering::SeqCst),
            ENTRIES
        );
    }

    fn counted_candidates(name: &NormalizedName, entries: usize) -> ResolvedCandidatesMap {
        HashMap::from([(
            name.clone(),
            (0..entries)
                .map(|n| ConcreteVersion::from(format!("1.0.{n}")))
                .collect::<Vec<_>>()
                .into(),
        )])
    }

    /// #2011: the list's parse lives on its `LockCandidates`, so selections without any memo
    /// still parse each candidate once.
    #[test]
    fn selections_without_a_memo_share_the_lock_candidates_parse() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        const ENTRIES: usize = 100;
        let name = NormalizedName::for_test("pkg");
        let candidates = counted_candidates(&name, ENTRIES);
        let resolved = HashMap::from([(name, ConcreteVersion::from("1.0.99"))]);
        let counting = CountingSetFormatter(CountingSemver::default());
        let key = crate::test_util::package_key("pkg");

        for n in 0..3 {
            let dep = MockDep {
                name: PackageName::new("pkg"),
                version_req: VersionReq::new(format!(">=1.0.{n}")),
                version_range: Range::default(),
                name_range: Range::default(),
            };
            let picked = pick(&dep, &key, &resolved, Some(&candidates), &counting);
            assert!(picked.is_some());
        }

        assert_eq!(
            counting.0.parses.load(std::sync::atomic::Ordering::SeqCst),
            ENTRIES
        );
    }

    /// #2011: the cache keeps the first formatter's parse; a later formatter never builds its own.
    #[test]
    fn lock_candidates_cache_keeps_the_first_formatters_parse() {
        let candidates = LockCandidates::from(vec![
            ConcreteVersion::from("1.0.0"),
            ConcreteVersion::from("1.0.1"),
        ]);
        let first = CountingSetFormatter(CountingSemver::default());
        let second = CountingSetFormatter(CountingSemver::default());

        candidates.cached_list(&first);
        candidates.cached_list(&second);

        assert_eq!(first.0.parses.load(std::sync::atomic::Ordering::SeqCst), 2);
        assert_eq!(second.0.parses.load(std::sync::atomic::Ordering::SeqCst), 0);
    }

    /// #2011: neither `Debug` nor equality depends on whether a selection filled the cache.
    #[test]
    fn lock_candidates_debug_and_eq_ignore_the_cache() {
        let cold = LockCandidates::from(vec![ConcreteVersion::from("1.0.0")]);
        let warm = cold.clone();
        warm.cached_list(&CaretFormatter);

        assert_eq!(format!("{cold:?}"), format!("{warm:?}"));
        assert_eq!(cold, warm);
    }

    /// #2012: a requirement nothing satisfies is memoized as a miss and stays one.
    #[test]
    fn memo_remembers_a_requirement_nothing_satisfies() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let name = NormalizedName::for_test("pkg");
        let candidates = counted_candidates(&name, 5);
        let resolved = HashMap::from([(name.clone(), ConcreteVersion::from("1.0.4"))]);
        let dep = MockDep {
            name: PackageName::new("pkg"),
            version_req: VersionReq::new(">=9.0.0"),
            version_range: Range::default(),
            name_range: Range::default(),
        };
        let mut memo = LockSelectionMemo::default();

        for _ in 0..2 {
            assert!(
                resolve_in_use_versions_memoized(
                    &dep,
                    &crate::test_util::package_key("pkg"),
                    &resolved,
                    Some(&candidates),
                    &CaretFormatter,
                    EcosystemId::Cargo,
                    &mut memo,
                )
                .is_none()
            );
        }

        assert_matches!(
            memo.by_name[&name].by_requirement[&VersionReq::new(">=9.0.0")],
            Outcome::NoMatch
        );
    }

    /// #1981 (security re-verification): a pass of many distinct requirements over one big
    /// candidate list must parse that list once, and each memoized selection must keep only
    /// its capped alternatives, not an allocation sized by the whole list.
    #[test]
    fn memo_parses_each_list_once_and_retains_only_capped_alternatives() {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        const ENTRIES: usize = 2000;
        const REQUIREMENTS: usize = 50;
        let name = NormalizedName::for_test("pkg");
        let candidates = HashMap::from([(
            name.clone(),
            (0..ENTRIES)
                .map(|n| ConcreteVersion::from(format!("1.0.{n}")))
                .collect::<Vec<_>>()
                .into(),
        )]);
        let resolved =
            HashMap::from([(name, ConcreteVersion::from(format!("1.0.{}", ENTRIES - 1)))]);
        let mut memo = LockSelectionMemo::default();

        for n in 0..REQUIREMENTS {
            let dep = MockDep {
                name: PackageName::new("pkg"),
                version_req: VersionReq::new(format!(">=1.0.{n}")),
                version_range: Range::default(),
                name_range: Range::default(),
            };
            let in_use = resolve_in_use_versions_memoized(
                &dep,
                &crate::test_util::package_key("pkg"),
                &resolved,
                Some(&candidates),
                &CaretFormatter,
                EcosystemId::Cargo,
                &mut memo,
            )
            .unwrap();
            assert_eq!(in_use.lock_alternatives().len(), MAX_LOCK_ALTERNATIVES);
            assert_eq!(
                in_use.alternative_coverage(),
                AlternativeCoverage::Truncated
            );
            assert_eq!(
                in_use
                    .lock_alternatives()
                    .first()
                    .map(ConcreteVersion::as_str),
                Some(format!("1.0.{}", ENTRIES - 1 - MAX_LOCK_ALTERNATIVES).as_str())
            );
        }

        assert_eq!(memo.by_name.len(), 1, "one memo per name");
        let memoized = &memo.by_name[&NormalizedName::for_test("pkg")];
        assert_eq!(memoized.by_requirement.len(), REQUIREMENTS);
        for outcome in memoized.by_requirement.values() {
            let Outcome::Selected(selection) = outcome else {
                panic!("every requirement selects a primary");
            };
            assert!(selection.alternatives.capacity() <= MAX_LOCK_ALTERNATIVES + 1);
        }
    }

    fn alternatives_around(primary: &str, locked: &[&str]) -> (Vec<String>, AlternativeCoverage) {
        let candidates: Vec<ConcreteVersion> =
            locked.iter().map(|v| ConcreteVersion::from(*v)).collect();
        let parsed = parse_all(&candidates);
        let candidates = Candidates {
            entries: &candidates,
            parsed,
            possible: vec![true; locked.len()],
            preference: &OwnerPreference::Unscoped,
        };
        let (alternatives, coverage) = candidates.nearest_others(&ConcreteVersion::from(primary));
        (
            alternatives.iter().map(|v| v.as_str().to_owned()).collect(),
            coverage,
        )
    }

    /// #1997: past the cap the entries nearest the primary stay, ascending, with ties going to
    /// the higher side; at or under the cap everything stays and the list is complete.
    #[test]
    fn nearest_others_keeps_the_cap_nearest_ascending_and_reports_truncation() {
        let locked: Vec<String> = (0..40).map(|n| format!("1.0.{n}")).collect();
        let locked: Vec<&str> = locked.iter().map(String::as_str).collect();

        let (middle, coverage) = alternatives_around("1.0.20", &locked);
        let expected: Vec<String> = (12..=28)
            .filter(|n| *n != 20)
            .map(|n| format!("1.0.{n}"))
            .collect();
        assert_eq!(coverage, AlternativeCoverage::Truncated);
        assert_eq!(middle.len(), MAX_LOCK_ALTERNATIVES);
        assert_eq!(middle, expected[..MAX_LOCK_ALTERNATIVES]);

        let (top, _) = alternatives_around("1.0.39", &locked);
        let expected: Vec<String> = (23..39).map(|n| format!("1.0.{n}")).collect();
        assert_eq!(top, expected);

        let (bottom, _) = alternatives_around("1.0.0", &locked);
        let expected: Vec<String> = (1..=16).map(|n| format!("1.0.{n}")).collect();
        assert_eq!(bottom, expected);

        let (all, coverage) = alternatives_around("1.0.5", &locked[..=MAX_LOCK_ALTERNATIVES]);
        assert_eq!(all.len(), MAX_LOCK_ALTERNATIVES);
        assert_eq!(coverage, AlternativeCoverage::Complete);
    }

    fn best_candidate_for_requirement<'a>(
        candidates: &'a [ConcreteVersion],
        requirement: &crate::VersionReq,
        formatter: &dyn EcosystemFormatter,
    ) -> Option<&'a ConcreteVersion> {
        let mask = satisfying_mask(candidates, requirement, formatter, None);
        Candidates {
            entries: candidates,
            parsed: parse_all(candidates),
            possible: mask,
            preference: &OwnerPreference::Unscoped,
        }
        .highest()
    }

    fn resolve_caret_pkg(requirement: &str, locked: &[&str]) -> Option<InUseVersions> {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("pkg"),
            version_req: VersionReq::new(requirement),
            version_range: Range::default(),
            name_range: Range::default(),
        };
        let mut candidates = HashMap::new();
        candidates.insert(
            NormalizedName::for_test("pkg"),
            locked
                .iter()
                .map(|v| ConcreteVersion::from(*v))
                .collect::<Vec<_>>()
                .into(),
        );

        let collapsed: HashMap<NormalizedName, ConcreteVersion> = locked
            .last()
            .map(|v| (NormalizedName::for_test("pkg"), ConcreteVersion::from(*v)))
            .into_iter()
            .collect();

        resolve_in_use_versions(
            &dep,
            &crate::test_util::package_key("pkg"),
            &collapsed,
            Some(&candidates),
            &CaretFormatter,
            EcosystemId::Cargo,
        )
    }

    /// Resolves a `pkg` dependency declaring `requirement` against `packages` split for `scope`,
    /// through the same path the LSP and CLI take.
    fn resolve_owned_pkg(
        packages: &crate::lockfile::ResolvedPackages,
        scope: &crate::lockfile::ImporterPath,
        requirement: &str,
    ) -> InUseVersions {
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::MockDep;

        let dep = MockDep {
            name: PackageName::new("pkg"),
            version_req: VersionReq::new(requirement),
            version_range: Range::default(),
            name_range: Range::default(),
        };
        let (collapsed, candidates) = packages.split_normalized_for(&CaretFormatter, scope);
        resolve_in_use_versions(
            &dep,
            &crate::test_util::package_key("pkg"),
            &collapsed,
            Some(&candidates),
            &CaretFormatter,
            EcosystemId::Cargo,
        )
        .unwrap()
    }

    fn pkg_entry(
        version: &str,
        owner: crate::lockfile::EntryOwner,
    ) -> crate::lockfile::ResolvedPackage {
        crate::lockfile::ResolvedPackage::new(
            "pkg".into(),
            version.into(),
            crate::lockfile::ResolvedSource::Registry {
                url: String::new(),
                checksum: String::new(),
            },
        )
        .with_placement(crate::lockfile::EntryPlacement::Hoisted { owner })
    }

    /// #1993: two members declare overlapping ranges that the lock resolved differently; each
    /// is handed its own importer's entry, not the highest satisfying one.
    #[test]
    fn owner_aware_selection_picks_the_requesting_members_entry() {
        use crate::lockfile::{EntryOwner, ImporterPath, ResolvedPackages};

        let importer = |path: &str| EntryOwner::Importer(ImporterPath::parse(path).unwrap());
        let mut packages = ResolvedPackages::new();
        packages.insert(pkg_entry("1.0.5", importer("packages/a")));
        packages.insert(pkg_entry("1.2.0", importer("packages/b")));

        let a = resolve_owned_pkg(
            &packages,
            &ImporterPath::parse("packages/a").unwrap(),
            "^1.0",
        );
        assert_eq!(a.primary(), "1.0.5");
        assert_eq!(
            a.lock_alternatives(),
            ["1.2.0"],
            "the other entry stays an alternative"
        );

        let b = resolve_owned_pkg(
            &packages,
            &ImporterPath::parse("packages/b").unwrap(),
            "^1.0",
        );
        assert_eq!(b.primary(), "1.2.0");
    }

    /// When the member's own entry does not satisfy its requirement, selection falls back to
    /// the highest satisfying entry overall rather than to nothing.
    #[test]
    fn owner_aware_selection_falls_back_when_the_own_entry_does_not_satisfy() {
        use crate::lockfile::{EntryOwner, ImporterPath, ResolvedPackages};

        let importer = |path: &str| EntryOwner::Importer(ImporterPath::parse(path).unwrap());
        let mut packages = ResolvedPackages::new();
        packages.insert(pkg_entry("1.0.5", importer("packages/a")));
        packages.insert(pkg_entry("2.1.0", importer("packages/b")));

        let a = resolve_owned_pkg(
            &packages,
            &ImporterPath::parse("packages/a").unwrap(),
            "^2.0",
        );
        assert_eq!(a.primary(), "2.1.0");
    }

    /// #1993 (yarn): the entry whose recorded descriptor is the requirement's own text wins over
    /// a higher entry that merely satisfies it.
    #[test]
    fn descriptor_selection_picks_the_entry_recording_the_requirement() {
        use crate::lockfile::{EntryOwner, ImporterPath, ResolvedPackages};

        let descriptors = |texts: &[&str]| {
            EntryOwner::Descriptors(texts.iter().map(|t| crate::VersionReq::new(*t)).collect())
        };
        let mut packages = ResolvedPackages::new();
        packages.insert(pkg_entry("1.0.5", descriptors(&["^1.0.0"])));
        packages.insert(pkg_entry("1.2.0", descriptors(&["^1.2.0", "^1.1.0"])));
        let scope = ImporterPath::root();

        assert_eq!(
            resolve_owned_pkg(&packages, &scope, "^1.0.0").primary(),
            "1.0.5"
        );
        assert_eq!(
            resolve_owned_pkg(&packages, &scope, "^1.1.0").primary(),
            "1.2.0"
        );
        assert_eq!(
            resolve_owned_pkg(&packages, &scope, "^1.0").primary(),
            "1.2.0",
            "no descriptor matches the text: highest satisfying"
        );
    }

    // --- 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,
            &crate::test_util::package_key("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,
            &crate::test_util::package_key("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,
            &crate::test_util::package_key("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,
            &crate::test_util::package_key("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,
            &crate::test_util::package_key("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(),
            &crate::test_util::package_key("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"]);
        assert!(versions.lock_alternatives().is_empty());
    }

    /// #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(),
            &crate::test_util::package_key("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([(
            NormalizedName::for_test("actions/checkout"),
            ConcreteVersion::new("4.7.0"),
        )]);
        let versions = resolve_in_use_versions(
            &sha_pinned_dep(),
            &crate::test_util::package_key("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(),
                &crate::test_util::package_key("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"
                    );
                }
            }
        }
    }
}