deps-core 0.11.0

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

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

use super::{EcosystemFormatter, RequirementMatcher, RequirementStatus, VersionData};

/// Stable [`Diagnostic::code`] set on the unsatisfiable-requirement diagnostic.
///
/// Set by `generate_diagnostics_from_cache`, so `build_unsatisfiable_fix_action`'s
/// stashed `CodeAction::data` can name it and the `deps-lsp` handler's diagnostic-binding
/// step can match on it — the same mechanism `build_vulnerability_fix_action` uses with an
/// advisory id, generalized to a constant since this diagnostic has no per-instance
/// identifier.
pub const UNSATISFIABLE_DIAGNOSTIC_CODE: &str = "unsatisfiable-requirement";

/// Diagnostic severity levels for the four per-dependency issue categories.
///
/// Threaded from `DiagnosticsConfig` (`deps-lsp`) through
/// [`crate::Ecosystem::generate_diagnostics`] into [`generate_diagnostics_from_cache`]
/// and [`generate_diagnostics`].
///
/// # Examples
///
/// ```
/// use deps_core::DiagnosticSeverities;
/// use tower_lsp_server::ls_types::DiagnosticSeverity;
///
/// let severities = DiagnosticSeverities::default();
/// assert_eq!(severities.outdated, DiagnosticSeverity::HINT);
/// assert_eq!(severities.unknown, DiagnosticSeverity::WARNING);
/// assert_eq!(severities.yanked, DiagnosticSeverity::WARNING);
/// assert_eq!(severities.unsatisfiable, DiagnosticSeverity::WARNING);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DiagnosticSeverities {
    /// Severity for a dependency with a newer version available.
    pub outdated: DiagnosticSeverity,
    /// Severity for a dependency not found in the registry (or with an invalid name).
    pub unknown: DiagnosticSeverity,
    /// Severity for a dependency pinned to a yanked/deprecated version.
    pub yanked: DiagnosticSeverity,
    /// Severity for a dependency whose requirement matches zero published versions.
    pub unsatisfiable: DiagnosticSeverity,
}

impl Default for DiagnosticSeverities {
    fn default() -> Self {
        Self {
            outdated: DiagnosticSeverity::HINT,
            unknown: DiagnosticSeverity::WARNING,
            yanked: DiagnosticSeverity::WARNING,
            unsatisfiable: DiagnosticSeverity::WARNING,
        }
    }
}

/// Shared shape for a [`EcosystemFormatter::compile_requirement`] guarded by one predicate.
///
/// This is the pattern several ecosystems' guards independently re-implemented
/// (`deps-go`'s pseudo-version check, `deps-composer`'s dev-branch/`@dev` check,
/// `deps-bundler`'s exact-pin check, `deps-maven`/`deps-gradle`'s malformed-range check,
/// `deps-nuget`'s malformed-requirement check). See
/// [`EcosystemFormatter::compile_requirement`]'s docs for why `None` is correct in exactly
/// this case: `is_undecidable(requirement)` true means the fetched `available` list
/// structurally cannot contain a version that would decide the match either way, so scanning
/// it would always report `Some(false)` and produce a false "no published version satisfies
/// this requirement" diagnostic.
///
/// Returns `None` when `is_undecidable(requirement)` is `true`. Otherwise builds `matcher`
/// from `requirement`'s owned `String` and boxes it as the trait object
/// [`EcosystemFormatter::compile_requirement`] returns.
///
/// Ecosystems whose guard is a fallible parse rather than a named predicate over the
/// requirement string (`deps-cargo`, `deps-npm`, `deps-pypi`, `deps-swift`) don't fit this
/// shape and implement `compile_requirement` directly via `.ok().map(...)` instead.
/// `deps-dart` implements `compile_requirement` but has no guard at all — every requirement
/// string is a valid Dart constraint by construction, so it is always `Some`.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{compile_requirement_unless, RequirementMatcher};
///
/// struct ExactMatcher(String);
/// impl RequirementMatcher for ExactMatcher {
///     fn matches(&self, version: &str) -> Option<bool> {
///         Some(version == self.0)
///     }
/// }
///
/// let is_pseudo_version = |r: &str| r.starts_with("v0.0.0-");
///
/// assert!(
///     compile_requirement_unless(
///         "v0.0.0-20191109021931-daa7c04131f5",
///         is_pseudo_version,
///         ExactMatcher,
///     )
///     .is_none()
/// );
/// assert!(compile_requirement_unless("v1.2.3", is_pseudo_version, ExactMatcher).is_some());
/// ```
pub fn compile_requirement_unless<M>(
    requirement: &str,
    is_undecidable: impl FnOnce(&str) -> bool,
    matcher: impl FnOnce(String) -> M,
) -> Option<Box<dyn RequirementMatcher>>
where
    M: RequirementMatcher + 'static,
{
    if is_undecidable(requirement) {
        return None;
    }
    Some(Box::new(matcher(requirement.to_string())))
}

/// Requirement strings longer than this are rejected by [`requirement_is_unsatisfiable`]
/// before compilation, rather than compiled and scanned. No real manifest requirement in any
/// supported ecosystem approaches this length; it exists solely to bound the cost of an
/// adversarial or corrupted requirement string. All eleven ecosystems' `compile_requirement`
/// implementations now parse `requirement` exactly once per dependency and reuse the parsed
/// form across every candidate in `matches` — Maven/Gradle/NuGet's `RequirementMatcher`s were
/// the last holdouts re-parsing per candidate, fixed alongside this comment — so the scan
/// itself is O(`available.len()`) in the size of the candidate list, not the requirement.
/// This cap stays as defense-in-depth against the one-time parse cost: Maven's range union
/// can still degrade non-linearly on a pathological multi-KB comma union, and a stray
/// oversized string is never a real requirement, only a corrupted or adversarial one.
const MAX_REQUIREMENT_LEN: usize = 256;

/// Returns `true` when no published version satisfies `requirement`.
///
/// `available` must be non-empty, `requirement` must be a concrete (non-empty, resolved,
/// not implausibly long) constraint, and no entry in `available` — of any kind: stable,
/// prerelease, or yanked — may satisfy it. All of the following must hold for `true`:
///
/// 1. `!available.is_empty()` — an empty or not-yet-loaded list means "unknown", not
///    "unsatisfiable" (FR-004: no diagnostic while loading or offline).
/// 2. `!requirement.as_str().trim().is_empty()`.
/// 3. `requirement.as_str().len() <= MAX_REQUIREMENT_LEN` — see that constant's docs; an
///    oversized requirement is treated the same as "unmodellable" (suppressed, not warned).
/// 4. `!formatter.requirement_is_unresolved(requirement)` (FR-005) — an unresolved
///    placeholder requirement was never actually checked against anything.
/// 5. `!formatter.requirement_is_undecidable_given_available(requirement, available)` — this
///    ecosystem's registry can hide a published version that would have decided the match.
/// 6. `formatter.compile_requirement(requirement)` returns `Some(matcher)` — this
///    ecosystem opted in and the requirement string itself parses.
/// 7. Scanning `available` with `matcher.matches`: **at least one** candidate returned
///    `Some(false)`, and **none** returned `Some(true)`. Candidates returning `None`
///    (unparseable candidate strings) are skipped and count toward neither side —
///    condition 7's "at least one `Some(false)`" is load-bearing: if every candidate is
///    unparseable, nothing was decided, so the verdict is `false` (no diagnostic) rather
///    than a vacuous `true`.
///
/// The scan short-circuits on the first `Some(true)` — O(N) worst case, and the newest-first
/// ordering of `available` means a satisfiable requirement typically exits within the first
/// few entries.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{requirement_is_unsatisfiable, EcosystemFormatter, RequirementMatcher};
/// use deps_core::{PackageName, VersionReq};
///
/// struct ExactMatcher(String);
/// impl RequirementMatcher for ExactMatcher {
///     fn matches(&self, version: &str) -> Option<bool> {
///         Some(version == self.0)
///     }
/// }
///
/// struct ExactFormatter;
/// impl EcosystemFormatter for ExactFormatter {
///     fn format_version_for_text_edit(&self, version: &str) -> String {
///         version.to_string()
///     }
///     fn package_url(&self, name: &PackageName) -> String {
///         name.to_string()
///     }
///     fn compile_requirement(
///         &self,
///         requirement: &VersionReq,
///     ) -> Option<Box<dyn RequirementMatcher>> {
///         Some(Box::new(ExactMatcher(requirement.as_str().to_string())))
///     }
/// }
///
/// let available = vec!["1.0.0".to_string(), "0.9.0".to_string()];
/// assert!(requirement_is_unsatisfiable(
///     &ExactFormatter,
///     &VersionReq::new("2.0.0"),
///     &available,
/// ));
/// assert!(!requirement_is_unsatisfiable(
///     &ExactFormatter,
///     &VersionReq::new("1.0.0"),
///     &available,
/// ));
/// ```
pub fn requirement_is_unsatisfiable(
    formatter: &dyn EcosystemFormatter,
    requirement: &VersionReq,
    available: &[String],
) -> bool {
    if available.is_empty() || requirement.as_str().trim().is_empty() {
        return false;
    }
    if requirement.as_str().len() > MAX_REQUIREMENT_LEN {
        return false;
    }
    if formatter.requirement_is_unresolved(requirement) {
        return false;
    }
    if formatter.requirement_is_undecidable_given_available(requirement, available) {
        return false;
    }
    let Some(matcher) = formatter.compile_requirement(requirement) else {
        return false;
    };

    let mut saw_decided_false = false;
    for candidate in available {
        match matcher.matches(candidate) {
            Some(true) => return false,
            Some(false) => saw_decided_false = true,
            None => {}
        }
    }
    saw_decided_false
}

/// Splits a strict-SemVer version string's stable `X.Y.Z` core from its pre-release
/// identifier, if `version` carries one — e.g. `"2.0.0-rc.1"` -> `Some("2.0.0")`,
/// `"2.0.0-rc.1+build.5"` -> `Some("2.0.0")`, `"2.0.0"` -> `None`.
///
/// `None` means `version` is already a stable release, not that it failed to parse — this
/// is a textual SemVer split, not a validating parse. Callers only rely on it for
/// strict-SemVer ecosystems (see
/// [`EcosystemFormatter::strict_semver_prerelease_exclusion`]), whose registries only
/// publish spec-conformant version strings.
fn semver_prerelease_base(version: &str) -> Option<&str> {
    let core = version.split('+').next().unwrap_or(version);
    core.find('-').map(|dash| &core[..dash])
}

