deps-engine 2.0.0

Composition root wiring deps-core's Ecosystem implementations for every driving adapter (deps-lsp, deps-cli, ...)
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
//! Vulnerability-scan target construction and fix-target-verification decision logic.
//!
//! Pure classification helpers extracted from `deps-lsp`'s `document/osv_scan.rs`: deciding
//! which dependencies to scan and how to resolve a recommended fix target's verification
//! status. The orchestration around these decisions — the phase-A/await/phase-B-commit shape,
//! the mid-flight staleness guard, and the `OsvClient` network calls themselves — stays in
//! `deps-lsp`'s `run_osv_scan_phase_a`/`run_osv_phase_b_and_commit`/
//! `run_osv_fix_target_verification`, since it owns a progress/staleness lifecycle this crate
//! must not know about (issue #1059).

use deps_core::ConcreteVersion;
use deps_core::EcosystemId;
use deps_core::PackageName;
use deps_core::lsp_helpers::{
    OsvNameAvailability, has_unqueryable_resolved_pin, resolve_in_use_versions,
};
use std::collections::HashMap;

/// Builds the OSV scan targets for one manifest's dependencies, applying the
/// version-selection policy from `architecture.md` §3 in order:
///
/// 0. Skip unless `formatter.source_is_public_registry_content(&dep.source())` — a patched
///    git/path fork must never be flagged with a CVE for a version it does
///    not actually contain, and neither must a genuinely different private registry's
///    dependency (only a verified crates.io mirror counts as public-registry content,
///    F1/F1b).
/// 1. Use the lock-file-resolved version if present.
/// 2. Otherwise use the declared requirement, if it is already concrete.
/// 3. Otherwise skip — querying a fabricated version is a silent false
///    negative, which is worse than not scanning at all.
///
/// **Go exception** (#228 follow-up, unified with #235's
/// [`deps_core::lsp_helpers::RequirementResolution::manifest_requirement_is_resolved_version`]):
/// step 1 is skipped entirely for a dependency whose manifest requirement is
/// itself the resolved version (a Go `require`-directive dependency), going
/// straight to step 2. Go's `go.mod` `require` line is already an exact
/// pinned version, never a range, unlike Cargo/npm where the manifest is a
/// range and the lockfile holds the pin. go.sum-derived `resolved_versions`
/// is unreliable here: go.sum is a checksum ledger that `go get`/`go build`
/// only ever append to (only `go mod tidy` prunes it), so its
/// last-occurrence-wins parse can surface a version still recorded in the
/// file but no longer selected by Go's MVS — silently querying OSV against
/// the wrong version. Routing through the formatter hook (rather than a bare
/// `ecosystem == EcosystemId::Go` check) also excludes Go's `exclude`/
/// `replace` directive pseudo-dependencies, whose `version_requirement()` is
/// not an in-use version.
///
/// Every dependency that does **not** become a [`deps_core::osv::ScanTarget`]
/// gets an explicit [`deps_core::osv::ScanOutcome::Skipped`] entry in the
/// returned map instead of silently vanishing (critique C1) — absence from
/// [`deps_core::osv::VulnerabilityMap`] must never happen for an input this
/// function considered.
///
/// Each dependency's map/target key comes from
/// [`deps_core::osv::vulnerability_keys`] rather than a bare
/// `formatter.normalize_package_name(dep.name())` (#394 S2): when two
/// occurrences of one name resolve to different in-use versions (or mix a
/// registry source with a git/path fork), their keys are disambiguated so
/// one occurrence's OSV result never overwrites another's in the shared
/// [`deps_core::osv::VulnerabilityMap`]. Occurrences that share both a name
/// and an identical in-use version keep the plain key and are scanned once —
/// a dedup, not a gap, since the OSV result would be identical either way.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{
///     DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
///     RequirementResolution, SourcePolicy,
/// };
/// use deps_core::test_util::stub_parse_result_with_dependencies;
/// use deps_core::{ConcreteVersion, EcosystemId, PackageName};
/// use deps_engine::classify::osv::build_scan_targets;
/// use std::collections::HashMap;
///
/// struct SimpleFormatter;
/// impl PackageNaming for SimpleFormatter {}
/// impl PackageRendering for SimpleFormatter {
///     fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
///         version.to_string()
///     }
///     fn package_url(&self, name: &PackageName) -> String {
///         name.as_str().to_string()
///     }
/// }
/// impl RequirementResolution for SimpleFormatter {}
/// impl DiagnosticMessages for SimpleFormatter {}
/// impl DiagnosticPolicy for SimpleFormatter {}
/// impl SourcePolicy for SimpleFormatter {}
/// impl OsvNaming for SimpleFormatter {}
///
/// // A single registry-sourced dependency ("dep-0"), with a lock-file-resolved version —
/// // step 1 of the ladder above.
/// let parsed = stub_parse_result_with_dependencies(1);
/// let mut resolved_versions = HashMap::new();
/// resolved_versions.insert(PackageName::new("dep-0"), ConcreteVersion::from("1.0.0"));
///
/// let (targets, skipped) = build_scan_targets(
///     parsed.as_ref(),
///     &resolved_versions,
///     &HashMap::new(),
///     &SimpleFormatter,
///     EcosystemId::Cargo,
/// );
///
/// assert_eq!(targets.len(), 1);
/// assert!(skipped.is_empty(), "the one dependency became a scan target, nothing to skip");
/// ```
pub fn build_scan_targets(
    parse_result: &dyn deps_core::ParseResult,
    resolved_versions: &HashMap<PackageName, ConcreteVersion>,
    resolved_version_candidates: &HashMap<PackageName, Vec<ConcreteVersion>>,
    formatter: &dyn deps_core::lsp_helpers::EcosystemFormatter,
    ecosystem: EcosystemId,
) -> (
    Vec<deps_core::osv::ScanTarget>,
    deps_core::osv::VulnerabilityMap,
) {
    use deps_core::osv::{OsvQueryName, ScanOutcome, SkipReason};
    use std::collections::hash_map::Entry;

    let mut targets: Vec<deps_core::osv::ScanTarget> = Vec::new();
    let mut target_index: HashMap<deps_core::osv::VulnKey, usize> = HashMap::new();
    let mut skipped = deps_core::osv::VulnerabilityMap::new();
    let keys = deps_core::osv::vulnerability_keys(
        parse_result,
        resolved_versions,
        Some(resolved_version_candidates),
        formatter,
        ecosystem,
    );

    for dep in parse_result.dependencies() {
        let normalized_name = formatter.normalize_package_name(dep.name());
        let key = deps_core::osv::vuln_key_for(dep, Some(&keys), formatter);

        if !formatter.source_is_public_registry_content(&dep.source()) {
            skipped.insert(key, ScanOutcome::Skipped(SkipReason::NonRegistrySource));
            continue;
        }

        // go.mod's `require` line, not go.sum, is authoritative for Go: go.sum is an
        // append-only ledger (only `go mod tidy` prunes it), so its last-occurrence-wins
        // parse can yield a stale, no-longer-selected version (see
        // `manifest_requirement_is_resolved_version`).
        let versions = resolve_in_use_versions(
            dep,
            &normalized_name,
            resolved_versions,
            Some(resolved_version_candidates),
            formatter,
            ecosystem,
        );

        let Some(versions) = versions else {
            let reason = if has_unqueryable_resolved_pin(dep, formatter, ecosystem) {
                SkipReason::ResolvedTagNotFullVersion
            } else {
                SkipReason::NoConcreteVersion
            };
            skipped.insert(key, ScanOutcome::Skipped(reason));
            continue;
        };

        let osv_name = match formatter.osv_name_availability(dep) {
            OsvNameAvailability::Ready => match formatter.osv_package_name(dep) {
                Some(name) => OsvQueryName::Confirmed(name),
                None => {
                    skipped.insert(key, ScanOutcome::Skipped(SkipReason::UnmappableName));
                    continue;
                }
            },
            OsvNameAvailability::AwaitingRegistryData {
                written_fallback: Some(name),
            } => OsvQueryName::Provisional(name),
            OsvNameAvailability::AwaitingRegistryData {
                written_fallback: None,
            } => {
                skipped.insert(
                    key,
                    ScanOutcome::Skipped(SkipReason::CanonicalNameUnconfirmed),
                );
                continue;
            }
        };

        let target = deps_core::osv::ScanTarget::from_native(
            key,
            osv_name,
            versions.primary().clone(),
            formatter,
        )
        .with_siblings(&versions, formatter);
        match target_index.entry(target.key.clone()) {
            Entry::Vacant(slot) => {
                slot.insert(targets.len());
                targets.push(target);
            }
            Entry::Occupied(slot) => {
                if let Some(existing) = targets.get_mut(*slot.get())
                    && matches!(existing.osv_name, OsvQueryName::Provisional(_))
                    && matches!(target.osv_name, OsvQueryName::Confirmed(_))
                {
                    *existing = target;
                }
            }
        }
    }

    (targets, skipped)
}
/// Outcome of classifying one dependency for [`build_latest_check_targets`]/
/// [`build_candidate_check_targets`]'s shared registry-source/cached-version/OSV-name gates
/// (code-review finding: the two functions used to duplicate this exact branch sequence, which
/// this PR's `StructuralSkipReason` retyping had to edit in lockstep in both copies).
enum DepCheckClassification<'a> {
    /// `formatter.source_is_public_registry_content` returned `false`.
    NonRegistrySource,
    /// No registry-cached version list yet for this dependency — absence, not a structural
    /// skip: a later commit populating `cached_versions` can still turn this into a real
    /// target (see both callers' own doc for why this must not be read as "not applicable").
    NoCachedVersions,
    /// A cached version list exists, but the OSV name still depends on registry data that has
    /// not landed (`OsvNameAvailability::AwaitingRegistryData`) — transient, never structural.
    AwaitingOsvName {
        /// This dependency's registry-cached version list.
        cached: &'a deps_core::lsp_helpers::PackageVersions,
    },
    /// A cached version list exists, but `formatter.osv_package_name` returned `None`.
    UnmappableName {
        /// This dependency's registry-cached version list, for a caller that still wants to
        /// report a real (if unmappable) candidate version.
        cached: &'a deps_core::lsp_helpers::PackageVersions,
    },
    /// A real, checkable target: the resolved OSV package name and this dependency's
    /// registry-cached version list.
    Target {
        /// `formatter.osv_package_name(dep)`'s resolved value.
        osv_name: deps_core::osv::OsvPackageName,
        /// This dependency's registry-cached version list.
        cached: &'a deps_core::lsp_helpers::PackageVersions,
    },
}

/// The shared classification steps behind [`DepCheckClassification`]'s variants — see that
/// type's doc.
fn classify_dep_for_check_targets<'a>(
    dep: &dyn deps_core::Dependency,
    cached_versions: &'a HashMap<PackageName, deps_core::lsp_helpers::PackageVersions>,
    formatter: &dyn deps_core::lsp_helpers::EcosystemFormatter,
) -> DepCheckClassification<'a> {
    if !formatter.source_is_public_registry_content(&dep.source()) {
        return DepCheckClassification::NonRegistrySource;
    }

    let normalized_name = formatter.normalize_package_name(dep.name());
    let Some(cached) = cached_versions
        .get(normalized_name.as_str())
        .or_else(|| cached_versions.get(dep.name()))
    else {
        return DepCheckClassification::NoCachedVersions;
    };

    if matches!(
        formatter.osv_name_availability(dep),
        OsvNameAvailability::AwaitingRegistryData { .. }
    ) {
        return DepCheckClassification::AwaitingOsvName { cached };
    }

    match formatter.osv_package_name(dep) {
        Some(osv_name) => DepCheckClassification::Target { osv_name, cached },
        None => DepCheckClassification::UnmappableName { cached },
    }
}