/// Reports whether `requirement` itself already names a pre-release tag — a `-` embedded
/// directly in a version token (no surrounding whitespace), as opposed to a whitespace-padded
/// hyphen range operator (npm's `"1.2.3 - 2.3.4"`).
///
/// Guards [`matching_prerelease_would_satisfy`] (#299 S1): when the requirement already pins
/// to a pre-release tuple (e.g. `^2.0.0-rc.5`), a published pre-release that fails to match is
/// rejected by ordinary version *ordering* against that explicit floor, not by SemVer's
/// default pre-release exclusion — enriching the message in that case would misattribute the
/// cause.
fn requirement_names_prerelease(requirement: &str) -> bool {
    let bytes = requirement.as_bytes();
    bytes.iter().enumerate().any(|(i, &b)| {
        b == b'-'
            && i > 0
            && i + 1 < bytes.len()
            && !bytes[i - 1].is_ascii_whitespace()
            && !bytes[i + 1].is_ascii_whitespace()
    })
}

/// For strict-SemVer ecosystems (see
/// [`EcosystemFormatter::strict_semver_prerelease_exclusion`]), finds the newest published,
/// non-yanked pre-release in `available` whose stable core would satisfy `requirement` —
/// evidence that `requirement` reads as unsatisfiable only because SemVer's default comparator
/// excludes pre-releases, not because no compatible version was ever published (#299).
///
/// Returns `None` when the ecosystem hasn't opted in, `requirement` itself already names a
/// pre-release (see [`requirement_names_prerelease`] — in that shape a non-matching candidate
/// is rejected by ordering against the requirement's own explicit floor, not by pre-release
/// exclusion), `requirement` doesn't compile, or no such pre-release exists. `available` is
/// assumed newest-first (see [`PackageVersions::available`]), so the first match found is the
/// newest.
fn matching_prerelease_would_satisfy(
    formatter: &dyn EcosystemFormatter,
    requirement: &VersionReq,
    available: &[String],
    yanked: &[String],
) -> Option<String> {
    if !formatter.strict_semver_prerelease_exclusion() {
        return None;
    }
    if requirement_names_prerelease(requirement.as_str()) {
        return None;
    }
    let matcher = formatter.compile_requirement(requirement)?;
    available.iter().find_map(|candidate| {
        let base = semver_prerelease_base(candidate)?;
        (!yanked.iter().any(|y| y == candidate) && matcher.matches(base) == Some(true))
            .then(|| candidate.clone())
    })
}

/// Returns `true` when `requirement` is satisfied by at least one entry in `available`, but
/// every matching entry is yanked — i.e. the dependency is currently satisfiable only by a
/// yanked/deprecated version.
///
/// Mutually exclusive with [`requirement_is_unsatisfiable`]: both scan `available` through the
/// same `formatter.compile_requirement` matcher, but this one additionally cross-references
/// `yanked` (see [`PackageVersions::yanked`]) to distinguish "satisfied, but only by a yanked
/// version" from "satisfied by an ordinary version" or "not satisfied at all". Callers should
/// only invoke this once `requirement_is_unsatisfiable` has returned `false` for the same
/// `requirement`/`available` pair, so a match is already known to exist.
///
/// Shares `requirement_is_unsatisfiable`'s guard cascade (empty `available`/`requirement`,
/// oversized `requirement`, unresolved placeholder `requirement`, uncompilable `requirement`)
/// — each returns `false` here for the identical reason it does there.
///
/// Unlike `requirement_is_unsatisfiable`, an undecided candidate (`matcher.matches` returns
/// `None` — an unparseable candidate string) does not just get skipped: it disqualifies a
/// `true` verdict entirely. That candidate might have been a genuine non-yanked match this
/// scan simply could not evaluate, so claiming "every match is yanked" without accounting for
/// it would be a false positive — the same #206 conservatism (nothing decided means no
/// diagnostic, not a guess) applied to a different question than `requirement_is_unsatisfiable`
/// asks.
fn requirement_matches_only_yanked(
    formatter: &dyn EcosystemFormatter,
    requirement: &VersionReq,
    available: &[String],
    yanked: &[String],
) -> bool {
    if available.is_empty() || yanked.is_empty() || requirement.as_str().trim().is_empty() {
        return false;
    }
    if requirement.as_str().len() > MAX_REQUIREMENT_LEN {
        return false;
    }
    if formatter.requirement_is_unresolved(requirement) {
        return false;
    }
    let Some(matcher) = formatter.compile_requirement(requirement) else {
        return false;
    };

    let mut saw_match = false;
    let mut saw_undecided = false;
    for candidate in available {
        match matcher.matches(candidate) {
            Some(true) => {
                saw_match = true;
                if !yanked.iter().any(|y| y == candidate) {
                    return false;
                }
            }
            Some(false) => {}
            None => saw_undecided = true,
        }
    }
    saw_match && !saw_undecided
}

/// Generates diagnostics using cached versions (no network calls).
///
/// Uses pre-fetched version information from the lifecycle's parallel fetch.
/// This avoids making additional network requests during diagnostic generation.
///
/// # Arguments
///
/// * `parse_result` - Parsed dependencies from manifest
/// * `versions` - Latest (registry) and resolved (lock file) version maps, keyed by package name
/// * `formatter` - Ecosystem-specific formatting and comparison logic
/// * `freshness` - Whether to differentiate an "outdated" diagnostic still within the
///   release cooldown window (severity is unaffected either way — see the "Newer version
///   available" message below)
/// * `severities` - Configured severity for each diagnostic category
/// * `now` - The instant every publish age in this call is computed against. Taken as a
///   parameter rather than read internally via `PublishTime::now()` (issue #227 M4) so
///   callers can pin an exact cooldown-boundary instant deterministically in tests, and
///   so every dependency in one document is aged against the same instant.
pub fn generate_diagnostics_from_cache(
    parse_result: &dyn ParseResult,
    versions: VersionData<'_>,
    formatter: &dyn EcosystemFormatter,
    freshness: crate::freshness::FreshnessSettings,
    severities: DiagnosticSeverities,
    now: PublishTime,
) -> Vec<Diagnostic> {
    let deps = parse_result.dependencies();
    let mut diagnostics = Vec::with_capacity(deps.len());

    for dep in deps {
        let normalized_name = formatter.normalize_package_name(dep.name());

        // Emitted before either early-`continue` below (registry outage,
        // no version range) so a registry failure never suppresses an OSV
        // finding — the two are independent data sources (FR-007/US-004).
        if let Some(vulnerabilities) = versions.vulnerabilities
            && let Some(ScanOutcome::Vulnerable(dv)) = vulnerabilities
                .get(&normalized_name)
                .or_else(|| vulnerabilities.get(dep.name().as_str()))
        {
            push_vulnerability_diagnostics(&mut diagnostics, dep, dv);
        }

        // Independent of the registry-outage/no-range early-`continue`s below,
        // for the same reason as the vulnerability push above — a yanked
        // finding from the lifecycle probe must never be suppressed by an
        // unrelated "latest" lookup failure.
        //
        // Two independent yanked-version checks exist and both run in this loop:
        // this one (#263) flags the specific in-use version (lockfile-resolved,
        // or an exact manifest pin) when it is yanked, while `yanked_only` below
        // (#247) flags a declared *range* requirement that can currently only be
        // satisfied by a yanked version, even with no lockfile at all. They answer
        // different questions and neither subsumes the other, but for a dependency
        // pinned to the one version that also happens to be the only version
        // satisfying its own requirement, both would fire on the same dependency.
        // `yanked_diagnostic_pushed` suppresses the second (#247) check once the
        // first (#263) already emitted a diagnostic for this dependency, so a
        // single dependency never gets two yanked diagnostics.
        //
        // The two checks deliberately keep different outdated-interaction policies —
        // this is not an oversight left over from the merge. This (#263) check has no
        // `continue`, so it co-emits alongside an "outdated" diagnostic for the same
        // dependency (see `test_generate_diagnostics_from_cache_yanked_and_outdated_both_emitted`,
        // asserting exactly that on the upstream #263 design). `yanked_only` below
        // (#247) does `continue`, suppressing "outdated" for the same dependency (see
        // `test_yanked_only_match_suppresses_outdated_diagnostic`). Each policy was
        // independently reviewed and tested before this merge; harmonizing them is out
        // of scope here.
        let yanked_diagnostic_pushed =
            if let Some(yanked_version) = versions.yanked.and_then(|y| y.get(&normalized_name)) {
                diagnostics.push(Diagnostic {
                    range: dep.version_range().unwrap_or_else(|| dep.name_range()),
                    severity: Some(severities.yanked),
                    message: format!("{} ({})", formatter.yanked_message(), yanked_version),
                    source: Some("deps-lsp".into()),
                    ..Default::default()
                });
                true
            } else {
                false
            };

        let package_versions = versions
            .cached
            .get(normalized_name.as_str())
            .or_else(|| versions.cached.get(dep.name()));

        let Some(package_versions) = package_versions else {
            // Skip "unknown" diagnostic if package exists in lock file
            // (registry fetch may have failed due to rate limiting), or if
            // the source isn't resolvable against the registry this LSP
            // queries (e.g. `CustomRegistry` / Git / Path) — an absent cache
            // entry there just means we never fetched it, not that the
            // package doesn't exist (#248). Name-syntax validation is
            // unaffected: it never depends on registry data.
            let in_lockfile = versions.resolved.contains_key(normalized_name.as_str())
                || versions.resolved.contains_key(dep.name());
            if !in_lockfile {
                // A fetch error/timeout (#267) is not evidence the package doesn't
                // exist — the registry was never successfully asked. Report it
                // distinctly from a genuine "not found" so a transient registry
                // outage or a malformed response (e.g. unparseable
                // maven-metadata.xml) doesn't masquerade as "Unknown package".
                let fetch_failed = dep.source().is_version_resolvable()
                    && versions
                        .fetch_failed
                        .is_some_and(|f| f.contains(normalized_name.as_str()));
                let message = match formatter.validate_package_name(dep.name().as_str()) {
                    Err(reason) => Some(format!("Invalid package name '{}': {reason}", dep.name())),
                    Ok(()) if fetch_failed => Some(format!(
                        "Registry lookup failed for '{}'; package status could not be determined",
                        dep.name()
                    )),
                    Ok(()) if dep.source().is_version_resolvable() => {
                        Some(format!("Unknown package '{}'", dep.name()))
                    }
                    Ok(()) => None,
                };
                if let Some(message) = message {
                    diagnostics.push(Diagnostic {
                        range: dep.name_range(),
                        severity: Some(severities.unknown),
                        message,
                        source: Some("deps-lsp".into()),
                        ..Default::default()
                    });
                }
            }
            continue;
        };
        let latest = package_versions.latest.as_str();

        let Some(version_range) = dep.version_range() else {
            continue;
        };

        // Path/git/URL/SDK/workspace dependencies never resolve against a
        // registry version list at all — `package_versions` (when present)
        // either came from a coincidentally-matching registry entry of the
        // same name (e.g. this workspace's own `deps-core = { path = ...
        // version = "0.10.1" }`, which only avoids a false WARNING today
        // because 0.10.1 also happens to be published) or an entirely
        // unrelated package (Dart's `{ sdk: flutter, version = "^3.24.0" }`
        // resolves against pub.dev's unrelated `flutter` package). Neither
        // is a meaningful "no published version satisfies this" check.
        let unsatisfiable = dep.source().is_version_resolvable()
            && dep.version_requirement().is_some_and(|version_req| {
                requirement_is_unsatisfiable(formatter, version_req, &package_versions.available)
            });

        if unsatisfiable {
            let req_str = dep.version_requirement().map_or("", |r| r.as_str());
            let mut message = format!(
                "No published version satisfies requirement '{req_str}'; latest is {latest}"
            );
            if let Some(prerelease) = dep.version_requirement().and_then(|version_req| {
                matching_prerelease_would_satisfy(
                    formatter,
                    version_req,
                    &package_versions.available,
                    &package_versions.yanked,
                )
            }) {
                use std::fmt::Write as _;
                let _ = write!(
                    message,
                    " (a pre-release, {prerelease}, is excluded by SemVer's default \
                     pre-release-matching rules; require it explicitly to use it)"
                );
            }
            diagnostics.push(Diagnostic {
                range: version_range,
                severity: Some(severities.unsatisfiable),
                message,
                source: Some("deps-lsp".into()),
                code: Some(NumberOrString::String(UNSATISFIABLE_DIAGNOSTIC_CODE.into())),
                ..Default::default()
            });
            continue;
        }

        // Same source-resolvability guard as `unsatisfiable` above — only meaningful once a
        // requirement is known to match *something* in `available` (see `requirement_is_unsatisfiable`).
        // `yanked_diagnostic_applies_to` additionally opts an ecosystem out for a requirement
        // shape where `removal_status()` is not a genuine per-version signal (npm/Composer
        // restrict to exact pins — see that method's docs). Skipped entirely when the in-use-version
        // check above already pushed a yanked diagnostic for this dependency (see
        // `yanked_diagnostic_pushed`), so the two checks never double-report.
        let yanked_only = !yanked_diagnostic_pushed
            && dep.source().is_version_resolvable()
            && dep.version_requirement().is_some_and(|version_req| {
                formatter.yanked_diagnostic_applies_to(version_req)
                    && requirement_matches_only_yanked(
                        formatter,
                        version_req,
                        &package_versions.available,
                        &package_versions.yanked,
                    )
            });

        if yanked_only {
            diagnostics.push(Diagnostic {
                range: version_range,
                severity: Some(severities.yanked),
                message: format!("{}; latest is {latest}", formatter.yanked_message()),
                source: Some("deps-lsp".into()),
                ..Default::default()
            });
            continue;
        }

        // As with the unsatisfiable check above, a non-resolvable source's `latest`
        // (when present at all) comes from an unrelated or coincidental cache entry,
        // not a real lookup against the registry this dependency actually resolves
        // against — so "Outdated" must not be evaluated for it either (#248).
        let status = match dep.version_requirement() {
            Some(version_req) if dep.source().is_version_resolvable() => {
                formatter.requirement_status(version_req, latest)
            }
            _ => RequirementStatus::Unresolved,
        };

        if status == RequirementStatus::Outdated {
            // Message-only differentiation: severity stays `severities.outdated` in both
            // cases (already the floor — see the module docs). A within-cooldown release
            // still deserves the recommendation, just with the extra context that it may
            // yet be yanked or superseded (issue #227 §4.3).
            let published_at = freshness
                .enabled
                .then_some(package_versions.published_at)
                .flatten();
            let message = match published_at {
                Some(published_at)
                    if is_within_cooldown(
                        published_at.age_secs_from(now),
                        freshness.cooldown_secs,
                    ) =>
                {
                    format!(
                        "Newer version available: {latest} (published {} — still within the release cooldown window)",
                        format_relative_age(published_at.age_secs_from(now))
                    )
                }
                _ => format!("Newer version available: {latest}"),
            };
            diagnostics.push(Diagnostic {
                range: version_range,
                severity: Some(severities.outdated),
                message,
                source: Some("deps-lsp".into()),
                ..Default::default()
            });
        }
    }

    diagnostics
}

/// Pushes one [`Diagnostic`] per advisory (each with its own severity, code,
/// and clickable `code_description`), capped at
/// [`ADVISORY_DISPLAY_CAP`] plus a trailing "+N more advisories" entry.
///
/// `N` is derived from `dv.total_known` — the batch result's reported count —
/// never from `dv.advisories.len()`, since invariant 3 (`architecture.md` §8)
/// caps the record *fetch* independently of the render cap.
fn push_vulnerability_diagnostics(
    diagnostics: &mut Vec<Diagnostic>,
    dep: &dyn Dependency,
    dv: &crate::osv::DependencyVulnerabilities,
) {
    let range = dep.version_range().unwrap_or_else(|| dep.name_range());

    let shown = dv.advisories.iter().take(ADVISORY_DISPLAY_CAP);
    let mut shown_count = 0usize;
    for advisory in shown {
        shown_count += 1;
        let code_description = advisory
            .url
            .parse::<Uri>()
            .ok()
            .map(|href| CodeDescription { href });

        diagnostics.push(Diagnostic {
            range,
            severity: Some(diagnostic_severity_for(advisory.severity)),
            message: format!(
                "{}: {}",
                advisory.id,
                advisory
                    .summary
                    .as_deref()
                    .unwrap_or("(no summary provided)")
            ),
            code: Some(NumberOrString::String(advisory.id.clone())),
            code_description,
            source: Some("deps-lsp".into()),
            ..Default::default()
        });
    }

    let remaining = dv.total_known.saturating_sub(shown_count);
    if remaining > 0 {
        diagnostics.push(Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::INFORMATION),
            message: format!("+{remaining} more advisories"),
            source: Some("deps-lsp".into()),
            ..Default::default()
        });
    }
}