/// Builds phase B.1's latest-check targets for **every** dependency with a registry-cached
/// latest (issue #1517).
///
/// Not just ones phase A already flagged [`deps_core::osv::ScanOutcome::Vulnerable`] at their
/// pinned version — closes the gap that let a cleanly-pinned dependency's malicious/vulnerable
/// `latest` go completely unchecked while every renderer (hover, diagnostics, code actions,
/// code lens, inlay hints, completion) and `deps-cli update`'s default mode still recommended
/// it as a safe upgrade.
///
/// `osv_name` comes from `formatter.osv_package_name(dep)` directly, not from phase A's
/// `osv_name_by_key` — that map only has entries for dependencies phase A actually built a
/// [`deps_core::osv::ScanTarget`] for, which excludes any dependency phase A skipped for
/// [`deps_core::osv::SkipReason::NoConcreteVersion`] (e.g. a `^1.0.4` requirement with no
/// committed lock file) — such a dependency still has a resolvable registry `latest` and must
/// still have it checked.
///
/// Every dependency considered gets either a [`deps_core::osv::ScanTarget`] in the returned
/// `Vec` or an explicit structural entry in the returned [`deps_core::osv::LatestStatusMap`] —
/// never silently neither, mirroring [`build_scan_targets`]'s own invariant 0 discipline
/// (absence must never be read as "clean" or "not applicable"). A dependency with no
/// registry-cached `latest` at all (the fetch hasn't completed, or the registry doesn't know
/// the package) gets neither: it isn't a structural gap, since a later commit populating
/// `cached_versions` can turn it into a real target — the map's absence there falls through to
/// [`deps_core::lsp_helpers::LatestVerdict::Unverified`] (fail-closed), not
/// [`deps_core::lsp_helpers::LatestVerdict::NotApplicable`].
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{
///     DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
///     PackageVersions, RequirementResolution, SourcePolicy,
/// };
/// use deps_core::osv::{UpgradeStatus, vulnerability_keys};
/// use deps_core::test_util::stub_parse_result_with_dependencies;
/// use deps_core::{ConcreteVersion, EcosystemId, PackageName};
/// use deps_engine::classify::osv::build_latest_check_targets;
/// use std::collections::HashMap;
///
/// struct SimpleFormatter;
/// impl PackageNaming for SimpleFormatter {}
/// impl PackageRendering for SimpleFormatter {
///     fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
///         version.to_string()
///     }
///     fn package_url(&self, name: &PackageName) -> String {
///         name.as_str().to_string()
///     }
/// }
/// impl RequirementResolution for SimpleFormatter {}
/// impl DiagnosticMessages for SimpleFormatter {}
/// impl DiagnosticPolicy for SimpleFormatter {}
/// impl SourcePolicy for SimpleFormatter {}
/// impl OsvNaming for SimpleFormatter {}
///
/// let parsed = stub_parse_result_with_dependencies(1);
/// let mut cached_versions = HashMap::new();
/// cached_versions.insert(
///     PackageName::new("dep-0"),
///     PackageVersions::latest_only("2.0.0"),
/// );
/// let vuln_keys = vulnerability_keys(
///     parsed.as_ref(),
///     &HashMap::new(),
///     None,
///     &SimpleFormatter,
///     EcosystemId::Cargo,
/// );
///
/// let (targets, structural) = build_latest_check_targets(
///     parsed.as_ref(),
///     &cached_versions,
///     &vuln_keys,
///     &SimpleFormatter,
/// );
///
/// assert_eq!(targets.len(), 1);
/// assert_eq!(targets[0].display_version, "2.0.0");
/// assert!(structural.is_empty(), "the one dependency became a real target, nothing structural");
/// ```
pub fn build_latest_check_targets(
    parse_result: &dyn deps_core::ParseResult,
    cached_versions: &HashMap<PackageName, deps_core::lsp_helpers::PackageVersions>,
    vuln_keys: &deps_core::osv::VulnKeys,
    formatter: &dyn deps_core::lsp_helpers::EcosystemFormatter,
) -> (
    Vec<deps_core::osv::ScanTarget>,
    deps_core::osv::LatestStatusMap,
) {
    use deps_core::osv::{SkipReason, StructuralSkipReason, UpgradeStatus, vuln_key_for};

    // TODO(#1727): candidate-side checks do not evaluate sibling release tags of the candidate.
    let mut targets = Vec::new();
    let mut structural = deps_core::osv::LatestStatusMap::new();
    let mut seen = std::collections::HashSet::new();

    for dep in parse_result.dependencies() {
        let key = vuln_key_for(dep, Some(vuln_keys), formatter);

        match classify_dep_for_check_targets(dep, cached_versions, formatter) {
            DepCheckClassification::NonRegistrySource => {
                structural.insert(
                    key,
                    UpgradeStatus::StructurallyUnchecked(StructuralSkipReason::NonRegistrySource),
                );
            }
            // No registry-cached latest yet — absence, not a structural skip (see doc above).
            DepCheckClassification::NoCachedVersions => {}
            DepCheckClassification::AwaitingOsvName { cached } => {
                structural.insert(
                    key,
                    UpgradeStatus::CandidateUnverified {
                        version: cached.latest.clone(),
                        reason: SkipReason::CanonicalNameUnconfirmed,
                    },
                );
            }
            DepCheckClassification::UnmappableName { cached } => {
                structural.insert(
                    key,
                    UpgradeStatus::CandidateUnverified {
                        version: cached.latest.clone(),
                        reason: SkipReason::UnmappableName,
                    },
                );
            }
            DepCheckClassification::Target { osv_name, cached } => {
                // Occurrences sharing a key share one result (see `build_scan_targets`).
                if !seen.insert(key.clone()) {
                    continue;
                }
                targets.push(deps_core::osv::ScanTarget::from_native(
                    key,
                    deps_core::osv::OsvQueryName::Confirmed(osv_name),
                    cached.latest.clone(),
                    formatter,
                ));
            }
        }
    }

    (targets, structural)
}

/// Bounds how many candidate versions per dependency [`build_candidate_check_targets`] checks
/// (#1524) — code actions/completion display at most a handful of "update to X" items per
/// dependency, so checking a small superset of that is enough to cover what a
/// candidate-offering surface could actually display, without unbounded OSV traffic for a
/// dependency with hundreds of published versions.
const MAX_CANDIDATE_CHECK_VERSIONS: usize = 6;

/// Builds phase B's candidate-check targets for #1524.
///
/// Organized into up to `MAX_CANDIDATE_CHECK_VERSIONS` "rounds": round `r`'s
/// `Vec<ScanTarget>` holds, for every dependency that has one, its `r`-th newest non-yanked
/// registry version (rank 0 = newest). Callers batch-check one round at a time via
/// [`deps_core::osv::OsvClient::check_candidates`]
/// — at most one target per [`deps_core::osv::VulnKey`] per round, so a single call never
/// collapses two of one dependency's own candidates into one result — and merge each round's
/// [`deps_core::osv::LatestStatusMap`]-shaped result into a
/// [`deps_core::osv::CandidateStatusMap`] keyed by the version each round actually checked.
///
/// Shares [`build_latest_check_targets`]'s structural-skip classification via
/// `classify_dep_for_check_targets` (non-public-registry source, unmappable OSV name) — recorded
/// once per dependency in the returned `structural` map as
/// [`deps_core::osv::CandidateStatuses::Structural`] (see that type's doc), never duplicated per
/// round.
///
/// Selection is deliberately simpler than
/// [`deps_core::completion::prepare_version_display_items`]'s exact display-item algorithm
/// (which needs the full `dyn Version` registry response this background task never has
/// cached, only the bare [`ConcreteVersion`] list [`deps_core::lsp_helpers::PackageVersions`]
/// carries): the newest `MAX_CANDIDATE_CHECK_VERSIONS` non-yanked entries from
/// [`deps_core::lsp_helpers::PackageVersions::available`], newest-first. A display item this
/// selection doesn't happen to cover (rare: `prepare_version_display_items`'s own "bump the
/// latest pick in" `#956` behavior) simply reads as
/// [`deps_core::lsp_helpers::LatestVerdict::Unverified`] and is excluded — over-conservative,
/// never under-conservative.
pub fn build_candidate_check_targets(
    parse_result: &dyn deps_core::ParseResult,
    cached_versions: &HashMap<PackageName, deps_core::lsp_helpers::PackageVersions>,
    vuln_keys: &deps_core::osv::VulnKeys,
    formatter: &dyn deps_core::lsp_helpers::EcosystemFormatter,
) -> (
    Vec<Vec<deps_core::osv::ScanTarget>>,
    deps_core::osv::CandidateStatusMap,
) {
    use deps_core::osv::{CandidateStatuses, StructuralSkipReason, vuln_key_for};

    let mut rounds: Vec<Vec<deps_core::osv::ScanTarget>> =
        vec![Vec::new(); MAX_CANDIDATE_CHECK_VERSIONS];
    let mut structural = deps_core::osv::CandidateStatusMap::new();
    let mut seen = std::collections::HashSet::new();

    for dep in parse_result.dependencies() {
        let key = vuln_key_for(dep, Some(vuln_keys), formatter);

        let (osv_name, package_versions) =
            match classify_dep_for_check_targets(dep, cached_versions, formatter) {
                DepCheckClassification::NonRegistrySource => {
                    structural.insert(
                        key,
                        CandidateStatuses::Structural(StructuralSkipReason::NonRegistrySource),
                    );
                    continue;
                }
                // No registry-cached version list yet — absence, not a structural skip (see
                // doc above), matching `build_latest_check_targets`'s identical treatment.
                DepCheckClassification::NoCachedVersions => continue,
                // Transient, like an absent cache: never recorded as structural.
                DepCheckClassification::AwaitingOsvName { .. } => continue,
                DepCheckClassification::UnmappableName { .. } => {
                    structural.insert(
                        key,
                        CandidateStatuses::Structural(StructuralSkipReason::UnmappableName),
                    );
                    continue;
                }
                DepCheckClassification::Target { osv_name, cached } => (osv_name, cached),
            };

        if !seen.insert(key.clone()) {
            continue;
        }

        let yanked: std::collections::HashSet<&ConcreteVersion> = package_versions
            .yanked
            .iter()
            .map(|(version, _)| version)
            .collect();

        for (rank, version) in package_versions
            .available
            .iter()
            .filter(|v| !yanked.contains(v))
            .take(MAX_CANDIDATE_CHECK_VERSIONS)
            .enumerate()
        {
            // `rank` is in `0..MAX_CANDIDATE_CHECK_VERSIONS` by construction (bounded by the
            // `take` above), matching `rounds`' own length — but a bare index would still
            // panic if that invariant were ever broken, so this fails closed instead.
            let Some(bucket) = rounds.get_mut(rank) else {
                continue;
            };
            bucket.push(deps_core::osv::ScanTarget::from_native(
                key.clone(),
                deps_core::osv::OsvQueryName::Confirmed(osv_name.clone()),
                version.clone(),
                formatter,
            ));
        }
    }

    (rounds, structural)
}

/// Outcome of `resolve_fix_target` for one vulnerable dependency.
#[derive(Debug, PartialEq, Eq)]
enum FixTargetResolution {
    /// No fix recommended, F failed [`deps_core::lsp_helpers::is_safe_version_string`], or no
    /// `osv_name` is on record for this key, or that name is only provisional (#1694) — nothing to
    /// verify or record; `fix_target_status`
    /// stays untouched (left at `NotChecked`).
    Skip,
    /// F's status was resolved without a network call by reusing the already-checked
    /// "latest" candidate's result (FR-002, F == latest).
    Resolved(deps_core::osv::UpgradeStatus),
    /// F differs from latest and needs a live [`deps_core::osv::OsvClient::check_candidates`]
    /// check — carries the [`deps_core::osv::ScanTarget`] to batch into the caller's single
    /// combined call (NFR-001). Keyed with the dependency's plain [`deps_core::osv::VulnKey`]:
    /// this candidate is always checked via a *separate* `check_candidates` call from the "B.1
    /// latest" candidates, so its result `HashMap` never shares a key space with the phase-A
    /// `VulnerabilityMap` — no suffix is needed to disambiguate.
    NeedsLiveCheck(deps_core::osv::ScanTarget),
}
/// Pure (network-free) decision logic for `run_osv_fix_target_verification`'s per-dependency
/// resolution order — see that function's doc for the two cases and their rationale. Split
/// out so each case is unit-testable without an `OsvClient`/network dependency.
fn resolve_fix_target(
    dv: &deps_core::osv::DependencyVulnerabilities,
    key: &deps_core::osv::VulnKey,
    latest_status: &deps_core::osv::LatestStatusMap,
    osv_name_by_key: &HashMap<deps_core::osv::VulnKey, deps_core::osv::OsvQueryName>,
    formatter: &dyn deps_core::lsp_helpers::EcosystemFormatter,
) -> FixTargetResolution {
    use deps_core::edit::{VulnFixSkip, resolve_recommended_fix};
    use deps_core::osv::{OsvQueryName, ScanTarget, UpgradeStatus};

    let latest = latest_status.get(key);

    // #1350: `resolve_recommended_fix` is the shared prefix (`recommended_fix` ->
    // `osv_version_to_native` -> `is_safe_version_string`) this function used to duplicate.
    // Deliberately the *unverified* helper, not `resolve_verified_fix`: this function is
    // itself the producer of `dv.fix_target_status`, so it must not gate on a status it
    // has not computed yet.
    let (fix, version_native) = match resolve_recommended_fix(dv, latest, formatter) {
        Ok(pair) => pair,
        Err(VulnFixSkip::NoRecommendedFix) => return FixTargetResolution::Skip,
        // `resolve_recommended_fix` already emits a WARN via `warn_rejected_value` for this
        // case (M1: consistent with every other unsafe-value rejection gate in this codebase,
        // not the accidental DEBUG this call site used before #1350) — this DEBUG line adds
        // only the batch-scan `key` that generic warning doesn't carry.
        Err(VulnFixSkip::UnsafeVersion) => {
            tracing::debug!(
                key = %key,
                "OSV #462: fix-target version failed validation, skipping verification"
            );
            return FixTargetResolution::Skip;
        }
        // `resolve_recommended_fix` can only ever return `NoRecommendedFix`/`UnsafeVersion` —
        // these five variants exist only for `plan_vulnerability_fix`'s later,
        // `resolve_verified_fix`-based decision. Handled explicitly rather than folded into a
        // wildcard (code review finding) so a future `VulnFixSkip` variant, or a change that
        // starts surfacing one of these here, is a compile error instead of silently
        // degrading to `Skip` — the same bug class `EcosystemId`'s exhaustive-match
        // convention exists to catch project-wide.
        Err(
            VulnFixSkip::UnverifiedTarget
            | VulnFixSkip::RequirementAlreadyResolves
            | VulnFixSkip::NoOpRewrite
            | VulnFixSkip::UnresolvedPlaceholder
            | VulnFixSkip::OversizedRequirement,
        ) => return FixTargetResolution::Skip,
    };

    // Issue #1517: only a *resolved* latest verdict (`CandidateClean`/`CandidateVulnerable`)
    // can be reused — `NotChecked`/`CandidateUnverified` (transient failure, structural skip,
    // or simply never checked) must always fall through to a live check below, never be
    // silently treated as "F already covered by the latest check".
    let reused_latest_version: Option<&str> = match latest {
        Some(
            UpgradeStatus::CandidateClean { version }
            | UpgradeStatus::CandidateVulnerable { version, .. },
        ) => Some(version.as_str()),
        // `UpgradeStatus` is `#[non_exhaustive]` across the crate boundary: the wildcard is
        // required by the compiler, not a stylistic shortcut — every variant defined *today*
        // (`NotChecked`, `CandidateUnverified`) is still handled by the fall-through-to-`None`
        // (never-reuse) behavior, matching this project's `EcosystemId`-style exhaustive-match
        // convention as closely as a foreign `#[non_exhaustive]` type allows.
        Some(_) | None => None,
    };
    if reused_latest_version == Some(version_native.as_str()) {
        return FixTargetResolution::Resolved(latest.cloned().unwrap_or(UpgradeStatus::NotChecked));
    }

    let Some(osv_name) = osv_name_by_key.get(key) else {
        tracing::debug!(
            key = %key,
            "OSV #462: no osv_name on record for fix-target verification, skipping"
        );
        return FixTargetResolution::Skip;
    };
    let osv_name = match osv_name {
        OsvQueryName::Confirmed(name) => name.clone(),
        OsvQueryName::Provisional(_) => {
            tracing::debug!(
                key = %key,
                "OSV #1694: unconfirmed package name, fix target stays unverified"
            );
            return FixTargetResolution::Skip;
        }
    };
    FixTargetResolution::NeedsLiveCheck(ScanTarget::new(
        key.clone(),
        OsvQueryName::Confirmed(osv_name),
        fix.version,
        ConcreteVersion::new(version_native),
    ))
}
/// Pure aggregation step of `run_osv_fix_target_verification`: resolves every vulnerable
/// dependency's fix target via `resolve_fix_target`.
///
/// Splits immediately-resolvable results (`resolved`) from the ones that need a live check
/// (`live_check_candidates`) — the latter collected into one `Vec` across *every* dependency
/// before the caller's single `check_candidates` call, so multiple dependencies needing a live
/// check always batch into one network round-trip rather than one per dependency (NFR-001).
/// Split out from the async orchestrator specifically so this batching/aggregation behavior is
/// unit-testable without an `OsvClient`.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{
///     DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
///     RequirementResolution, SourcePolicy,
/// };
/// use deps_core::osv::{
///     Advisory, Capped, DependencyVulnerabilities, OsvVersion, ScanOutcome, UpgradeStatus,
///     VulnSeverity, VulnerabilityMap,
/// };
/// use deps_core::test_util::vuln_key;
/// use deps_core::{ConcreteVersion, PackageName};
/// use deps_engine::classify::osv::collect_fix_target_resolutions;
/// use std::collections::HashMap;
/// use std::sync::Arc;
///
/// struct SimpleFormatter;
/// impl PackageNaming for SimpleFormatter {}
/// impl PackageRendering for SimpleFormatter {
///     fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
///         version.to_string()
///     }
///     fn package_url(&self, name: &PackageName) -> String {
///         name.as_str().to_string()
///     }
/// }
/// impl RequirementResolution for SimpleFormatter {}
/// impl DiagnosticMessages for SimpleFormatter {}
/// impl DiagnosticPolicy for SimpleFormatter {}
/// impl SourcePolicy for SimpleFormatter {}
/// impl OsvNaming for SimpleFormatter {}
///
/// let advisory = Arc::new(
///     Advisory::new(
///         "RUSTSEC-2024-0001".to_string(),
///         "2024-01-01T00:00:00Z".to_string(),
///         VulnSeverity::High,
///     )
///     .expect("valid osv id")
///     .with_fixed_versions(vec![OsvVersion::new("1.2.0")]),
/// );
/// let latest_status = UpgradeStatus::CandidateClean {
///     version: ConcreteVersion::new("1.2.0"),
/// };
/// let dv = DependencyVulnerabilities::new(Capped::new(vec![advisory], 1));
///
/// let mut vulnerabilities = VulnerabilityMap::new();
/// vulnerabilities.insert(vuln_key("pkg"), ScanOutcome::Vulnerable(dv));
///
/// let mut latest_status_map = HashMap::new();
/// latest_status_map.insert(vuln_key("pkg"), latest_status.clone());
///
/// // F (the fix, 1.2.0) equals the already-checked "latest" candidate — resolved without a
/// // live network check.
/// let (resolved, live_check_candidates) = collect_fix_target_resolutions(
///     &vulnerabilities,
///     &[vuln_key("pkg")],
///     &HashMap::new(),
///     &latest_status_map,
///     &SimpleFormatter,
/// );
///
/// assert_eq!(resolved, vec![(vuln_key("pkg"), latest_status)]);
/// assert!(live_check_candidates.is_empty());
/// ```
pub fn collect_fix_target_resolutions(
    vulnerabilities: &deps_core::osv::VulnerabilityMap,
    vulnerable_keys: &[deps_core::osv::VulnKey],
    osv_name_by_key: &HashMap<deps_core::osv::VulnKey, deps_core::osv::OsvQueryName>,
    latest_status: &deps_core::osv::LatestStatusMap,
    formatter: &dyn deps_core::lsp_helpers::EcosystemFormatter,
) -> (
    Vec<(deps_core::osv::VulnKey, deps_core::osv::UpgradeStatus)>,
    Vec<deps_core::osv::ScanTarget>,
) {
    use deps_core::osv::ScanOutcome;

    let mut resolved = Vec::new();
    let mut live_check_candidates = Vec::new();

    for key in vulnerable_keys {
        let Some(ScanOutcome::Vulnerable(dv)) = vulnerabilities.get(key) else {
            continue;
        };
        match resolve_fix_target(dv, key, latest_status, osv_name_by_key, formatter) {
            FixTargetResolution::Skip => {}
            FixTargetResolution::Resolved(status) => resolved.push((key.clone(), status)),
            FixTargetResolution::NeedsLiveCheck(target) => live_check_candidates.push(target),
        }
    }

    (resolved, live_check_candidates)
}
/// Applies a live [`deps_core::osv::OsvClient::check_candidates`] result back onto the matching
/// dependency's `fix_target_status`.
///
/// Keyed by the same plain [`deps_core::osv::VulnKey`] the vulnerable dependency was scanned
/// under.
///
/// A key absent from `statuses` (timeout, OSV outage, or a chunk `check_candidates` itself
/// dropped) simply leaves that dependency's `fix_target_status` untouched — still
/// `NotChecked` if it was never set, which is exactly the fail-closed degradation
/// FR-004/NFR-002 call for (never a panic, never a fabricated "verified" status).
///
/// # Examples
///
/// ```
/// use deps_core::osv::{
///     Advisory, Capped, DependencyVulnerabilities, ScanOutcome, UpgradeStatus, VulnSeverity,
///     VulnerabilityMap,
/// };
/// use deps_core::test_util::vuln_key;
/// use deps_core::ConcreteVersion;
/// use deps_engine::classify::osv::apply_live_fix_target_statuses;
/// use std::collections::HashMap;
/// use std::sync::Arc;
///
/// let advisory = Arc::new(
///     Advisory::new(
///         "RUSTSEC-2024-0001".to_string(),
///         "2024-01-01T00:00:00Z".to_string(),
///         VulnSeverity::High,
///     )
///     .expect("valid osv id"),
/// );
/// let dv = DependencyVulnerabilities::new(Capped::new(vec![advisory], 1));
///
/// let mut vulnerabilities = VulnerabilityMap::new();
/// vulnerabilities.insert(vuln_key("pkg"), ScanOutcome::Vulnerable(dv));
///
/// let mut statuses = HashMap::new();
/// statuses.insert(
///     vuln_key("pkg"),
///     UpgradeStatus::CandidateClean {
///         version: ConcreteVersion::new("1.2.0"),
///     },
/// );
///
/// apply_live_fix_target_statuses(&mut vulnerabilities, statuses);
///
/// let ScanOutcome::Vulnerable(dv) = vulnerabilities.get(&vuln_key("pkg")).unwrap() else {
///     unreachable!()
/// };
/// assert_eq!(
///     dv.fix_target_status,
///     UpgradeStatus::CandidateClean {
///         version: ConcreteVersion::new("1.2.0")
///     }
/// );
/// ```
pub fn apply_live_fix_target_statuses(
    vulnerabilities: &mut deps_core::osv::VulnerabilityMap,
    statuses: HashMap<deps_core::osv::VulnKey, deps_core::osv::UpgradeStatus>,
) {
    use deps_core::osv::ScanOutcome;

    for (key, status) in statuses {
        if let Some(ScanOutcome::Vulnerable(dv)) = vulnerabilities.get_mut(&key) {
            dv.fix_target_status = status;
        }
    }
}

/// Projects `targets` down to `key -> osv_name`.
///
/// A two-line helper centralizing an identical inline `HashMap` build `deps-lsp` used to
/// duplicate at `document/osv_scan.rs:116` and `deps-cli`'s `--security-only` planner (#1329)
/// needs too — both consume this instead of re-deriving it from [`build_scan_targets`]'s own
/// `Vec<deps_core::osv::ScanTarget>` output.
///
/// # Examples
///
/// ```
/// use deps_core::ConcreteVersion;
/// use deps_core::osv::{OsvPackageName, OsvQueryName, OsvVersion, ScanTarget};
/// use deps_core::test_util::vuln_key;
/// use deps_engine::classify::osv::osv_name_by_key;
///
/// let name = OsvQueryName::Confirmed(OsvPackageName::new("serde").unwrap());
/// let targets = vec![ScanTarget::new(
///     vuln_key("serde"),
///     name.clone(),
///     OsvVersion::new("1.0.0"),
///     ConcreteVersion::new("1.0.0"),
/// )];
/// let map = osv_name_by_key(&targets);
/// assert_eq!(map.get(&vuln_key("serde")), Some(&name));
/// ```
#[must_use]
pub fn osv_name_by_key(
    targets: &[deps_core::osv::ScanTarget],
) -> HashMap<deps_core::osv::VulnKey, deps_core::osv::OsvQueryName> {
    targets
        .iter()
        .map(|t| (t.key.clone(), t.osv_name.clone()))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::classify::resolved::collect_in_use_versions;
    use deps_core::VersionReq;
    use std::assert_matches;

    mod osv_scan_target_tests {
        use super::*;
        use deps_core::Dependency;
        use deps_core::lsp_helpers::{
            DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
            RequirementResolution, SourcePolicy,
        };
        use deps_core::parser::DependencySource;
        use deps_core::position::{Position, Range};
        use deps_core::test_util::StubFormatter;
        use std::any::Any;

        struct MockDep {
            name: PackageName,
            version_req: Option<VersionReq>,
            source: DependencySource,
        }

        impl Dependency for MockDep {
            fn name(&self) -> &PackageName {
                &self.name
            }
            fn name_range(&self) -> Range {
                // Distinct per instance: `vulnerability_keys` (#394 S2) keys a
                // `HashMap<Range, String>` by `name_range()` — a fixed range would
                // make every `MockDep` collide on one map entry.
                let addr = std::ptr::from_ref(self) as u32;
                Range::new(Position::new(0, addr), Position::new(0, addr + 1))
            }
            fn version_requirement(&self) -> Option<&VersionReq> {
                self.version_req.as_ref()
            }
            fn version_range(&self) -> Option<Range> {
                None
            }
            fn source(&self) -> DependencySource {
                self.source.clone()
            }
            fn as_any(&self) -> &dyn Any {
                self
            }
        }

        struct MockParseResult {
            deps: Vec<MockDep>,
        }

        impl deps_core::ParseResult for MockParseResult {
            fn dependencies(&self) -> Vec<&dyn Dependency> {
                self.deps.iter().map(|d| d as &dyn Dependency).collect()
            }
            fn workspace_root(&self) -> Option<&std::path::Path> {
                None
            }
            fn uri(&self) -> &url::Url {
                static URI: std::sync::OnceLock<url::Url> = std::sync::OnceLock::new();
                URI.get_or_init(|| deps_core::test_util::test_uri("/test/Cargo.toml"))
            }
            fn as_any(&self) -> &dyn Any {
                self
            }
        }

        use deps_core::osv::{ScanOutcome, SkipReason};

        // `is_concrete_version`/`concrete_pin_version` unit tests moved to
        // `deps-core`'s `lsp_helpers::in_use_version` module alongside the
        // functions themselves (#394).

        #[test]
        fn build_scan_targets_step0_skips_non_registry_source_even_with_lockfile_version() {
            // A git/path/patched fork must never be flagged with a CVE for a
            // version it does not actually contain, even when its lockfile
            // entry carries a plausible-looking version (critique C2).
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("time"),
                    version_req: Some(VersionReq::new("0.1.43")),
                    source: DependencySource::Git {
                        url: "https://github.com/example/time".to_string(),
                        rev: None,
                    },
                }],
            };
            let mut resolved = HashMap::new();
            resolved.insert(PackageName::new("time"), "0.1.43".into());

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Cargo,
            );
            assert!(targets.is_empty());
            assert_matches!(
                skipped.get(&deps_core::test_util::vuln_key("time")),
                Some(ScanOutcome::Skipped(SkipReason::NonRegistrySource))
            );
        }

        #[test]
        fn build_scan_targets_step1_prefers_lockfile_resolved_version() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("serde"),
                    version_req: Some(VersionReq::new("^1.0")),
                    source: DependencySource::Registry,
                }],
            };
            let mut resolved = HashMap::new();
            resolved.insert(PackageName::new("serde"), "1.0.195".into());

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Cargo,
            );
            assert_eq!(targets.len(), 1);
            assert_eq!(targets[0].version, "1.0.195");
            assert!(skipped.is_empty());
        }

        /// Formatter stub mirroring `GoFormatter`'s override: every
        /// dependency's manifest requirement is itself the resolved version
        /// (#235's `manifest_requirement_is_resolved_version` unification).
        const MOCK_GO_FORMATTER: StubFormatter = StubFormatter::new()
            .with_package_url_prefix("https://pkg.go.dev/")
            .with_manifest_requirement_as_resolved_version();

        struct MockVPrefixFormatter;
        impl PackageNaming for MockVPrefixFormatter {}

        impl PackageRendering for MockVPrefixFormatter {
            fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
                version.to_string()
            }

            fn package_url(&self, name: &PackageName) -> String {
                format!("https://example.com/{}", name.as_str())
            }
        }

        impl RequirementResolution for MockVPrefixFormatter {}

        impl DiagnosticMessages for MockVPrefixFormatter {}

        impl DiagnosticPolicy for MockVPrefixFormatter {}

        impl SourcePolicy for MockVPrefixFormatter {}

        impl OsvNaming for MockVPrefixFormatter {
            fn osv_version(&self, version: &ConcreteVersion) -> deps_core::osv::OsvVersion {
                let version = version.as_str();
                deps_core::osv::OsvVersion::new(version.strip_prefix('v').unwrap_or(version))
            }
        }

        #[test]
        fn build_scan_targets_normalizes_version_via_formatter_osv_version_hook() {
            // Go's mandatory "v" prefix isn't valid OSV SEMVER (#228) — must route through
            // the formatter hook rather than sending the native spelling on the wire.
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("github.com/gin-gonic/gin"),
                    version_req: Some(VersionReq::new("v1.9.0")),
                    source: DependencySource::Registry,
                }],
            };
            let mut resolved = HashMap::new();
            resolved.insert(
                PackageName::new("github.com/gin-gonic/gin"),
                "v1.9.0".into(),
            );

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &MockVPrefixFormatter,
                EcosystemId::Go,
            );
            assert_eq!(targets.len(), 1);
            assert_eq!(targets[0].version, "1.9.0");
            // display_version keeps the ecosystem-native "v" spelling (S1
            // regression guard) — only the wire-format `version` is stripped.
            assert_eq!(targets[0].display_version, "v1.9.0");
            assert!(skipped.is_empty());
        }

        #[test]
        fn build_scan_targets_leaves_version_unaffected_for_default_identity_formatter() {
            // Regression guard: ecosystems that do not override osv_version
            // must keep sending the native spelling verbatim (no regression
            // from introducing the hook).
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("serde"),
                    version_req: Some(VersionReq::new("^1.0")),
                    source: DependencySource::Registry,
                }],
            };
            let mut resolved = HashMap::new();
            resolved.insert(PackageName::new("serde"), "1.0.195".into());

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Cargo,
            );
            assert_eq!(targets.len(), 1);
            assert_eq!(targets[0].version, "1.0.195");
            assert_eq!(targets[0].display_version, "1.0.195");
            assert!(skipped.is_empty());
        }

        #[test]
        fn build_scan_targets_go_ignores_stale_lockfile_version_uses_go_mod_requirement() {
            // go.sum is append-only (only `go mod tidy` prunes it) and sorted ascending by
            // semver, so a stale higher version from before a downgrade can sort last and
            // win last-occurrence-wins parsing. go.mod's `require` line is already an exact
            // pin, so for Go the manifest — not lockfile-derived `resolved_versions` — must
            // be authoritative for OSV scanning.
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("github.com/pkg/errors"),
                    version_req: Some(VersionReq::new("v0.8.1")),
                    source: DependencySource::Registry,
                }],
            };
            let mut resolved = HashMap::new();
            // Stale entry: go.sum still records v0.9.1 from before a
            // downgrade back to v0.8.1 that only `go get` (not `go mod
            // tidy`) performed.
            resolved.insert(PackageName::new("github.com/pkg/errors"), "v0.9.1".into());

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &MOCK_GO_FORMATTER,
                EcosystemId::Go,
            );
            assert_eq!(targets.len(), 1);
            // `.version` (the wire-format value) goes through `formatter.osv_version`,
            // whose shared default (`deps-core`) strips a leading `v`/`V` — `MOCK_GO_FORMATTER`
            // doesn't override it, unlike the real `GoFormatter`. `.display_version` is the
            // raw, untransformed value this test is actually about (manifest vs. lockfile
            // authority), so it keeps the native "v" spelling.
            assert_eq!(targets[0].version, "0.8.1");
            assert_eq!(targets[0].display_version, "v0.8.1");
            assert!(skipped.is_empty());
        }

        /// #667 follow-up (impl-critic): before this reclassification, a Deno `jsr:`
        /// dependency's bare requirement always failed the version gate under
        /// `AlwaysRange` (`resolve_in_use_version` always `None`), so `DenoFormatter::
        /// osv_package_name`'s `_ => None` arm for `jsr:` never actually ran in a live
        /// scan. Now that Deno is `ConcreteIfFullVersion`, a bare-full-version-pinned
        /// `jsr:` dependency passes the version gate and correctness rests entirely on
        /// that match arm — this exercises it end-to-end through the real
        /// `DenoFormatter`, not just `osv_package_name`'s own unit test in isolation.
        #[cfg(feature = "deno")]
        #[test]
        fn build_scan_targets_deno_bare_pinned_jsr_dep_is_unmappable_name_skip() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("jsr:@std/fs"),
                    version_req: Some(VersionReq::new("1.0.0")),
                    source: DependencySource::Registry,
                }],
            };

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &HashMap::new(),
                &HashMap::new(),
                &deps_deno::DenoFormatter,
                EcosystemId::Deno,
            );

            assert!(targets.is_empty(), "jsr: dep must never reach an OSV query");
            assert_eq!(skipped.len(), 1);
            // Key is the full scheme-qualified name: `DenoFormatter` doesn't override
            // `normalize_package_name`, unlike `osv_package_name` (which strips the
            // scheme only for `npm:` and returns `None` for everything else).
            assert_matches!(
                skipped.get(&deps_core::test_util::vuln_key("jsr:@std/fs")),
                Some(ScanOutcome::Skipped(SkipReason::UnmappableName))
            );
        }

        /// #1545: `ComposerFormatter::osv_package_name`'s lowercase override had an
        /// incorrect `#[cfg(feature = "lsp-responses")]` gate, so a `deps-cli` build
        /// (which never enables `lsp-responses`) silently fell back to `OsvNaming`'s
        /// identity default and sent Packagist's mixed-case spelling to OSV.dev's
        /// case-sensitive API. Exercises the real `ComposerFormatter` end-to-end (not
        /// just `osv_package_name`'s own unit test in isolation) so this regression
        /// class — a gated `OsvNaming` override silently no-op'ing — is caught by CI
        /// under a non-`lsp-responses` build, mirroring the Deno/jsr precedent above.
        #[cfg(feature = "composer")]
        #[test]
        fn build_scan_targets_composer_mixed_case_name_is_lowercased_for_osv() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("Symfony/Http-Kernel"),
                    version_req: Some(VersionReq::new("4.4.0")),
                    source: DependencySource::Registry,
                }],
            };

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &HashMap::new(),
                &HashMap::new(),
                &deps_composer::ComposerFormatter,
                EcosystemId::Composer,
            );

            assert_eq!(targets.len(), 1);
            assert_eq!(targets[0].osv_name.name(), "symfony/http-kernel");
            assert!(skipped.is_empty());
        }

        /// #1663: a separator-only Poetry key normalizes to an empty OSV name, which OSV
        /// rejects with a batch-wide HTTP 400 — it must be skipped as `UnmappableName` while a
        /// valid sibling still yields its (PEP 503-normalized) query.
        #[cfg(feature = "pypi")]
        #[test]
        fn build_scan_targets_pypi_separator_only_key_is_skipped_and_sibling_still_queried() {
            let dep = |name: &str| MockDep {
                name: PackageName::new(name),
                version_req: Some(VersionReq::new("==1.0.0")),
                source: DependencySource::Registry,
            };
            let parse_result = MockParseResult {
                deps: vec![dep("Werkzeug"), dep("---")],
            };

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &HashMap::new(),
                &HashMap::new(),
                &deps_pypi::PypiFormatter,
                EcosystemId::Pypi,
            );

            assert_eq!(targets.len(), 1);
            assert_eq!(targets[0].osv_name.name(), "werkzeug");
            assert_eq!(skipped.len(), 1);
            // The skip is keyed by the normalized name, which is empty for `---`.
            assert_matches!(
                skipped.get(&deps_core::test_util::vuln_key("")),
                Some(ScanOutcome::Skipped(SkipReason::UnmappableName))
            );
        }

        /// #1689: a Dart `+N` build-number pin with no lock file is a concrete OSV query target.
        #[cfg(feature = "dart")]
        #[test]
        fn build_scan_targets_dart_plus_build_number_pin_without_lockfile_is_queried() {
            let dep = |name: &str, req: &str| MockDep {
                name: PackageName::new(name),
                version_req: Some(VersionReq::new(req)),
                source: DependencySource::Registry,
            };
            let parse_result = MockParseResult {
                deps: vec![
                    dep("image_picker_android", "0.8.13+1"),
                    dep("caret_pkg", "^0.8.13+1"),
                ],
            };

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &HashMap::new(),
                &HashMap::new(),
                &deps_dart::DartFormatter,
                EcosystemId::Dart,
            );

            assert_eq!(targets.len(), 1, "{skipped:?}");
            assert_eq!(targets[0].display_version, "0.8.13+1");
        }

        /// #1556 impl-critic S1: a GitHub Actions SHA pin whose `TagIndex`-resolved tag is
        /// itself a moving-major/partial name (here, `v1`, from a `# v1` comment) is NOT a
        /// queryable OSV version — `TagIndex.sha_to_tag` is first-wins over every tag
        /// pointing at that commit, so it can just as easily hand back `"v1"` or `"2.9"` as
        /// a genuine full tag, and querying OSV.dev with a fabricated version is exactly
        /// the #503 invariant this must not regress. `resolved_pin_version`'s raw output
        /// must still pass through the same full-semver-shape gate
        /// (`concrete_pin_version`) as manifest text before `resolve_in_use_version`
        /// accepts it — see the positive case below for the tag shape that IS accepted.
        #[cfg(feature = "github-actions")]
        #[test]
        fn build_scan_targets_github_actions_sha_pin_with_moving_major_comment_stays_skipped() {
            use deps_core::lsp_helpers::{CommitSha, TagIndex};
            use deps_core::osv::{ScanOutcome, SkipReason};
            use deps_github_actions::{GithubActionsFormatter, GithubActionsRegistry};
            use std::sync::Arc;

            let sha = "d".repeat(40);
            let uri = deps_core::test_util::test_uri("/repo/.github/workflows/ci.yml");
            let content = format!("steps:\n  - uses: actions/checkout@{sha} # v1\n");
            let parse_result =
                deps_github_actions::parse_workflow_yaml(&content, &uri).expect("valid yaml");

            let cache = Arc::new(deps_core::HttpCache::new());
            let registry = GithubActionsRegistry::new(cache);
            let tag_index = registry.tag_index();
            let mut index = TagIndex::default();
            index.insert_sha_pin(
                CommitSha::parse(&sha).unwrap(),
                deps_core::lsp_helpers::ResolvedPin::most_specific(
                    deps_core::ConcreteVersion::new("v1"),
                ),
            );
            tag_index.insert(PackageName::new("actions/checkout"), Arc::new(index));
            let formatter = GithubActionsFormatter::new(tag_index);

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &HashMap::new(),
                &HashMap::new(),
                &formatter,
                EcosystemId::GithubActions,
            );

            assert!(
                targets.is_empty(),
                "a moving-major TagIndex-resolved tag must not reach OSV as a fabricated version: {targets:?}"
            );
            assert_matches!(
                skipped.get(&deps_core::test_util::vuln_key("actions/checkout")),
                Some(ScanOutcome::Skipped(SkipReason::ResolvedTagNotFullVersion))
            );
        }

        /// #1668: a SHA pin whose commit carries a two-component release tag (`v2.9`) plus its
        /// moving alias (`v2`) is scanned as `v2.9`; a commit carrying only the moving alias
        /// (`v2`) stays skipped, with the accurate "resolved tag is not a full version" reason.
        #[cfg(feature = "github-actions")]
        #[test]
        fn build_scan_targets_github_actions_sha_pin_two_component_release_tag() {
            use deps_core::lsp_helpers::{CommitSha, TagIndex};
            use deps_core::osv::{ScanOutcome, SkipReason};
            use deps_github_actions::{GithubActionsFormatter, GithubActionsRegistry};
            use std::sync::Arc;

            let sha = "f".repeat(40);
            let uri = deps_core::test_util::test_uri("/repo/.github/workflows/ci.yml");
            let content = format!("steps:\n  - uses: actions/checkout@{sha} # v2.9\n");
            let parse_result =
                deps_github_actions::parse_workflow_yaml(&content, &uri).expect("valid yaml");
            let commit = CommitSha::parse(&sha).unwrap();

            for (tags, expected) in [
                (vec!["v2", "v2.9"], Some("v2.9")),
                (vec!["v2.9", "v2.9.1"], Some("v2.9.1")),
                (vec!["v2.9"], Some("v2.9")),
                (vec!["v2"], None),
            ] {
                let cache = Arc::new(deps_core::HttpCache::new());
                let registry = GithubActionsRegistry::new(cache);
                let tag_index = registry.tag_index();
                tag_index.insert(
                    PackageName::new("actions/checkout"),
                    Arc::new(
                        TagIndex::from_tags(tags.iter().map(|t| (*t, &commit)))
                            .with_canonical_repo_name(
                                deps_core::github::CanonicalRepoName::from_commit_url(
                                    "https://api.github.com/repos/actions/checkout/commits/abc",
                                ),
                            ),
                    ),
                );
                let formatter = GithubActionsFormatter::new(tag_index);

                let (targets, skipped) = build_scan_targets(
                    &parse_result,
                    &HashMap::new(),
                    &HashMap::new(),
                    &formatter,
                    EcosystemId::GithubActions,
                );

                match expected {
                    Some(version) => {
                        assert_eq!(targets.len(), 1, "{tags:?}: {skipped:?}");
                        assert_eq!(targets[0].display_version, version);
                        assert!(skipped.is_empty());
                    }
                    None => {
                        assert!(targets.is_empty(), "{tags:?}: {targets:?}");
                        assert_matches!(
                            skipped.get(&deps_core::test_util::vuln_key("actions/checkout")),
                            Some(ScanOutcome::Skipped(SkipReason::ResolvedTagNotFullVersion))
                        );
                    }
                }
            }
        }

        /// #1556: the actually-intended fix — a GitHub Actions SHA pin whose `TagIndex`
        /// resolves it to a genuine full `major.minor.patch` tag (here `v1.3.0`, matching
        /// the issue's own `moonrepo/setup-rust@<sha> # v1` example where the SHA's real
        /// tag turns out to be a full release) must reach a real OSV scan target, even
        /// though the pin's own trailing `# v1` comment alone is not full-semver-shaped.
        /// Exercises the real `deps-github-actions` formatter end-to-end (not just
        /// `resolve_in_use_version`'s isolated unit tests), mirroring the Deno/Composer
        /// end-to-end precedent above.
        #[cfg(feature = "github-actions")]
        #[test]
        fn build_scan_targets_github_actions_sha_pin_tag_index_resolves_to_full_semver_tag() {
            use deps_core::lsp_helpers::{CommitSha, TagIndex};
            use deps_github_actions::{GithubActionsFormatter, GithubActionsRegistry};
            use std::sync::Arc;

            let sha = "e".repeat(40);
            let uri = deps_core::test_util::test_uri("/repo/.github/workflows/ci.yml");
            let content = format!("steps:\n  - uses: actions/checkout@{sha} # v1\n");
            let parse_result =
                deps_github_actions::parse_workflow_yaml(&content, &uri).expect("valid yaml");

            let cache = Arc::new(deps_core::HttpCache::new());
            let registry = GithubActionsRegistry::new(cache);
            let tag_index = registry.tag_index();
            let mut index = TagIndex::default();
            index.insert_sha_pin(
                CommitSha::parse(&sha).unwrap(),
                deps_core::lsp_helpers::ResolvedPin::most_specific(
                    deps_core::ConcreteVersion::new("v1.3.0"),
                ),
            );
            let index = index.with_canonical_repo_name(
                deps_core::github::CanonicalRepoName::from_commit_url(
                    "https://api.github.com/repos/actions/checkout/commits/abc",
                ),
            );
            tag_index.insert(PackageName::new("actions/checkout"), Arc::new(index));
            let formatter = GithubActionsFormatter::new(tag_index);

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &HashMap::new(),
                &HashMap::new(),
                &formatter,
                EcosystemId::GithubActions,
            );

            assert_eq!(
                targets.len(),
                1,
                "expected the SHA pin to reach a real OSV scan target: {skipped:?}"
            );
            assert!(skipped.is_empty());
            assert_eq!(targets[0].display_version, "v1.3.0");
        }

        /// #1709: every release tag on the pinned commit reaches the scan target, for a SHA pin
        /// and for an exact tag pin (primary stays the written tag); no sibling for a lone tag.
        #[cfg(feature = "github-actions")]
        #[test]
        fn build_scan_targets_github_actions_attaches_sibling_release_tags() {
            use deps_core::lsp_helpers::{CommitSha, TagIndex};
            use deps_github_actions::{GithubActionsFormatter, GithubActionsRegistry};
            use std::sync::Arc;

            let sha = "e".repeat(40);
            let commit = CommitSha::parse(&sha).unwrap();
            let uri = deps_core::test_util::test_uri("/repo/.github/workflows/ci.yml");
            let content = format!(
                "steps:\n  - uses: actions/checkout@{sha}\n  - uses: other/action@v4.9.0\n"
            );
            let parse_result =
                deps_github_actions::parse_workflow_yaml(&content, &uri).expect("valid yaml");

            let registry = GithubActionsRegistry::new(Arc::new(deps_core::HttpCache::new()));
            let tag_index = registry.tag_index();
            let canonical = |repo: &str| {
                deps_core::github::CanonicalRepoName::from_commit_url(&format!(
                    "https://api.github.com/repos/{repo}/commits/abc"
                ))
            };
            tag_index.insert(
                PackageName::new("actions/checkout"),
                Arc::new(
                    TagIndex::from_tags([("v4.8.0", &commit), ("v4.9.0", &commit)])
                        .with_canonical_repo_name(canonical("actions/checkout")),
                ),
            );
            tag_index.insert(
                PackageName::new("other/action"),
                Arc::new(
                    TagIndex::from_tags([("v4.9.0", &commit), ("v4.10.0", &commit)])
                        .with_canonical_repo_name(canonical("other/action")),
                ),
            );
            let formatter = GithubActionsFormatter::new(tag_index);

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &HashMap::new(),
                &HashMap::new(),
                &formatter,
                EcosystemId::GithubActions,
            );

            assert!(skipped.is_empty(), "{skipped:?}");
            let versions = |name: &str| {
                let target = targets
                    .iter()
                    .find(|t| t.key.as_str() == name)
                    .expect("target for name");
                (
                    target.display_version.to_string(),
                    target
                        .siblings()
                        .iter()
                        .map(|s| s.display_version().to_string())
                        .collect::<Vec<_>>(),
                )
            };
            assert_eq!(
                versions("actions/checkout"),
                ("v4.8.0".to_string(), vec!["v4.9.0".to_string()])
            );
            assert_eq!(
                versions("other/action"),
                ("v4.9.0".to_string(), vec!["v4.10.0".to_string()])
            );
        }

        #[test]
        fn build_scan_targets_without_a_tag_pin_has_no_siblings() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("log4j-core"),
                    version_req: Some(VersionReq::new("2.14.1")),
                    source: DependencySource::Registry,
                }],
            };
            let (targets, _) = build_scan_targets(
                &parse_result,
                &HashMap::new(),
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Maven,
            );
            assert!(targets.iter().all(|t| t.siblings().is_empty()));
        }

        #[test]
        fn build_scan_targets_step2_uses_concrete_requirement_verbatim() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("log4j-core"),
                    version_req: Some(VersionReq::new("2.14.1")),
                    source: DependencySource::Registry,
                }],
            };
            let resolved = HashMap::new();

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Maven,
            );
            assert_eq!(targets.len(), 1);
            assert_eq!(targets[0].version, "2.14.1");
            assert!(skipped.is_empty());
        }

        #[test]
        fn build_scan_targets_step2_strips_pin_marker_for_operator_prefixed_requirements() {
            // impl-critic M2: `concrete_pin_version` (originally PyPI `==`-only) also
            // strips Cargo's `=` and NuGet's `[..]` exact-pin markers via the shared helper.
            let cargo_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("time"),
                    version_req: Some(VersionReq::new("=1.2.3")),
                    source: DependencySource::Registry,
                }],
            };
            let (targets, skipped) = build_scan_targets(
                &cargo_result,
                &HashMap::new(),
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Cargo,
            );
            assert_eq!(targets.len(), 1);
            assert_eq!(targets[0].version, "1.2.3");
            assert!(skipped.is_empty());

            let nuget_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("Newtonsoft.Json"),
                    version_req: Some(VersionReq::new("[1.0.0]")),
                    source: DependencySource::Registry,
                }],
            };
            let (targets, skipped) = build_scan_targets(
                &nuget_result,
                &HashMap::new(),
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::NuGet,
            );
            assert_eq!(targets.len(), 1);
            assert_eq!(targets[0].version, "1.0.0");
            assert!(skipped.is_empty());
        }

        #[test]
        fn build_scan_targets_step3_skips_caret_range_with_no_lockfile_entry() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("serde"),
                    version_req: Some(VersionReq::new("^1.0")),
                    source: DependencySource::Registry,
                }],
            };
            let resolved = HashMap::new();

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Cargo,
            );
            assert!(targets.is_empty());
            assert_matches!(
                skipped.get(&deps_core::test_util::vuln_key("serde")),
                Some(ScanOutcome::Skipped(SkipReason::NoConcreteVersion))
            );
        }

        #[test]
        fn build_scan_targets_step3_skips_wildcard_with_no_lockfile_entry() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("serde"),
                    version_req: Some(VersionReq::new("*")),
                    source: DependencySource::Registry,
                }],
            };
            let resolved = HashMap::new();

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Cargo,
            );
            assert!(targets.is_empty());
            assert_matches!(
                skipped.get(&deps_core::test_util::vuln_key("serde")),
                Some(ScanOutcome::Skipped(SkipReason::NoConcreteVersion))
            );
        }

        #[test]
        fn build_scan_targets_all_non_registry_sources_are_skipped() {
            let sources = vec![
                DependencySource::Path {
                    path: "../local".to_string(),
                },
                DependencySource::Url {
                    url: "https://example.com/pkg.tgz".to_string(),
                },
                DependencySource::Sdk {
                    sdk: "flutter".to_string(),
                },
                DependencySource::Workspace,
                DependencySource::CustomRegistry {
                    url: "https://private.example.com".to_string(),
                },
            ];

            for source in sources {
                let parse_result = MockParseResult {
                    deps: vec![MockDep {
                        name: PackageName::new("pkg"),
                        version_req: Some(VersionReq::new("1.0.0")),
                        source: source.clone(),
                    }],
                };
                let mut resolved = HashMap::new();
                resolved.insert(PackageName::new("pkg"), "1.0.0".into());

                let (targets, skipped) = build_scan_targets(
                    &parse_result,
                    &resolved,
                    &HashMap::new(),
                    &StubFormatter::DEFAULT,
                    EcosystemId::Cargo,
                );
                assert!(targets.is_empty(), "{source:?} must be skipped (step 0)");
                assert_matches!(
                    skipped.get(&deps_core::test_util::vuln_key("pkg")),
                    Some(ScanOutcome::Skipped(SkipReason::NonRegistrySource))
                );
            }
        }

        #[test]
        fn build_scan_targets_never_drops_a_dependency_silently() {
            // Critique C1: every dependency considered must end up in either
            // `targets` or `skipped` — never absent from both.
            let parse_result = MockParseResult {
                deps: vec![
                    MockDep {
                        name: PackageName::new("concrete"),
                        version_req: Some(VersionReq::new("2.14.1")),
                        source: DependencySource::Registry,
                    },
                    MockDep {
                        name: PackageName::new("range-only"),
                        version_req: Some(VersionReq::new("^1.0")),
                        source: DependencySource::Registry,
                    },
                    MockDep {
                        name: PackageName::new("git-dep"),
                        version_req: Some(VersionReq::new("1.0.0")),
                        source: DependencySource::Git {
                            url: "https://example.com/git-dep".to_string(),
                            rev: None,
                        },
                    },
                ],
            };
            let resolved = HashMap::new();

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Maven,
            );

            assert_eq!(targets.len(), 1);
            assert_eq!(targets[0].key.as_str(), "concrete");
            assert_eq!(skipped.len(), 2);
            assert_matches!(
                skipped.get(&deps_core::test_util::vuln_key("range-only")),
                Some(ScanOutcome::Skipped(SkipReason::NoConcreteVersion))
            );
            assert_matches!(
                skipped.get(&deps_core::test_util::vuln_key("git-dep")),
                Some(ScanOutcome::Skipped(SkipReason::NonRegistrySource))
            );
        }

        // `collect_in_use_versions` (§4.6) reuses the same `resolve_in_use_version`
        // ladder as `build_scan_targets` above, plus its own step-0 filter —
        // these tests exercise that reuse directly.

        #[test]
        fn collect_in_use_versions_prefers_lockfile_resolved_version() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("serde"),
                    version_req: Some(VersionReq::new("^1.0")),
                    source: DependencySource::Registry,
                }],
            };
            let mut resolved = HashMap::new();
            resolved.insert(PackageName::new("serde"), "1.0.195".into());

            let in_use = collect_in_use_versions(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Cargo,
            );
            assert_eq!(
                in_use.get(&PackageName::new("serde")),
                Some(&vec![ConcreteVersion::from("1.0.195")])
            );
        }

        #[test]
        fn collect_in_use_versions_concrete_pin_without_lockfile() {
            // Closes the former R4 gap: an exact pin with no lock file must
            // still produce an in-use version for the yanked probe.
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("log4j-core"),
                    version_req: Some(VersionReq::new("2.14.1")),
                    source: DependencySource::Registry,
                }],
            };
            let resolved = HashMap::new();

            let in_use = collect_in_use_versions(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Maven,
            );
            assert_eq!(
                in_use.get(&PackageName::new("log4j-core")),
                Some(&vec![ConcreteVersion::from("2.14.1")])
            );
        }

        #[test]
        fn collect_in_use_versions_strips_pep440_double_equals_pin_for_pypi() {
            // The scenario the plan's R4 closure claim actually targets:
            // a PyPI `requirements.txt`-style `==` exact pin with no lock
            // file. `in_use.get(..)` must be the bare `"4.9.0"` so it can
            // ever match a real registry version string during the probe.
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("typing_extensions"),
                    version_req: Some(VersionReq::new("==4.9.0")),
                    source: DependencySource::Registry,
                }],
            };
            let resolved = HashMap::new();

            let in_use = collect_in_use_versions(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Pypi,
            );
            assert_eq!(
                in_use.get(&PackageName::new("typing_extensions")),
                Some(&vec![ConcreteVersion::from("4.9.0")]),
                "pep440 '==' comparator must be stripped, not carried into the in-use version"
            );
        }

        #[test]
        fn collect_in_use_versions_skips_non_concrete_requirement_with_no_lockfile() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("serde"),
                    version_req: Some(VersionReq::new("^1.0")),
                    source: DependencySource::Registry,
                }],
            };
            let resolved = HashMap::new();

            let in_use = collect_in_use_versions(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Cargo,
            );
            assert!(in_use.is_empty());
        }

        #[test]
        fn collect_in_use_versions_excludes_non_registry_source_even_with_lockfile_version() {
            // Step 0 (§4.5): a patched git/path fork must never be flagged
            // for a registry version it does not contain.
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("time"),
                    version_req: Some(VersionReq::new("0.1.43")),
                    source: DependencySource::Git {
                        url: "https://github.com/example/time".to_string(),
                        rev: None,
                    },
                }],
            };
            let mut resolved = HashMap::new();
            resolved.insert(PackageName::new("time"), "0.1.43".into());

            let in_use = collect_in_use_versions(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Cargo,
            );
            assert!(in_use.is_empty());
        }

        #[test]
        fn collect_in_use_versions_tracks_all_occurrences_of_duplicate_name() {
            // Regression guard for #394: two occurrences of the same name with different
            // pins (e.g. `[dependencies]` + `[dev-dependencies]`) must both surface — a
            // name-keyed `HashMap<PackageName, String>` would drop all but the last pin.
            let parse_result = MockParseResult {
                deps: vec![
                    MockDep {
                        name: PackageName::new("time"),
                        version_req: Some(VersionReq::new("=0.1.43")),
                        source: DependencySource::Registry,
                    },
                    MockDep {
                        name: PackageName::new("time"),
                        version_req: Some(VersionReq::new("=0.1.44")),
                        source: DependencySource::Registry,
                    },
                ],
            };
            let resolved = HashMap::new();

            let in_use = collect_in_use_versions(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
                EcosystemId::Cargo,
            );
            assert_eq!(
                in_use.get(&PackageName::new("time")),
                Some(&vec![
                    ConcreteVersion::from("0.1.43"),
                    ConcreteVersion::from("0.1.44")
                ]),
                "both occurrences' in-use versions must be tracked, not just the last one"
            );
        }
    }

    /// #1624 tester gap 1: `build_latest_check_targets`/`build_candidate_check_targets`'s
    /// structural-skip insert paths and `build_candidate_check_targets`'s per-rank
    /// round-bucketing loop, previously entirely unexercised by any unit test (only the one
    /// doctest above, which covers just the "real target" happy path).
    mod build_check_targets_tests {
        use super::*;
        use deps_core::Dependency;
        use deps_core::lsp_helpers::{
            DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
            PackageVersions, RequirementResolution, SourcePolicy,
        };
        use deps_core::osv::{CandidateStatuses, StructuralSkipReason, UpgradeStatus};
        use deps_core::parser::DependencySource;
        use deps_core::position::{Position, Range};
        use deps_core::test_util::StubFormatter;
        use std::any::Any;
        use std::sync::Arc;

        struct MockDep {
            name: PackageName,
            source: DependencySource,
        }

        impl Dependency for MockDep {
            fn name(&self) -> &PackageName {
                &self.name
            }
            fn name_range(&self) -> Range {
                let addr = std::ptr::from_ref(self) as u32;
                Range::new(Position::new(0, addr), Position::new(0, addr + 1))
            }
            fn version_requirement(&self) -> Option<&VersionReq> {
                None
            }
            fn version_range(&self) -> Option<Range> {
                None
            }
            fn source(&self) -> DependencySource {
                self.source.clone()
            }
            fn as_any(&self) -> &dyn Any {
                self
            }
        }

        struct MockParseResult {
            deps: Vec<MockDep>,
        }

        impl deps_core::ParseResult for MockParseResult {
            fn dependencies(&self) -> Vec<&dyn Dependency> {
                self.deps.iter().map(|d| d as &dyn Dependency).collect()
            }
            fn workspace_root(&self) -> Option<&std::path::Path> {
                None
            }
            fn uri(&self) -> &url::Url {
                static URI: std::sync::OnceLock<url::Url> = std::sync::OnceLock::new();
                URI.get_or_init(|| deps_core::test_util::test_uri("/test/Cargo.toml"))
            }
            fn as_any(&self) -> &dyn Any {
                self
            }
        }

        /// A formatter whose package name is never mappable to an OSV ecosystem name —
        /// `StubFormatter`'s `OsvNaming` default (always `Some`) can't drive the
        /// `UnmappableName` structural-skip branch.
        struct UnmappableNameFormatter;
        impl PackageNaming for UnmappableNameFormatter {}
        impl PackageRendering for UnmappableNameFormatter {
            fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
                version.to_string()
            }
            fn package_url(&self, name: &PackageName) -> String {
                name.as_str().to_string()
            }
        }
        impl RequirementResolution for UnmappableNameFormatter {}
        impl DiagnosticMessages for UnmappableNameFormatter {}
        impl DiagnosticPolicy for UnmappableNameFormatter {}
        impl SourcePolicy for UnmappableNameFormatter {}
        impl OsvNaming for UnmappableNameFormatter {
            fn osv_package_name(
                &self,
                _dep: &dyn Dependency,
            ) -> Option<deps_core::osv::OsvPackageName> {
                None
            }
        }

        /// A formatter whose OSV name is derived from registry data that has not landed yet;
        /// `with_fallback` offers the written name as a provisional query name (#1694).
        #[derive(Default)]
        struct AwaitingNameFormatter {
            with_fallback: bool,
        }
        impl PackageNaming for AwaitingNameFormatter {}
        impl PackageRendering for AwaitingNameFormatter {
            fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
                version.to_string()
            }
            fn package_url(&self, name: &PackageName) -> String {
                name.as_str().to_string()
            }
        }
        impl RequirementResolution for AwaitingNameFormatter {}
        impl DiagnosticMessages for AwaitingNameFormatter {}
        impl DiagnosticPolicy for AwaitingNameFormatter {}
        impl SourcePolicy for AwaitingNameFormatter {}
        impl OsvNaming for AwaitingNameFormatter {
            fn osv_name_availability(
                &self,
                dep: &dyn Dependency,
            ) -> deps_core::lsp_helpers::OsvNameAvailability {
                deps_core::lsp_helpers::OsvNameAvailability::AwaitingRegistryData {
                    written_fallback: self
                        .with_fallback
                        .then(|| deps_core::osv::OsvPackageName::new_or_skip(dep.name().as_str()))
                        .flatten(),
                }
            }
        }

        fn awaiting_name_fixture() -> (
            MockParseResult,
            deps_core::osv::VulnKeys,
            HashMap<PackageName, PackageVersions>,
        ) {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("gha-action"),
                    source: DependencySource::Registry,
                }],
            };
            let vuln_keys = vuln_keys_for(&parse_result, &AwaitingNameFormatter::default());
            let mut cached_versions = HashMap::new();
            cached_versions.insert(
                PackageName::new("gha-action"),
                PackageVersions::latest_only("1.0.0"),
            );
            (parse_result, vuln_keys, cached_versions)
        }

        #[test]
        fn build_latest_check_targets_awaiting_osv_name_is_unverified_not_structural() {
            let (parse_result, vuln_keys, cached_versions) = awaiting_name_fixture();

            let (targets, statuses) = build_latest_check_targets(
                &parse_result,
                &cached_versions,
                &vuln_keys,
                &AwaitingNameFormatter::default(),
            );

            assert!(targets.is_empty());
            assert_eq!(
                statuses.get(&deps_core::test_util::vuln_key("gha-action")),
                Some(&UpgradeStatus::CandidateUnverified {
                    version: ConcreteVersion::new("1.0.0"),
                    reason: deps_core::osv::SkipReason::CanonicalNameUnconfirmed,
                })
            );
        }

        #[test]
        fn build_candidate_check_targets_awaiting_osv_name_records_no_entry() {
            let (parse_result, vuln_keys, cached_versions) = awaiting_name_fixture();

            let (rounds, statuses) = build_candidate_check_targets(
                &parse_result,
                &cached_versions,
                &vuln_keys,
                &AwaitingNameFormatter::default(),
            );

            assert!(rounds.iter().all(Vec::is_empty));
            assert!(
                statuses.is_empty(),
                "a transient name gap must never be stored as structural: {statuses:?}"
            );
        }

        /// #1694: an unconfirmed casing queries the written name as a provisional target
        /// (only a positive answer is trusted); a confirmed one is the authoritative target.
        #[cfg(feature = "github-actions")]
        #[test]
        fn build_scan_targets_github_actions_unconfirmed_name_is_provisional() {
            use deps_core::lsp_helpers::TagIndex;
            use deps_core::osv::OsvQueryName;
            use deps_github_actions::{GithubActionsFormatter, GithubActionsRegistry};
            use std::sync::Arc;

            let uri = deps_core::test_util::test_uri("/repo/.github/workflows/ci.yml");
            let parse_result = deps_github_actions::parse_workflow_yaml(
                "steps:\n  - uses: azure/setup-kubectl@v4.1.2\n",
                &uri,
            )
            .expect("valid yaml");
            let registry = GithubActionsRegistry::new(Arc::new(deps_core::HttpCache::new()));
            let written = deps_core::osv::OsvPackageName::new("azure/setup-kubectl").unwrap();
            let canonical = deps_core::osv::OsvPackageName::new("Azure/setup-kubectl").unwrap();

            for warm_without_canonical in [false, true] {
                let tag_index = registry.tag_index();
                tag_index.clear();
                if warm_without_canonical {
                    tag_index.insert(
                        PackageName::new("azure/setup-kubectl"),
                        Arc::new(TagIndex::default()),
                    );
                }
                let formatter = GithubActionsFormatter::new(tag_index);

                let (targets, skipped) = build_scan_targets(
                    &parse_result,
                    &HashMap::new(),
                    &HashMap::new(),
                    &formatter,
                    EcosystemId::GithubActions,
                );

                assert!(skipped.is_empty(), "{skipped:?}");
                assert_eq!(targets.len(), 1);
                assert_eq!(
                    targets[0].osv_name,
                    OsvQueryName::Provisional(written.clone()),
                    "warm_without_canonical={warm_without_canonical}"
                );
            }

            let tag_index = registry.tag_index();
            tag_index.insert(
                PackageName::new("azure/setup-kubectl"),
                Arc::new(TagIndex::default().with_canonical_repo_name(
                    deps_core::github::CanonicalRepoName::from_commit_url(
                        "https://api.github.com/repos/Azure/setup-kubectl/commits/abc",
                    ),
                )),
            );
            let formatter = GithubActionsFormatter::new(tag_index);
            let (targets, _) = build_scan_targets(
                &parse_result,
                &HashMap::new(),
                &HashMap::new(),
                &formatter,
                EcosystemId::GithubActions,
            );
            assert_eq!(targets[0].osv_name, OsvQueryName::Confirmed(canonical));
        }

        /// #1684: a floating `@v4` scans the release its tag's commit carries, and stays an
        /// honest skip while the index is cold or the commit only carries the floating tag.
        #[cfg(feature = "github-actions")]
        #[test]
        fn build_scan_targets_github_actions_floating_tag_resolves_via_commit() {
            use deps_core::lsp_helpers::{CommitSha, TagIndex};
            use deps_core::osv::{OsvQueryName, ScanOutcome, SkipReason};
            use deps_github_actions::{GithubActionsFormatter, GithubActionsRegistry};
            use std::sync::Arc;

            let uri = deps_core::test_util::test_uri("/repo/.github/workflows/ci.yml");
            let parse_result = deps_github_actions::parse_workflow_yaml(
                "steps:\n  - uses: actions/checkout@v4\n",
                &uri,
            )
            .expect("valid yaml");
            let registry = GithubActionsRegistry::new(Arc::new(deps_core::HttpCache::new()));
            let key = deps_core::test_util::vuln_key("actions/checkout");
            let commit = CommitSha::parse(&"a".repeat(40)).unwrap();
            let scan = |tags: &[&str]| {
                let tag_index = registry.tag_index();
                tag_index.clear();
                if !tags.is_empty() {
                    let index = TagIndex::from_tags(tags.iter().map(|t| (*t, &commit)))
                        .with_canonical_repo_name(
                            deps_core::github::CanonicalRepoName::from_commit_url(
                                "https://api.github.com/repos/actions/checkout/commits/abc",
                            ),
                        );
                    tag_index.insert(PackageName::new("actions/checkout"), Arc::new(index));
                }
                build_scan_targets(
                    &parse_result,
                    &HashMap::new(),
                    &HashMap::new(),
                    &GithubActionsFormatter::new(tag_index),
                    EcosystemId::GithubActions,
                )
            };

            let (targets, skipped) = scan(&["v4", "v4.2.2"]);
            assert!(skipped.is_empty(), "{skipped:?}");
            assert_eq!(targets.len(), 1);
            assert_eq!(targets[0].version, "4.2.2");
            assert_matches!(targets[0].osv_name, OsvQueryName::Confirmed(_));

            let (targets, skipped) = scan(&[]);
            assert!(targets.is_empty());
            assert_matches!(
                skipped.get(&key),
                Some(ScanOutcome::Skipped(SkipReason::NoConcreteVersion))
            );

            let (targets, skipped) = scan(&["v4"]);
            assert!(targets.is_empty());
            assert_matches!(
                skipped.get(&key),
                Some(ScanOutcome::Skipped(SkipReason::ResolvedTagNotFullVersion))
            );
        }

        /// #1694: a written name that is not a valid OSV name stays a fail-closed skip.
        #[test]
        fn build_scan_targets_awaiting_name_without_fallback_is_unconfirmed_skip() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("gha-action"),
                    source: DependencySource::Registry,
                }],
            };
            let mut resolved = HashMap::new();
            resolved.insert(
                PackageName::new("gha-action"),
                ConcreteVersion::new("1.0.0"),
            );

            let (targets, skipped) = build_scan_targets(
                &parse_result,
                &resolved,
                &HashMap::new(),
                &AwaitingNameFormatter::default(),
                EcosystemId::Cargo,
            );

            assert!(targets.is_empty());
            assert_matches!(
                skipped.get(&deps_core::test_util::vuln_key("gha-action")),
                Some(deps_core::osv::ScanOutcome::Skipped(
                    deps_core::osv::SkipReason::CanonicalNameUnconfirmed
                ))
            );
        }

        /// A formatter reporting a different name availability per successive dependency.
        struct SequencedNameFormatter {
            ready: [bool; 2],
            calls: std::sync::atomic::AtomicUsize,
        }
        impl PackageNaming for SequencedNameFormatter {}
        impl PackageRendering for SequencedNameFormatter {
            fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
                version.to_string()
            }
            fn package_url(&self, name: &PackageName) -> String {
                name.as_str().to_string()
            }
        }
        impl RequirementResolution for SequencedNameFormatter {}
        impl DiagnosticMessages for SequencedNameFormatter {}
        impl DiagnosticPolicy for SequencedNameFormatter {}
        impl SourcePolicy for SequencedNameFormatter {}
        impl OsvNaming for SequencedNameFormatter {
            fn osv_name_availability(
                &self,
                dep: &dyn Dependency,
            ) -> deps_core::lsp_helpers::OsvNameAvailability {
                let idx = self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                if self.ready[idx] {
                    deps_core::lsp_helpers::OsvNameAvailability::Ready
                } else {
                    deps_core::lsp_helpers::OsvNameAvailability::AwaitingRegistryData {
                        written_fallback: deps_core::osv::OsvPackageName::new_or_skip(
                            dep.name().as_str(),
                        ),
                    }
                }
            }
        }

        /// #1694 (critic M1): occurrences sharing a key collapse to one target, and a
        /// confirmed name wins over a provisional one whichever comes first.
        #[test]
        fn build_scan_targets_dedups_per_key_preferring_confirmed_name() {
            use deps_core::osv::OsvQueryName;

            let mut resolved = HashMap::new();
            resolved.insert(PackageName::new("dup"), ConcreteVersion::new("1.0.0"));
            let name = deps_core::osv::OsvPackageName::new("dup").unwrap();

            for (ready, expected) in [
                ([false, true], OsvQueryName::Confirmed(name.clone())),
                ([true, false], OsvQueryName::Confirmed(name.clone())),
                ([false, false], OsvQueryName::Provisional(name)),
            ] {
                let parse_result = MockParseResult {
                    deps: ["dup", "dup"]
                        .into_iter()
                        .map(|n| MockDep {
                            name: PackageName::new(n),
                            source: DependencySource::Registry,
                        })
                        .collect(),
                };
                let formatter = SequencedNameFormatter {
                    ready,
                    calls: std::sync::atomic::AtomicUsize::new(0),
                };
                let (targets, _) = build_scan_targets(
                    &parse_result,
                    &resolved,
                    &HashMap::new(),
                    &formatter,
                    EcosystemId::Cargo,
                );
                assert_eq!(targets.len(), 1, "ready={ready:?}");
                assert_eq!(targets[0].osv_name, expected, "ready={ready:?}");
            }
        }

        fn vuln_keys_for(
            parse_result: &dyn deps_core::ParseResult,
            formatter: &dyn deps_core::lsp_helpers::EcosystemFormatter,
        ) -> deps_core::osv::VulnKeys {
            deps_core::osv::vulnerability_keys(
                parse_result,
                &HashMap::new(),
                None,
                formatter,
                EcosystemId::Cargo,
            )
        }

        #[test]
        fn build_latest_check_targets_non_registry_source_is_structurally_unchecked() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("vendored"),
                    source: DependencySource::Path {
                        path: "../vendored".to_string(),
                    },
                }],
            };
            let vuln_keys = vuln_keys_for(&parse_result, &StubFormatter::DEFAULT);

            let (targets, structural) = build_latest_check_targets(
                &parse_result,
                &HashMap::new(),
                &vuln_keys,
                &StubFormatter::DEFAULT,
            );

            assert!(targets.is_empty());
            assert_eq!(
                structural.get(&deps_core::test_util::vuln_key("vendored")),
                Some(&UpgradeStatus::StructurallyUnchecked(
                    StructuralSkipReason::NonRegistrySource
                ))
            );
        }

        #[test]
        fn build_candidate_check_targets_non_registry_source_is_structural() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("vendored"),
                    source: DependencySource::Path {
                        path: "../vendored".to_string(),
                    },
                }],
            };
            let vuln_keys = vuln_keys_for(&parse_result, &StubFormatter::DEFAULT);

            let (rounds, structural) = build_candidate_check_targets(
                &parse_result,
                &HashMap::new(),
                &vuln_keys,
                &StubFormatter::DEFAULT,
            );

            assert!(
                rounds.iter().all(Vec::is_empty),
                "no round may hold a non-registry dependency"
            );
            assert_eq!(
                structural.get(&deps_core::test_util::vuln_key("vendored")),
                Some(&CandidateStatuses::Structural(
                    StructuralSkipReason::NonRegistrySource
                ))
            );
        }

        #[test]
        fn build_candidate_check_targets_unmappable_name_is_structural() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("jsr-pinned"),
                    source: DependencySource::Registry,
                }],
            };
            let vuln_keys = vuln_keys_for(&parse_result, &UnmappableNameFormatter);
            let mut cached_versions = HashMap::new();
            cached_versions.insert(
                PackageName::new("jsr-pinned"),
                PackageVersions::latest_only("1.0.0"),
            );

            let (rounds, structural) = build_candidate_check_targets(
                &parse_result,
                &cached_versions,
                &vuln_keys,
                &UnmappableNameFormatter,
            );

            assert!(
                rounds.iter().all(Vec::is_empty),
                "an unmappable name has no OSV-checkable round targets"
            );
            assert_eq!(
                structural.get(&deps_core::test_util::vuln_key("jsr-pinned")),
                Some(&CandidateStatuses::Structural(
                    StructuralSkipReason::UnmappableName
                ))
            );
        }

        fn duplicated_registry_dep() -> MockParseResult {
            MockParseResult {
                deps: vec![
                    MockDep {
                        name: PackageName::new("lodash"),
                        source: DependencySource::Registry,
                    },
                    MockDep {
                        name: PackageName::new("lodash"),
                        source: DependencySource::Registry,
                    },
                ],
            }
        }

        #[test]
        fn build_latest_check_targets_dedups_duplicate_key_occurrences() {
            let parse_result = duplicated_registry_dep();
            let vuln_keys = vuln_keys_for(&parse_result, &StubFormatter::DEFAULT);
            let mut cached_versions = HashMap::new();
            cached_versions.insert(
                PackageName::new("lodash"),
                PackageVersions::latest_only("4.17.21"),
            );

            let (targets, structural) = build_latest_check_targets(
                &parse_result,
                &cached_versions,
                &vuln_keys,
                &StubFormatter::DEFAULT,
            );

            assert_eq!(
                targets.len(),
                1,
                "two same-key occurrences are checked once"
            );
            assert!(structural.is_empty());
        }

        #[test]
        fn build_candidate_check_targets_dedups_duplicate_key_occurrences() {
            let parse_result = duplicated_registry_dep();
            let vuln_keys = vuln_keys_for(&parse_result, &StubFormatter::DEFAULT);
            let mut cached_versions = HashMap::new();
            let available: Arc<[ConcreteVersion]> = Arc::from(vec![
                ConcreteVersion::new("2.0.0"),
                ConcreteVersion::new("1.0.0"),
            ]);
            cached_versions.insert(
                PackageName::new("lodash"),
                PackageVersions::new(ConcreteVersion::new("2.0.0"), available),
            );

            let (rounds, _) = build_candidate_check_targets(
                &parse_result,
                &cached_versions,
                &vuln_keys,
                &StubFormatter::DEFAULT,
            );

            assert_eq!(rounds[0].len(), 1);
            assert_eq!(rounds[1].len(), 1);
        }

        fn dup_other_dup() -> MockParseResult {
            let dep = |name: &str| MockDep {
                name: PackageName::new(name),
                source: DependencySource::Registry,
            };
            MockParseResult {
                deps: vec![dep("dup"), dep("other"), dep("dup")],
            }
        }

        #[test]
        fn build_latest_check_targets_keeps_first_occurrence_order() {
            let parse_result = dup_other_dup();
            let vuln_keys = vuln_keys_for(&parse_result, &StubFormatter::DEFAULT);
            let mut cached_versions = HashMap::new();
            cached_versions.insert(
                PackageName::new("dup"),
                PackageVersions::latest_only("2.0.0"),
            );
            cached_versions.insert(
                PackageName::new("other"),
                PackageVersions::latest_only("3.0.0"),
            );

            let (targets, _) = build_latest_check_targets(
                &parse_result,
                &cached_versions,
                &vuln_keys,
                &StubFormatter::DEFAULT,
            );

            let keys: Vec<_> = targets.iter().map(|t| t.key.clone()).collect();
            assert_eq!(
                keys,
                [
                    deps_core::test_util::vuln_key("dup"),
                    deps_core::test_util::vuln_key("other")
                ]
            );
            assert_eq!(targets[0].display_version, "2.0.0");
            assert_eq!(targets[1].display_version, "3.0.0");
        }

        #[test]
        fn build_candidate_check_targets_keeps_first_occurrence_order() {
            let parse_result = dup_other_dup();
            let vuln_keys = vuln_keys_for(&parse_result, &StubFormatter::DEFAULT);
            let mut cached_versions = HashMap::new();
            for (name, newest) in [("dup", "2.0.0"), ("other", "3.0.0")] {
                let available: Arc<[ConcreteVersion]> =
                    Arc::from(vec![ConcreteVersion::new(newest)]);
                cached_versions.insert(
                    PackageName::new(name),
                    PackageVersions::new(ConcreteVersion::new(newest), available),
                );
            }

            let (rounds, _) = build_candidate_check_targets(
                &parse_result,
                &cached_versions,
                &vuln_keys,
                &StubFormatter::DEFAULT,
            );

            let keys: Vec<_> = rounds[0].iter().map(|t| t.key.clone()).collect();
            assert_eq!(
                keys,
                [
                    deps_core::test_util::vuln_key("dup"),
                    deps_core::test_util::vuln_key("other")
                ]
            );
            assert_eq!(rounds[0][0].display_version, "2.0.0");
            assert_eq!(rounds[0][1].display_version, "3.0.0");
            assert!(rounds[1..].iter().all(Vec::is_empty));
        }

        #[test]
        fn build_candidate_check_targets_buckets_newest_first_by_round() {
            let parse_result = MockParseResult {
                deps: vec![MockDep {
                    name: PackageName::new("pkg"),
                    source: DependencySource::Registry,
                }],
            };
            let vuln_keys = vuln_keys_for(&parse_result, &StubFormatter::DEFAULT);
            let mut cached_versions = HashMap::new();
            let available: Arc<[ConcreteVersion]> = Arc::from(vec![
                ConcreteVersion::new("3.0.0"),
                ConcreteVersion::new("2.0.0"),
                ConcreteVersion::new("1.0.0"),
            ]);
            cached_versions.insert(
                PackageName::new("pkg"),
                PackageVersions::new(ConcreteVersion::new("3.0.0"), available),
            );

            let (rounds, structural) = build_candidate_check_targets(
                &parse_result,
                &cached_versions,
                &vuln_keys,
                &StubFormatter::DEFAULT,
            );

            assert!(structural.is_empty());
            assert_eq!(
                rounds[0].len(),
                1,
                "round 0 must hold this dependency's newest candidate"
            );
            assert_eq!(rounds[0][0].display_version, "3.0.0");
            assert_eq!(rounds[1].len(), 1);
            assert_eq!(rounds[1][0].display_version, "2.0.0");
            assert_eq!(rounds[2].len(), 1);
            assert_eq!(rounds[2][0].display_version, "1.0.0");
            assert!(
                rounds[3..].iter().all(Vec::is_empty),
                "only 3 candidate versions were available, so later rounds must stay empty"
            );
        }
    }

    /// #462: `resolve_fix_target`'s pure per-dependency decision logic (reuse / provably
    /// clean / needs a live check / skip), and `apply_live_fix_target_statuses`'s handling of
    /// a live-check result map that may be missing keys (timeout/outage).
    mod fix_target_verification_tests {
        use super::*;
        use deps_core::osv::{
            Advisory, Capped, DependencyVulnerabilities, OsvVersion, ScanOutcome, UpgradeStatus,
            VulnSeverity, VulnerabilityMap,
        };
        use deps_core::test_util::StubFormatter;
        use std::sync::Arc;

        fn advisory(id: &str, fixed_versions: &[&str]) -> Arc<Advisory> {
            Arc::new(
                Advisory::new(
                    id.to_string(),
                    "2023-01-01T00:00:00Z".to_string(),
                    VulnSeverity::High,
                )
                .expect("valid osv id")
                .with_fixed_versions(
                    fixed_versions
                        .iter()
                        .copied()
                        .map(OsvVersion::new)
                        .collect(),
                ),
            )
        }

        fn dv(advisories: Vec<Arc<Advisory>>) -> DependencyVulnerabilities {
            let total = advisories.len();
            DependencyVulnerabilities::new(Capped::new(advisories, total))
        }

        /// Builds a one-entry [`deps_core::osv::LatestStatusMap`] for `"pkg"`.
        fn latest_status_map(status: UpgradeStatus) -> deps_core::osv::LatestStatusMap {
            let mut map = deps_core::osv::LatestStatusMap::new();
            map.insert(deps_core::test_util::vuln_key("pkg"), status);
            map
        }

        #[test]
        fn resolve_fix_target_skips_when_no_fix_is_recommended() {
            // No advisory has a known fix, so `recommended_fix()` returns `None`.
            let dv = dv(vec![advisory("A1", &[])]);
            let resolution = resolve_fix_target(
                &dv,
                &deps_core::test_util::vuln_key("pkg"),
                &HashMap::new(),
                &HashMap::new(),
                &StubFormatter::DEFAULT,
            );
            assert_eq!(resolution, FixTargetResolution::Skip);
        }

        #[test]
        fn resolve_fix_target_reuses_latest_when_f_equals_latest() {
            // Case (c): F (1.2.0, the only advisory's fix) coincides with the already-checked
            // "latest" candidate — reuse its result, no live check queued.
            let latest_status = UpgradeStatus::CandidateClean {
                version: ConcreteVersion::new("1.2.0"),
            };
            let dv = dv(vec![advisory("A1", &["1.2.0"])]);
            let latest_status_map = latest_status_map(latest_status.clone());

            let resolution = resolve_fix_target(
                &dv,
                &deps_core::test_util::vuln_key("pkg"),
                &latest_status_map,
                &HashMap::new(),
                &StubFormatter::DEFAULT,
            );
            assert_eq!(resolution, FixTargetResolution::Resolved(latest_status));
        }

        #[test]
        fn resolve_fix_target_always_needs_live_check_when_f_differs_from_latest() {
            // #462 critic C1: no data-derived shortcut — F is *computed from* these exact
            // advisories, so "F <= advisories' fix" is a tautology that proves nothing about
            // an advisory phase A never fetched. F (1.2.0) != latest (3.0.0) must always
            // queue a live check.
            let dv = dv(vec![advisory("A1", &["1.2.0"])]);
            let latest_status_map = latest_status_map(UpgradeStatus::CandidateClean {
                version: ConcreteVersion::new("3.0.0"),
            });
            let mut osv_name_by_key = HashMap::new();
            osv_name_by_key.insert(
                deps_core::test_util::vuln_key("pkg"),
                deps_core::osv::OsvQueryName::Confirmed(
                    deps_core::osv::OsvPackageName::new("pkg").unwrap(),
                ),
            );

            let resolution = resolve_fix_target(
                &dv,
                &deps_core::test_util::vuln_key("pkg"),
                &latest_status_map,
                &osv_name_by_key,
                &StubFormatter::DEFAULT,
            );
            assert_eq!(
                resolution,
                FixTargetResolution::NeedsLiveCheck(deps_core::osv::ScanTarget::new(
                    deps_core::test_util::vuln_key("pkg"),
                    deps_core::osv::OsvQueryName::Confirmed(
                        deps_core::osv::OsvPackageName::new("pkg").unwrap()
                    ),
                    OsvVersion::new("1.2.0"),
                    ConcreteVersion::new("1.2.0"),
                ))
            );
        }

        #[test]
        fn resolve_fix_target_never_reuses_a_candidate_unverified_latest() {
            // Issue #1517: a transient (or structural) `CandidateUnverified` latest-check
            // result must never be mistaken for a resolved "F == latest" match — even when
            // its own `version` field happens to equal F, that field is not a confirmed
            // clean/vulnerable verdict, so this must still queue a live check.
            let dv = dv(vec![advisory("A1", &["1.2.0"])]);
            let latest_status_map = latest_status_map(UpgradeStatus::CandidateUnverified {
                version: ConcreteVersion::new("1.2.0"),
                reason: deps_core::osv::SkipReason::QueryFailed,
            });
            let mut osv_name_by_key = HashMap::new();
            osv_name_by_key.insert(
                deps_core::test_util::vuln_key("pkg"),
                deps_core::osv::OsvQueryName::Confirmed(
                    deps_core::osv::OsvPackageName::new("pkg").unwrap(),
                ),
            );

            let resolution = resolve_fix_target(
                &dv,
                &deps_core::test_util::vuln_key("pkg"),
                &latest_status_map,
                &osv_name_by_key,
                &StubFormatter::DEFAULT,
            );
            assert_eq!(
                resolution,
                FixTargetResolution::NeedsLiveCheck(deps_core::osv::ScanTarget::new(
                    deps_core::test_util::vuln_key("pkg"),
                    deps_core::osv::OsvQueryName::Confirmed(
                        deps_core::osv::OsvPackageName::new("pkg").unwrap()
                    ),
                    OsvVersion::new("1.2.0"),
                    ConcreteVersion::new("1.2.0"),
                ))
            );
        }

        /// #1694: a fix target can never be verified through an unconfirmed name — a clean
        /// answer there is not evidence, so the fix stays unverified and no query is queued.
        #[test]
        fn resolve_fix_target_skips_provisional_name_and_queues_no_live_check() {
            let dv = dv(vec![advisory("A1", &["1.2.0"])]);
            let key = deps_core::test_util::vuln_key("pkg");
            let latest_status_map = latest_status_map(UpgradeStatus::CandidateClean {
                version: ConcreteVersion::new("3.0.0"),
            });
            let mut osv_name_by_key = HashMap::new();
            osv_name_by_key.insert(
                key.clone(),
                deps_core::osv::OsvQueryName::Provisional(
                    deps_core::osv::OsvPackageName::new("pkg").unwrap(),
                ),
            );

            assert_eq!(
                resolve_fix_target(
                    &dv,
                    &key,
                    &latest_status_map,
                    &osv_name_by_key,
                    &StubFormatter::DEFAULT,
                ),
                FixTargetResolution::Skip
            );

            let mut vulnerabilities = VulnerabilityMap::new();
            vulnerabilities.insert(key.clone(), ScanOutcome::Vulnerable(dv));
            let (resolved, live_check_candidates) = collect_fix_target_resolutions(
                &vulnerabilities,
                &[key],
                &osv_name_by_key,
                &latest_status_map,
                &StubFormatter::DEFAULT,
            );
            assert!(resolved.is_empty(), "{resolved:?}");
            assert!(
                live_check_candidates.is_empty(),
                "{live_check_candidates:?}"
            );
        }

        #[test]
        fn resolve_fix_target_skips_when_osv_name_is_unavailable() {
            // A live check is needed (F != latest) but no `osv_name` is on record for this
            // key — nothing to query, so this degrades to `Skip` rather than panicking or
            // building a `ScanTarget` with an empty name.
            let dv = dv(vec![advisory("A1", &["1.0.0"])]);
            let resolution = resolve_fix_target(
                &dv,
                &deps_core::test_util::vuln_key("pkg"),
                &HashMap::new(),
                &HashMap::new(),
                &StubFormatter::DEFAULT,
            );
            assert_eq!(resolution, FixTargetResolution::Skip);
        }

        #[test]
        fn resolve_fix_target_skips_when_f_is_not_a_safe_version_string() {
            // A malformed `fixed_versions` entry (as if it somehow reached this dependency's
            // `advisories` despite OSV's own wire-boundary validation) must never be queued
            // for a live check or treated as any kind of resolvable target — `is_safe_version_string`
            // rejects it before anything else runs.
            let dv = dv(vec![advisory("A1", &["1.2.0\", \"evil\": \"true"])]);
            let resolution = resolve_fix_target(
                &dv,
                &deps_core::test_util::vuln_key("pkg"),
                &HashMap::new(),
                &HashMap::new(),
                &StubFormatter::DEFAULT,
            );
            assert_eq!(resolution, FixTargetResolution::Skip);
        }

        #[test]
        fn collect_fix_target_resolutions_batches_multiple_dependencies_needing_live_check_into_one_vec()
         {
            // #462 NFR-001: three vulnerable dependencies — "reused" (F == latest, resolved
            // without a call), "live-a" and "live-b" (F != latest, both need a live check) —
            // must collapse into exactly one `resolved` entry and one `live_check_candidates`
            // Vec of length 2, proving multiple dependencies needing verification are batched
            // into a single prospective `check_candidates` call rather than one per dependency.
            let mut vulnerabilities = VulnerabilityMap::new();
            vulnerabilities.insert(
                deps_core::test_util::vuln_key("reused"),
                ScanOutcome::Vulnerable(dv(vec![advisory("A1", &["1.0.0"])])),
            );
            vulnerabilities.insert(
                deps_core::test_util::vuln_key("live-a"),
                ScanOutcome::Vulnerable(dv(vec![advisory("A2", &["1.2.0"])])),
            );
            vulnerabilities.insert(
                deps_core::test_util::vuln_key("live-b"),
                ScanOutcome::Vulnerable(dv(vec![advisory("A3", &["2.2.0"])])),
            );

            let vulnerable_keys = vec![
                deps_core::test_util::vuln_key("reused"),
                deps_core::test_util::vuln_key("live-a"),
                deps_core::test_util::vuln_key("live-b"),
            ];
            let mut latest_status: deps_core::osv::LatestStatusMap = HashMap::new();
            latest_status.insert(
                deps_core::test_util::vuln_key("reused"),
                UpgradeStatus::CandidateClean {
                    version: ConcreteVersion::new("1.0.0"),
                },
            );
            latest_status.insert(
                deps_core::test_util::vuln_key("live-a"),
                UpgradeStatus::CandidateClean {
                    version: ConcreteVersion::new("9.0.0"),
                },
            );
            latest_status.insert(
                deps_core::test_util::vuln_key("live-b"),
                UpgradeStatus::CandidateClean {
                    version: ConcreteVersion::new("9.0.0"),
                },
            );
            let mut osv_name_by_key = HashMap::new();
            osv_name_by_key.insert(
                deps_core::test_util::vuln_key("reused"),
                deps_core::osv::OsvQueryName::Confirmed(
                    deps_core::osv::OsvPackageName::new("reused").unwrap(),
                ),
            );
            osv_name_by_key.insert(
                deps_core::test_util::vuln_key("live-a"),
                deps_core::osv::OsvQueryName::Confirmed(
                    deps_core::osv::OsvPackageName::new("live-a").unwrap(),
                ),
            );
            osv_name_by_key.insert(
                deps_core::test_util::vuln_key("live-b"),
                deps_core::osv::OsvQueryName::Confirmed(
                    deps_core::osv::OsvPackageName::new("live-b").unwrap(),
                ),
            );

            let (resolved, live_check_candidates) = collect_fix_target_resolutions(
                &vulnerabilities,
                &vulnerable_keys,
                &osv_name_by_key,
                &latest_status,
                &StubFormatter::DEFAULT,
            );

            assert_eq!(resolved.len(), 1, "{resolved:?}");
            assert_eq!(resolved[0].0.as_str(), "reused");

            assert_eq!(live_check_candidates.len(), 2, "{live_check_candidates:?}");
            let keys: std::collections::HashSet<&str> = live_check_candidates
                .iter()
                .map(|t| t.key.as_str())
                .collect();
            assert!(keys.contains("live-a"));
            assert!(keys.contains("live-b"));
        }

        #[test]
        fn apply_live_fix_target_statuses_sets_only_matching_keys_leaving_others_untouched() {
            // Case (e): a live-check batch that timed out for one dependency simply omits
            // its key from `statuses` — that dependency's `fix_target_status` must stay
            // `NotChecked` afterward, with no panic, while a dependency whose result did
            // arrive gets it applied.
            let mut vulnerabilities = VulnerabilityMap::new();
            vulnerabilities.insert(
                deps_core::test_util::vuln_key("checked"),
                ScanOutcome::Vulnerable(dv(vec![advisory("A1", &["1.0.0"])])),
            );
            vulnerabilities.insert(
                deps_core::test_util::vuln_key("timed-out"),
                ScanOutcome::Vulnerable(dv(vec![advisory("A2", &["1.0.0"])])),
            );

            let mut statuses = HashMap::new();
            statuses.insert(
                deps_core::test_util::vuln_key("checked"),
                UpgradeStatus::CandidateClean {
                    version: ConcreteVersion::new("1.0.0"),
                },
            );
            // "timed-out" deliberately has no entry in `statuses`.

            apply_live_fix_target_statuses(&mut vulnerabilities, statuses);

            let ScanOutcome::Vulnerable(checked) = vulnerabilities
                .get(&deps_core::test_util::vuln_key("checked"))
                .unwrap()
            else {
                panic!("expected Vulnerable");
            };
            assert_eq!(
                checked.fix_target_status,
                UpgradeStatus::CandidateClean {
                    version: ConcreteVersion::new("1.0.0")
                }
            );

            let ScanOutcome::Vulnerable(timed_out) = vulnerabilities
                .get(&deps_core::test_util::vuln_key("timed-out"))
                .unwrap()
            else {
                panic!("expected Vulnerable");
            };
            assert_eq!(timed_out.fix_target_status, UpgradeStatus::NotChecked);
        }
    }
}