/// Generates diagnostics by fetching from registry (makes network calls).
///
/// **Warning**: This function makes network requests for each dependency.
/// Prefer `generate_diagnostics_from_cache` when cached versions are available. Not called
/// anywhere in this workspace (`deps-lsp` always has cached versions by the time
/// diagnostics run) — kept as public API for external callers of `deps-core` as a library,
/// re-exported as `deps_core::lsp_generate_diagnostics`. Does not emit a yanked-version
/// diagnostic: `get_latest_matching`'s trait contract filters yanked versions by default
/// (see [`Registry::get_latest_matching`]), so the version it returns is never yanked
/// under a normal requirement (#233).
pub async fn generate_diagnostics<R: Registry + ?Sized>(
    parse_result: &dyn ParseResult,
    registry: &R,
    formatter: &dyn EcosystemFormatter,
    _freshness: crate::freshness::FreshnessSettings,
    severities: DiagnosticSeverities,
) -> Vec<Diagnostic> {
    let deps = parse_result.dependencies();
    let mut diagnostics = Vec::with_capacity(deps.len());

    for dep in deps {
        // Deliberately `get_versions`, not `get_versions_with`: diagnostics render no
        // publish ages, so paying for a registry's extra freshness fetch here would be
        // pure waste. This function is not called anywhere in this workspace (see the
        // doc comment above), so `_freshness` stays unused by design, not oversight.
        let versions = match registry.get_versions(dep.name()).await {
            Ok(v) => v,
            Err(e) => {
                // Same distinction as `generate_diagnostics_from_cache`/`FetchResult::fetch_failed`
                // (#267): a genuine not-found means the registry answered "no such package",
                // while any other error means the registry couldn't be asked at all.
                let message = match formatter.validate_package_name(dep.name().as_str()) {
                    Err(reason) => format!("Invalid package name '{}': {reason}", dep.name()),
                    Ok(()) if e.is_not_found() => format!("Unknown package '{}'", dep.name()),
                    Ok(()) => format!(
                        "Registry lookup failed for '{}'; package status could not be determined",
                        dep.name()
                    ),
                };
                diagnostics.push(Diagnostic {
                    range: dep.name_range(),
                    severity: Some(severities.unknown),
                    message,
                    source: Some("deps-lsp".into()),
                    ..Default::default()
                });
                continue;
            }
        };

        let Some(version_req) = dep.version_requirement() else {
            continue;
        };
        let Some(version_range) = dep.version_range() else {
            continue;
        };

        let matching = registry
            .get_latest_matching(dep.name(), version_req)
            .await
            .ok()
            .flatten();

        if matching.is_some() {
            let latest = crate::registry::find_latest_stable(&versions);
            if let Some(latest) = latest
                && formatter.requirement_status(version_req, latest.version_string())
                    == RequirementStatus::Outdated
            {
                diagnostics.push(Diagnostic {
                    range: version_range,
                    severity: Some(severities.outdated),
                    message: format!("Newer version available: {}", latest.version_string()),
                    source: Some("deps-lsp".into()),
                    ..Default::default()
                });
            }
        }
    }

    diagnostics
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lsp_helpers::test_support::*;
    use crate::lsp_helpers::*;
    use crate::{PackageName, VersionReq};

    use std::collections::{HashMap, HashSet};
    use std::sync::Arc;

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

        let formatter = MockFormatter;

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

        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::WARNING));
        assert!(diagnostics[0].message.contains("Unknown package"));
        assert!(diagnostics[0].message.contains("unknown-pkg"));
    }

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

        // A package missing from `cached` because its registry fetch errored
        // or timed out (#267) must not be reported as "Unknown package" — the
        // registry was never successfully asked, so absence is not evidence
        // the package doesn't exist.
        let formatter = MockFormatter;

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

        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();
        let fetch_failed = HashSet::from(["flaky-pkg".to_string()]);

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions).with_fetch_failed(&fetch_failed),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert_eq!(diagnostics.len(), 1);
        assert!(!diagnostics[0].message.contains("Unknown package"));
        assert!(diagnostics[0].message.contains("Registry lookup failed"));
        assert!(diagnostics[0].message.contains("flaky-pkg"));
    }

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

        // A syntactically invalid name is a local, name-only check independent
        // of any registry round trip — it must win over a fetch-failure
        // marker for the same (invalid) name, not be suppressed by it.
        let formatter = RejectingFormatter;

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

        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();
        let fetch_failed = HashSet::from(["bad name".to_string()]);

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions).with_fetch_failed(&fetch_failed),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert_eq!(diagnostics.len(), 1);
        assert!(diagnostics[0].message.contains("Invalid package name"));
    }

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

        // A formatter that rejects every name must produce exactly one
        // "Invalid package name" diagnostic per unresolved dependency, never
        // both that and "Unknown package".
        let formatter = RejectingFormatter;

        let parse_result = MockParseResult {
            deps: vec![MockDep {
                name: "bad-pkg".into(),
                version_req: "1.0.0".into(),
                version_range: Range::new(Position::new(0, 10), Position::new(0, 20)),
                name_range: Range::new(Position::new(0, 0), Position::new(0, 7)),
            }],
            uri: crate::test_util::test_uri("/test/package.json"),
        };

        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::WARNING));
        assert!(diagnostics[0].message.starts_with("Invalid package name"));
        assert!(!diagnostics[0].message.contains("Unknown package"));
    }

    #[tokio::test]
    async fn test_generate_diagnostics_invalid_package_name() {
        use tower_lsp_server::ls_types::{Position, Range};

        // Network variant: a registry lookup failure combined with a rejected
        // name must produce "Invalid package name", not "Unknown package".
        let formatter = RejectingFormatter;

        let parse_result = MockParseResult {
            deps: vec![MockDep {
                name: "bad-pkg".into(),
                version_req: "1.0.0".into(),
                version_range: Range::new(Position::new(0, 10), Position::new(0, 20)),
                name_range: Range::new(Position::new(0, 0), Position::new(0, 7)),
            }],
            uri: crate::test_util::test_uri("/test/package.json"),
        };

        let diagnostics = generate_diagnostics(
            &parse_result,
            &ErrorRegistry,
            &formatter,
            crate::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
        )
        .await;

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::WARNING));
        assert!(diagnostics[0].message.starts_with("Invalid package name"));
        assert!(!diagnostics[0].message.contains("Unknown package"));
    }

    #[tokio::test]
    async fn test_generate_diagnostics_unknown_uses_configured_severity() {
        use tower_lsp_server::ls_types::{Position, Range};

        // `NotFoundRegistry`, not `ErrorRegistry`: "Unknown package" is only
        // correct when the registry was actually asked and said "no such
        // package" (#267 C1) — an opaque `CacheError` must not reach this
        // branch, or a transient outage would be mislabeled as a genuinely
        // nonexistent dependency.
        let formatter = MockFormatter;

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

        let severities = DiagnosticSeverities {
            unknown: DiagnosticSeverity::ERROR,
            ..DiagnosticSeverities::default()
        };

        let diagnostics = generate_diagnostics(
            &parse_result,
            &NotFoundRegistry,
            &formatter,
            crate::FreshnessSettings::default(),
            severities,
        )
        .await;

        assert_eq!(diagnostics.len(), 1);
        assert!(diagnostics[0].message.starts_with("Unknown package"));
        assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::ERROR));
    }

    #[tokio::test]
    async fn test_generate_diagnostics_registry_error_not_reported_as_unknown() {
        use tower_lsp_server::ls_types::{Position, Range};

        // #267 C1: an opaque registry failure (`ErrorRegistry`'s `CacheError`,
        // standing in for a network error, timeout, or malformed response)
        // must not produce "Unknown package" — the registry was never
        // successfully asked, so absence of a result is not evidence the
        // package doesn't exist.
        let formatter = MockFormatter;

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

        let diagnostics = generate_diagnostics(
            &parse_result,
            &ErrorRegistry,
            &formatter,
            crate::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
        )
        .await;

        assert_eq!(diagnostics.len(), 1);
        assert!(!diagnostics[0].message.contains("Unknown package"));
        assert!(diagnostics[0].message.contains("Registry lookup failed"));
    }

    #[tokio::test]
    async fn test_generate_diagnostics_outdated_uses_configured_severity() {
        use tower_lsp_server::ls_types::{Position, Range};

        let formatter = MockFormatter;

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

        let severities = DiagnosticSeverities {
            outdated: DiagnosticSeverity::ERROR,
            ..DiagnosticSeverities::default()
        };

        let diagnostics = generate_diagnostics(
            &parse_result,
            &OutdatedRegistry,
            &formatter,
            crate::FreshnessSettings::default(),
            severities,
        )
        .await;

        let outdated_diag = diagnostics
            .iter()
            .find(|d| d.message.starts_with("Newer version available"))
            .expect("expected an outdated diagnostic");
        assert_eq!(outdated_diag.severity, Some(DiagnosticSeverity::ERROR));
    }

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

        let formatter = MockFormatter;

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

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

        let resolved_versions = HashMap::new();

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::HINT));
        assert!(diagnostics[0].message.contains("Newer version available"));
        assert!(diagnostics[0].message.contains("2.0.0"));
    }

    /// Issue #227 §4.3: an outdated dependency whose `latest` was published within the
    /// configured cooldown window gets the extra context appended, severity unchanged.
    #[test]
    fn test_generate_diagnostics_from_cache_outdated_within_cooldown_appends_context() {
        use std::collections::HashMap;
        use tower_lsp_server::ls_types::{Position, Range};

        let formatter = MockFormatter;

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

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

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::HINT));
        assert_eq!(
            diagnostics[0].message,
            "Newer version available: 2.0.0 (published 1 hour ago — still within the release cooldown window)"
        );
        // Guards against reintroducing the "ago ago" duplication bug found while
        // writing this test — `format_relative_age` already appends "ago".
        assert!(!diagnostics[0].message.contains("ago ago"));
    }

    /// Same setup, but `latest` was published well outside the cooldown window — the
    /// message must stay exactly the pre-feature text.
    #[test]
    fn test_generate_diagnostics_from_cache_outdated_outside_cooldown_plain_message() {
        use std::collections::HashMap;
        use tower_lsp_server::ls_types::{Position, Range};

        let formatter = MockFormatter;

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

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

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].message, "Newer version available: 2.0.0");
    }

    /// `freshness.enabled: false` suppresses the cooldown differentiation even when the
    /// publish age would otherwise qualify.
    #[test]
    fn test_generate_diagnostics_from_cache_outdated_freshness_disabled_plain_message() {
        use std::collections::HashMap;
        use tower_lsp_server::ls_types::{Position, Range};

        let formatter = MockFormatter;

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

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

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::freshness::FreshnessSettings {
                enabled: false,
                ..crate::freshness::FreshnessSettings::default()
            },
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].message, "Newer version available: 2.0.0");
    }

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

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

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

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

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::freshness::FreshnessSettings {
                enabled: true,
                cooldown_secs: COOLDOWN_SECS,
            },
            DiagnosticSeverities::default(),
            now,
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(
            diagnostics[0].message, "Newer version available: 2.0.0",
            "age exactly equal to cooldown_secs must not be within cooldown"
        );
    }

    /// Same fixture, one second younger — must flip to the within-cooldown message.
    #[test]
    fn test_generate_diagnostics_from_cache_outdated_cooldown_boundary_one_second_inside() {
        use std::collections::HashMap;
        use tower_lsp_server::ls_types::{Position, Range};

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

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

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

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::freshness::FreshnessSettings {
                enabled: true,
                cooldown_secs: COOLDOWN_SECS,
            },
            DiagnosticSeverities::default(),
            now,
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(
            diagnostics[0].message,
            "Newer version available: 2.0.0 (published 1 minute ago — still within the release cooldown window)",
            "age == cooldown_secs - 1 must be within cooldown"
        );
    }

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

        let formatter = MockFormatter;

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

        let mut cached_versions = HashMap::new();
        cached_versions.insert("serde".into(), PackageVersions::latest_only("1.0.214"));

        let resolved_versions = HashMap::new();

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert!(
            diagnostics.is_empty(),
            "Expected no diagnostics for up-to-date dependency"
        );
    }

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

        let formatter = MockFormatter;

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

        let mut cached_versions = HashMap::new();
        cached_versions.insert("serde".into(), PackageVersions::latest_only("1.0.214"));
        cached_versions.insert("tokio".into(), PackageVersions::latest_only("2.0.0"));

        let resolved_versions = HashMap::new();

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert_eq!(diagnostics.len(), 2);

        let has_outdated = diagnostics
            .iter()
            .any(|d| d.message.contains("Newer version"));
        let has_unknown = diagnostics
            .iter()
            .any(|d| d.message.contains("Unknown package"));

        assert!(has_outdated, "Expected outdated version diagnostic");
        assert!(has_unknown, "Expected unknown package diagnostic");
    }

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

        let formatter = MockUnresolvedFormatter;

        let parse_result = MockParseResult {
            deps: vec![MockDep {
                name: "spring-boot-starter".into(),
                version_req: "$missing".into(),
                version_range: Range::new(Position::new(0, 10), Position::new(0, 20)),
                name_range: Range::new(Position::new(0, 0), Position::new(0, 5)),
            }],
            uri: crate::test_util::test_uri("/test/libs.versions.toml"),
        };

        let mut cached_versions = HashMap::new();
        cached_versions.insert(
            "spring-boot-starter".into(),
            PackageVersions::latest_only("3.2.0"),
        );

        let resolved_versions = HashMap::new();

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert!(
            diagnostics.is_empty(),
            "Expected no diagnostics for an unresolved requirement, got: {diagnostics:?}"
        );
    }

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

        let formatter = MockFormatter;

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

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

        let severities = DiagnosticSeverities {
            yanked: DiagnosticSeverity::ERROR,
            ..DiagnosticSeverities::default()
        };

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions).with_yanked(&yanked),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            severities,
            PublishTime::now(),
        );

        let yanked_diag = diagnostics
            .iter()
            .find(|d| d.message.starts_with(formatter.yanked_message()))
            .expect("expected a yanked diagnostic");
        assert_eq!(yanked_diag.severity, Some(DiagnosticSeverity::ERROR));
        assert!(yanked_diag.message.contains("1.0.5"));
    }

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

        let formatter = MockFormatter;

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

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

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions).with_yanked(&yanked),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        let yanked_diag = diagnostics
            .iter()
            .find(|d| d.message.starts_with(formatter.yanked_message()))
            .expect("expected a yanked diagnostic");
        assert_eq!(yanked_diag.severity, Some(DiagnosticSeverity::WARNING));
    }

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

        // Regression guard for the four handlers (hover, completion, code_lens,
        // inlay_hints) that keep calling `VersionData::new` without
        // `.with_yanked(..)` — `yanked: None` must never produce a diagnostic.
        let formatter = MockFormatter;

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

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

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert!(
            !diagnostics
                .iter()
                .any(|d| d.message.starts_with(formatter.yanked_message())),
            "Expected no yanked diagnostic when `yanked` is None, got: {diagnostics:?}"
        );
    }

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

        // Proves the yanked push sits before the early-`continue`s, so a dep
        // that is both yanked (in-use version) and outdated (vs. latest)
        // gets both diagnostics.
        let formatter = MockFormatter;

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

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

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions).with_yanked(&yanked),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert_eq!(
            diagnostics.len(),
            2,
            "expected both diagnostics: {diagnostics:?}"
        );
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.starts_with(formatter.yanked_message()))
        );
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.contains("Newer version available"))
        );
    }

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

        let formatter = MockFormatter;
        let name_range = Range::new(Position::new(0, 0), Position::new(0, 5));

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

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

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions).with_yanked(&yanked),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        let yanked_diag = diagnostics
            .iter()
            .find(|d| d.message.starts_with(formatter.yanked_message()))
            .expect("expected a yanked diagnostic even without a version_range");
        assert_eq!(yanked_diag.range, name_range);
    }

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

        /// Mirrors a Composer/NuGet/Swift-shaped formatter whose normalized
        /// name differs from the manifest-declared raw name.
        struct MockLowercaseFormatter;
        impl EcosystemFormatter for MockLowercaseFormatter {
            fn format_version_for_text_edit(&self, version: &str) -> String {
                version.to_string()
            }
            fn package_url(&self, name: &PackageName) -> String {
                format!("https://example.com/{name}")
            }
            fn normalize_package_name(&self, name: &PackageName) -> String {
                name.to_string().to_lowercase()
            }
        }

        let formatter = MockLowercaseFormatter;

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

        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();
        let mut yanked = HashMap::new();
        // Keyed by the *normalized* (lowercase) name, not the raw manifest name.
        yanked.insert("newtonsoft.json".to_string(), "13.0.1".to_string());

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions).with_yanked(&yanked),
            &formatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.starts_with(formatter.yanked_message())),
            "expected normalized-name lookup to resolve the yanked entry, got: {diagnostics:?}"
        );
    }

    #[test]
    fn test_generate_diagnostics_unsatisfiable_enriched_with_matching_prerelease() {
        let cached_versions = {
            let mut m = HashMap::new();
            m.insert(
                "dep".into(),
                PackageVersions {
                    latest: "1.5.0".to_string(),
                    available: Arc::from(vec![
                        "2.0.0-rc.1".to_string(),
                        "1.5.0".to_string(),
                        "1.4.0".to_string(),
                    ]),
                    yanked: Arc::from(Vec::<String>::new()),
                    published_at: None,
                },
            );
            m
        };
        let resolved_versions = HashMap::new();
        let uri = crate::test_util::test_uri("/test/Cargo.toml");
        let mut dependency = dep_at("dep");
        dependency.version_req = VersionReq::new("^2.0.0");
        let parse_result = SingleDepParseResult {
            dep: dependency,
            uri,
        };

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &StrictSemverFormatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        let message = diagnostics
            .iter()
            .find(|d| d.message.contains("No published version satisfies"))
            .map(|d| d.message.as_str())
            .expect("unsatisfiable WARNING must fire");
        assert!(
            message.contains("2.0.0-rc.1") && message.contains("pre-release"),
            "message must mention the matching pre-release, got: {message}"
        );
    }

    #[test]
    fn test_generate_diagnostics_unsatisfiable_no_enrichment_without_matching_prerelease() {
        let cached_versions = {
            let mut m = HashMap::new();
            m.insert(
                "dep".into(),
                PackageVersions {
                    latest: "1.5.0".to_string(),
                    available: Arc::from(vec!["1.5.0".to_string(), "1.4.0".to_string()]),
                    yanked: Arc::from(Vec::<String>::new()),
                    published_at: None,
                },
            );
            m
        };
        let resolved_versions = HashMap::new();
        let uri = crate::test_util::test_uri("/test/Cargo.toml");
        let mut dependency = dep_at("dep");
        dependency.version_req = VersionReq::new("^2.0.0");
        let parse_result = SingleDepParseResult {
            dep: dependency,
            uri,
        };

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &StrictSemverFormatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        let message = diagnostics
            .iter()
            .find(|d| d.message.contains("No published version satisfies"))
            .map(|d| d.message.as_str())
            .expect("unsatisfiable WARNING must fire");
        assert!(
            !message.contains("pre-release"),
            "message must not mention a pre-release when none satisfies, got: {message}"
        );
    }

    #[test]
    fn test_generate_diagnostics_unsatisfiable_skipped_for_non_registry_sources() {
        use crate::parser::DependencySource;

        let cached_versions = {
            let mut m = HashMap::new();
            m.insert("dep".into(), PackageVersions::latest_only("9.9.9"));
            m
        };
        let resolved_versions = HashMap::new();
        let uri = crate::test_util::test_uri("/test/Cargo.toml");

        // Requirement "1.0.0" against available ["9.9.9"] is unsatisfiable
        // under ExactMatchFormatter — proven by the Registry-source case below.
        for source in [
            DependencySource::Path {
                path: "../local".into(),
            },
            DependencySource::Git {
                url: "https://example.com/repo.git".into(),
                rev: None,
            },
            DependencySource::Url {
                url: "https://example.com/pkg.tar.gz".into(),
            },
            DependencySource::Sdk {
                sdk: "flutter".into(),
            },
            DependencySource::Workspace,
            DependencySource::CustomRegistry {
                url: "my-corp".into(),
            },
        ] {
            let parse_result = SingleDepParseResult {
                dep: NonRegistryDep(dep_at("dep"), source.clone()),
                uri: uri.clone(),
            };
            let diagnostics = generate_diagnostics_from_cache(
                &parse_result,
                VersionData::new(&cached_versions, &resolved_versions),
                &ExactMatchFormatter,
                crate::freshness::FreshnessSettings::default(),
                DiagnosticSeverities::default(),
                PublishTime::now(),
            );
            assert!(
                diagnostics
                    .iter()
                    .all(|d| !d.message.contains("No published version satisfies")),
                "source {source:?} must never produce the unsatisfiable-requirement WARNING"
            );
        }

        // Control: the same requirement/available pair on a Registry-source
        // dependency DOES produce the WARNING, proving the loop above isn't
        // vacuously passing because the fixture never triggers it at all.
        let registry_parse_result = SingleDepParseResult {
            dep: dep_at("dep"),
            uri,
        };
        let diagnostics = generate_diagnostics_from_cache(
            &registry_parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &ExactMatchFormatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.contains("No published version satisfies")),
            "control case: a Registry-source dependency must still produce the WARNING"
        );
    }

    #[test]
    fn test_generate_diagnostics_unknown_package_skipped_for_non_registry_sources() {
        use crate::parser::DependencySource;

        // No cache entry at all for "dep" — simulates a `CustomRegistry`
        // dependency, which this LSP never fetches from a real registry.
        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();
        let uri = crate::test_util::test_uri("/test/Cargo.toml");

        let parse_result = SingleDepParseResult {
            dep: NonRegistryDep(
                dep_at("dep"),
                DependencySource::CustomRegistry {
                    url: "my-corp".into(),
                },
            ),
            uri: uri.clone(),
        };
        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );
        assert!(
            diagnostics
                .iter()
                .all(|d| !d.message.contains("Unknown package")),
            "a CustomRegistry-sourced dependency must never produce the \"Unknown package\" WARNING"
        );

        // Control: the same missing cache entry on a Registry-source
        // dependency DOES produce the WARNING.
        let registry_parse_result = SingleDepParseResult {
            dep: dep_at("dep"),
            uri,
        };
        let diagnostics = generate_diagnostics_from_cache(
            &registry_parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.contains("Unknown package")),
            "control case: a Registry-source dependency must still produce the WARNING"
        );
    }

    #[test]
    fn test_generate_diagnostics_invalid_name_still_reported_for_non_registry_sources() {
        use crate::parser::DependencySource;

        // Invalid-name validation is pure syntax checking, independent of
        // registry data — it must still fire even when the source is not
        // resolvable (unlike "Unknown package", which requires a real lookup).
        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();
        let uri = crate::test_util::test_uri("/test/package.json");

        let parse_result = SingleDepParseResult {
            dep: NonRegistryDep(
                dep_at("dep"),
                DependencySource::CustomRegistry {
                    url: "my-corp".into(),
                },
            ),
            uri,
        };
        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &RejectingFormatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );
        assert_eq!(diagnostics.len(), 1);
        assert!(diagnostics[0].message.starts_with("Invalid package name"));
    }

    #[test]
    fn test_generate_diagnostics_outdated_skipped_for_non_registry_sources() {
        use crate::parser::DependencySource;

        // "dep" resolves to a coincidentally-matching cache entry with a newer
        // "latest", as would happen for a Cargo path dependency that happens
        // to share a name with an unrelated published crate.
        let cached_versions = {
            let mut m = HashMap::new();
            m.insert("dep".into(), PackageVersions::latest_only("9.9.9"));
            m
        };
        let resolved_versions = HashMap::new();
        let uri = crate::test_util::test_uri("/test/Cargo.toml");

        let parse_result = SingleDepParseResult {
            dep: NonRegistryDep(
                dep_at("dep"),
                DependencySource::CustomRegistry {
                    url: "my-corp".into(),
                },
            ),
            uri: uri.clone(),
        };
        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );
        assert!(
            diagnostics
                .iter()
                .all(|d| !d.message.contains("Newer version available")),
            "a CustomRegistry-sourced dependency must never produce the \"Outdated\" WARNING"
        );

        // Control: the same requirement/cache pair on a Registry-source
        // dependency DOES produce the WARNING.
        let registry_parse_result = SingleDepParseResult {
            dep: dep_at("dep"),
            uri,
        };
        let diagnostics = generate_diagnostics_from_cache(
            &registry_parse_result,
            VersionData::new(&cached_versions, &resolved_versions),
            &MockFormatter,
            crate::freshness::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.contains("Newer version available")),
            "control case: a Registry-source dependency must still produce the WARNING"
        );
    }

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

        let formatter = MockFormatter;
        let parse_result = MockParseResult {
            deps: vec![dep_at("vulnerable-pkg")],
            uri: crate::test_util::test_uri("/test/Cargo.toml"),
        };

        // Registry data is entirely absent (as if the registry fetch failed),
        // which must never suppress the OSV finding.
        let cached_versions = HashMap::new();
        let resolved_versions = HashMap::new();

        let mut vulns: VulnerabilityMap = VulnerabilityMap::new();
        vulns.insert(
            "vulnerable-pkg".to_string(),
            ScanOutcome::Vulnerable(DependencyVulnerabilities {
                advisories: vec![sample_advisory("RUSTSEC-2020-0071", VulnSeverity::High)],
                total_known: 1,
                upgrade_status: UpgradeStatus::NotChecked,
            }),
        );

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions).with_vulnerabilities(&vulns),
            &formatter,
            crate::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        let vuln_diag = diagnostics
            .iter()
            .find(|d| d.message.contains("RUSTSEC-2020-0071"))
            .expect("vulnerability diagnostic must be emitted even without registry data");
        assert_eq!(vuln_diag.severity, Some(DiagnosticSeverity::WARNING));
        assert_eq!(
            vuln_diag.code,
            Some(NumberOrString::String("RUSTSEC-2020-0071".to_string()))
        );
    }

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

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

        let advisories: Vec<_> = (0..ADVISORY_DISPLAY_CAP)
            .map(|i| sample_advisory(&format!("ADV-{i}"), VulnSeverity::Low))
            .collect();

        let mut vulns: VulnerabilityMap = VulnerabilityMap::new();
        vulns.insert(
            "noisy-pkg".to_string(),
            ScanOutcome::Vulnerable(DependencyVulnerabilities {
                advisories,
                total_known: 40,
                upgrade_status: UpgradeStatus::NotChecked,
            }),
        );

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions).with_vulnerabilities(&vulns),
            &formatter,
            crate::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        let more_diag = diagnostics
            .iter()
            .find(|d| d.message.contains("more advisories"))
            .expect("expected a trailing +N more advisories diagnostic");
        assert!(
            more_diag.message.contains("+35"),
            "got: {}",
            more_diag.message
        );
    }

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

        let formatter = MockFormatter;
        let parse_result = MockParseResult {
            deps: vec![dep_at("git-pkg")],
            uri: crate::test_util::test_uri("/test/Cargo.toml"),
        };
        let mut cached_versions = HashMap::new();
        cached_versions.insert("git-pkg".into(), PackageVersions::latest_only("1.0.0"));
        let resolved_versions = HashMap::new();

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

        let diagnostics = generate_diagnostics_from_cache(
            &parse_result,
            VersionData::new(&cached_versions, &resolved_versions).with_vulnerabilities(&vulns),
            &formatter,
            crate::FreshnessSettings::default(),
            DiagnosticSeverities::default(),
            PublishTime::now(),
        );

        assert!(
            diagnostics.iter().all(|d| d.code.is_none()),
            "a Skipped outcome must never render an advisory diagnostic"
        );
    }

    /// Table-driven coverage for `requirement_is_unsatisfiable` (plan §4), using a
    /// formatter whose `compile_requirement` is configured per test via a closure-backed
    /// matcher, rather than one of the fixed ecosystem formatters.
    mod requirement_is_unsatisfiable_tests {
        use super::*;

        type Decide = Arc<dyn Fn(&str) -> Option<bool> + Send + Sync>;

        /// A matcher backed by a type-erased closure, so each test can express its own
        /// per-candidate decision table without a new named type per test.
        struct ClosureMatcher(Decide);

        impl RequirementMatcher for ClosureMatcher {
            fn matches(&self, version: &str) -> Option<bool> {
                (self.0)(version)
            }
        }

        /// A formatter whose `compile_requirement` is `None` (requirement is treated as
        /// unmodellable) unless `requirement.as_str() == "modelled"`, in which case it
        /// returns a `ClosureMatcher` wrapping `decide`. `requirement_is_unresolved` fires
        /// on the literal string `"unresolved"`.
        struct TableFormatter {
            decide: Decide,
        }

        impl TableFormatter {
            fn new(decide: impl Fn(&str) -> Option<bool> + Send + Sync + 'static) -> Self {
                Self {
                    decide: Arc::new(decide),
                }
            }
        }

        impl EcosystemFormatter for TableFormatter {
            fn format_version_for_text_edit(&self, version: &str) -> String {
                version.to_string()
            }
            fn package_url(&self, name: &PackageName) -> String {
                name.to_string()
            }
            fn requirement_is_unresolved(&self, requirement: &VersionReq) -> bool {
                requirement.as_str() == "unresolved"
            }
            fn compile_requirement(
                &self,
                requirement: &VersionReq,
            ) -> Option<Box<dyn RequirementMatcher>> {
                if requirement.as_str() != "modelled" {
                    return None;
                }
                Some(Box::new(ClosureMatcher(Arc::clone(&self.decide)))
                    as Box<dyn RequirementMatcher>)
            }
        }

        fn versions(strs: &[&str]) -> Vec<String> {
            strs.iter().map(|s| (*s).to_string()).collect()
        }

        #[test]
        fn test_empty_available_list_is_false() {
            let formatter = TableFormatter::new(|_v| Some(true));
            assert!(!requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new("modelled"),
                &[],
            ));
        }

        #[test]
        fn test_empty_requirement_string_is_false() {
            let formatter = TableFormatter::new(|_v| Some(false));
            assert!(!requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new(""),
                &versions(&["1.0.0"]),
            ));
        }

        /// S-1 (security): an oversized requirement is rejected before `compile_requirement`
        /// is even called, bounding the cost of an adversarial/corrupted requirement string
        /// regardless of how expensive that ecosystem's matcher is per candidate.
        #[test]
        fn test_oversized_requirement_is_false_without_compiling() {
            let formatter =
                TableFormatter::new(|_v| panic!("must not compile/scan an oversized requirement"));
            let oversized = "1".repeat(MAX_REQUIREMENT_LEN + 1);
            assert!(!requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new(oversized),
                &versions(&["1.0.0"]),
            ));
        }

        #[test]
        fn test_unresolved_requirement_is_false() {
            let formatter = TableFormatter::new(|_v| Some(false));
            assert!(!requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new("unresolved"),
                &versions(&["1.0.0"]),
            ));
        }

        #[test]
        fn test_compile_requirement_none_is_false() {
            let formatter = TableFormatter::new(|_v| Some(false));
            assert!(!requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new("not-modelled"),
                &versions(&["1.0.0"]),
            ));
        }

        #[test]
        fn test_all_candidates_decided_false_is_true() {
            let formatter = TableFormatter::new(|_v| Some(false));
            assert!(requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.0.0", "2.0.0", "3.0.0"]),
            ));
        }

        #[test]
        fn test_one_match_among_many_non_matches_is_false() {
            let formatter = TableFormatter::new(|v| Some(v == "2.0.0"));
            assert!(!requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.0.0", "2.0.0", "3.0.0"]),
            ));
        }

        /// S2 regression: every candidate unparseable means nothing was decided, so the
        /// verdict must be `false` (no diagnostic), not a vacuous `true`.
        #[test]
        fn test_all_candidates_unparseable_is_false() {
            let formatter = TableFormatter::new(|_v| None);
            assert!(!requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.0.0", "2.0.0"]),
            ));
        }

        /// S2 regression, other half: a single junk entry among otherwise-all-`Some(false)`
        /// candidates is skipped, not fatal to the whole scan.
        #[test]
        fn test_one_unparseable_candidate_among_false_is_still_true() {
            let formatter = TableFormatter::new(|v| if v == "junk" { None } else { Some(false) });
            assert!(requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.0.0", "junk", "2.0.0"]),
            ));
        }

        /// §1.3: a match on a candidate that happens to be yanked still counts as
        /// satisfied — `available` carries no yanked flag, so this is exercised the same
        /// way any other match is: the matcher deciding `Some(true)` for that entry.
        #[test]
        fn test_match_on_yanked_only_candidate_is_false() {
            let formatter = TableFormatter::new(|v| Some(v == "1.0.0-yanked"));
            assert!(!requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.0.0-yanked"]),
            ));
        }

        /// §1.2: same, for a prerelease-only match.
        #[test]
        fn test_match_on_prerelease_only_candidate_is_false() {
            let formatter = TableFormatter::new(|v| Some(v == "2.0.0-beta.1"));
            assert!(!requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["2.0.0-beta.1"]),
            ));
        }

        #[test]
        fn test_scan_short_circuits_on_first_match() {
            let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
            let calls_clone = Arc::clone(&calls);
            let formatter = TableFormatter::new(move |v| {
                calls_clone.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                Some(v == "1.0.0")
            });
            let result = requirement_is_unsatisfiable(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.0.0", "0.9.0", "0.8.0"]),
            );
            assert!(!result);
            assert_eq!(
                calls.load(std::sync::atomic::Ordering::SeqCst),
                1,
                "must stop scanning at the first Some(true)"
            );
        }
    }

    /// Coverage for `matching_prerelease_would_satisfy` and `semver_prerelease_base` (#299):
    /// enriching the unsatisfiable-requirement WARNING for strict-SemVer ecosystems with a
    /// mention of a published pre-release that would satisfy the requirement's stable core.
    mod matching_prerelease_would_satisfy_tests {
        use super::*;

        /// Same matcher as `StrictSemverFormatter` (defined in the parent `tests` module and
        /// shared with the `generate_diagnostics_from_cache` end-to-end coverage), but not
        /// opted into `strict_semver_prerelease_exclusion` — mirrors Maven/NuGet/Composer/
        /// Gradle, which must never get the enrichment.
        struct NonStrictFormatter;
        impl EcosystemFormatter for NonStrictFormatter {
            fn format_version_for_text_edit(&self, version: &str) -> String {
                version.to_string()
            }
            fn package_url(&self, name: &PackageName) -> String {
                name.to_string()
            }
            fn compile_requirement(
                &self,
                requirement: &VersionReq,
            ) -> Option<Box<dyn RequirementMatcher>> {
                requirement
                    .as_str()
                    .parse::<semver::VersionReq>()
                    .ok()
                    .map(|req| Box::new(RealSemverMatcher(req)) as Box<dyn RequirementMatcher>)
            }
        }

        fn versions(strs: &[&str]) -> Vec<String> {
            strs.iter().map(|s| (*s).to_string()).collect()
        }

        #[test]
        fn test_semver_prerelease_base() {
            assert_eq!(semver_prerelease_base("2.0.0-rc.1"), Some("2.0.0"));
            assert_eq!(semver_prerelease_base("2.0.0-rc.1+build.5"), Some("2.0.0"));
            assert_eq!(semver_prerelease_base("2.0.0"), None);
            assert_eq!(semver_prerelease_base("2.0.0+build.5"), None);
        }

        #[test]
        fn test_requirement_names_prerelease() {
            assert!(requirement_names_prerelease("2.0.0-rc.5"));
            assert!(requirement_names_prerelease("^2.0.0-rc.5"));
            assert!(requirement_names_prerelease("~2.0.0-rc.5"));
            assert!(requirement_names_prerelease(">=2.0.0-rc.5"));
            assert!(requirement_names_prerelease("=2.0.0-rc.5"));
            assert!(!requirement_names_prerelease("^2.0.0"));
            assert!(!requirement_names_prerelease(">=1.0.0, <2.0.0"));
            // npm's whitespace-padded hyphen range operator must not be mistaken for an
            // embedded pre-release tag.
            assert!(!requirement_names_prerelease("1.2.3 - 2.3.4"));
        }

        /// (a) No pre-release exists among `available` — no enrichment.
        #[test]
        fn test_no_prerelease_available_returns_none() {
            assert_eq!(
                matching_prerelease_would_satisfy(
                    &StrictSemverFormatter,
                    &VersionReq::new("^2.0.0"),
                    &versions(&["1.5.0", "1.4.0"]),
                    &[],
                ),
                None
            );
        }

        /// (b) A pre-release exists that would satisfy the requirement's stable core — the
        /// scenario from the issue's example (`^2.0.0` vs. published `2.0.0-rc.1`).
        #[test]
        fn test_matching_prerelease_is_found() {
            assert_eq!(
                matching_prerelease_would_satisfy(
                    &StrictSemverFormatter,
                    &VersionReq::new("^2.0.0"),
                    &versions(&["2.0.0-rc.1", "1.5.0"]),
                    &[],
                ),
                Some("2.0.0-rc.1".to_string())
            );
        }

        /// The newest matching pre-release wins when several are published (`available` is
        /// newest-first).
        #[test]
        fn test_returns_newest_matching_prerelease_first() {
            assert_eq!(
                matching_prerelease_would_satisfy(
                    &StrictSemverFormatter,
                    &VersionReq::new("^2.0.0"),
                    &versions(&["2.0.0-rc.2", "2.0.0-rc.1", "1.5.0"]),
                    &[],
                ),
                Some("2.0.0-rc.2".to_string())
            );
        }

        /// A published pre-release whose stable core still fails the requirement (wrong
        /// major version) must not be surfaced.
        #[test]
        fn test_non_matching_prerelease_returns_none() {
            assert_eq!(
                matching_prerelease_would_satisfy(
                    &StrictSemverFormatter,
                    &VersionReq::new("^2.0.0"),
                    &versions(&["3.0.0-rc.1", "1.5.0"]),
                    &[],
                ),
                None
            );
        }

        /// (c) The requirement is itself an exact pin to a nonexistent pre-release
        /// (`=2.0.0-rc.5`) — existing #206 behavior. A published pre-release with a
        /// different tag must not be surfaced, since the requirement already names a
        /// pre-release tag (`requirement_names_prerelease` bails before even compiling).
        #[test]
        fn test_exact_prerelease_pin_does_not_misfire_on_unrelated_prerelease() {
            assert_eq!(
                matching_prerelease_would_satisfy(
                    &StrictSemverFormatter,
                    &VersionReq::new("=2.0.0-rc.5"),
                    &versions(&["2.0.0-rc.1", "1.5.0"]),
                    &[],
                ),
                None
            );
        }

        /// S1 regression: a `^`-ranged requirement whose floor itself names a pre-release
        /// tag must not enrich, even though `2.0.0-rc.1`'s stable core (`2.0.0`) would
        /// satisfy `^2.0.0-rc.5` (verified against real `semver` 1.0.28) — the real reason
        /// `2.0.0-rc.1` doesn't match is ordering against the requirement's own explicit
        /// floor (`rc.1 < rc.5`), not SemVer's default pre-release exclusion.
        #[test]
        fn test_caret_requirement_naming_prerelease_returns_none() {
            assert_eq!(
                matching_prerelease_would_satisfy(
                    &StrictSemverFormatter,
                    &VersionReq::new("^2.0.0-rc.5"),
                    &versions(&["2.0.0-rc.1", "1.5.0"]),
                    &[],
                ),
                None
            );
        }

        /// S1 regression, `~` shape.
        #[test]
        fn test_tilde_requirement_naming_prerelease_returns_none() {
            assert_eq!(
                matching_prerelease_would_satisfy(
                    &StrictSemverFormatter,
                    &VersionReq::new("~2.0.0-rc.5"),
                    &versions(&["2.0.0-rc.1", "1.5.0"]),
                    &[],
                ),
                None
            );
        }

        /// S1 regression, `>=` shape.
        #[test]
        fn test_gte_requirement_naming_prerelease_returns_none() {
            assert_eq!(
                matching_prerelease_would_satisfy(
                    &StrictSemverFormatter,
                    &VersionReq::new(">=2.0.0-rc.5"),
                    &versions(&["2.0.0-rc.1", "1.5.0"]),
                    &[],
                ),
                None
            );
        }

        /// M1: a matching pre-release that is itself yanked must not be surfaced — it isn't
        /// actually usable, so naming it as "would satisfy" would be misleading.
        #[test]
        fn test_yanked_matching_prerelease_is_skipped() {
            assert_eq!(
                matching_prerelease_would_satisfy(
                    &StrictSemverFormatter,
                    &VersionReq::new("^2.0.0"),
                    &versions(&["2.0.0-rc.1", "1.5.0"]),
                    &versions(&["2.0.0-rc.1"]),
                ),
                None
            );
        }

        /// M1: a yanked pre-release is skipped in favor of an older, non-yanked matching one.
        #[test]
        fn test_yanked_matching_prerelease_falls_back_to_non_yanked() {
            assert_eq!(
                matching_prerelease_would_satisfy(
                    &StrictSemverFormatter,
                    &VersionReq::new("^2.0.0"),
                    &versions(&["2.0.0-rc.2", "2.0.0-rc.1", "1.5.0"]),
                    &versions(&["2.0.0-rc.2"]),
                ),
                Some("2.0.0-rc.1".to_string())
            );
        }

        /// Ecosystems that have not opted in (Maven/NuGet/Composer/Gradle) never get the
        /// enrichment, even against a requirement/available pair that would otherwise match.
        #[test]
        fn test_non_opted_in_ecosystem_returns_none() {
            assert_eq!(
                matching_prerelease_would_satisfy(
                    &NonStrictFormatter,
                    &VersionReq::new("^2.0.0"),
                    &versions(&["2.0.0-rc.1", "1.5.0"]),
                    &[],
                ),
                None
            );
        }
    }

    /// Coverage for `requirement_matches_only_yanked` and its wiring into
    /// `generate_diagnostics_from_cache` (issue #247): the cache-only diagnostics path's
    /// substitute for the network path's `current.removal_status()` check in `generate_diagnostics`,
    /// which never fires against a real registry because `Registry::get_latest_matching`
    /// filters yanked entries out by contract on every current implementation (#233). This
    /// scans `available`/`yanked` directly instead, so it observes yanked entries that
    /// `get_latest_matching` never returns.
    mod requirement_matches_only_yanked_tests {
        use super::*;

        type Decide = Arc<dyn Fn(&str) -> Option<bool> + Send + Sync>;

        struct ClosureMatcher(Decide);

        impl RequirementMatcher for ClosureMatcher {
            fn matches(&self, version: &str) -> Option<bool> {
                (self.0)(version)
            }
        }

        /// Same shape as `requirement_is_unsatisfiable_tests::TableFormatter`:
        /// `compile_requirement` only opts in for the literal requirement string `"modelled"`.
        struct TableFormatter {
            decide: Decide,
        }

        impl TableFormatter {
            fn new(decide: impl Fn(&str) -> Option<bool> + Send + Sync + 'static) -> Self {
                Self {
                    decide: Arc::new(decide),
                }
            }
        }

        impl EcosystemFormatter for TableFormatter {
            fn format_version_for_text_edit(&self, version: &str) -> String {
                version.to_string()
            }
            fn package_url(&self, name: &PackageName) -> String {
                name.to_string()
            }
            fn requirement_is_unresolved(&self, requirement: &VersionReq) -> bool {
                requirement.as_str() == "unresolved"
            }
            fn compile_requirement(
                &self,
                requirement: &VersionReq,
            ) -> Option<Box<dyn RequirementMatcher>> {
                if requirement.as_str() != "modelled" {
                    return None;
                }
                Some(Box::new(ClosureMatcher(Arc::clone(&self.decide)))
                    as Box<dyn RequirementMatcher>)
            }
        }

        fn versions(strs: &[&str]) -> Vec<String> {
            strs.iter().map(|s| (*s).to_string()).collect()
        }

        #[test]
        fn test_yanked_only_match_is_true() {
            let formatter = TableFormatter::new(|v| Some(v == "1.2.1"));
            assert!(requirement_matches_only_yanked(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.2.1"]),
                &versions(&["1.2.1"]),
            ));
        }

        #[test]
        fn test_no_match_is_false() {
            let formatter = TableFormatter::new(|_v| Some(false));
            assert!(!requirement_matches_only_yanked(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.2.1"]),
                &versions(&["1.2.1"]),
            ));
        }

        #[test]
        fn test_match_on_non_yanked_alongside_yanked_is_false() {
            // "^1.0" matches both a yanked 1.0.0 and a non-yanked 1.0.1 — a non-yanked
            // alternative exists, so this must not be reported as "yanked-only".
            let formatter = TableFormatter::new(|v| Some(v == "1.0.0" || v == "1.0.1"));
            assert!(!requirement_matches_only_yanked(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.0.1", "1.0.0"]),
                &versions(&["1.0.0"]),
            ));
        }

        #[test]
        fn test_scan_continues_past_a_yanked_match_to_find_a_non_yanked_alternative() {
            // Same as above but with the yanked candidate ordered first, so a scan that
            // stopped at the first `Some(true)` (as `requirement_is_unsatisfiable` does) would
            // wrongly report "yanked-only" here.
            let formatter = TableFormatter::new(|v| Some(v == "1.0.0" || v == "1.0.1"));
            assert!(!requirement_matches_only_yanked(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.0.0", "1.0.1"]),
                &versions(&["1.0.0"]),
            ));
        }

        #[test]
        fn test_empty_yanked_list_is_false_without_compiling() {
            let formatter =
                TableFormatter::new(|_v| panic!("must not compile/scan when yanked is empty"));
            assert!(!requirement_matches_only_yanked(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.0.0"]),
                &[],
            ));
        }

        #[test]
        fn test_empty_available_list_is_false() {
            let formatter = TableFormatter::new(|_v| Some(true));
            assert!(!requirement_matches_only_yanked(
                &formatter,
                &VersionReq::new("modelled"),
                &[],
                &versions(&["1.0.0"]),
            ));
        }

        #[test]
        fn test_unresolved_requirement_is_false() {
            let formatter = TableFormatter::new(|_v| Some(true));
            assert!(!requirement_matches_only_yanked(
                &formatter,
                &VersionReq::new("unresolved"),
                &versions(&["1.0.0"]),
                &versions(&["1.0.0"]),
            ));
        }

        #[test]
        fn test_compile_requirement_none_is_false() {
            let formatter = TableFormatter::new(|_v| Some(true));
            assert!(!requirement_matches_only_yanked(
                &formatter,
                &VersionReq::new("not-modelled"),
                &versions(&["1.0.0"]),
                &versions(&["1.0.0"]),
            ));
        }

        /// End-to-end: `generate_diagnostics_from_cache` emits the yanked diagnostic (default
        /// severity, `formatter.yanked_message()` plus a "; latest is X" suffix mirroring the
        /// sibling unsatisfiable diagnostic's actionability) and nothing else for a dependency
        /// whose requirement matches only a yanked version.
        #[test]
        fn test_generate_diagnostics_from_cache_yanked_only_match_fires_yanked_diagnostic() {
            let formatter = TableFormatter::new(|v| Some(v == "1.2.1"));

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

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

            let diagnostics = generate_diagnostics_from_cache(
                &parse_result,
                VersionData::new(&cached_versions, &resolved_versions),
                &formatter,
                crate::freshness::FreshnessSettings::default(),
                DiagnosticSeverities::default(),
                PublishTime::now(),
            );

            assert_eq!(diagnostics.len(), 1, "expected exactly one diagnostic");
            assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::WARNING));
            assert_eq!(
                diagnostics[0].message,
                format!("{}; latest is 2.0.0", formatter.yanked_message())
            );
        }

        /// #247 vs. #263 dedup: a dependency whose in-use version (lock-file-resolved, or an
        /// exact pin) is yanked *and* is the only version satisfying its own requirement
        /// triggers both the in-use-version check (`versions.yanked`, #263) and the
        /// requirement-only-satisfiable-by-yanked check (`requirement_matches_only_yanked`,
        /// #247). Exactly one diagnostic must be emitted, not two.
        #[test]
        fn test_generate_diagnostics_from_cache_yanked_dedup_in_use_and_requirement_only_match() {
            let formatter = TableFormatter::new(|v| Some(v == "1.2.1"));

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

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

            let diagnostics = generate_diagnostics_from_cache(
                &parse_result,
                VersionData::new(&cached_versions, &resolved_versions).with_yanked(&in_use_yanked),
                &formatter,
                crate::freshness::FreshnessSettings::default(),
                DiagnosticSeverities::default(),
                PublishTime::now(),
            );

            // Two diagnostics are expected, not one: the in-use-version check (#263) has
            // no `continue`, so it co-emits alongside the ordinary "outdated" diagnostic
            // for the same dependency (the fixture's declared requirement "modelled"
            // does not itself equal `latest` "2.0.0", so `requirement_status` reports
            // `Outdated`) — this is #263's deliberate, separately-tested policy, see
            // `test_generate_diagnostics_from_cache_yanked_and_outdated_both_emitted`.
            // What this test actually proves is narrower: exactly one *yanked*
            // diagnostic, not two — #247's `yanked_only` check must not also fire.
            let yanked_diags: Vec<_> = diagnostics
                .iter()
                .filter(|d| d.message.starts_with(formatter.yanked_message()))
                .collect();
            assert_eq!(
                yanked_diags.len(),
                1,
                "expected exactly one yanked diagnostic, got: {diagnostics:?}"
            );
            // The in-use-version check (#263) runs first and wins.
            assert_eq!(
                yanked_diags[0].message,
                format!("{} (1.2.1)", formatter.yanked_message())
            );
            assert_eq!(
                diagnostics.len(),
                2,
                "expected exactly the yanked diagnostic plus the co-emitted outdated \
                 diagnostic (#263's policy), got: {diagnostics:?}"
            );
            assert!(
                diagnostics
                    .iter()
                    .any(|d| d.message == "Newer version available: 2.0.0"),
                "expected the co-emitted outdated diagnostic, got: {diagnostics:?}"
            );
        }

        /// `severities.yanked` reaches the emitted diagnostic on the cache-only path, the same
        /// way `outdated_severity`/`unknown_severity`/`unsatisfiable_severity` already do.
        #[test]
        fn test_generate_diagnostics_from_cache_yanked_only_match_uses_configured_severity() {
            let formatter = TableFormatter::new(|v| Some(v == "1.2.1"));

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

            let mut cached_versions = HashMap::new();
            cached_versions.insert(
                "serde".into(),
                PackageVersions {
                    latest: "1.2.1".to_string(),
                    available: Arc::from(vec!["1.2.1".to_string()]),
                    yanked: Arc::from(vec!["1.2.1".to_string()]),
                    published_at: None,
                },
            );
            let resolved_versions = HashMap::new();

            let severities = DiagnosticSeverities {
                yanked: DiagnosticSeverity::ERROR,
                ..DiagnosticSeverities::default()
            };

            let diagnostics = generate_diagnostics_from_cache(
                &parse_result,
                VersionData::new(&cached_versions, &resolved_versions),
                &formatter,
                crate::freshness::FreshnessSettings::default(),
                severities,
                PublishTime::now(),
            );

            assert_eq!(diagnostics.len(), 1);
            assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::ERROR));
        }

        /// When a non-yanked version also satisfies the requirement, no yanked diagnostic
        /// fires — the dependency falls through to the ordinary outdated/up-to-date check.
        #[test]
        fn test_generate_diagnostics_from_cache_match_with_non_yanked_alternative_skips_yanked_diagnostic()
         {
            let formatter = TableFormatter::new(|v| Some(v == "1.0.0" || v == "1.0.1"));

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

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

            let diagnostics = generate_diagnostics_from_cache(
                &parse_result,
                VersionData::new(&cached_versions, &resolved_versions),
                &formatter,
                crate::freshness::FreshnessSettings::default(),
                DiagnosticSeverities::default(),
                PublishTime::now(),
            );

            assert!(
                !diagnostics
                    .iter()
                    .any(|d| d.message.starts_with(formatter.yanked_message())),
                "a non-yanked match exists, so no yanked diagnostic should fire, got: {diagnostics:?}"
            );
        }

        /// M1 regression: an undecided candidate (`matcher.matches` returns `None`) must not
        /// be silently skipped — it might have been a genuine non-yanked match this scan
        /// could not evaluate, so it disqualifies a `true` verdict entirely.
        #[test]
        fn test_undecided_candidate_prevents_true_verdict() {
            let formatter = TableFormatter::new(|v| match v {
                "1.2.1" => Some(true),
                "unparseable" => None,
                _ => Some(false),
            });
            assert!(!requirement_matches_only_yanked(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["1.2.1", "unparseable"]),
                &versions(&["1.2.1"]),
            ));
        }

        /// Same scenario, but the undecided candidate is scanned before the yanked match —
        /// proves the early `return false` on a non-yanked match doesn't accidentally mask
        /// this case, and that the `saw_undecided` flag survives regardless of scan order.
        #[test]
        fn test_undecided_candidate_before_match_still_prevents_true_verdict() {
            let formatter = TableFormatter::new(|v| match v {
                "1.2.1" => Some(true),
                "unparseable" => None,
                _ => Some(false),
            });
            assert!(!requirement_matches_only_yanked(
                &formatter,
                &VersionReq::new("modelled"),
                &versions(&["unparseable", "1.2.1"]),
                &versions(&["1.2.1"]),
            ));
        }

        #[test]
        fn test_oversized_requirement_is_false_without_compiling() {
            let formatter =
                TableFormatter::new(|_v| panic!("must not compile/scan an oversized requirement"));
            let oversized = "1".repeat(MAX_REQUIREMENT_LEN + 1);
            assert!(!requirement_matches_only_yanked(
                &formatter,
                &VersionReq::new(oversized),
                &versions(&["1.0.0"]),
                &versions(&["1.0.0"]),
            ));
        }

        /// The yanked-only-match diagnostic must never fire for a non-registry-resolvable
        /// dependency source (path/git/URL/SDK/workspace) — the same guard
        /// `requirement_is_unsatisfiable` already has (see
        /// `test_generate_diagnostics_unsatisfiable_skipped_for_non_registry_sources`).
        #[test]
        fn test_yanked_only_match_skipped_for_non_registry_sources() {
            let formatter = TableFormatter::new(|v| Some(v == "1.2.1"));
            let uri = crate::test_util::test_uri("/test/Cargo.toml");

            let mut cached_versions = HashMap::new();
            cached_versions.insert(
                "dep".into(),
                PackageVersions {
                    latest: "2.0.0".to_string(),
                    available: Arc::from(vec!["2.0.0".to_string(), "1.2.1".to_string()]),
                    yanked: Arc::from(vec!["1.2.1".to_string()]),
                    published_at: None,
                },
            );
            let resolved_versions = HashMap::new();

            let dep = MockDep {
                name: "dep".into(),
                version_req: "modelled".into(),
                version_range: Range::new(Position::new(0, 10), Position::new(0, 20)),
                name_range: Range::new(Position::new(0, 0), Position::new(0, 3)),
            };
            let parse_result = SingleDepParseResult {
                dep: NonRegistryDep(
                    dep,
                    crate::parser::DependencySource::Path {
                        path: "../local".into(),
                    },
                ),
                uri,
            };

            let diagnostics = generate_diagnostics_from_cache(
                &parse_result,
                VersionData::new(&cached_versions, &resolved_versions),
                &formatter,
                crate::freshness::FreshnessSettings::default(),
                DiagnosticSeverities::default(),
                PublishTime::now(),
            );

            assert!(
                diagnostics
                    .iter()
                    .all(|d| !d.message.starts_with(formatter.yanked_message())),
                "a path dependency must never produce the yanked diagnostic, got: {diagnostics:?}"
            );
        }

        /// The `continue` after emitting the yanked diagnostic must suppress the sibling
        /// outdated check for the same dependency — proven directly rather than just
        /// inferred from `diagnostics.len() == 1` elsewhere in this module.
        #[test]
        fn test_yanked_only_match_suppresses_outdated_diagnostic() {
            let formatter = TableFormatter::new(|v| Some(v == "1.2.1"));

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

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

            let diagnostics = generate_diagnostics_from_cache(
                &parse_result,
                VersionData::new(&cached_versions, &resolved_versions),
                &formatter,
                crate::freshness::FreshnessSettings::default(),
                DiagnosticSeverities::default(),
                PublishTime::now(),
            );

            assert!(
                !diagnostics
                    .iter()
                    .any(|d| d.message.contains("Newer version available")),
                "the yanked diagnostic must suppress the outdated hint, not add to it, got: {diagnostics:?}"
            );
        }
    }
}